context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using UnityEngine;
using System;
using System.Text;
using System.Collections;
namespace TeamUtility.IO
{
#region [Enumerations]
public enum InputDPADButton
{
Left, Right, Up, Down,
Left_Up, Right_Up,
Left_Down, Right_Down, Any
}
public enum InputTriggerButton
{
Left, Right, Any
}
public enum InputTriggerAxis
{
Left, Right
}
public enum InputDPADAxis
{
Horizontal, Vertical
}
public enum InputDevice
{
KeyboardAndMouse,
Joystick
}
#endregion
public sealed class InputAdapter : MonoBehaviour
{
public event Action<InputDevice> InputDeviceChanged;
[SerializeField]
private bool dontDestroyOnLoad = false;
[SerializeField]
[Tooltip("If enabled you will switch automatically to joystick/keyboard input when the user presses a joystick/keyboard button or a joystick/mouse axis")]
private bool allowRealtimeInputDeviceSwitch = true;
[SerializeField]
[Tooltip("If enabled you'll check every frame wich device the user is trying to use and switch the input device accordingly.")]
private bool checkInputDeviceEveryFrame = false;
[SerializeField]
[Range(1, 30)]
[Tooltip("How many times per second do you want to check wich device the user is trying to use.\nA higher value will mean a faster and smoother transition between keyboard and joystick input.")]
private int inputDeviceChecksPerSecond = 15;
[SerializeField]
[Range(1.0f, 5.0f)]
private float updateJoystickCountInterval = 1.0f;
[SerializeField]
private string keyboardConfiguration = "KeyboardAndMouse";
[SerializeField]
private string windowsJoystickConfiguration = "Windows_Gamepad";
[SerializeField]
private string osxJoystickConfiguration = "OSX_Gamepad";
[SerializeField]
private string linuxJoystickConfiguration = "Linux_Gamepad";
[SerializeField]
private string leftTriggerAxis = "LeftTrigger";
[SerializeField]
private string rightTriggerAxis = "RightTrigger";
[SerializeField]
private string dpadHorizontalAxis = "DPADHorizontal";
[SerializeField]
private string dpadVerticalAxis = "DPADVertical";
private Vector2 _lastDpadValues = Vector2.zero;
private Vector2 _currentDpadValues = Vector2.zero;
private Vector2 _lastTriggerValues = Vector2.zero;
private Vector2 _currentTriggerValues = Vector2.zero;
private InputDevice _inputDevice;
private float _lastInputDeviceCheck;
private int _joystickCount = 0;
private int _firstJoystickKey = 330;
private string _joystickConfiguration;
private string _keyboardConfiguration;
private static InputAdapter _instance;
#region [Static Accessors]
public static InputAdapter Instance
{
get
{
return _instance;
}
}
public static InputDevice inputDevice
{
get
{
return _instance._inputDevice;
}
set
{
if(value != _instance._inputDevice)
{
if(value == InputDevice.Joystick && _instance._joystickCount > 0)
{
_instance.SetInputDevice(InputDevice.Joystick);
}
else
{
_instance.SetInputDevice(InputDevice.KeyboardAndMouse);
}
}
}
}
public static string KeyboardConfiguration
{
get
{
return _instance._keyboardConfiguration;
}
}
public static string JoystickConfiguration
{
get
{
return _instance._joystickConfiguration;
}
}
public static Vector3 mousePosition
{
get
{
return InputManager.mousePosition;
}
}
public static float GetAxis(string axisName)
{
return InputManager.GetAxis(axisName);
}
public static float GetTriggerAxis(InputTriggerAxis axis)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return 0.0f;
if(axis == InputTriggerAxis.Left)
{
return InputManager.GetAxis(_instance.leftTriggerAxis);
}
else
{
return InputManager.GetAxis(_instance.rightTriggerAxis);
}
}
public static float GetDPADAxis(InputDPADAxis axis)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return 0.0f;
if(axis == InputDPADAxis.Horizontal)
{
return InputManager.GetAxis(_instance.dpadHorizontalAxis);
}
else
{
return InputManager.GetAxis(_instance.dpadVerticalAxis);
}
}
public static bool GetButton(string buttonName)
{
return InputManager.GetButton(buttonName);
}
public static bool GetButtonDown(string buttonName)
{
return InputManager.GetButtonDown(buttonName);
}
public static bool GetButtonUp(string buttonName)
{
return InputManager.GetButtonUp(buttonName);
}
public static bool GetMouseButton(int button)
{
return InputManager.GetMouseButton(button);
}
public static bool GetMouseButtonDown(int button)
{
return InputManager.GetMouseButtonDown(button);
}
public static bool GetMouseButtonUp(int button)
{
return InputManager.GetMouseButtonUp(button);
}
public static bool GetDPADButton(InputDPADButton button)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return false;
if(button == InputDPADButton.Any) {
return (!Mathf.Approximately(_instance._currentDpadValues.x, 0.0f) ||
!Mathf.Approximately(_instance._currentDpadValues.y, 0.0f));
}
bool state = false;
switch(button)
{
case InputDPADButton.Left_Up:
state = (_instance._currentDpadValues.x <= -1.0f && _instance._currentDpadValues.y >= 1.0f);
break;
case InputDPADButton.Right_Up:
state = (_instance._currentDpadValues.x >= 1.0f && _instance._currentDpadValues.y >= 1.0f);
break;
case InputDPADButton.Left_Down:
state = (_instance._currentDpadValues.x <= -1.0f && _instance._currentDpadValues.y <= -1.0f);
break;
case InputDPADButton.Right_Down:
state = (_instance._currentDpadValues.x >= 1.0f && _instance._currentDpadValues.y <= -1.0f);
break;
case InputDPADButton.Left:
state = (_instance._currentDpadValues.x <= -1.0f);
break;
case InputDPADButton.Right:
state = (_instance._currentDpadValues.x >= 1.0f);
break;
case InputDPADButton.Up:
state = (_instance._currentDpadValues.y >= 1.0f);
break;
case InputDPADButton.Down:
state = (_instance._currentDpadValues.y <= -1.0f);
break;
default:
break;
}
return state;
}
public static bool GetDPADButtonDown(InputDPADButton button)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return false;
if(button == InputDPADButton.Any) {
return ((!Mathf.Approximately(_instance._currentDpadValues.x, 0.0f) && Mathf.Approximately(_instance._lastDpadValues.x, 0.0f)) ||
(!Mathf.Approximately(_instance._currentDpadValues.y, 0.0f) && Mathf.Approximately(_instance._lastDpadValues.y, 0.0f)));
}
bool state = false;
switch(button)
{
case InputDPADButton.Left_Up:
state = (_instance._currentDpadValues.x <= -1.0f && _instance._lastDpadValues.x > -1.0f &&
_instance._currentDpadValues.y >= 1.0f && _instance._lastDpadValues.y < 1.0f);
break;
case InputDPADButton.Right_Up:
state = (_instance._currentDpadValues.x >= 1.0f && _instance._lastDpadValues.x < 1.0f &&
_instance._currentDpadValues.y >= 1.0f && _instance._lastDpadValues.y < 1.0f);
break;
case InputDPADButton.Left_Down:
state = (_instance._currentDpadValues.x <= -1.0f && _instance._lastDpadValues.x > -1.0f &&
_instance._currentDpadValues.y <= -1.0f && _instance._lastDpadValues.y > -1.0f);
break;
case InputDPADButton.Right_Down:
state = (_instance._currentDpadValues.x >= 1.0f && _instance._lastDpadValues.x < 1.0f &&
_instance._currentDpadValues.y <= -1.0f && _instance._lastDpadValues.y > -1.0f);
break;
case InputDPADButton.Left:
state = (_instance._currentDpadValues.x <= -1.0f && _instance._lastDpadValues.x > -1.0f);
break;
case InputDPADButton.Right:
state = (_instance._currentDpadValues.x >= 1.0f && _instance._lastDpadValues.x < 1.0f);
break;
case InputDPADButton.Up:
state = (_instance._currentDpadValues.y >= 1.0f && _instance._lastDpadValues.y < 1.0f);
break;
case InputDPADButton.Down:
state = (_instance._currentDpadValues.y <= -1.0f && _instance._lastDpadValues.y > -1.0f);
break;
default:
break;
}
return state;
}
public static bool GetDPADButtonUp(InputDPADButton button)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return false;
if(button == InputDPADButton.Any) {
return ((Mathf.Approximately(_instance._currentDpadValues.x, 0.0f) && !Mathf.Approximately(_instance._lastDpadValues.x, 0.0f)) ||
(Mathf.Approximately(_instance._currentDpadValues.y, 0.0f) && !Mathf.Approximately(_instance._lastDpadValues.y, 0.0f)));
}
bool state = false;
switch(button)
{
case InputDPADButton.Left_Up:
state = (_instance._currentDpadValues.x > -1.0f && _instance._lastDpadValues.x <= -1.0f &&
_instance._currentDpadValues.y < 1.0f && _instance._lastDpadValues.y >= 1.0f);
break;
case InputDPADButton.Right_Up:
state = (_instance._currentDpadValues.x < 1.0f && _instance._lastDpadValues.x >= 1.0f &&
_instance._currentDpadValues.y < 1.0f && _instance._lastDpadValues.y >= 1.0f);
break;
case InputDPADButton.Left_Down:
state = (_instance._currentDpadValues.x > -1.0f && _instance._lastDpadValues.x <= -1.0f &&
_instance._currentDpadValues.y > -1.0f && _instance._lastDpadValues.y <= -1.0f);
break;
case InputDPADButton.Right_Down:
state = (_instance._currentDpadValues.x < 1.0f && _instance._lastDpadValues.x >= 1.0f &&
_instance._currentDpadValues.y > -1.0f && _instance._lastDpadValues.y <= -1.0f);
break;
case InputDPADButton.Left:
state = (_instance._currentDpadValues.x > -1.0f && _instance._lastDpadValues.x <= -1.0f);
break;
case InputDPADButton.Right:
state = (_instance._currentDpadValues.x < 1.0f && _instance._lastDpadValues.x >= 1.0f);
break;
case InputDPADButton.Up:
state = (_instance._currentDpadValues.y < 1.0f && _instance._lastDpadValues.y >= 1.0f);
break;
case InputDPADButton.Down:
state = (_instance._currentDpadValues.y > -1.0f && _instance._lastDpadValues.y <= -1.0f);
break;
default:
break;
}
return state;
}
public static bool GetTriggerButton(InputTriggerButton button)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return false;
if(button == InputTriggerButton.Left)
{
return (_instance._currentTriggerValues.x >= 1.0f);
}
else if(button == InputTriggerButton.Right)
{
return (_instance._currentTriggerValues.y >= 1.0f);
}
else
{
return (_instance._currentTriggerValues.x >= 1.0f || _instance._currentTriggerValues.y >= 1.0f);
}
}
public static bool GetTriggerButtonDown(InputTriggerButton button)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return false;
if(button == InputTriggerButton.Left)
{
return (_instance._currentTriggerValues.x >= 1.0f && _instance._lastTriggerValues.x < 1.0f);
}
else if(button == InputTriggerButton.Right)
{
return (_instance._currentTriggerValues.y >= 1.0f && _instance._lastTriggerValues.y < 1.0f);
}
else
{
return (_instance._currentTriggerValues.x >= 1.0f && _instance._lastTriggerValues.x < 1.0f) ||
(_instance._currentTriggerValues.y >= 1.0f && _instance._lastTriggerValues.y < 1.0f);
}
}
public static bool GetTriggerButtonUp(InputTriggerButton button)
{
if(_instance._inputDevice == InputDevice.KeyboardAndMouse)
return false;
if(button == InputTriggerButton.Left)
{
return (_instance._currentTriggerValues.x < 1.0f && _instance._lastTriggerValues.x >= 1.0f);
}
else if(button == InputTriggerButton.Right)
{
return (_instance._currentTriggerValues.y < 1.0f && _instance._lastTriggerValues.y >= 1.0f);
}
else
{
return (_instance._currentTriggerValues.x < 1.0f && _instance._lastTriggerValues.x >= 1.0f) ||
(_instance._currentTriggerValues.y < 1.0f && _instance._lastTriggerValues.y >= 1.0f);
}
}
public static void ResetInputAxes()
{
InputManager.ResetInputConfiguration(PlayerID.One);
InputManager.ResetInputAxes();
}
public static string[] GetJoystickNames()
{
return InputManager.GetJoystickNames();
}
public static bool IsUsingJoystick()
{
return (inputDevice == InputDevice.Joystick);
}
public static bool IsUsingKeyboardAndMouse()
{
return (inputDevice == InputDevice.KeyboardAndMouse);
}
#endregion
private void Awake()
{
if(_instance != null)
{
Destroy(this);
}
else
{
SetInputManagerConfigurations();
SetInputDevice(InputDevice.KeyboardAndMouse);
_instance = this;
_joystickCount = InputManager.GetJoystickNames().Length;
_lastInputDeviceCheck = Time.deltaTime;
if(dontDestroyOnLoad)
{
DontDestroyOnLoad(gameObject);
}
}
}
private void Start()
{
StartCoroutine(UpdateJoystickCount());
}
private void Update()
{
if(allowRealtimeInputDeviceSwitch)
{
if(checkInputDeviceEveryFrame)
{
UpdateInputDevice();
_lastInputDeviceCheck = Time.time;
}
else
{
if(Time.time >= _lastInputDeviceCheck + (1.0f / inputDeviceChecksPerSecond))
{
UpdateInputDevice();
_lastInputDeviceCheck = Time.time;
}
}
}
UpdateTriggerAndDPAD();
}
private void UpdateTriggerAndDPAD()
{
if(_inputDevice == InputDevice.Joystick)
{
_lastDpadValues = _currentDpadValues;
_currentDpadValues.x = InputManager.GetAxis(_instance.dpadHorizontalAxis);
_currentDpadValues.y = InputManager.GetAxis(_instance.dpadVerticalAxis);
_lastTriggerValues = _currentTriggerValues;
_currentTriggerValues.x = InputManager.GetAxis(_instance.leftTriggerAxis);
_currentTriggerValues.y = InputManager.GetAxis(_instance.rightTriggerAxis);
}
else
{
_lastDpadValues = Vector2.zero;
_currentDpadValues = Vector2.zero;
_lastTriggerValues = Vector2.zero;
_lastTriggerValues = Vector2.zero;
}
}
private IEnumerator UpdateJoystickCount()
{
while(true)
{
_joystickCount = InputManager.GetJoystickNames().Length;
if(_inputDevice == InputDevice.Joystick && _joystickCount == 0)
{
Debug.LogWarning("Lost connection with joystick. Switching to keyboard and mouse input.");
SetInputDevice(InputDevice.KeyboardAndMouse);
}
yield return new WaitForSeconds(updateJoystickCountInterval);
}
}
private void UpdateInputDevice()
{
bool anyJoystickKey = false;
if(_inputDevice == InputDevice.Joystick)
{
if(InputManager.anyKey)
{
for(int i = 0; i <= 19; i++)
{
if(InputManager.GetKey((KeyCode)(_firstJoystickKey + i)))
{
anyJoystickKey = true;
break;
}
}
if(!anyJoystickKey)
{
SetInputDevice(InputDevice.KeyboardAndMouse);
}
}
else
{
if(InputManager.AnyInput(_keyboardConfiguration))
{
SetInputDevice(InputDevice.KeyboardAndMouse);
}
}
}
else
{
if(InputManager.anyKey)
{
for(int i = 0; i <= 19; i++)
{
if(InputManager.GetKey((KeyCode)(_firstJoystickKey + i)))
{
anyJoystickKey = true;
break;
}
}
if(anyJoystickKey)
{
SetInputDevice(InputDevice.Joystick);
}
}
else
{
if(InputManager.AnyInput(_joystickConfiguration))
{
SetInputDevice(InputDevice.Joystick);
}
}
}
}
private void SetInputDevice(InputDevice inpuDevice)
{
_inputDevice = inpuDevice;
if(inpuDevice == InputDevice.Joystick)
{
#if UNITY_5
Cursor.visible = false;
#else
Cursor.visible = false;
#endif
InputManager.SetInputConfiguration(_joystickConfiguration, PlayerID.One);
Debug.Log("Current Input Device: Joystick");
}
else
{
#if UNITY_5
Cursor.visible = true;
#else
Cursor.visible = true;
#endif
InputManager.SetInputConfiguration(_keyboardConfiguration, PlayerID.One);
Debug.Log("Current Input Device: KeyboardAndMouse");
}
ResetInputAxes();
RaiseInputDeviceChangedEvent();
}
private void SetInputManagerConfigurations()
{
_keyboardConfiguration = keyboardConfiguration;
switch(Application.platform)
{
case RuntimePlatform.WindowsPlayer:
case RuntimePlatform.WindowsEditor:
case RuntimePlatform.WindowsWebPlayer:
_joystickConfiguration = windowsJoystickConfiguration;
break;
case RuntimePlatform.OSXPlayer:
case RuntimePlatform.OSXEditor:
case RuntimePlatform.OSXWebPlayer:
_joystickConfiguration = osxJoystickConfiguration;
break;
case RuntimePlatform.LinuxPlayer:
_joystickConfiguration = linuxJoystickConfiguration;
break;
default:
Debug.LogWarning("Unsupported XBOX 360 Controller driver. The default Windows driver configuration has been chosen.");
_joystickConfiguration = windowsJoystickConfiguration;
break;
}
}
private void RaiseInputDeviceChangedEvent()
{
if(InputDeviceChanged != null)
{
InputDeviceChanged(_inputDevice);
}
}
private void OnDestroy()
{
#if UNITY_5
Cursor.visible = true;
#else
Cursor.visible = true;
#endif
StopAllCoroutines();
}
#if UNITY_EDITOR
[UnityEditor.MenuItem("Team Utility/Input Manager/Create Input Adapter", false, 3)]
private static void Create()
{
GameObject gameObject = new GameObject("Input Adapter");
gameObject.AddComponent<InputAdapter>();
UnityEditor.Selection.activeGameObject = gameObject;
}
#endif
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Experimental;
using UnityEditor.Experimental.VFX;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Experimental.VFX;
using UnityEditor.VFX;
using UnityEditor.VFX.UI;
using Object = UnityEngine.Object;
using UnityEditorInternal;
using System.Reflection;
[CustomEditor(typeof(VFXContext), true)]
[CanEditMultipleObjects]
public class VFXContextEditor : VFXSlotContainerEditor
{
SerializedProperty spaceProperty;
SerializedObject dataObject;
float m_Width;
VFXViewController m_ViewController;
VFXContextController m_ContextController;
protected new void OnEnable()
{
UnityEngine.Object[] allData = targets.Cast<VFXContext>().Select(t => t.GetData()).Distinct().Where(t => t != null).Cast<UnityEngine.Object>().ToArray();
if (allData.Length > 0)
{
dataObject = new SerializedObject(allData);
spaceProperty = dataObject.FindProperty("m_Space");
}
else
{
dataObject = null;
spaceProperty = null;
}
if (!serializedObject.isEditingMultipleObjects)
{
m_ViewController = VFXViewController.GetController(((VFXContext)target).GetGraph().GetResource());
m_ViewController.useCount++;
m_ContextController = m_ViewController.GetRootNodeController((VFXContext)target, 0) as VFXContextController;
}
base.OnEnable();
}
private new void OnDisable()
{
base.OnDisable();
if(m_ViewController != null)
{
m_ViewController.useCount--;
m_ViewController = null;
}
}
public override void DoInspectorGUI()
{
if (spaceProperty != null)
EditorGUILayout.PropertyField(spaceProperty);
base.DoInspectorGUI();
}
void DoAttributeLayoutGUI(string label, StructureOfArrayProvider.BucketInfo[] layout)
{
GUILayout.Label(label, Styles.header);
// Used to distribute width evenly for each cell, induces a one-frame latency
var w = GUILayoutUtility.GetLastRect().width;
if (Event.current.type != EventType.Layout && w > 0)
m_Width = w - 48;
int maxSize = 0;
foreach (StructureOfArrayProvider.BucketInfo bucket in layout)
maxSize = Math.Max(maxSize, bucket.size);
DrawAttributeLayoutGrid(layout, maxSize);
}
void DrawAttributeLayoutGrid(StructureOfArrayProvider.BucketInfo[] layout, int maxSize)
{
int i = 0;
float height = 16.0f;
Rect r = GUILayoutUtility.GetRect(m_Width, layout.Length * height);
foreach (var bucket in layout)
{
float x = r.x;
float y = r.y + i * height;
float cellwidth = (m_Width - 16) / maxSize;
Rect cellRect = new Rect(x, y, 16, height);
GUI.Label(cellRect, i.ToString(), Styles.cell);
int bucketSize = bucket.size;
int usedSize = bucket.usedSize;
x += 16;
for (int j = 0; j < maxSize; j++)
{
cellRect = new Rect(x, y, cellwidth, height);
if (j < usedSize)
{
var attrib = bucket.attributes[j];
if (attrib.name != null)
Styles.DataTypeLabel(cellRect, attrib.name, attrib.type, Styles.cell);
else
Styles.DataTypeLabel(cellRect, "", VFXValueType.None, Styles.cell);
}
else
{
if (j < bucketSize)
Styles.DataTypeLabel(cellRect, "", VFXValueType.None, Styles.cell);
else
GUI.Label(cellRect, "");
}
x += cellwidth;
}
i++;
}
}
public override void OnInspectorGUI()
{
if (dataObject != null)
dataObject.Update();
if (m_ContextController != null && m_ContextController.letter != '\0')
{
GUILayout.Label(m_ContextController.letter.ToString(),Styles.letter);
}
base.OnInspectorGUI();
if (dataObject != null)
if (dataObject.ApplyModifiedProperties())
{
foreach (VFXContext ctx in targets.OfType<VFXContext>())
{
// notify that something changed.
ctx.Invalidate(VFXModel.InvalidationCause.kSettingChanged);
}
}
if (serializedObject.isEditingMultipleObjects) return; // Summary Only visible for single selection
// Context / SystemData
if (dataObject == null) return;
var context = (VFXContext)target;
var data = (VFXData)dataObject.targetObject;
// Particle context data
if (data.type == VFXDataType.kParticle)
{
VFXDataParticle particleData = data as VFXDataParticle;
EditorGUILayout.Space();
{
Styles.Row(Styles.header, "Name", "Value");
Styles.Row(Styles.cell, "Capacity", particleData.capacity.ToString());
EditorGUILayout.Space();
var attributes = data.GetAttributes();
if (attributes.Count() > 0)
{
EditorGUILayout.LabelField("System Attribute Summary", Styles.header);
foreach (var attr in attributes)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(attr.attrib.name, Styles.cell);
Styles.DataTypeLabel(attr.attrib.type.ToString(), attr.attrib.type, Styles.cell, GUILayout.Width(64));
int size = VFXExpressionHelper.GetSizeOfType(attr.attrib.type) * 4;
GUILayout.Label(size + " byte" + (size > 1 ? "s" : "") , Styles.cell, GUILayout.Width(64));
var mode = attr.mode;
GUILayout.Label(mode.ToString(), Styles.cell, GUILayout.Width(64));
}
}
}
StructureOfArrayProvider.BucketInfo[] current = particleData.GetCurrentAttributeLayout();
StructureOfArrayProvider.BucketInfo[] source = particleData.GetSourceAttributeLayout();
if (current.Length > 0)
{
GUILayout.Space(24);
DoAttributeLayoutGUI("Current Attribute Layout", current);
}
if (source.Length > 0)
{
GUILayout.Space(12);
DoAttributeLayoutGUI("Source Attribute Layout", source);
}
}
}
if (VFXViewPreference.displayExtraDebugInfo)
{
// Extra debug data
EditorGUILayout.Space();
{
Styles.Row(Styles.header, "Name", "Value");
Styles.Row(Styles.cell, "Context Type", context.contextType.ToString());
Styles.Row(Styles.cell, "Task Type", context.taskType.ToString());
Styles.Row(Styles.cell, "Input Data Type", context.inputType.ToString());
Styles.Row(Styles.cell, "Context Data Type", data.type.ToString());
Styles.Row(Styles.cell, "Can Be Compiled", context.CanBeCompiled().ToString());
EditorGUILayout.Space();
var attributeInfos = data.GetAttributesForContext(context);
VFXAttributeInfo[] infos;
// Early check for context consistency
try
{
infos = attributeInfos.ToArray();
}
catch
{
EditorGUILayout.HelpBox("Context is not connected or results in invalid system, please ensure all flow connections are correct.", MessageType.Warning, true);
return;
}
EditorGUILayout.LabelField("Attributes used by Context", Styles.header);
foreach (var info in infos)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(info.attrib.name, Styles.cell);
Styles.DataTypeLabel(info.attrib.type.ToString(), info.attrib.type, Styles.cell, GUILayout.Width(80));
Styles.AttributeModeLabel(info.mode.ToString(), info.mode, Styles.cell, GUILayout.Width(80));
}
}
EditorGUILayout.Space();
Styles.Row(Styles.header, "Blocks");
foreach (var block in context.activeChildrenWithImplicit)
Styles.Row(Styles.cell, block.name, !context.children.Contains(block) ? "implicit" : "");
EditorGUILayout.Space();
}
}
}
}
| |
using System;
using System.Threading;
using NUnit.Framework;
namespace Tharga.Influx_Capacitor.Tests
{
[TestFixture]
public class StopwatchHighPrecision_Tests
{
[Test]
public void Should_not_give_any_time_when_not_started()
{
//Arrange
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
//Act
Thread.Sleep(100);
//Assert
Assert.That(sw.ElapsedTotal, Is.EqualTo(0));
Assert.That(sw.ElapsedSegment, Is.EqualTo(0));
}
[Test]
public void Should_give_time_when_started()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
//Act
sw.Start();
Thread.Sleep(waitTime);
//Assert
var segment = sw.ElapsedSegment;
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.GreaterThan(waitTime));
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.LessThan(waitTime * 2));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.GreaterThan(waitTime));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.LessThan(waitTime * 2));
}
[Test]
public void Should_not_continue_when_stopped()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
sw.Start();
Thread.Sleep(waitTime);
sw.Stop();
//Act
Thread.Sleep(waitTime*2);
//Assert
var segment = sw.ElapsedSegment;
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.GreaterThan(waitTime));
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.LessThan(waitTime * 2));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.GreaterThan(waitTime));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.LessThan(waitTime * 2));
}
[Test]
public void Should_get_new_segments_when_running()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
sw.Start();
Thread.Sleep(waitTime);
var segment1 = sw.ElapsedSegment;
//Act
var segment2 = sw.ElapsedSegment;
//Assert
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.GreaterThan(waitTime));
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.LessThan(waitTime * 2));
Assert.That(new TimeSpan(segment2).TotalMilliseconds, Is.LessThan(waitTime));
}
[Test]
public void Should_not_get_new_segments_when_never_started()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
//sw.Start();
Thread.Sleep(waitTime);
//Act
var segment1 = sw.ElapsedSegment;
//Assert
var segment2 = sw.ElapsedSegment;
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.EqualTo(0));
Assert.That(new TimeSpan(segment2).TotalMilliseconds, Is.LessThan(waitTime));
}
[Test]
public void Should_not_get_new_segments_when_stopped()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
sw.Start();
Thread.Sleep(waitTime);
sw.Stop();
Thread.Sleep(waitTime);
//Act
var segment1 = sw.ElapsedSegment;
//Assert
var segment2 = sw.ElapsedSegment;
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.GreaterThanOrEqualTo(waitTime));
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.LessThan(waitTime * 2));
Assert.That(new TimeSpan(segment2).TotalMilliseconds, Is.LessThan(waitTime));
}
[Test]
public void When_resetting_and_the_timer_is_never_started()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
Thread.Sleep(waitTime);
//Act
sw.Reset();
Thread.Sleep(waitTime);
//Assert
var segment1 = sw.ElapsedSegment;
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.EqualTo(0));
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.EqualTo(0));
}
[Test]
public void When_resetting_and_the_timer_is_started()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
sw.Start();
Thread.Sleep(waitTime);
//Act
sw.Reset();
//Assert
var segment1 = sw.ElapsedSegment;
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.LessThan(waitTime));
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.LessThan(waitTime));
}
[Test]
public void When_resetting_and_the_timer_is_stopped()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
sw.Start();
Thread.Sleep(waitTime);
sw.Stop();
//Act
sw.Reset();
Thread.Sleep(waitTime);
//Assert
var segment1 = sw.ElapsedSegment;
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.EqualTo(0));
Assert.That(new TimeSpan(segment1).TotalMilliseconds, Is.EqualTo(0));
}
[Test]
public void Should_not_continue_when_paused()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
sw.Start();
Thread.Sleep(waitTime);
sw.Pause();
//Act
Thread.Sleep(waitTime * 2);
//Assert
var segment = sw.ElapsedSegment;
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.GreaterThan(waitTime));
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.LessThan(waitTime * 2));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.GreaterThan(waitTime));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.LessThan(waitTime * 2));
}
[Test]
public void Should_continue_on_when_resumed_after_pause()
{
//Arrange
var waitTime = 100;
var sw = new Tharga.InfluxCapacitor.Entities.StopwatchHighPrecision();
sw.Start();
Thread.Sleep(waitTime);
sw.Pause();
Thread.Sleep(waitTime);
sw.Resume();
//Act
Thread.Sleep(waitTime);
//Assert
var segment = sw.ElapsedSegment;
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.GreaterThan(waitTime*2));
Assert.That(new TimeSpan(sw.ElapsedTotal).TotalMilliseconds, Is.LessThan(waitTime * 3));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.GreaterThan(waitTime*2));
Assert.That(new TimeSpan(segment).TotalMilliseconds, Is.LessThan(waitTime * 3));
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new SyntaxAnnotation("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<ISymbol> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsFromDelegateInvoke(
SymbolAndProjectId<IMethodSymbol> symbolAndProjectId, Document document, CancellationToken cancellationToken);
public abstract SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context.CanChangeSignature
? ImmutableArray.Create(new ChangeSignatureCodeAction(this, context))
: ImmutableArray<ChangeSignatureCodeAction>.Empty;
}
internal ChangeSignatureResult ChangeSignature(Document document, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken)
{
var context = GetContextAsync(document, position, restrictToDeclarations: false, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
if (context.CanChangeSignature)
{
return ChangeSignatureWithContext(context, cancellationToken);
}
else
{
switch (context.CannotChangeSignatureReason)
{
case CannotChangeSignatureReason.DefinedInMetadata:
errorHandler(FeaturesResources.The_member_is_defined_in_metadata, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.IncorrectKind:
errorHandler(FeaturesResources.You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.InsufficientParameters:
errorHandler(FeaturesResources.This_signature_does_not_contain_parameters_that_can_be_changed, NotificationSeverity.Error);
break;
}
return new ChangeSignatureResult(succeeded: false);
}
}
private async Task<ChangeSignatureAnalyzedContext> GetContextAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var symbol = await GetInvocationSymbolAsync(document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-lang symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
if (symbol is IMethodSymbol)
{
var method = symbol as IMethodSymbol;
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol)
{
symbol = (symbol as IEventSymbol).Type;
}
if (symbol is INamedTypeSymbol)
{
var typeSymbol = symbol as INamedTypeSymbol;
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.DefinedInMetadata);
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
var parameterConfiguration = ParameterConfiguration.Create(symbol.GetParameters().ToList(), symbol is IMethodSymbol && (symbol as IMethodSymbol).IsExtensionMethod);
if (!parameterConfiguration.IsChangeable())
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.InsufficientParameters);
}
return new ChangeSignatureAnalyzedContext(
document.Project, symbol, parameterConfiguration);
}
private ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var options = GetChangeSignatureOptions(context, CancellationToken.None);
if (options.IsCancelled)
{
return new ChangeSignatureResult(succeeded: false);
}
return ChangeSignatureWithContext(context, options, cancellationToken);
}
internal ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
var succeeded = TryCreateUpdatedSolution(context, options, cancellationToken, out var updatedSolution);
return new ChangeSignatureResult(succeeded, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges);
}
internal ChangeSignatureOptionsResult GetChangeSignatureOptions(
ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
var changeSignatureOptionsService = context.Solution.Workspace.Services.GetService<IChangeSignatureOptionsService>();
var isExtensionMethod = context.Symbol is IMethodSymbol && (context.Symbol as IMethodSymbol).IsExtensionMethod;
return changeSignatureOptionsService.GetChangeSignatureOptions(context.Symbol, context.ParameterConfiguration, notificationService);
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
SymbolAndProjectId symbolAndProjectId,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
var streamingProgress = new StreamingProgressCollector(
StreamingFindReferencesProgress.Instance);
IImmutableSet<Document> documents = null;
var engine = new FindReferencesSearchEngine(
solution,
documents,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
streamingProgress,
cancellationToken);
await engine.FindReferencesAsync(symbolAndProjectId).ConfigureAwait(false);
return streamingProgress.GetReferencedSymbols();
}
}
private bool TryCreateUpdatedSolution(
ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken, out Solution updatedSolution)
{
updatedSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
bool hasLocationsInMetadata = false;
var symbols = FindChangeSignatureReferencesAsync(
SymbolAndProjectId.Create(declaredSymbol, context.Project.Id),
context.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
foreach (var symbol in symbols)
{
if (symbol.Definition.Kind == SymbolKind.Method &&
((symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertyGet || (symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
hasLocationsInMetadata = true;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Event)
{
var eventSymbol = symbolWithSyntacticParameters as IEventSymbol;
var type = eventSymbol.Type as INamedTypeSymbol;
if (type != null && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Method)
{
var methodSymbol = symbolWithSyntacticParameters as IMethodSymbol;
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
if (!TryGetNodeWithEditableSignatureOrAttributes(def, updatedSolution, out var nodeToUpdate, out var documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
hasLocationsInMetadata = true;
continue;
}
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, updatedSolution, out var nodeToUpdate2, out var documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
if (hasLocationsInMetadata)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
if (!notificationService.ConfirmMessageBox(FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue, severity: NotificationSeverity.Warning))
{
return false;
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = updatedSolution.GetDocument(docId);
var updater = doc.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
var root = doc.GetSyntaxRootSynchronously(CancellationToken.None);
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignature(doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, CreateCompensatingSignatureChange(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.FormatAsync(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: null,
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None).WaitAndGetResult(CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(docId, updatedRoots[docId]);
}
return true;
}
private void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
SyntaxNode node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected static List<IUnifiedArgumentSyntax> PermuteArguments(
Document document,
ISymbol declarationSymbol,
List<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = declarationSymbol.GetParameters().ToList();
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Count).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (int i = 0; i < declarationParametersToPermute.Count; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex.HasValue ? updatedIndex.Value : -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = new List<IUnifiedArgumentSyntax>();
int expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
bool seenNamedArgument = false;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
bool removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (int i = declarationParametersToPermute.Count; i < arguments.Count; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Count)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments;
}
private static SignatureChange CreateCompensatingSignatureChange(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (declarationSymbol.GetParameters().Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Count)
{
var origStuff = updatedSignature.OriginalConfiguration.ToListOfParameters();
var newStuff = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var realStuff = declarationSymbol.GetParameters();
var bonusParameters = realStuff.Skip(origStuff.Count);
origStuff.AddRange(bonusParameters);
newStuff.AddRange(bonusParameters);
var newOrigParams = ParameterConfiguration.Create(origStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
var newUpdatedParams = ParameterConfiguration.Create(newStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
updatedSignature = new SignatureChange(newOrigParams, newUpdatedParams);
}
return updatedSignature;
}
private static List<IParameterSymbol> GetParametersToPermute(
List<IUnifiedArgumentSyntax> arguments,
List<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
int position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = new List<IParameterSymbol>();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Count)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute;
}
}
}
| |
/*
* 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 log4net.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Tests.Common;
using log4net;
using System.Reflection;
using System.Data.Common;
// DBMS-specific:
using MySql.Data.MySqlClient;
using OpenSim.Data.MySQL;
using Mono.Data.Sqlite;
using OpenSim.Data.SQLite;
namespace OpenSim.Data.Tests
{
[TestFixture(Description = "Inventory store tests (MySQL)")]
public class MySqlInventoryTests : InventoryTests<MySqlConnection, MySQLInventoryData>
{
}
public class InventoryTests<TConn, TInvStore> : BasicDataServiceTest<TConn, TInvStore>
where TConn : DbConnection, new()
where TInvStore : class, IInventoryDataPlugin, new()
{
public IInventoryDataPlugin db;
public UUID zero = UUID.Zero;
public UUID folder1 = UUID.Random();
public UUID folder2 = UUID.Random();
public UUID folder3 = UUID.Random();
public UUID owner1 = UUID.Random();
public UUID owner2 = UUID.Random();
public UUID owner3 = UUID.Random();
public UUID item1 = UUID.Random();
public UUID item2 = UUID.Random();
public UUID item3 = UUID.Random();
public UUID asset1 = UUID.Random();
public UUID asset2 = UUID.Random();
public UUID asset3 = UUID.Random();
public string name1;
public string name2 = "First Level folder";
public string name3 = "First Level folder 2";
public string niname1 = "My Shirt";
public string iname1 = "Shirt";
public string iname2 = "Text Board";
public string iname3 = "No Pants Barrel";
public InventoryTests(string conn) : base(conn)
{
name1 = "Root Folder for " + owner1.ToString();
}
public InventoryTests() : this("") { }
protected override void InitService(object service)
{
ClearDB();
db = (IInventoryDataPlugin)service;
db.Initialise(m_connStr);
}
private void ClearDB()
{
DropTables("inventoryitems", "inventoryfolders");
ResetMigrations("InventoryStore");
}
[Test]
public void T001_LoadEmpty()
{
TestHelpers.InMethod();
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryFolder(folder1), Is.Null);
Assert.That(db.getInventoryFolder(folder2), Is.Null);
Assert.That(db.getInventoryFolder(folder3), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getInventoryItem(item1), Is.Null);
Assert.That(db.getInventoryItem(item2), Is.Null);
Assert.That(db.getInventoryItem(item3), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getUserRootFolder(owner1), Is.Null);
}
// 01x - folder tests
[Test]
public void T010_FolderNonParent()
{
TestHelpers.InMethod();
InventoryFolderBase f1 = NewFolder(folder2, folder1, owner1, name2);
// the folder will go in
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(f1a, Is.Null);
}
[Test]
public void T011_FolderCreate()
{
TestHelpers.InMethod();
InventoryFolderBase f1 = NewFolder(folder1, zero, owner1, name1);
// TODO: this is probably wrong behavior, but is what we have
// db.updateInventoryFolder(f1);
// InventoryFolderBase f1a = db.getUserRootFolder(owner1);
// Assert.That(uuid1, Is.EqualTo(f1a.ID))
// Assert.That(name1, Text.Matches(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
// Assert.That(db.getUserRootFolder(owner1), Is.Null);
// succeed with true
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(folder1, Is.EqualTo(f1a.ID), "Assert.That(folder1, Is.EqualTo(f1a.ID))");
Assert.That(name1, Is.StringMatching(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
}
// we now have the following tree
// folder1
// +--- folder2
// +--- folder3
[Test]
public void T012_FolderList()
{
TestHelpers.InMethod();
InventoryFolderBase f2 = NewFolder(folder3, folder1, owner1, name3);
db.addInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T013_FolderHierarchy()
{
TestHelpers.InMethod();
int n = db.getFolderHierarchy(zero).Count; // (for dbg - easier to see what's returned)
Assert.That(n, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
n = db.getFolderHierarchy(folder1).Count;
Assert.That(n, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T014_MoveFolder()
{
TestHelpers.InMethod();
InventoryFolderBase f2 = db.getInventoryFolder(folder2);
f2.ParentID = folder3;
db.moveInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T015_FolderHierarchy()
{
TestHelpers.InMethod();
Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
// Item tests
[Test]
public void T100_NoItems()
{
TestHelpers.InMethod();
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0))");
}
// TODO: Feeding a bad inventory item down the data path will
// crash the system. This is largely due to the builder
// routines. That should be fixed and tested for.
[Test]
public void T101_CreatItems()
{
TestHelpers.InMethod();
db.addInventoryItem(NewItem(item1, folder3, owner1, iname1, asset1));
db.addInventoryItem(NewItem(item2, folder3, owner1, iname2, asset2));
db.addInventoryItem(NewItem(item3, folder3, owner1, iname3, asset3));
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3))");
}
[Test]
public void T102_CompareItems()
{
TestHelpers.InMethod();
InventoryItemBase i1 = db.getInventoryItem(item1);
InventoryItemBase i2 = db.getInventoryItem(item2);
InventoryItemBase i3 = db.getInventoryItem(item3);
Assert.That(i1.Name, Is.EqualTo(iname1), "Assert.That(i1.Name, Is.EqualTo(iname1))");
Assert.That(i2.Name, Is.EqualTo(iname2), "Assert.That(i2.Name, Is.EqualTo(iname2))");
Assert.That(i3.Name, Is.EqualTo(iname3), "Assert.That(i3.Name, Is.EqualTo(iname3))");
Assert.That(i1.Owner, Is.EqualTo(owner1), "Assert.That(i1.Owner, Is.EqualTo(owner1))");
Assert.That(i2.Owner, Is.EqualTo(owner1), "Assert.That(i2.Owner, Is.EqualTo(owner1))");
Assert.That(i3.Owner, Is.EqualTo(owner1), "Assert.That(i3.Owner, Is.EqualTo(owner1))");
Assert.That(i1.AssetID, Is.EqualTo(asset1), "Assert.That(i1.AssetID, Is.EqualTo(asset1))");
Assert.That(i2.AssetID, Is.EqualTo(asset2), "Assert.That(i2.AssetID, Is.EqualTo(asset2))");
Assert.That(i3.AssetID, Is.EqualTo(asset3), "Assert.That(i3.AssetID, Is.EqualTo(asset3))");
}
[Test]
public void T103_UpdateItem()
{
TestHelpers.InMethod();
// TODO: probably shouldn't have the ability to have an
// owner of an item in a folder not owned by the user
InventoryItemBase i1 = db.getInventoryItem(item1);
i1.Name = niname1;
i1.Description = niname1;
i1.Owner = owner2;
db.updateInventoryItem(i1);
i1 = db.getInventoryItem(item1);
Assert.That(i1.Name, Is.EqualTo(niname1), "Assert.That(i1.Name, Is.EqualTo(niname1))");
Assert.That(i1.Description, Is.EqualTo(niname1), "Assert.That(i1.Description, Is.EqualTo(niname1))");
Assert.That(i1.Owner, Is.EqualTo(owner2), "Assert.That(i1.Owner, Is.EqualTo(owner2))");
}
[Test]
public void T104_RandomUpdateItem()
{
TestHelpers.InMethod();
PropertyScrambler<InventoryFolderBase> folderScrambler =
new PropertyScrambler<InventoryFolderBase>()
.DontScramble(x => x.Owner)
.DontScramble(x => x.ParentID)
.DontScramble(x => x.ID);
UUID owner = UUID.Random();
UUID folder = UUID.Random();
UUID rootId = UUID.Random();
UUID rootAsset = UUID.Random();
InventoryFolderBase f1 = NewFolder(folder, zero, owner, name1);
folderScrambler.Scramble(f1);
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner);
Assert.That(f1a, Constraints.PropertyCompareConstraint(f1));
folderScrambler.Scramble(f1a);
db.updateInventoryFolder(f1a);
InventoryFolderBase f1b = db.getUserRootFolder(owner);
Assert.That(f1b, Constraints.PropertyCompareConstraint(f1a));
//Now we have a valid folder to insert into, we can insert the item.
PropertyScrambler<InventoryItemBase> inventoryScrambler =
new PropertyScrambler<InventoryItemBase>()
.DontScramble(x => x.ID)
.DontScramble(x => x.AssetID)
.DontScramble(x => x.Owner)
.DontScramble(x => x.Folder);
InventoryItemBase root = NewItem(rootId, folder, owner, iname1, rootAsset);
inventoryScrambler.Scramble(root);
db.addInventoryItem(root);
InventoryItemBase expected = db.getInventoryItem(rootId);
Assert.That(expected, Constraints.PropertyCompareConstraint(root)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorIdentification)
.IgnoreProperty(x => x.CreatorData));
inventoryScrambler.Scramble(expected);
db.updateInventoryItem(expected);
InventoryItemBase actual = db.getInventoryItem(rootId);
Assert.That(actual, Constraints.PropertyCompareConstraint(expected)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorIdentification)
.IgnoreProperty(x => x.CreatorData));
}
[Test]
public void T999_StillNull()
{
TestHelpers.InMethod();
// After all tests are run, these should still return no results
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
}
private InventoryItemBase NewItem(UUID id, UUID parent, UUID owner, string name, UUID asset)
{
InventoryItemBase i = new InventoryItemBase();
i.ID = id;
i.Folder = parent;
i.Owner = owner;
i.CreatorId = owner.ToString();
i.Name = name;
i.Description = name;
i.AssetID = asset;
return i;
}
private InventoryFolderBase NewFolder(UUID id, UUID parent, UUID owner, string name)
{
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
f.ParentID = parent;
f.Owner = owner;
f.Name = name;
return f;
}
}
}
| |
/*
* 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.IO;
using System.IO.Compression;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// Handles an individual archive read request
/// </summary>
public class ArchiveReadRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_scene;
protected Stream m_loadStream;
protected Guid m_requestId;
protected string m_errorMessage;
/// <value>
/// Should the archive being loaded be merged with what is already on the region?
/// </value>
protected bool m_merge;
/// <value>
/// Should we ignore any assets when reloading the archive?
/// </value>
protected bool m_skipAssets;
/// <summary>
/// Used to cache lookups for valid uuids.
/// </summary>
private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
public ArchiveReadRequest(Scene scene, string loadPath, bool merge, bool skipAssets, Guid requestId)
{
m_scene = scene;
try
{
m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
}
m_errorMessage = String.Empty;
m_merge = merge;
m_skipAssets = skipAssets;
m_requestId = requestId;
}
public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge, bool skipAssets, Guid requestId)
{
m_scene = scene;
m_loadStream = loadStream;
m_merge = merge;
m_skipAssets = skipAssets;
m_requestId = requestId;
}
/// <summary>
/// Dearchive the region embodied in this request.
/// </summary>
public void DearchiveRegion()
{
// The same code can handle dearchiving 0.1 and 0.2 OpenSim Archive versions
DearchiveRegion0DotStar();
}
private void DearchiveRegion0DotStar()
{
int successfulAssetRestores = 0;
int failedAssetRestores = 0;
List<string> serialisedSceneObjects = new List<string>();
List<string> serialisedParcels = new List<string>();
string filePath = "NONE";
TarArchiveReader archive = new TarArchiveReader(m_loadStream);
byte[] data;
TarArchiveReader.TarEntryType entryType;
try
{
while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
{
//m_log.DebugFormat(
// "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
continue;
if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
{
serialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
}
else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
{
if (LoadAsset(filePath, data))
successfulAssetRestores++;
else
failedAssetRestores++;
if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
{
LoadTerrain(filePath, data);
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
{
LoadRegionSettings(filePath, data);
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH))
{
serialisedParcels.Add(Encoding.UTF8.GetString(data));
}
else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
{
LoadControlFile(filePath, data);
}
}
//m_log.Debug("[ARCHIVER]: Reached end of archive");
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Aborting load with error in archive file {0}. {1}", filePath, e);
m_errorMessage += e.ToString();
m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage);
return;
}
finally
{
archive.Close();
}
if (!m_skipAssets)
{
m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
if (failedAssetRestores > 0)
{
m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
}
}
if (!m_merge)
{
m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
m_scene.DeleteAllSceneObjects();
}
// Try to retain the original creator/owner/lastowner if their uuid is present on this grid
// otherwise, use the master avatar uuid instead
// Reload serialized parcels
m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
List<LandData> landData = new List<LandData>();
foreach (string serialisedParcel in serialisedParcels)
{
LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
if (!ResolveUserUuid(parcel.OwnerID))
parcel.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
landData.Add(parcel);
}
m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
// Reload serialized prims
m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>();
int sceneObjectsLoadedCount = 0;
foreach (string serialisedSceneObject in serialisedSceneObjects)
{
/*
m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
// Really large xml files (multi megabyte) appear to cause
// memory problems
// when loading the xml. But don't enable this check yet
if (serialisedSceneObject.Length > 5000000)
{
m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
continue;
}
*/
SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
// For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
// on the same region server and multiple examples a single object archive to be imported
// to the same scene (when this is possible).
sceneObject.ResetIDs();
foreach (SceneObjectPart part in sceneObject.Children.Values)
{
if (!ResolveUserUuid(part.CreatorID))
part.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
if (!ResolveUserUuid(part.OwnerID))
part.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
if (!ResolveUserUuid(part.LastOwnerID))
part.LastOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
// And zap any troublesome sit target information
part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
part.SitTargetPosition = new Vector3(0, 0, 0);
// Fix ownership/creator of inventory items
// Not doing so results in inventory items
// being no copy/no mod for everyone
lock (part.TaskInventory)
{
TaskInventoryDictionary inv = part.TaskInventory;
foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
{
if (!ResolveUserUuid(kvp.Value.OwnerID))
{
kvp.Value.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
}
if (!ResolveUserUuid(kvp.Value.CreatorID))
{
kvp.Value.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
}
}
}
}
if (m_scene.AddRestoredSceneObject(sceneObject, true, false))
{
sceneObjectsLoadedCount++;
sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
if (ignoredObjects > 0)
m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage);
}
/// <summary>
/// Look up the given user id to check whether it's one that is valid for this grid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
private bool ResolveUserUuid(UUID uuid)
{
if (!m_validUserUuids.ContainsKey(uuid))
{
UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
if (account != null)
m_validUserUuids.Add(uuid, true);
else
m_validUserUuids.Add(uuid, false);
}
if (m_validUserUuids[uuid])
return true;
else
return false;
}
/// <summary>
/// Load an asset
/// </summary>
/// <param name="assetFilename"></param>
/// <param name="data"></param>
/// <returns>true if asset was successfully loaded, false otherwise</returns>
private bool LoadAsset(string assetPath, byte[] data)
{
// Right now we're nastily obtaining the UUID from the filename
string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
if (i == -1)
{
m_log.ErrorFormat(
"[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
return false;
}
string extension = filename.Substring(i);
string uuid = filename.Remove(filename.Length - extension.Length);
if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
{
sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
if (assetType == (sbyte)AssetType.Unknown)
m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
//m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
asset.Data = data;
// We're relying on the asset service to do the sensible thing and not store the asset if it already
// exists.
m_scene.AssetService.Store(asset);
/**
* Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
* it might be best done when dearchive takes place on a separate thread
if (asset.Type=AssetType.Texture)
{
IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
if (cacheLayerDecode != null)
cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
}
*/
return true;
}
else
{
m_log.ErrorFormat(
"[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
assetPath, extension);
return false;
}
}
/// <summary>
/// Load region settings data
/// </summary>
/// <param name="settingsPath"></param>
/// <param name="data"></param>
/// <returns>
/// true if settings were loaded successfully, false otherwise
/// </returns>
private bool LoadRegionSettings(string settingsPath, byte[] data)
{
RegionSettings loadedRegionSettings;
try
{
loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
settingsPath, e);
return false;
}
RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
currentRegionSettings.Save();
IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
if (estateModule != null)
estateModule.sendRegionHandshakeToAll();
return true;
}
/// <summary>
/// Load terrain data
/// </summary>
/// <param name="terrainPath"></param>
/// <param name="data"></param>
/// <returns>
/// true if terrain was resolved successfully, false otherwise.
/// </returns>
private bool LoadTerrain(string terrainPath, byte[] data)
{
ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
MemoryStream ms = new MemoryStream(data);
terrainModule.LoadFromStream(terrainPath, ms);
ms.Close();
m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
return true;
}
/// <summary>
/// Load oar control file
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
private void LoadControlFile(string path, byte[] data)
{
//Create the XmlNamespaceManager.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
// Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader xtr
= new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
// Loaded metadata will empty if no information exists in the archive
currentRegionSettings.LoadedCreationDateTime = 0;
currentRegionSettings.LoadedCreationID = "";
while (xtr.Read())
{
if (xtr.NodeType == XmlNodeType.Element)
{
if (xtr.Name.ToString() == "datetime")
{
int value;
if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
currentRegionSettings.LoadedCreationDateTime = value;
}
else if (xtr.Name.ToString() == "id")
{
currentRegionSettings.LoadedCreationID = xtr.ReadElementContentAsString();
}
}
}
currentRegionSettings.Save();
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
/// <summary>
/// The Subfield class represents an alternative field definition used
/// by dynamic fields. They can only be associated with a containing
/// field object.
/// </summary>
public class Subfield
{
#region Internal Classes
/// <summary>
/// The SubfieldMap class tracks the reference field/value pairs which indicate a field
/// should use the alternate subfield definition rather than the usual defn (allows Dynamic Fields)
/// </summary>
private class SubfieldMap
{
private byte refFieldNum;
private object refFieldValue;
internal SubfieldMap(byte refFieldNum, object refFieldValue)
{
this.refFieldNum = refFieldNum;
this.refFieldValue = refFieldValue;
}
internal SubfieldMap(SubfieldMap subfieldMap)
{
this.refFieldNum = subfieldMap.refFieldNum;
this.refFieldValue = subfieldMap.refFieldValue;
}
/// <summary>
/// Checks if the reference fields in a given message indicate the subfield (alternate)
/// definition should be used
/// </summary>
/// <param name="mesg">message of interest</param>
/// <returns>true if the subfield is active</returns>
internal bool CanMesgSupport(Mesg mesg)
{
Field field = mesg.GetField(refFieldNum);
if (field != null)
{
object value = field.GetValue(0, Fit.SubfieldIndexMainField);
// Float refvalues are not supported
if (Convert.ToInt64(value) == Convert.ToInt64(refFieldValue))
{
return true;
}
}
return false;
}
}
#endregion Internal Classes
#region Fields
private string name;
private byte type;
private float scale;
private float offset;
private string units;
private List<SubfieldMap> maps;
private List<FieldComponent> components;
#endregion // Fields
#region Properties
internal string Name
{
get
{
return name;
}
}
internal byte Type
{
get
{
return type;
}
}
internal float Scale
{
get
{
return scale;
}
}
internal float Offset
{
get
{
return offset;
}
}
internal string Units
{
get
{
return units;
}
}
internal List<FieldComponent> Components
{
get
{
return components;
}
}
#endregion // Properties
#region Constructors
internal Subfield(Subfield subfield)
{
if (subfield == null)
{
this.name = "unknown";
this.type = 0;
this.scale = 1f;
this.offset = 0f;
this.units = "";
this.maps = new List<SubfieldMap>();
this.components = new List<FieldComponent>();
return;
}
this.name = subfield.name;
this.type = subfield.type;
this.scale = subfield.scale;
this.offset = subfield.offset;
this.units = subfield.units;
this.maps = new List<SubfieldMap>();
foreach (SubfieldMap map in subfield.maps)
{
this.maps.Add(new SubfieldMap(map));
}
this.components = new List<FieldComponent>();
foreach (FieldComponent comp in subfield.components)
{
this.components.Add(new FieldComponent(comp));
}
}
internal Subfield(string name, byte type, float scale, float offset, string units)
{
this.name = name;
this.type = type;
this.scale = scale;
this.offset = offset;
this.units = units;
this.maps = new List<SubfieldMap>();
this.components = new List<FieldComponent>();
}
#endregion // Constructors
#region Methods
internal void AddMap(byte refFieldNum, object refFieldValue)
{
maps.Add(new SubfieldMap(refFieldNum, refFieldValue));
}
internal void AddComponent(FieldComponent newComponent)
{
components.Add(newComponent);
}
/// <summary>
/// Checks if the reference fields in a given message indicate the subfield (alternate)
/// definition should be used
/// </summary>
/// <param name="mesg">message of interest</param>
/// <returns>true if the subfield is active</returns>
public bool CanMesgSupport(Mesg mesg)
{
foreach (SubfieldMap map in maps)
{
if (map.CanMesgSupport(mesg))
{
return true;
}
}
return false;
}
#endregion // Methods
} // Class
} // namespace
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
using OpenSim.Framework;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.BotManager
{
public class AvatarFollower : MovementAction
{
public class AvatarFollowerDescription : MovementDescription
{
private const float DEFAULT_STOP_FOLLOW_DISTANCE = 2f;
private const float DEFAULT_START_FOLLOW_DISTANCE = 3f;
private const float DEFAULT_LOST_AVATAR_DISTANCE = 1000f;
public bool AllowRunning { get; set; }
public bool AllowJumping { get; set; }
public bool AllowFlying { get; set; }
public Vector3 FollowOffset { get; set; }
public bool FollowRequiresLineOfSight { get; set; }
public UUID FollowUUID { get; set; }
public float StopFollowingDistance { get; set; }
public float StartFollowingDistance { get; set; }
public float LostAvatarDistance { get; set; }
public bool LostAvatar { get; set; }
public bool Paused { get; set; }
public int NumberOfTimesJumpAttempted { get; set; }
public AvatarFollowerDescription(UUID avatarID, Dictionary<int, object> options)
{
AllowRunning = AllowJumping = AllowFlying = true;
FollowUUID = avatarID;
StartFollowingDistance = DEFAULT_START_FOLLOW_DISTANCE;
StopFollowingDistance = DEFAULT_STOP_FOLLOW_DISTANCE;
LostAvatarDistance = DEFAULT_LOST_AVATAR_DISTANCE;
const int BOT_ALLOW_RUNNING = 1;
const int BOT_ALLOW_FLYING = 2;
const int BOT_ALLOW_JUMPING = 3;
const int BOT_FOLLOW_OFFSET = 4;
const int BOT_REQUIRES_LINE_OF_SIGHT = 5;
const int BOT_START_FOLLOWING_DISTANCE = 6;
const int BOT_STOP_FOLLOWING_DISTANCE = 7;
const int BOT_LOST_AVATAR_DISTANCE = 8;
foreach (KeyValuePair<int, object> kvp in options)
{
switch (kvp.Key)
{
case BOT_ALLOW_RUNNING:
if (kvp.Value is int)
AllowRunning = ((int)kvp.Value) == 1 ? true : false;
break;
case BOT_ALLOW_FLYING:
if (kvp.Value is int)
AllowFlying = ((int)kvp.Value) == 1 ? true : false;
break;
case BOT_ALLOW_JUMPING:
if (kvp.Value is int)
AllowJumping = ((int)kvp.Value) == 1 ? true : false;
break;
case BOT_FOLLOW_OFFSET:
if (kvp.Value is Vector3)
FollowOffset = (Vector3)kvp.Value;
break;
case BOT_REQUIRES_LINE_OF_SIGHT:
if (kvp.Value is int)
FollowRequiresLineOfSight = ((int)kvp.Value) == 1 ? true : false;
break;
case BOT_START_FOLLOWING_DISTANCE:
if (kvp.Value is float || kvp.Value is int)
StartFollowingDistance = (float)kvp.Value;
break;
case BOT_STOP_FOLLOWING_DISTANCE:
if (kvp.Value is float || kvp.Value is int)
StopFollowingDistance = (float)kvp.Value;
break;
case BOT_LOST_AVATAR_DISTANCE:
if (kvp.Value is float || kvp.Value is int)
LostAvatarDistance = (float)kvp.Value;
break;
}
}
}
}
private List<Vector3> m_significantAvatarPositions = new List<Vector3>();
private int m_currentPos;
private AvatarFollowerDescription m_description;
public AvatarFollower(MovementDescription desc, BotMovementController controller) :
base(desc, controller)
{
m_description = (AvatarFollowerDescription)desc;
}
//We don't use either of these events as they don't make sense for avatar following
public override void TriggerChangingNodes(ScenePresence botPresence, int nextNode) { }
public override void TriggerFailedToMoveToNextNode(ScenePresence botPresence, int nextNode) { }
public override void Start()
{
ScenePresence presence = m_controller.Scene.GetScenePresence(m_description.FollowUUID);
if (presence != null)
{
var pa = presence.PhysicsActor;
if (pa != null)
pa.OnRequestTerseUpdate += EventManager_OnClientMovement;
}
}
public override void Stop()
{
ScenePresence presence = m_controller.Scene.GetScenePresence(m_description.FollowUUID);
if (presence != null)
{
var pa = presence.PhysicsActor;
if (pa != null)
pa.OnRequestTerseUpdate -= EventManager_OnClientMovement;
}
ScenePresence botPresence = m_controller.Scene.GetScenePresence(m_controller.Bot.AgentID);
if (botPresence != null)
{
var pa = botPresence.PhysicsActor;
StopMoving(botPresence, pa != null && pa.Flying, true);
}
}
public override void UpdateInformation()
{
// FOLLOW an avatar - this is looking for an avatar UUID so wont follow a prim here - yet
//Call this each iteration so that if the av leaves, we don't get stuck following a null person
ScenePresence presence = m_controller.Scene.GetScenePresence(m_description.FollowUUID);
ScenePresence botPresence = m_controller.Scene.GetScenePresence(m_controller.Bot.AgentID);
//If its still null, the person doesn't exist, cancel the follow and return
if (presence == null)
{
if (!m_description.LostAvatar)
{
m_description.LostAvatar = true;
TriggerAvatarLost(botPresence, presence, 0.0f);
//We stopped, fix the animation
UpdateMovementAnimations(false);
}
m_description.Paused = true;
return;
}
Vector3 targetPos = presence.AbsolutePosition + m_description.FollowOffset;
Vector3 ourCurrentPos = botPresence.AbsolutePosition;
Util.ForceValidRegionXYZ(ref targetPos);
double distance = Util.GetDistanceTo(targetPos, ourCurrentPos);
float closeToPoint = m_toAvatar ? m_description.StartFollowingDistance : m_description.StopFollowingDistance;
List<SceneObjectPart> raycastEntities = llCastRay(ourCurrentPos,
targetPos);
if (m_description.FollowRequiresLineOfSight)
{
if (raycastEntities.Count > 0)
{
//Lost the avatar, fire the event
if (!m_description.LostAvatar)
{
m_description.LostAvatar = true;
TriggerAvatarLost(botPresence, presence, (float)distance);
//We stopped, fix the animation
UpdateMovementAnimations(false);
}
m_description.Paused = true;
return;
}
}
if (distance > 10) //Greater than 10 meters, give up
{
//Try direct then, since it is way out of range
DirectFollowing(presence, botPresence);
}
else if (distance < closeToPoint && raycastEntities.Count == 0)
//If the raycastEntities isn't zero, there is something between us and the avatar, don't stop on the other side of walls, etc
{
//We're here!
//If we were having to fly to here, stop flying
if (m_description.NumberOfTimesJumpAttempted > 0)
{
botPresence.PhysicsActor.Flying = false;
walkTo(botPresence, botPresence.AbsolutePosition);
//Fix the animation from flying > walking
UpdateMovementAnimations(false);
}
m_description.NumberOfTimesJumpAttempted = 0;
}
else
{
if (raycastEntities.Count == 0)
//Nothing between us and the target, go for it!
DirectFollowing(presence, botPresence);
else
//if (!BestFitPathFollowing (raycastEntities))//If this doesn't work, try significant positions
SignificantPositionFollowing(presence, botPresence);
}
ClearOutInSignificantPositions(botPresence, false);
}
public override void CheckInformationBeforeMove()
{
ScenePresence presence = m_controller.Scene.GetScenePresence(m_description.FollowUUID);
//If its still null, the person doesn't exist, cancel the follow and return
if (presence == null)
return;
//Check to see whether we are close to our avatar, and fire the event if needed
Vector3 targetPos = presence.AbsolutePosition + m_description.FollowOffset;
Util.ForceValidRegionXYZ(ref targetPos);
ScenePresence botPresence = m_controller.Scene.GetScenePresence(m_controller.Bot.AgentID);
Vector3 ourCurrentPos = botPresence.AbsolutePosition;
double distance = Util.GetDistanceTo(targetPos, ourCurrentPos);
float closeToPoint = m_toAvatar ? m_description.StartFollowingDistance : m_description.StopFollowingDistance;
//Fix how we are running
botPresence.SetAlwaysRun = presence.SetAlwaysRun;
if (distance < closeToPoint)
{
//Fire our event once
if (!m_toAvatar) //Changed
{
//Fix the animation
UpdateMovementAnimations(false);
}
m_toAvatar = true;
var physActor = presence.PhysicsActor;
bool fly = physActor == null ? m_description.AllowFlying : (m_description.AllowFlying && physActor.Flying);
StopMoving(botPresence, fly, true);
return;
}
if (distance > m_description.LostAvatarDistance)
{
//Lost the avatar, fire the event
if (!m_description.LostAvatar)
{
m_description.LostAvatar = true;
TriggerAvatarLost(botPresence, presence, 0.0f);
//We stopped, fix the animation
UpdateMovementAnimations(false);
}
m_description.Paused = true;
}
else if (m_description.LostAvatar)
{
m_description.LostAvatar = false;
m_paused = false; //Fixed pause status, avatar entered our range again
}
m_toAvatar = false;
}
private void EventManager_OnClientMovement()
{
ScenePresence presence = m_controller.Scene.GetScenePresence(m_description.FollowUUID);
if (presence == null)
return;
Vector3 pos = presence.AbsolutePosition;
lock (m_significantAvatarPositions)
{
m_significantAvatarPositions.Add(pos);
}
}
#region Significant Position Following Code
private void ClearOutInSignificantPositions(ScenePresence botPresence, bool checkPositions)
{
int closestPosition = 0;
double closestDistance = 0;
Vector3[] sigPos;
lock (m_significantAvatarPositions)
{
sigPos = new Vector3[m_significantAvatarPositions.Count];
m_significantAvatarPositions.CopyTo(sigPos);
}
for (int i = 0; i < sigPos.Length; i++)
{
double val = Util.GetDistanceTo(botPresence.AbsolutePosition, sigPos[i]);
if (closestDistance == 0 || closestDistance > val)
{
closestDistance = val;
closestPosition = i;
}
}
if (m_currentPos > closestPosition)
{
m_currentPos = closestPosition + 2;
//Going backwards? We must have no idea where we are
}
else //Going forwards in the line, all good
m_currentPos = closestPosition + 2;
//Remove all insignificant
List<Vector3> vectors = new List<Vector3>();
for (int i = sigPos.Length - 50; i < sigPos.Length; i++)
{
if (i < 0)
continue;
vectors.Add(sigPos[i]);
}
m_significantAvatarPositions = vectors;
}
private void SignificantPositionFollowing(ScenePresence presence, ScenePresence botPresence)
{
//Do this first
ClearOutInSignificantPositions(botPresence, true);
var physActor = presence.PhysicsActor;
bool fly = physActor == null ? m_description.AllowFlying : (m_description.AllowFlying && physActor.Flying);
if (m_significantAvatarPositions.Count > 0 && m_currentPos + 1 < m_significantAvatarPositions.Count)
{
m_nodeGraph.Clear();
Vector3 targetPos = m_significantAvatarPositions[m_currentPos + 1];
Util.ForceValidRegionXYZ(ref targetPos);
Vector3 diffAbsPos = targetPos - botPresence.AbsolutePosition;
if (!fly && (diffAbsPos.Z < -0.25 || m_description.NumberOfTimesJumpAttempted > 5))
{
if (m_description.NumberOfTimesJumpAttempted > 5 || diffAbsPos.Z < -3)
{
if (m_description.NumberOfTimesJumpAttempted <= 5)
m_description.NumberOfTimesJumpAttempted = 6;
if (m_description.AllowFlying)
fly = true;
}
else
{
if (!m_description.AllowJumping)
{
m_description.NumberOfTimesJumpAttempted--;
targetPos.Z = botPresence.AbsolutePosition.Z + 0.15f;
}
else
{
if (!JumpDecisionTree(botPresence, targetPos))
{
m_description.NumberOfTimesJumpAttempted--;
targetPos.Z = botPresence.AbsolutePosition.Z + 0.15f;
}
else
{
if (m_description.NumberOfTimesJumpAttempted < 0)
m_description.NumberOfTimesJumpAttempted = 0;
m_description.NumberOfTimesJumpAttempted++;
}
}
}
}
else if (!fly)
{
if (diffAbsPos.Z > 3)
{
//We should fly down to the avatar, rather than fall
if (m_description.AllowFlying)
fly = true;
}
m_description.NumberOfTimesJumpAttempted--;
if (m_description.NumberOfTimesJumpAttempted < 0)
m_description.NumberOfTimesJumpAttempted = 0;
}
bool run = m_description.AllowRunning ? presence.SetAlwaysRun : false;
m_nodeGraph.Add(targetPos, fly ? TravelMode.Fly : (run ? TravelMode.Run : TravelMode.Walk));
}
}
#endregion
#region Direct Following code
private void DirectFollowing(ScenePresence presence, ScenePresence botPresence)
{
Vector3 targetPos = presence.AbsolutePosition + m_description.FollowOffset;
Util.ForceValidRegionXYZ(ref targetPos);
Vector3 ourPos = botPresence.AbsolutePosition;
Vector3 diffAbsPos = targetPos - ourPos;
var physActor = presence.PhysicsActor;
bool fly = physActor == null ? m_description.AllowFlying : (m_description.AllowFlying && physActor.Flying);
if (!fly && (diffAbsPos.Z > 0.25 || m_description.NumberOfTimesJumpAttempted > 5))
{
if (m_description.NumberOfTimesJumpAttempted > 5 || diffAbsPos.Z > 3)
{
if (m_description.NumberOfTimesJumpAttempted <= 5)
m_description.NumberOfTimesJumpAttempted = 6;
if (m_description.AllowFlying)
fly = true;
}
else
{
if (!m_description.AllowJumping)
{
m_description.NumberOfTimesJumpAttempted--;
targetPos.Z = ourPos.Z + 0.15f;
}
else
{
if (!JumpDecisionTree(botPresence, targetPos))
{
m_description.NumberOfTimesJumpAttempted--;
targetPos.Z = ourPos.Z + 0.15f;
}
else
{
if (m_description.NumberOfTimesJumpAttempted < 0)
m_description.NumberOfTimesJumpAttempted = 0;
m_description.NumberOfTimesJumpAttempted++;
}
}
}
}
else if (!fly)
{
if (diffAbsPos.Z < -3)
{
//We should fly down to the avatar, rather than fall
//We also know that because this is the old, we have no entities in our way
//(unless this is > 10m, but that case is messed up anyway, needs dealt with later)
//so we can assume that it is safe to fly
if (m_description.AllowFlying)
fly = true;
}
m_description.NumberOfTimesJumpAttempted--;
}
m_nodeGraph.Clear();
bool run = m_description.AllowRunning ? presence.SetAlwaysRun : false;
m_nodeGraph.Add(targetPos, fly ? TravelMode.Fly : (run ? TravelMode.Run : TravelMode.Walk));
}
/// <summary>
/// See whether we should jump based on the start and end positions given
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
private bool JumpDecisionTree(ScenePresence start, Vector3 end)
{
//Cast a ray in the direction that we are going
List<SceneObjectPart> entities = llCastRay(start.AbsolutePosition, end);
foreach (SceneObjectPart entity in entities)
{
if (!entity.IsAttachment)
{
if (entity.Scale.Z > start.PhysicsActor.Size.Z) return true;
}
}
return false;
}
public List<SceneObjectPart> llCastRay(Vector3 start, Vector3 end)
{
Vector3 dir = new Vector3((end - start).X, (end - start).Y, (end - start).Z);
Vector3 startvector = new Vector3(start.X, start.Y, start.Z);
Vector3 endvector = new Vector3(end.X, end.Y, end.Z);
List<SceneObjectPart> entities = new List<SceneObjectPart>();
List<ContactResult> results = m_controller.Scene.PhysicsScene.RayCastWorld(startvector, dir, dir.Length(), 5);
double distance = Util.GetDistanceTo(startvector, endvector);
if (distance == 0)
distance = 0.001;
foreach (ContactResult result in results)
{
if (result.CollisionActor != null && result.CollisionActor.PhysicsActorType == ActorType.Prim)
{
SceneObjectPart child = m_controller.Scene.GetSceneObjectPart(result.CollisionActor.Uuid);
if (!entities.Contains(child))
{
entities.Add(child);
}
}
}
return entities;
}
#endregion
}
}
| |
/*
* 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 UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
namespace Lucene.Net.Store
{
/// <summary>Abstract base class for output to a file in a Directory. A random-access
/// output stream. Used for all Lucene index output operations.
/// </summary>
/// <seealso cref="Directory">
/// </seealso>
/// <seealso cref="IndexInput">
/// </seealso>
public abstract class IndexOutput
{
private UnicodeUtil.UTF8Result utf8Result = new UnicodeUtil.UTF8Result();
/// <summary>Writes a single byte.</summary>
/// <seealso cref="IndexInput.ReadByte()">
/// </seealso>
public abstract void WriteByte(byte b);
/// <summary>Writes an array of bytes.</summary>
/// <param name="b">the bytes to write
/// </param>
/// <param name="length">the number of bytes to write
/// </param>
/// <seealso cref="IndexInput.ReadBytes(byte[],int,int)">
/// </seealso>
public virtual void WriteBytes(byte[] b, int length)
{
WriteBytes(b, 0, length);
}
/// <summary>Writes an array of bytes.</summary>
/// <param name="b">the bytes to write
/// </param>
/// <param name="offset">the offset in the byte array
/// </param>
/// <param name="length">the number of bytes to write
/// </param>
/// <seealso cref="IndexInput.ReadBytes(byte[],int,int)">
/// </seealso>
public abstract void WriteBytes(byte[] b, int offset, int length);
/// <summary>Writes an int as four bytes.</summary>
/// <seealso cref="IndexInput.ReadInt()">
/// </seealso>
public virtual void WriteInt(int i)
{
WriteByte((byte) (i >> 24));
WriteByte((byte) (i >> 16));
WriteByte((byte) (i >> 8));
WriteByte((byte) i);
}
/// <summary>Writes an int in a variable-length format. Writes between one and
/// five bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// </summary>
/// <seealso cref="IndexInput.ReadVInt()">
/// </seealso>
public virtual void WriteVInt(int i)
{
while ((i & ~ 0x7F) != 0)
{
WriteByte((byte) ((i & 0x7f) | 0x80));
i = SupportClass.Number.URShift(i, 7);
}
WriteByte((byte) i);
}
/// <summary>Writes a long as eight bytes.</summary>
/// <seealso cref="IndexInput.ReadLong()">
/// </seealso>
public virtual void WriteLong(long i)
{
WriteInt((int) (i >> 32));
WriteInt((int) i);
}
/// <summary>Writes an long in a variable-length format. Writes between one and five
/// bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// </summary>
/// <seealso cref="IndexInput.ReadVLong()">
/// </seealso>
public virtual void WriteVLong(long i)
{
while ((i & ~ 0x7F) != 0)
{
WriteByte((byte) ((i & 0x7f) | 0x80));
i = SupportClass.Number.URShift(i, 7);
}
WriteByte((byte) i);
}
/// <summary>Writes a string.</summary>
/// <seealso cref="IndexInput.ReadString()">
/// </seealso>
public virtual void WriteString(string s)
{
UnicodeUtil.UTF16toUTF8(s, 0, s.Length, utf8Result);
WriteVInt(utf8Result.length);
WriteBytes(utf8Result.result, 0, utf8Result.length);
}
/// <summary>Writes a sub sequence of chars from s as "modified UTF-8" encoded bytes.</summary>
/// <param name="s">the source of the characters</param>
/// <param name="start">the first character in the sequence</param>
/// <param name="length">the number of characters in the sequence</param>
[Obsolete("please pre-convert to UTF-8 bytes or use WriteString()")]
public virtual void WriteChars(string s, int start, int length)
{
int end = start + length;
for (int i = start; i < end; i++)
{
int code = (int) s[i];
if (code >= 0x01 && code <= 0x7F)
WriteByte((byte) code);
else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0)
{
WriteByte((byte) (0xC0 | (code >> 6)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
else
{
WriteByte((byte) (0xE0 | (SupportClass.Number.URShift(code, 12))));
WriteByte((byte) (0x80 | ((code >> 6) & 0x3F)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
}
}
/// <summary>Writes a sub sequence of chars from s as "modified UTF-8" encoded bytes.</summary>
/// <param name="s">the source of the characters</param>
/// <param name="start">the first character in the sequence</param>
/// <param name="length">the number of characters in the sequence</param>
[Obsolete("please pre-convert to UTF-8 bytes or use WriteString()")]
public virtual void WriteChars(char[] s, int start, int length)
{
int end = start + length;
for (int i = start; i < end; i++)
{
int code = (int) s[i];
if (code >= 0x01 && code <= 0x7F)
WriteByte((byte) code);
else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0)
{
WriteByte((byte) (0xC0 | (code >> 6)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
else
{
WriteByte((byte) (0xE0 | (SupportClass.Number.URShift(code, 12))));
WriteByte((byte) (0x80 | ((code >> 6) & 0x3F)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
}
}
private static int COPY_BUFFER_SIZE = 16384;
private byte[] copyBuffer;
/// <summary>Copy numBytes bytes from input to ourself. </summary>
public virtual void CopyBytes(IndexInput input, long numBytes)
{
long left = numBytes;
if (copyBuffer == null)
copyBuffer = new byte[COPY_BUFFER_SIZE];
while (left > 0)
{
int toCopy;
if (left > COPY_BUFFER_SIZE)
toCopy = COPY_BUFFER_SIZE;
else
toCopy = (int) left;
input.ReadBytes(copyBuffer, 0, toCopy);
WriteBytes(copyBuffer, 0, toCopy);
left -= toCopy;
}
}
/// <summary>Forces any buffered output to be written. </summary>
public abstract void Flush();
/// <summary>Closes this stream to further operations. </summary>
public abstract void Close();
/// <summary>Returns the current position in this file, where the next write will
/// occur.
/// </summary>
/// <seealso cref="Seek(long)">
/// </seealso>
public abstract long GetFilePointer();
/// <summary>Sets current position in this file, where the next write will occur.</summary>
/// <seealso cref="GetFilePointer()">
/// </seealso>
public abstract void Seek(long pos);
/// <summary>The number of bytes in the file. </summary>
public abstract long Length();
/// <summary>
/// Set the file length. By default, this method does
/// nothing (it's optional for a Directory to implement
/// it). But, certain Directory implementations (for
/// example @see FSDirectory) can use this to inform the
/// underlying IO system to pre-allocate the file to the
/// specified size. If the length is longer than the
/// current file length, the bytes added to the file are
/// undefined. Otherwise the file is truncated.
/// <param name="length">file length</param>
/// </summary>
public virtual void SetLength(long length)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
public struct ReadOnlySpan<T>
{
/// <summary>
/// Creates a new read-only span 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 ReadOnlySpan(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
_length = array.Length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
}
/// <summary>
/// Creates a new read-only span over the portion of the target array beginning
/// at 'start' index and covering the remainder of the array.
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the read-only span.</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"/> is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
int arrayLength = array.Length;
if ((uint)start > (uint)arrayLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = arrayLength - start;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new read-only span 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 read-only span.</param>
/// <param name="length">The number of items in the read-only span.</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 (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new read-only span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ReadOnlySpan(void* pointer, int length)
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = null;
_byteOffset = new IntPtr(pointer);
}
/// <summary>
/// Create a new read-only span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because
/// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when the specified object is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length)
{
if (obj == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
IntPtr byteOffset = Unsafe.ByteOffset<T>(ref pinnable.Data, ref objectData);
return new ReadOnlySpan<T>(pinnable, byteOffset, length);
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length)
{
Debug.Assert(length >= 0);
_length = length;
_pinnable = pinnable;
_byteOffset = byteOffset;
}
/// <summary>
/// The number of items in the read-only span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns the specified element of the read-only span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= ((uint)_length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { return Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index); }
else
return Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
}
}
/// <summary>
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
if ((uint)_length > (uint)destination.Length)
return false;
// TODO: This is a tide-over implementation as we plan to add a overlap-safe cpblk-based api to Unsafe. (https://github.com/dotnet/corefx/issues/13427)
unsafe
{
ref T src = ref DangerousGetPinnableReference();
ref T dst = ref destination.DangerousGetPinnableReference();
IntPtr srcMinusDst = Unsafe.ByteOffset<T>(ref dst, ref src);
int length = _length;
bool srcGreaterThanDst = (sizeof(IntPtr) == sizeof(int)) ? srcMinusDst.ToInt32() >= 0 : srcMinusDst.ToInt64() >= 0;
if (srcGreaterThanDst)
{
// Source address greater than or equal to destination address. Can do normal copy.
for (int i = 0; i < length; i++)
{
Unsafe.Add<T>(ref dst, i) = Unsafe.Add<T>(ref src, i);
}
}
else
{
// Source address less than destination address. Must do backward copy.
int i = length;
while (i-- != 0)
{
Unsafe.Add<T>(ref dst, i) = Unsafe.Add<T>(ref src, i);
}
}
return true;
}
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(T[] array) => new ReadOnlySpan<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment) => new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Forms a slice out of the given read-only span, 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 (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
int length = _length - start;
return new ReadOnlySpan<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Forms a slice out of the given read-only span, 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 (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
return new ReadOnlySpan<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Copies the contents of this read-only span 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()
{
if (_length == 0)
return SpanHelpers.PerTypeValues<T>.EmptyArray;
T[] result = new T[_length];
CopyTo(result);
return result;
}
/// <summary>
/// Returns a 0-length read-only span whose base is the null pointer.
/// </summary>
public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
unsafe { return ref Unsafe.AsRef<T>(_byteOffset.ToPointer()); }
else
return ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
}
// These expose the internal representation for Span-related apis use only.
internal Pinnable<T> Pinnable => _pinnable;
internal IntPtr ByteOffset => _byteOffset;
//
// If the Span was constructed from an object,
//
// _pinnable = that object (unsafe-casted to a Pinnable<T>)
// _byteOffset = offset in bytes from "ref _pinnable.Data" to "ref span[0]"
//
// If the Span was constructed from a native pointer,
//
// _pinnable = null
// _byteOffset = the pointer
//
private readonly Pinnable<T> _pinnable;
private readonly IntPtr _byteOffset;
private readonly int _length;
}
}
| |
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
using Duende.IdentityServer;
using Duende.IdentityServer.Events;
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Stores;
using Microsoft.AspNetCore.Identity;
using SignInResult = Microsoft.AspNetCore.Identity.SignInResult;
namespace IdentityServerHost.Quickstart.UI
{
/// <summary>
/// This sample controller implements a typical login/logout/provision workflow for local and external accounts.
/// The login service encapsulates the interactions with the user data store. This data store is in-memory only and cannot be used for production!
/// The interaction service provides a way for the UI to communicate with identityserver for validation and context retrieval
/// </summary>
[SecurityHeaders]
[AllowAnonymous]
public class AccountController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IAuthenticationSchemeProvider _schemeProvider;
private readonly IIdentityProviderStore _identityProviderStore;
private readonly IEventService _events;
private readonly SignInManager<IdentityUser> _signInManager;
public AccountController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IAuthenticationSchemeProvider schemeProvider,
IIdentityProviderStore identityProviderStore,
IEventService events,
SignInManager<IdentityUser> signInManager)
{
_interaction = interaction;
_clientStore = clientStore;
_schemeProvider = schemeProvider;
_identityProviderStore = identityProviderStore;
_events = events;
_signInManager = signInManager;
}
/// <summary>
/// Entry point into the login workflow
/// </summary>
[HttpGet]
public async Task<IActionResult> Login(string returnUrl)
{
// build a model so we know what to show on the login page
var vm = await BuildLoginViewModelAsync(returnUrl);
if (vm.IsExternalLoginOnly)
{
// we only have one option for logging in and it's an external provider
return RedirectToAction("Challenge", "External", new { scheme = vm.ExternalLoginScheme, returnUrl });
}
return View(vm);
}
/// <summary>
/// Handle postback from username/password login
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string button)
{
// check if we are in the context of an authorization request
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
// the user clicked the "cancel" button
if (button != "login")
{
if (context != null)
{
// if the user cancels, send a result back into IdentityServer as if they
// denied the consent (even if this client does not require consent).
// this will send back an access denied OIDC error response to the client.
await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", model.ReturnUrl);
}
return Redirect(model.ReturnUrl);
}
else
{
// since we don't have a valid context, then we just go back to the home page
return Redirect("~/");
}
}
if (ModelState.IsValid)
{
// find user by username
var user = await _signInManager.UserManager.FindByNameAsync(model.Username);
// validate username/password using ASP.NET Identity
if (user != null && (await _signInManager.CheckPasswordSignInAsync(user, model.Password, true)) == SignInResult.Success)
{
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId));
// only set explicit expiration here if user chooses "remember me".
// otherwise we rely upon expiration configured in cookie middleware.
AuthenticationProperties props = null;
if (AccountOptions.AllowRememberLogin && model.RememberLogin)
{
props = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
};
};
// issue authentication cookie with subject ID and username
var isuser = new IdentityServerUser(user.Id)
{
DisplayName = user.UserName
};
await HttpContext.SignInAsync(isuser, props);
if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", model.ReturnUrl);
}
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}
// request for a local page
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
else if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect("~/");
}
else
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId:context?.Client.ClientId));
ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
var vm = await BuildLoginViewModelAsync(model);
return View(vm);
}
/// <summary>
/// Show logout page
/// </summary>
[HttpGet]
public async Task<IActionResult> Logout(string logoutId)
{
// build a model so the logout page knows what to display
var vm = await BuildLogoutViewModelAsync(logoutId);
if (vm.ShowLogoutPrompt == false)
{
// if the request for logout was properly authenticated from IdentityServer, then
// we don't need to show the prompt and can just log the user out directly.
return await Logout(vm);
}
return View(vm);
}
/// <summary>
/// Handle logout page postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout(LogoutInputModel model)
{
// build a model so the logged out page knows what to display
var vm = await BuildLoggedOutViewModelAsync(model.LogoutId);
if (User?.Identity.IsAuthenticated == true)
{
// delete local authentication cookie
await HttpContext.SignOutAsync();
// raise the logout event
await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));
}
// check if we need to trigger sign-out at an upstream identity provider
if (vm.TriggerExternalSignout)
{
// build a return URL so the upstream provider will redirect back
// to us after the user has logged out. this allows us to then
// complete our single sign-out processing.
string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
// this triggers a redirect to the external provider for sign-out
return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
}
return View("LoggedOut", vm);
}
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
/*****************************************/
/* helper APIs for the AccountController */
/*****************************************/
private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
{
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
{
var local = context.IdP == Duende.IdentityServer.IdentityServerConstants.LocalIdentityProvider;
// this is meant to short circuit the UI and only trigger the one external IdP
var vm = new LoginViewModel
{
EnableLocalLogin = local,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
};
if (!local)
{
vm.ExternalProviders = new[] { new ExternalProvider { AuthenticationScheme = context.IdP } };
}
return vm;
}
var schemes = await _schemeProvider.GetAllSchemesAsync();
var providers = schemes
.Where(x => x.DisplayName != null)
.Select(x => new ExternalProvider
{
DisplayName = x.DisplayName ?? x.Name,
AuthenticationScheme = x.Name
}).ToList();
var dyanmicSchemes = (await _identityProviderStore.GetAllSchemeNamesAsync())
.Where(x => x.Enabled)
.Select(x => new ExternalProvider
{
AuthenticationScheme = x.Scheme,
DisplayName = x.DisplayName
});
providers.AddRange(dyanmicSchemes);
var allowLocal = true;
if (context?.Client.ClientId != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);
if (client != null)
{
allowLocal = client.EnableLocalLogin;
if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
{
providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
}
}
}
return new LoginViewModel
{
AllowRememberLogin = AccountOptions.AllowRememberLogin,
EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
ExternalProviders = providers.ToArray()
};
}
private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model)
{
var vm = await BuildLoginViewModelAsync(model.ReturnUrl);
vm.Username = model.Username;
vm.RememberLogin = model.RememberLogin;
return vm;
}
private async Task<LogoutViewModel> BuildLogoutViewModelAsync(string logoutId)
{
var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt };
if (User?.Identity.IsAuthenticated != true)
{
// if the user is not authenticated, then just show logged out page
vm.ShowLogoutPrompt = false;
return vm;
}
var context = await _interaction.GetLogoutContextAsync(logoutId);
if (context?.ShowSignoutPrompt == false)
{
// it's safe to automatically sign-out
vm.ShowLogoutPrompt = false;
return vm;
}
// show the logout prompt. this prevents attacks where the user
// is automatically signed out by another malicious web page.
return vm;
}
private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId)
{
// get context information (client name, post logout redirect URI and iframe for federated signout)
var logout = await _interaction.GetLogoutContextAsync(logoutId);
var vm = new LoggedOutViewModel
{
AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut,
PostLogoutRedirectUri = logout?.PostLogoutRedirectUri,
ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName,
SignOutIframeUrl = logout?.SignOutIFrameUrl,
LogoutId = logoutId
};
if (User?.Identity.IsAuthenticated == true)
{
var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value;
if (idp != null && idp != Duende.IdentityServer.IdentityServerConstants.LocalIdentityProvider)
{
var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp);
if (providerSupportsSignout)
{
if (vm.LogoutId == null)
{
// if there's no current logout context, we need to create one
// this captures necessary info from the current logged in user
// before we signout and redirect away to the external IdP for signout
vm.LogoutId = await _interaction.CreateLogoutContextAsync();
}
vm.ExternalAuthenticationScheme = idp;
}
}
}
return vm;
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\IO\Testing\Tcl\Plot3DVectors.tcl
// output file is AVPlot3DVectors.cs
/// <summary>
/// The testing class derived from AVPlot3DVectors
/// </summary>
public class AVPlot3DVectorsClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVPlot3DVectors(String [] argv)
{
//Prefix Content is: ""
//[]
// All Plot3D vector functions[]
//[]
// Create the RenderWindow, Renderer and both Actors[]
//[]
renWin = vtkRenderWindow.New();
ren1 = vtkRenderer.New();
ren1.SetBackground((double).8,(double).8,(double).2);
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
vectorLabels = "Velocity Vorticity Momentum Pressure_Gradient";
vectorFunctions = "200 201 202 210";
camera = new vtkCamera();
light = new vtkLight();
// All text actors will share the same text prop[]
textProp = new vtkTextProperty();
textProp.SetFontSize((int)10);
textProp.SetFontFamilyToArial();
textProp.SetColor((double).3,(double)1,(double)1);
i = 0;
foreach (string vectorFunction in vectorFunctions.Split(new char[]{' '}))
{
pl3d[getArrayIndex(vectorFunction)] = new vtkPLOT3DReader();
pl3d[getArrayIndex(vectorFunction)].SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/bluntfinxyz.bin");
pl3d[getArrayIndex(vectorFunction)].SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/bluntfinq.bin");
pl3d[getArrayIndex(vectorFunction)].SetVectorFunctionNumber((int)(int)(getArrayIndex(vectorFunction)));
pl3d[getArrayIndex(vectorFunction)].Update();
plane[getArrayIndex(vectorFunction)] = new vtkStructuredGridGeometryFilter();
plane[getArrayIndex(vectorFunction)].SetInputConnection((vtkAlgorithmOutput)pl3d[getArrayIndex(vectorFunction)].GetOutputPort());
plane[getArrayIndex(vectorFunction)].SetExtent((int)25,(int)25,(int)0,(int)100,(int)0,(int)100);
hog[getArrayIndex(vectorFunction)] = new vtkHedgeHog();
hog[getArrayIndex(vectorFunction)].SetInputConnection((vtkAlgorithmOutput)plane[getArrayIndex(vectorFunction)].GetOutputPort());
maxnorm = pl3d[getArrayIndex(vectorFunction)].GetOutput().GetPointData().GetVectors().GetMaxNorm();
hog[getArrayIndex(vectorFunction)].SetScaleFactor((double)1.0/maxnorm);
mapper[getArrayIndex(vectorFunction)] = vtkPolyDataMapper.New();
mapper[getArrayIndex(vectorFunction)].SetInputConnection((vtkAlgorithmOutput)hog[getArrayIndex(vectorFunction)].GetOutputPort());
actor[getArrayIndex(vectorFunction)] = new vtkActor();
actor[getArrayIndex(vectorFunction)].SetMapper((vtkMapper)mapper[getArrayIndex(vectorFunction)]);
ren[getArrayIndex(vectorFunction)] = vtkRenderer.New();
ren[getArrayIndex(vectorFunction)].SetBackground((double)0.5,(double).5,(double).5);
ren[getArrayIndex(vectorFunction)].SetActiveCamera((vtkCamera)camera);
ren[getArrayIndex(vectorFunction)].AddLight((vtkLight)light);
renWin.AddRenderer(ren[getArrayIndex(vectorFunction)]);
ren[getArrayIndex(vectorFunction)].AddActor((vtkProp)actor[getArrayIndex(vectorFunction)]);
textMapper[getArrayIndex(vectorFunction)] = new vtkTextMapper();
textMapper[getArrayIndex(vectorFunction)].SetInput(vectorLabels.Split(new char[] { ' ' })[i]);
textMapper[getArrayIndex(vectorFunction)].SetTextProperty((vtkTextProperty)textProp);
text[getArrayIndex(vectorFunction)] = new vtkActor2D();
text[getArrayIndex(vectorFunction)].SetMapper((vtkMapper2D)textMapper[getArrayIndex(vectorFunction)]);
text[getArrayIndex(vectorFunction)].SetPosition((double)2,(double)5);
ren[getArrayIndex(vectorFunction)].AddActor2D((vtkProp)text[getArrayIndex(vectorFunction)]);
i = i + 1;
}
//[]
// now layout renderers[]
column = 1;
row = 1;
deltaX = 1.0/2.0;
deltaY = 1.0/2.0;
foreach (string vectorFunction in vectorFunctions.Split(new char[]{' '}))
{
ren[getArrayIndex(vectorFunction)].SetViewport((double)(column - 1) * deltaX + (deltaX * .05), (double)(row - 1) * deltaY + (deltaY * .05), (double)column * deltaX - (deltaX * .05), (double)row * deltaY - (deltaY * .05));
column = column + 1;
if ((column) > 2)
{
column = 1;
row = row + 1;
}
}
camera.SetViewUp((double)1,(double)0,(double)0);
camera.SetFocalPoint((double)0,(double)0,(double)0);
camera.SetPosition((double).4,(double)-.5,(double)-.75);
ren[200].ResetCamera();
camera.Dolly((double)1.25);
ren[200].ResetCameraClippingRange();
ren[201].ResetCameraClippingRange();
ren[202].ResetCameraClippingRange();
ren[210].ResetCameraClippingRange();
light.SetPosition(camera.GetPosition()[0],camera.GetPosition()[1],camera.GetPosition()[2]);
light.SetFocalPoint(camera.GetFocalPoint()[0],camera.GetFocalPoint()[1],camera.GetFocalPoint()[2]);
renWin.SetSize(350,350);
renWin.Render();
iren.Initialize();
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderWindow renWin;
static vtkRenderer ren1;
static vtkRenderWindowInteractor iren;
static string vectorLabels;
static string vectorFunctions;
static vtkCamera camera;
static vtkLight light;
static vtkTextProperty textProp;
static int i;
static vtkPLOT3DReader[] pl3d = new vtkPLOT3DReader[230];
static vtkStructuredGridGeometryFilter[] plane = new vtkStructuredGridGeometryFilter[230];
static vtkHedgeHog[] hog = new vtkHedgeHog[230];
static double maxnorm;
static vtkPolyDataMapper[] mapper = new vtkPolyDataMapper[230];
static vtkActor[] actor = new vtkActor[230];
static vtkRenderer[] ren = new vtkRenderer[230];
static vtkTextMapper[] textMapper = new vtkTextMapper[230];
static vtkActor2D[] text = new vtkActor2D[230];
static int column;
static int row;
static double deltaX;
static double deltaY;
/// <summary>
/// hack to make this test work from tcl
/// </summary>
public static int getArrayIndex(string str)
{
string[] arrFunc = vectorFunctions.Split(new char[] { ' ' });
string[] arrLabel = vectorLabels.Split(new char[] { ' ' });
for (int i = 0; i < arrLabel.Length; i++)
{
if (arrLabel[i].Equals(str))
{
return i;
}
}
for (int i = 0; i < arrFunc.Length; i++)
{
if (arrFunc[i].Equals(str))
{
return System.Convert.ToInt32(str);
}
}
return -1;
}
/// <summary>
/// Returns the variable in the index [i] of the System.Array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="i"></param>
public static Object lindex(System.Array arr, int i)
{
return arr.GetValue(i);
}
/// <summary>
/// Returns the variable in the index [index] of the array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static double lindex(IntPtr arr, int index)
{
double[] destination = new double[index + 1];
System.Runtime.InteropServices.Marshal.Copy(arr, destination, 0, index + 1);
return destination[index];
}
/// <summary>
/// Returns the variable in the index [index] of the vtkLookupTable [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static long lindex(vtkLookupTable arr, double index)
{
return arr.GetIndex(index);
}
/// <summary>
/// Returns the substring ([index], [index]+1) in the string [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static int lindex(String arr, int index)
{
string[] str = arr.Split(new char[]{' '});
return System.Int32.Parse(str[index]);
}
/// <summary>
/// Returns the index [index] in the int array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static int lindex(int[] arr, int index)
{
return arr[index];
}
/// <summary>
/// Returns the index [index] in the float array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static float lindex(float[] arr, int index)
{
return arr[index];
}
/// <summary>
/// Returns the index [index] in the double array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static double lindex(double[] arr, int index)
{
return arr[index];
}
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static string GetvectorLabels()
{
return vectorLabels;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetvectorLabels(string toSet)
{
vectorLabels = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static string GetvectorFunctions()
{
return vectorFunctions;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetvectorFunctions(string toSet)
{
vectorFunctions = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcamera()
{
return camera;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcamera(vtkCamera toSet)
{
camera = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLight Getlight()
{
return light;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setlight(vtkLight toSet)
{
light = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTextProperty GettextProp()
{
return textProp;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettextProp(vtkTextProperty toSet)
{
textProp = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Geti()
{
return i;
}
///<summary> A Set Method for Static Variables </summary>
public static void Seti(int toSet)
{
i = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPLOT3DReader[] Getpl3d()
{
return pl3d;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpl3d(vtkPLOT3DReader[] toSet)
{
pl3d = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGridGeometryFilter[] Getplane()
{
return plane;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane(vtkStructuredGridGeometryFilter[] toSet)
{
plane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHedgeHog[] Gethog()
{
return hog;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sethog(vtkHedgeHog[] toSet)
{
hog = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getmaxnorm()
{
return maxnorm;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmaxnorm(double toSet)
{
maxnorm = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper[] Getmapper()
{
return mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmapper(vtkPolyDataMapper[] toSet)
{
mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor[] Getactor()
{
return actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setactor(vtkActor[] toSet)
{
actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer[] Getren()
{
return ren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren(vtkRenderer[] toSet)
{
ren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTextMapper[] GettextMapper()
{
return textMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettextMapper(vtkTextMapper[] toSet)
{
textMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor2D[] Gettext()
{
return text;
}
///<summary> A Set Method for Static Variables </summary>
public static void Settext(vtkActor2D[] toSet)
{
text = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getcolumn()
{
return column;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcolumn(int toSet)
{
column = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getrow()
{
return row;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setrow(int toSet)
{
row = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double GetdeltaX()
{
return deltaX;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetdeltaX(double toSet)
{
deltaX = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double GetdeltaY()
{
return deltaY;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetdeltaY(double toSet)
{
deltaY = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(renWin!= null){renWin.Dispose();}
if(ren1!= null){ren1.Dispose();}
if(iren!= null){iren.Dispose();}
if(camera!= null){camera.Dispose();}
if(light!= null){light.Dispose();}
if(textProp!= null){textProp.Dispose();}
}
}
//--- end of script --//
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using JiebaNet.Segmenter.Common;
using JiebaNet.Segmenter.FinalSeg;
namespace JiebaNet.Segmenter
{
public class JiebaSegmenter
{
private static readonly WordDictionary WordDict = WordDictionary.Instance;
private static readonly IFinalSeg FinalSeg = Viterbi.Instance;
private static readonly ISet<string> LoadedPath = new HashSet<string>();
private static readonly object locker = new object();
internal IDictionary<string, string> UserWordTagTab { get; set; }
#region Regular Expressions
internal static readonly Regex RegexChineseDefault = new Regex(@"([\u4E00-\u9FD5a-zA-Z0-9+#&\._]+)", RegexOptions.Compiled);
internal static readonly Regex RegexSkipDefault = new Regex(@"(\r\n|\s)", RegexOptions.Compiled);
internal static readonly Regex RegexChineseCutAll = new Regex(@"([\u4E00-\u9FD5]+)", RegexOptions.Compiled);
internal static readonly Regex RegexSkipCutAll = new Regex(@"[^a-zA-Z0-9+#\n]", RegexOptions.Compiled);
internal static readonly Regex RegexEnglishChars = new Regex(@"[a-zA-Z0-9]", RegexOptions.Compiled);
internal static readonly Regex RegexUserDict = new Regex("^(?<word>.+?)(?<freq> [0-9]+)?(?<tag> [a-z]+)?$", RegexOptions.Compiled);
#endregion
public JiebaSegmenter()
{
UserWordTagTab = new Dictionary<string, string>();
}
/// <summary>
/// The main function that segments an entire sentence that contains
/// Chinese characters into seperated words.
/// </summary>
/// <param name="text">The string to be segmented.</param>
/// <param name="cutAll">Specify segmentation pattern. True for full pattern, False for accurate pattern.</param>
/// <param name="hmm">Whether to use the Hidden Markov Model.</param>
/// <returns></returns>
public IEnumerable<string> Cut(string text, bool cutAll = false, bool hmm = true)
{
var reHan = RegexChineseDefault;
var reSkip = RegexSkipDefault;
Func<string, IEnumerable<string>> cutMethod = null;
if (cutAll)
{
reHan = RegexChineseCutAll;
reSkip = RegexSkipCutAll;
}
if (cutAll)
{
cutMethod = CutAll;
}
else if (hmm)
{
cutMethod = CutDag;
}
else
{
cutMethod = CutDagWithoutHmm;
}
return CutIt(text, cutMethod, reHan, reSkip, cutAll);
}
public IEnumerable<string> CutForSearch(string text, bool hmm = true)
{
var result = new List<string>();
var words = Cut(text, hmm: hmm);
foreach (var w in words)
{
if (w.Length > 2)
{
foreach (var i in Enumerable.Range(0, w.Length - 1))
{
var gram2 = w.Substring(i, 2);
if (WordDict.ContainsWord(gram2))
{
result.Add(gram2);
}
}
}
if (w.Length > 3)
{
foreach (var i in Enumerable.Range(0, w.Length - 2))
{
var gram3 = w.Substring(i, 3);
if (WordDict.ContainsWord(gram3))
{
result.Add(gram3);
}
}
}
result.Add(w);
}
return result;
}
public IEnumerable<Token> Tokenize(string text, TokenizerMode mode = TokenizerMode.Default, bool hmm = true)
{
var result = new List<Token>();
var start = 0;
if (mode == TokenizerMode.Default)
{
foreach (var w in Cut(text, hmm: hmm))
{
var width = w.Length;
result.Add(new Token(w, start, start + width));
start += width;
}
}
else
{
foreach (var w in Cut(text, hmm: hmm))
{
var width = w.Length;
if (width > 2)
{
for (var i = 0; i < width - 1; i++)
{
var gram2 = w.Substring(i, 2);
if (WordDict.ContainsWord(gram2))
{
result.Add(new Token(gram2, start + i, start + i + 2));
}
}
}
if (width > 3)
{
for (var i = 0; i < width - 2; i++)
{
var gram3 = w.Substring(i, 3);
if (WordDict.ContainsWord(gram3))
{
result.Add(new Token(gram3, start + i, start + i + 3));
}
}
}
result.Add(new Token(w, start, start + width));
start += width;
}
}
return result;
}
#region Internal Cut Methods
internal IDictionary<int, List<int>> GetDag(string sentence)
{
var dag = new Dictionary<int, List<int>>();
var trie = WordDict.Trie;
var N = sentence.Length;
for (var k = 0; k < sentence.Length; k++)
{
var templist = new List<int>();
var i = k;
var frag = sentence.Substring(k, 1);
while (i < N && trie.ContainsKey(frag))
{
if (trie[frag] > 0)
{
templist.Add(i);
}
i++;
// TODO:
if (i < N)
{
frag = sentence.Sub(k, i + 1);
}
}
if (templist.Count == 0)
{
templist.Add(k);
}
dag[k] = templist;
}
return dag;
}
internal IDictionary<int, Pair<int>> Calc(string sentence, IDictionary<int, List<int>> dag)
{
var n = sentence.Length;
var route = new Dictionary<int, Pair<int>>();
route[n] = new Pair<int>(0, 0.0);
var logtotal = Math.Log(WordDict.Total);
for (var i = n - 1; i > -1; i--)
{
var candidate = new Pair<int>(-1, double.MinValue);
foreach (int x in dag[i])
{
var freq = Math.Log(WordDict.GetFreqOrDefault(sentence.Sub(i, x + 1))) - logtotal + route[x + 1].Freq;
if (candidate.Freq < freq)
{
candidate.Freq = freq;
candidate.Key = x;
}
}
route[i] = candidate;
}
return route;
}
internal IEnumerable<string> CutAll(string sentence)
{
var dag = GetDag(sentence);
var words = new List<string>();
var lastPos = -1;
foreach (var pair in dag)
{
var k = pair.Key;
var nexts = pair.Value;
if (nexts.Count == 1 && k > lastPos)
{
words.Add(sentence.Substring(k, nexts[0] + 1 - k));
lastPos = nexts[0];
}
else
{
foreach (var j in nexts)
{
if (j > k)
{
words.Add(sentence.Substring(k, j + 1 - k));
lastPos = j;
}
}
}
}
return words;
}
internal IEnumerable<string> CutDag(string sentence)
{
var dag = GetDag(sentence);
var route = Calc(sentence, dag);
var tokens = new List<string>();
var x = 0;
var n = sentence.Length;
var buf = string.Empty;
while (x < n)
{
var y = route[x].Key + 1;
var w = sentence.Substring(x, y - x);
if (y - x == 1)
{
buf += w;
}
else
{
if (buf.Length > 0)
{
AddBufferToWordList(tokens, buf);
buf = string.Empty;
}
tokens.Add(w);
}
x = y;
}
if (buf.Length > 0)
{
AddBufferToWordList(tokens, buf);
}
return tokens;
}
internal IEnumerable<string> CutDagWithoutHmm(string sentence)
{
var dag = GetDag(sentence);
var route = Calc(sentence, dag);
var words = new List<string>();
var x = 0;
string buf = string.Empty;
var N = sentence.Length;
var y = -1;
while (x < N)
{
y = route[x].Key + 1;
var l_word = sentence.Substring(x, y - x);
if (RegexEnglishChars.IsMatch(l_word) && l_word.Length == 1)
{
buf += l_word;
x = y;
}
else
{
if (buf.Length > 0)
{
words.Add(buf);
buf = string.Empty;
}
words.Add(l_word);
x = y;
}
}
if (buf.Length > 0)
{
words.Add(buf);
}
return words;
}
internal IEnumerable<string> CutIt(string text, Func<string, IEnumerable<string>> cutMethod,
Regex reHan, Regex reSkip, bool cutAll)
{
var result = new List<string>();
var blocks = reHan.Split(text);
foreach (var blk in blocks)
{
if (string.IsNullOrWhiteSpace(blk))
{
continue;
}
if (reHan.IsMatch(blk))
{
foreach (var word in cutMethod(blk))
{
result.Add(word);
}
}
else
{
var tmp = reSkip.Split(blk);
foreach (var x in tmp)
{
if (reSkip.IsMatch(x))
{
result.Add(x);
}
else if (!cutAll)
{
foreach (var ch in x)
{
result.Add(ch.ToString());
}
}
else
{
result.Add(x);
}
}
}
}
return result;
}
#endregion
#region Extend Main Dict
/// <summary>
/// Loads user dictionaries.
/// </summary>
/// <param name="userDictFile"></param>
public void LoadUserDict(string userDictFile)
{
var dictFullPath = Path.GetFullPath(userDictFile);
Debug.WriteLine("Initializing user dictionary: " + userDictFile);
lock (locker)
{
if (LoadedPath.Contains(dictFullPath))
return;
try
{
var startTime = DateTime.Now.Millisecond;
var lines = File.ReadAllLines(dictFullPath, Encoding.UTF8);
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
var tokens = RegexUserDict.Match(line.Trim()).Groups;
var word = tokens["word"].Value.Trim();
var freq = tokens["freq"].Value.Trim();
var tag = tokens["tag"].Value.Trim();
var actualFreq = freq.Length > 0 ? int.Parse(freq) : 0;
AddWord(word, actualFreq, tag);
}
Debug.WriteLine("user dict '{0}' load finished, time elapsed {1} ms",
dictFullPath, DateTime.Now.Millisecond - startTime);
}
catch (IOException e)
{
Debug.Fail(string.Format("'{0}' load failure, reason: {1}", dictFullPath, e.Message));
}
catch (FormatException fe)
{
Debug.Fail(fe.Message);
}
}
}
public void AddWord(string word, int freq = 0, string tag = null)
{
if (freq <= 0)
{
freq = WordDict.SuggestFreq(word, Cut(word, hmm: false));
}
WordDict.AddWord(word, freq);
// Add user word tag of POS
if (!string.IsNullOrEmpty(tag))
{
UserWordTagTab[word] = tag;
}
}
public void DeleteWord(string word)
{
WordDict.DeleteWord(word);
}
#endregion
#region Private Helpers
private void AddBufferToWordList(List<string> words, string buf)
{
if (buf.Length == 1)
{
words.Add(buf);
}
else
{
if (!WordDict.ContainsWord(buf))
{
var tokens = FinalSeg.Cut(buf);
words.AddRange(tokens);
}
else
{
words.AddRange(buf.Select(ch => ch.ToString()));
}
}
}
#endregion
}
public enum TokenizerMode
{
Default,
Search
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using Vexe.Editor.Drawers;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using UnityObject = UnityEngine.Object;
namespace Vexe.Editor
{
/// <summary>
/// Defines a one-to-one mappying that maps a 'type' to a drawer.
/// Type could be a member type (int, string, List etc) or an attribute type (Popup, Slider etc)
/// The mapping could be exact, or loose. This is deterimined by the 'isForChildren' parameter.
/// If it's false (meaning loose mapping) then the drawer would be used on any subclass of the type we're mapping the drawer to,
/// otherwise (exact binding) the drawer would be mapped to that type only.
/// For ex, we want our ListDrawer<> to draw any List<> so we use loose binding (for children)
/// We want our StringDrawer to 'only' draw strings, so we use exact binding (not for children)
/// The caller then should specify how to 'bake' (instantiate) the drawer given the input type and drawer type.
/// For ex, all we need to instantiate a StringDrawer is just to say new StringDrawer()
/// but to instantiate ListDrawer<> we need to insert a value for the generic parameter which happens to be the same
/// parameter as the in our list. So the baked drawer type is: drawerType.MakeGenericType(type.GetGenericArguments()[0])
/// Note that the order of mapping matter. That's why only 'Insert' is public and not Add. You're not meant as a user
/// not modify the order of the built-in drawers.
/// For instance RecursiveDrawer must always come last, as it's meant to be a 'fallback' drawer.
///
/// Please see RegisterCustomDrawerExample.cs for sample usage of this system.
/// </summary>
public class TypeDrawerMapper
{
private readonly List<Type> _types = new List<Type>();
private readonly List<Type> _drawerTypes = new List<Type>();
private readonly List<bool> _isForChildren = new List<bool>();
private readonly List<Func<Type, Type, Type>> _bakeDrawerType = new List<Func<Type, Type, Type>>();
internal BaseDrawer GetDrawer(Type forType)
{
for (int i = 0; i < _types.Count; i++)
{
var type = _types[i];
var isForChildren = _isForChildren[i];
if ((isForChildren && forType.IsA(type) || forType.IsSubclassOrImplementerOfRawGeneric(type)) || forType == type)
{
var drawerType = _drawerTypes[i];
var bakedType = _bakeDrawerType[i](forType, drawerType);
return bakedType.Instance<BaseDrawer>();
}
}
Debug.LogError("No appropriate drawer found for type: " + forType);
return null;
}
internal void AddBuiltinTypes()
{
// Basics
{
this.Add<string, StringDrawer>()
.Add<char, CharDrawer>()
.Add<int, IntDrawer>()
.Add<uint, UIntDrawer>()
.Add<short, ShortDrawer>()
.Add<ushort, UShortDrawer>()
.Add<float, FloatDrawer>()
.Add<byte, ByteDrawer>()
.Add<sbyte, SByteDrawer>()
.Add<double, DoubleDrawer>()
.Add<long, LongDrawer>()
.Add<ulong, ULongDrawer>()
.Add<bool, BoolDrawer>()
.Add<Color, ColorDrawer>()
.Add<Color32, Color32Drawer>()
.Add<Vector2, Vector2Drawer>()
.Add<Vector3, Vector3Drawer>()
.Add<Vector4, Vector4Drawer>()
.Add<Matrix4x4, Drawers.Matrix4x4Drawer>()
.Add<Quaternion, QuaternionDrawer>()
.Add<Gradient, GradientDrawer>()
.Add<AnimationCurve, AnimationCurveDrawer>()
.Add<LayerMask, LayerMaskDrawer>()
.Add<Rect, RectDrawer>()
.Add<Bounds, BoundsDrawer>()
.Add<Enum, EnumDrawer>(true)
.Add<UnityObject, UnityObjectDrawer>(true);
}
// Collections
{
this.Add(typeof(List<>), typeof(ListDrawer<>), true, BakeTypeArgsInDrawer)
.Add(typeof(Array), typeof(ArrayDrawer<>), true, (a, d) => d.MakeGenericType(a.GetElementType()))
.Add(typeof(IDictionary<,>), typeof(IDictionaryDrawer<,>), true, (a, d) => {
if (a.IsAbstract)
{
Debug.LogError("Mapping error: IDictionary type {0} is abstract thus the drawer can't instantiate an instance of it. " +
"Falling back to RecursiveDrawer".FormatWith(a));
return typeof(RecursiveDrawer);
}
if (a.GetConstructor(Type.EmptyTypes) == null)
{
Debug.LogError("Mapping error: IDictionary type {0} must have a public empty constructor in order for it to be mapped with {1}. " +
"Falling back to RecursiveDrawer".FormatWith(a, d));
return typeof(RecursiveDrawer);
}
return BakeTypeArgsInDrawer(a, d);
});
}
// Nullable
{
Add(typeof(Nullable<>), typeof(NullableDrawer<>), false, BakeTypeInDrawer);
}
// User
{
// Constraints
{
this.Add<iMinAttribute, iMinDrawer>()
.Add<fMinAttribute, fMinDrawer>()
.Add<iMaxAttribute, iMaxDrawer>()
.Add<fMaxAttribute, fMaxDrawer>()
.Add<iClampAttribute, iClampDrawer>()
.Add<fClampAttribute, fClampDrawer>();
}
// Regex
{
Add(typeof(RegexAttribute), typeof(RegexDrawer<>), true, BakeTypeInDrawer);
}
// Decorates
{
this.Add<CommentAttribute, CommentDrawer>()
.Add<WhitespaceAttribute, WhiteSpaceDrawer>()
.Add<ReadOnlyAttribute, ReadOnlyDrawer>();
;
}
// Enums
{
Add<EnumMaskAttribute, EnumMaskDrawer>();
}
// Filters
{
this.Add<FilterEnumAttribute, FilterEnumDrawer>()
.Add<FilterTagsAttribute, FilterTagsDrawer>();
}
// Others
{
this.Add<AssignableAttribute, AssignableDrawer>()
.Add<DraggableAttribute, DraggableDrawer>()
.Add<InlineAttribute, InlineDrawer>()
.Add<OnChangedAttribute, OnChangedDrawer>()
.Add<OnChangedNoArgAttribute, OnChangedNoArgDrawer>()
.Add<PathAttribute, PathDrawer>()
.Add<ShowTypeAttribute, ShowTypeDrawer>()
.Add<fSliderAttribute, fSliderDrawer>()
.Add<iSliderAttribute, iSliderDrawer>()
.Add<vSliderAttribute, vSliderDrawer>()
.Add<ParagraphAttribute, ParagraphDrawer>()
.Add<ButtonAttribute, ButtonDrawer>()
.Add<ResourcePathAttribute, ResourcePathDrawer>();
}
// Popups
{
this.Add<IntPopupAttribute, IntPopupDrawer>()
.Add<UIntPopupAttribute, UIntPopupDrawer>()
.Add<BytePopupAttribute, BytePopupDrawer>()
.Add<SBytePopupAttribute, SBytePopupDrawer>()
.Add<ShortPopupDrawer, ShortPopupDrawer>()
.Add<UShortPopupAttribute, UShortPopupDrawer>()
.Add<FloatPopupAttribute, FloatPopupDrawer>()
.Add<DoublePopupAttribute, DoublePopupDrawer>()
.Add<LongPopupAttribute, LongPopupDrawer>()
.Add<CharPopupAttribute, CharPopupDrawer>()
.Add<AnimVarAttribute, AnimVarDrawer>()
.Add<StringPopupAttribute, StringPopupDrawer>()
.Add<InputAxisAttribute, InputAxisDrawer>()
.Add<TagsAttribute, TagsDrawer>();
}
// Randoms
{
this.Add<iRandAttribute, iRandDrawer>()
.Add<fRandAttribute, fRandDrawer>();
}
// Selections
{
this.Add<SelectEnumAttribute, SelectEnumDrawer>()
.Add<SelectSceneAttribute, SelectSceneDrawer>();
}
// Vectors
{
this.Add<BetterV2Attribute, BetterV2Drawer>()
.Add<BetterV3Attribute, BetterV3Drawer>();
}
}
// Fallback
{
Add<object, RecursiveDrawer>(true);
}
}
private TypeDrawerMapper Add(Type type, Type drawerType, bool isForChildren, Func<Type, Type, Type> bakeDrawerType)
{
_types.Add(type);
_drawerTypes.Add(drawerType);
_isForChildren.Add(isForChildren);
_bakeDrawerType.Add(bakeDrawerType);
return this;
}
private TypeDrawerMapper Add<TType, TDrawer>(bool isForChildren)
{
return Add(typeof(TType), typeof(TDrawer), isForChildren, BakeDirect);
}
private TypeDrawerMapper Add<TType, TDrawer>()
{
return Add<TType, TDrawer>(false);
}
public TypeDrawerMapper Insert(Type type, Type drawerType, bool isForChildren, Func<Type, Type, Type> bakeDrawerType)
{
if (!drawerType.IsA<BaseDrawer>())
ErrorHelper.TypeMismatch(typeof(BaseDrawer), drawerType);
_types.Insert(type);
_drawerTypes.Insert(drawerType);
_isForChildren.Insert(isForChildren);
_bakeDrawerType.Insert(bakeDrawerType);
return this;
}
public TypeDrawerMapper Insert<TType, TDrawer>(bool isForChildren)
{
return Insert(typeof(TType), typeof(TDrawer), isForChildren, BakeDirect);
}
public TypeDrawerMapper Insert<TType, TDrawer>()
{
return Insert<TType, TDrawer>(false);
}
/// <summary>
/// Bakes a generic drawer whose generic argument is 'type'
/// </summary>
public Type BakeTypeInDrawer(Type type, Type drawerType)
{
try
{
if (type.IsSubclassOfRawGeneric(typeof(Nullable<>)))
type = type.GetGenericArguments()[0];
return drawerType.MakeGenericType(type);
}
catch (ArgumentException e)
{
Debug.LogError("Failed to bake drawer ({0}) for type ({1}): {2} at {3}".FormatWith(drawerType.GetNiceName(), type.GetNiceName(), e.Message, e.StackTrace));
return typeof(RecursiveDrawer);
}
}
/// <summary>
/// Returns the drawer type immediately
/// </summary>
public Type BakeDirect(Type type, Type drawerType)
{
return drawerType;
}
/// <summary>
/// Bakes a generic drawer whose generic arguments are the generice arguments of 'type'
/// </summary>
public Type BakeTypeArgsInDrawer(Type type, Type drawerType)
{
return drawerType.MakeGenericType(type.GetGenericArgsInThisOrAbove());
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Text;
///<summary>
/// Mutable String class, optimized for speed and memory allocations while retrieving the final result as a string.
/// Similar use than StringBuilder, but avoid a lot of allocations done by StringBuilder (conversion of int and float to string, frequent capacity change, etc.)
/// Author: Nicolas Gadenne contact@gaddygames.com
///</summary>
public class FastString
{
///<summary>Immutable string. Generated at last moment, only if needed</summary>
private string m_stringGenerated = "";
///<summary>Is m_stringGenerated is up to date ?</summary>
private bool m_isStringGenerated = false;
///<summary>Working mutable string</summary>
private char[] m_buffer = null;
private int m_bufferPos = 0;
private int m_charsCapacity = 0;
///<summary>Temporary string used for the Replace method</summary>
private List<char> m_replacement = null;
private object m_valueControl = null;
private int m_valueControlInt = int.MinValue;
public FastString( int initialCapacity = 32 )
{
m_buffer = new char[ m_charsCapacity = initialCapacity ];
}
public bool IsEmpty()
{
return (m_isStringGenerated ? (m_stringGenerated == null) : (m_bufferPos == 0));
}
///<summary>Return the string</summary>
public override string ToString()
{
if( !m_isStringGenerated ) // Regenerate the immutable string if needed
{
m_stringGenerated = new string( m_buffer, 0, m_bufferPos );
m_isStringGenerated = true;
}
return m_stringGenerated;
}
// Value controls methods: use a value to check if the string has to be regenerated.
///<summary>Return true if the valueControl has changed (and update it)</summary>
public bool IsModified( int newControlValue )
{
bool changed = (newControlValue != m_valueControlInt);
if( changed )
m_valueControlInt = newControlValue;
return changed;
}
///<summary>Return true if the valueControl has changed (and update it)</summary>
public bool IsModified( object newControlValue )
{
bool changed = !(newControlValue.Equals( m_valueControl ));
if( changed )
m_valueControl = newControlValue;
return changed;
}
// Set methods:
///<summary>Set a string, no memorry allocation</summary>
public void Set( string str )
{
// We fill the m_chars list to manage future appends, but we also directly set the final stringGenerated
Clear();
Append( str );
m_stringGenerated = str;
m_isStringGenerated = true;
}
///<summary>Caution, allocate some memory</summary>
public void Set( object str )
{
Set( str.ToString() );
}
///<summary>Append several params: no memory allocation unless params are of object type</summary>
public void Set<T1, T2>( T1 str1, T2 str2 )
{
Clear();
Append( str1 ); Append( str2 );
}
public void Set<T1, T2, T3>( T1 str1, T2 str2, T3 str3 )
{
Clear();
Append( str1 ); Append( str2 ); Append( str3 );
}
public void Set<T1, T2, T3, T4>( T1 str1, T2 str2, T3 str3, T4 str4 )
{
Clear();
Append( str1 ); Append( str2 ); Append( str3 ); Append( str4 );
}
///<summary>Allocate a little memory (20 byte)</summary>
public void Set( params object[] str )
{
Clear();
for( int i=0; i<str.Length; i++ )
Append( str[ i ] );
}
// Append methods, to build the string without allocation
///<summary>Reset the m_char array</summary>
public FastString Clear()
{
m_bufferPos = 0;
m_isStringGenerated = false;
return this;
}
///<summary>Append a string without memory allocation</summary>
public FastString Append( string value )
{
ReallocateIFN( value.Length );
int n = value.Length;
for( int i=0; i<n; i++ )
m_buffer[ m_bufferPos + i ] = value[ i ];
m_bufferPos += n;
m_isStringGenerated = false;
return this;
}
///<summary>Append an object.ToString(), allocate some memory</summary>
public FastString Append( object value )
{
Append( value.ToString() );
return this;
}
///<summary>Append an int without memory allocation</summary>
public FastString Append( int value )
{
// Allocate enough memory to handle any int number
ReallocateIFN( 16 );
// Handle the negative case
if( value < 0 )
{
value = -value;
m_buffer[ m_bufferPos++ ] = '-';
}
// Copy the digits in reverse order
int nbChars = 0;
do
{
m_buffer[ m_bufferPos++ ] = (char)('0' + value%10);
value /= 10;
nbChars++;
} while( value != 0 );
// Reverse the result
for( int i=nbChars/2-1; i>=0; i-- )
{
char c = m_buffer[ m_bufferPos-i-1 ];
m_buffer[ m_bufferPos-i-1 ] = m_buffer[ m_bufferPos-nbChars+i ];
m_buffer[ m_bufferPos-nbChars+i ] = c;
}
m_isStringGenerated = false;
return this;
}
///<summary>Append a float without memory allocation.</summary>
public FastString Append( float valueF )
{
double value = valueF;
m_isStringGenerated = false;
ReallocateIFN( 32 ); // Check we have enough buffer allocated to handle any float number
// Handle the 0 case
if( value == 0 )
{
m_buffer[ m_bufferPos++ ] = '0';
return this;
}
// Handle the negative case
if( value < 0 )
{
value = -value;
m_buffer[ m_bufferPos++ ] = '-';
}
// Get the 7 meaningful digits as a long
int nbDecimals = 0;
while( value < 1000000 )
{
value *= 10;
nbDecimals++;
}
long valueLong = (long)System.Math.Round( value );
// Parse the number in reverse order
int nbChars = 0;
bool isLeadingZero = true;
while( valueLong != 0 || nbDecimals >= 0 )
{
// We stop removing leading 0 when non-0 or decimal digit
if( valueLong%10 != 0 || nbDecimals <= 0 )
isLeadingZero = false;
// Write the last digit (unless a leading zero)
if( !isLeadingZero )
m_buffer[ m_bufferPos + (nbChars++) ] = (char)('0' + valueLong%10);
// Add the decimal point
if( --nbDecimals == 0 && !isLeadingZero )
m_buffer[ m_bufferPos + (nbChars++) ] = '.';
valueLong /= 10;
}
m_bufferPos += nbChars;
// Reverse the result
for( int i=nbChars/2-1; i>=0; i-- )
{
char c = m_buffer[ m_bufferPos-i-1 ];
m_buffer[ m_bufferPos-i-1 ] = m_buffer[ m_bufferPos-nbChars+i ];
m_buffer[ m_bufferPos-nbChars+i ] = c;
}
return this;
}
///<summary>Replace all occurences of a string by another one</summary>
public FastString Replace( string oldStr, string newStr )
{
if( m_bufferPos == 0 )
return this;
if( m_replacement == null )
m_replacement = new List<char>();
// Create the new string into m_replacement
for( int i=0; i<m_bufferPos; i++ )
{
bool isToReplace = false;
if( m_buffer[ i ] == oldStr[ 0 ] ) // If first character found, check for the rest of the string to replace
{
int k=1;
while( k < oldStr.Length && m_buffer[ i+k ] == oldStr[ k ] )
k++;
isToReplace = (k >= oldStr.Length);
}
if( isToReplace ) // Do the replacement
{
i += oldStr.Length-1;
if( newStr != null )
for( int k=0; k<newStr.Length; k++ )
m_replacement.Add( newStr[ k ] );
}
else // No replacement, copy the old character
m_replacement.Add( m_buffer[ i ] );
}
// Copy back the new string into m_chars
ReallocateIFN( m_replacement.Count - m_bufferPos );
for( int k=0; k<m_replacement.Count; k++ )
m_buffer[ k ] = m_replacement[ k ];
m_bufferPos = m_replacement.Count;
m_replacement.Clear();
m_isStringGenerated = false;
return this;
}
private void ReallocateIFN( int nbCharsToAdd )
{
if( m_bufferPos + nbCharsToAdd > m_charsCapacity )
{
m_charsCapacity = System.Math.Max( m_charsCapacity + nbCharsToAdd, m_charsCapacity * 2 );
char[] newChars = new char[ m_charsCapacity ];
m_buffer.CopyTo( newChars, 0 );
m_buffer = newChars;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class ConvertTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
//Test Case Calls
[TestMethod]
public MFTestResults Cast_FloatingPoint()
{
MFTestResults res = MFTestResults.Pass;
uint u1;
uint u2;
double d1;
float f1;
long l1;
long l2;
double d2;
Random rand = new Random();
for (int i = 0; i < 100; i++)
{
u1 = (uint)rand.Next();
d1 = (double)u1; // Does not work correctly (d1 is close to 0)
u2 = (uint)d1;
if (d1 != u1 || u2 != u1)
{
Log.Comment("Cast from uint to double failed");
res = MFTestResults.Fail;
}
f1 = (float)u1; // Same problem
if (f1 != u1)
{
Log.Comment("Cast from uint to float failed");
res = MFTestResults.Fail;
}
l1 = (long)u1;
u2 = (uint)l1;
if (l1 != u1 || u2 != u1)
{
Log.Comment("Cast from uint to long failed");
res = MFTestResults.Fail;
}
d2 = l1; // Same problem
l2 = (long)d2;
if (d2 != l1 || l2 != l1)
{
Log.Comment("Cast from long to double failed");
res = MFTestResults.Fail;
}
}
return res;
}
//Test Case Calls
[TestMethod]
public MFTestResults Convert_Positive()
{
string number = "12";
int actualNumber = 12;
SByte value_sb = Convert.ToSByte(number);
if (value_sb != (byte)12)
{
return MFTestResults.Fail;
}
//--//
Byte value_b = Convert.ToByte(number);
if (value_b != (byte)12)
{
return MFTestResults.Fail;
}
//--//
Int16 value_s16 = Convert.ToInt16(number);
if (value_s16 != (short)12)
{
return MFTestResults.Fail;
}
//--//
UInt16 value_u16 = Convert.ToUInt16(number);
if (value_u16 != (ushort)12)
{
return MFTestResults.Fail;
}
//--//
Int32 value_s32 = Convert.ToInt32(number);
if (value_s32 != (int)12)
{
return MFTestResults.Fail;
}
//--//
UInt32 value_u32 = Convert.ToUInt32(number);
if (value_u32 != (uint)12)
{
return MFTestResults.Fail;
}
//--//
Int64 value_s64 = Convert.ToInt32(number);
if (value_s64 != (long)12)
{
return MFTestResults.Fail;
}
//--//
UInt64 value_u64 = Convert.ToUInt64(number);
if (value_u64 != (ulong)12)
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
//Test Case Calls
[TestMethod]
public MFTestResults Convert_PositivePlus()
{
string number = "+12";
int actualNumber = 12;
SByte value_sb = Convert.ToSByte(number);
if (value_sb != (byte)12)
{
return MFTestResults.Fail;
}
//--//
Byte value_b = Convert.ToByte(number);
if (value_b != (byte)12)
{
return MFTestResults.Fail;
}
//--//
Int16 value_s16 = Convert.ToInt16(number);
if (value_s16 != (short)12)
{
return MFTestResults.Fail;
}
//--//
UInt16 value_u16 = Convert.ToUInt16(number);
if (value_u16 != (ushort)12)
{
return MFTestResults.Fail;
}
//--//
Int32 value_s32 = Convert.ToInt32(number);
if (value_s32 != (int)12)
{
return MFTestResults.Fail;
}
//--//
UInt32 value_u32 = Convert.ToUInt32(number);
if (value_u32 != (uint)12)
{
return MFTestResults.Fail;
}
//--//
Int64 value_s64 = Convert.ToInt32(number);
if (value_s64 != (long)12)
{
return MFTestResults.Fail;
}
//--//
UInt64 value_u64 = Convert.ToUInt64(number);
if (value_u64 != (ulong)12)
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_Negative()
{
string number = "-12";
int actualNumber = -12;
SByte value_sb = Convert.ToSByte(number);
if (value_sb != (sbyte)actualNumber)
{
return MFTestResults.Fail;
}
//--//
try
{
Byte value_b = Convert.ToByte(number);
return MFTestResults.Fail;
}
catch
{
}
//--//
Int16 value_s16 = Convert.ToInt16(number);
if (value_s16 != (short)actualNumber)
{
return MFTestResults.Fail;
}
//--//
try
{
UInt16 value_u16 = Convert.ToUInt16(number);
return MFTestResults.Fail;
}
catch
{
}
//--//
Int32 value_s32 = Convert.ToInt32(number);
if (value_s32 != (int)actualNumber)
{
return MFTestResults.Fail;
}
//--//
try
{
UInt32 value_u32 = Convert.ToUInt32(number);
return MFTestResults.Fail;
}
catch
{
}
//--//
Int64 value_s64 = Convert.ToInt32(number);
if (value_s64 != (long)actualNumber)
{
return MFTestResults.Fail;
}
//--//
try
{
UInt64 value_u64 = Convert.ToUInt64(number);
return MFTestResults.Fail;
}
catch
{
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_Double()
{
string number = "36.123456";
double actualNumber = 36.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_Plus()
{
string number = "+36.123456";
double actualNumber = 36.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_Neg()
{
string number = "-36.123456";
double actualNumber = -36.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_Whitespace()
{
string intnum = " -3484 ";
string number = " +36.123456 ";
long actualInt = -3484;
double actualNumber = 36.123456;
if (actualInt != Convert.ToInt16(intnum))
{
return MFTestResults.Fail;
}
if (actualInt != Convert.ToInt32(intnum))
{
return MFTestResults.Fail;
}
if (actualInt != Convert.ToInt64(intnum))
{
return MFTestResults.Fail;
}
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_DoubleNormalizeNeg()
{
string number = "-3600030383448481.123456";
double actualNumber = -3600030383448481.123456;
double value_dd = Convert.ToDouble(number);
if (value_dd != actualNumber)
{
return MFTestResults.Fail;
}
number = "+0.00000000484874758559e-3";
actualNumber = 4.84874758559e-12;
if (actualNumber != Convert.ToDouble(number))
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_HexInt()
{
string number = "0x01234567";
int actualNumber = 0x01234567;
int value = Convert.ToInt32(number, 16);
if (value != actualNumber)
{
return MFTestResults.Fail;
}
number = "0x89abcdef";
unchecked
{
actualNumber = (int)0x89abcdef;
}
if (actualNumber != Convert.ToInt32(number, 16))
{
return MFTestResults.Fail;
}
number = "0x0AbF83C";
actualNumber = 0xAbF83C;
if (actualNumber != Convert.ToInt32(number, 16))
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_BoundaryValues()
{
double valMax = double.MaxValue;
string numMax = valMax.ToString();
double valMin = double.MinValue;
string numMin = valMin.ToString();
if(valMax != Convert.ToDouble(numMax)) return MFTestResults.Fail;
if(valMin != Convert.ToDouble(numMin)) return MFTestResults.Fail;
valMax = float.MaxValue;
numMax = valMax.ToString();
valMin = float.MinValue;
numMin = valMin.ToString();
if(valMax != Convert.ToDouble(numMax)) return MFTestResults.Fail;
if(valMin != Convert.ToDouble(numMin)) return MFTestResults.Fail;
long lMax = long.MaxValue;
numMax = lMax.ToString();
long lMin = long.MinValue;
numMin = lMin.ToString();
if(lMax != Convert.ToInt64(numMax)) return MFTestResults.Fail;
if(lMin != Convert.ToInt64(numMin)) return MFTestResults.Fail;
ulong ulMax = ulong.MaxValue;
numMax = ulMax.ToString();
ulong ulMin = ulong.MinValue;
numMin = ulMin.ToString();
if(ulMax != Convert.ToUInt64(numMax)) return MFTestResults.Fail;
if(ulMin != Convert.ToUInt64(numMin)) return MFTestResults.Fail;
long iMax = int.MaxValue;
numMax = iMax.ToString();
long iMin = int.MinValue;
numMin = iMin.ToString();
if(iMax != Convert.ToInt32(numMax)) return MFTestResults.Fail;
if(iMin != Convert.ToInt32(numMin)) return MFTestResults.Fail;
uint uiMax = uint.MaxValue;
numMax = uiMax.ToString();
uint uiMin = uint.MinValue;
numMin = uiMin.ToString();
if(uiMax != Convert.ToUInt32(numMax)) return MFTestResults.Fail;
if(uiMin != Convert.ToUInt32(numMin)) return MFTestResults.Fail;
short sMax = short.MaxValue;
numMax = sMax.ToString();
short sMin = short.MinValue;
numMin = sMin.ToString();
if(sMax != Convert.ToInt16(numMax)) return MFTestResults.Fail;
if(sMin != Convert.ToInt16(numMin)) return MFTestResults.Fail;
ushort usMax = ushort.MaxValue;
numMax = usMax.ToString();
ushort usMin = ushort.MinValue;
numMin = usMin.ToString();
if(usMax != Convert.ToUInt16(numMax)) return MFTestResults.Fail;
if(usMin != Convert.ToUInt16(numMin)) return MFTestResults.Fail;
sbyte sbMax = sbyte.MaxValue;
numMax = sbMax.ToString();
sbyte sbMin = sbyte.MinValue;
numMin = sbMin.ToString();
if(sbMax != Convert.ToSByte(numMax)) return MFTestResults.Fail;
if(sbMin != Convert.ToSByte(numMin)) return MFTestResults.Fail;
byte bMax = byte.MaxValue;
numMax = bMax.ToString();
byte bMin = byte.MinValue;
numMin = bMin.ToString();
if(bMax != Convert.ToByte(numMax)) return MFTestResults.Fail;
if(bMin != Convert.ToByte(numMin)) return MFTestResults.Fail;
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_LeadingZeroValues()
{
string number = "00000000";
if(0 != Convert.ToInt16(number)) return MFTestResults.Fail;
if(0 != Convert.ToInt32(number)) return MFTestResults.Fail;
if(0 != Convert.ToInt64(number)) return MFTestResults.Fail;
number = "+00000000000";
if(0 != Convert.ToInt16(number)) return MFTestResults.Fail;
if(0 != Convert.ToInt32(number)) return MFTestResults.Fail;
if(0 != Convert.ToInt64(number)) return MFTestResults.Fail;
number = "-00000000000";
if(0 != Convert.ToInt16(number)) return MFTestResults.Fail;
if(0 != Convert.ToInt32(number)) return MFTestResults.Fail;
if(0 != Convert.ToInt64(number)) return MFTestResults.Fail;
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_LeadingZeros()
{
string number = "000003984";
int actualNumber = 3984;
if ((short)actualNumber != Convert.ToInt16(number))
{
return MFTestResults.Fail;
}
if (actualNumber != Convert.ToInt32(number))
{
return MFTestResults.Fail;
}
if (actualNumber != Convert.ToInt64(number))
{
return MFTestResults.Fail;
}
number = "-00000003489";
actualNumber = -3489;
if ((short)actualNumber != Convert.ToInt16(number))
{
return MFTestResults.Fail;
}
if (actualNumber != Convert.ToInt32(number))
{
return MFTestResults.Fail;
}
if (actualNumber != Convert.ToInt64(number))
{
return MFTestResults.Fail;
}
number = "+00000003489";
actualNumber = 3489;
if ((short)actualNumber != Convert.ToInt16(number))
{
return MFTestResults.Fail;
}
if (actualNumber != Convert.ToInt32(number))
{
return MFTestResults.Fail;
}
if (actualNumber != Convert.ToInt64(number))
{
return MFTestResults.Fail;
}
number = "+000000043984.00048850000";
double numD = 4.39840004885;
if (numD == Convert.ToDouble(number))
{
return MFTestResults.Fail;
}
number = "-000000043984.00048850000";
numD = -4.39840004885;
if (numD == Convert.ToDouble(number))
{
return MFTestResults.Fail;
}
number = "000000043984.000488500e-006";
numD = 4.39840004885e2;
if (numD == Convert.ToDouble(number))
{
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Convert_64ParsePerf()
{
string number = "-7446744073709551615";
long val = 0;
DateTime start = DateTime.Now;
for (int i = 0; i < 0x1000; i++)
{
val = Convert.ToInt64(number);
}
Log.Comment("Time: " + (DateTime.Now - start).ToString());
return val == -7446744073709551615L ? MFTestResults.Pass : MFTestResults.Fail;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Raw
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Represents a raw disk image.
/// </summary>
/// <remarks>This disk format is simply an uncompressed capture of all blocks on a disk</remarks>
public sealed class Disk : VirtualDisk
{
private DiskImageFile _file;
/// <summary>
/// Initializes a new instance of the Disk class.
/// </summary>
/// <param name="stream">The stream to read</param>
/// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param>
public Disk(Stream stream, Ownership ownsStream)
: this(stream, ownsStream, null)
{
}
/// <summary>
/// Initializes a new instance of the Disk class.
/// </summary>
/// <param name="stream">The stream to read</param>
/// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param>
/// <param name="geometry">The emulated geometry of the disk.</param>
public Disk(Stream stream, Ownership ownsStream, Geometry geometry)
{
_file = new DiskImageFile(stream, ownsStream, geometry);
}
/// <summary>
/// Initializes a new instance of the Disk class.
/// </summary>
/// <param name="path">The path to the disk image</param>
public Disk(string path)
{
_file = new DiskImageFile(new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, null);
}
/// <summary>
/// Initializes a new instance of the Disk class.
/// </summary>
/// <param name="path">The path to the disk image</param>
/// <param name="access">The access requested to the disk</param>
public Disk(string path, FileAccess access)
{
FileShare share = (access == FileAccess.Read) ? FileShare.Read : FileShare.None;
_file = new DiskImageFile(new FileStream(path, FileMode.Open, access, share), Ownership.Dispose, null);
}
/// <summary>
/// Initializes a new instance of the Disk class.
/// </summary>
/// <param name="file">The contents of the disk.</param>
private Disk(DiskImageFile file)
{
_file = file;
}
/// <summary>
/// Gets the geometry of the disk.
/// </summary>
public override Geometry Geometry
{
get { return _file.Geometry; }
}
/// <summary>
/// Gets the type of disk represented by this object.
/// </summary>
public override VirtualDiskClass DiskClass
{
get { return _file.DiskType; }
}
/// <summary>
/// Gets the capacity of the disk (in bytes).
/// </summary>
public override long Capacity
{
get { return _file.Capacity; }
}
/// <summary>
/// Gets the content of the disk as a stream.
/// </summary>
/// <remarks>Note the returned stream is not guaranteed to be at any particular position. The actual position
/// will depend on the last partition table/file system activity, since all access to the disk contents pass
/// through a single stream instance. Set the stream position before accessing the stream.</remarks>
public override SparseStream Content
{
get { return _file.Content; }
}
/// <summary>
/// Gets the layers that make up the disk.
/// </summary>
public override IEnumerable<VirtualDiskLayer> Layers
{
get { yield return _file; }
}
/// <summary>
/// Gets information about the type of disk.
/// </summary>
/// <remarks>This property provides access to meta-data about the disk format, for example whether the
/// BIOS geometry is preserved in the disk file.</remarks>
public override VirtualDiskTypeInfo DiskTypeInfo
{
get { return DiskFactory.MakeDiskTypeInfo(); }
}
/// <summary>
/// Initializes a stream as an unformatted disk.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk</param>
/// <returns>An object that accesses the stream as a disk</returns>
public static Disk Initialize(Stream stream, Ownership ownsStream, long capacity)
{
return Initialize(stream, ownsStream, capacity, null);
}
/// <summary>
/// Initializes a stream as an unformatted disk.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk</param>
/// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default</param>
/// <returns>An object that accesses the stream as a disk</returns>
public static Disk Initialize(Stream stream, Ownership ownsStream, long capacity, Geometry geometry)
{
return new Disk(DiskImageFile.Initialize(stream, ownsStream, capacity, geometry));
}
/// <summary>
/// Initializes a stream as an unformatted floppy disk.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="type">The type of floppy disk image to create</param>
/// <returns>An object that accesses the stream as a disk</returns>
public static Disk Initialize(Stream stream, Ownership ownsStream, FloppyDiskType type)
{
return new Disk(DiskImageFile.Initialize(stream, ownsStream, type));
}
/// <summary>
/// Create a new differencing disk, possibly within an existing disk.
/// </summary>
/// <param name="fileSystem">The file system to create the disk on</param>
/// <param name="path">The path (or URI) for the disk to create</param>
/// <returns>The newly created disk</returns>
public override VirtualDisk CreateDifferencingDisk(DiscFileSystem fileSystem, string path)
{
throw new NotSupportedException("Differencing disks not supported for raw disks");
}
/// <summary>
/// Create a new differencing disk.
/// </summary>
/// <param name="path">The path (or URI) for the disk to create</param>
/// <returns>The newly created disk</returns>
public override VirtualDisk CreateDifferencingDisk(string path)
{
throw new NotSupportedException("Differencing disks not supported for raw disks");
}
/// <summary>
/// Disposes of underlying resources.
/// </summary>
/// <param name="disposing">Set to <c>true</c> if called within Dispose(),
/// else <c>false</c>.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_file != null)
{
_file.Dispose();
}
_file = null;
}
}
finally
{
base.Dispose(disposing);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
// ReSharper disable CommentTypo
static class Common
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
[Conditional("DEBUG")]
public static void Log(string format, params object[] args)
{
// Should this be trace?
Debug.WriteLine("=== COSTURA === " + string.Format(format, args));
}
static void CopyTo(Stream source, Stream destination)
{
var array = new byte[81920];
int count;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
destination.Write(array, 0, count);
}
}
static void CreateDirectory(string tempBasePath)
{
if (!Directory.Exists(tempBasePath))
{
Directory.CreateDirectory(tempBasePath);
}
}
static byte[] ReadStream(Stream stream)
{
var data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
return data;
}
public static string CalculateChecksum(string filename)
{
using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var bs = new BufferedStream(fs))
using (var sha1 = new SHA1CryptoServiceProvider())
{
var hash = sha1.ComputeHash(bs);
var formatted = new StringBuilder(2 * hash.Length);
foreach (var b in hash)
{
formatted.AppendFormat("{0:X2}", b);
}
return formatted.ToString();
}
}
public static Assembly ReadExistingAssembly(AssemblyName name)
{
var currentDomain = AppDomain.CurrentDomain;
var assemblies = currentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var currentName = assembly.GetName();
if (string.Equals(currentName.Name, name.Name, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(CultureToString(currentName.CultureInfo), CultureToString(name.CultureInfo), StringComparison.InvariantCultureIgnoreCase))
{
Log("Assembly '{0}' already loaded, returning existing assembly", assembly.FullName);
return assembly;
}
}
return null;
}
static string CultureToString(CultureInfo culture)
{
if (culture == null)
{
return "";
}
return culture.Name;
}
public static Assembly ReadFromDiskCache(string tempBasePath, AssemblyName requestedAssemblyName)
{
var name = requestedAssemblyName.Name.ToLowerInvariant();
if (requestedAssemblyName.CultureInfo != null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name))
{
name = $"{requestedAssemblyName.CultureInfo.Name}.{name}";
}
var bittyness = IntPtr.Size == 8 ? "64" : "32";
var assemblyTempFilePath = Path.Combine(tempBasePath, string.Concat(name, ".dll"));
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
assemblyTempFilePath = Path.ChangeExtension(assemblyTempFilePath, "exe");
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
assemblyTempFilePath = Path.Combine(Path.Combine(tempBasePath, bittyness), string.Concat(name, ".dll"));
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
assemblyTempFilePath = Path.ChangeExtension(assemblyTempFilePath, "exe");
if (File.Exists(assemblyTempFilePath))
{
return Assembly.LoadFile(assemblyTempFilePath);
}
return null;
}
public static Assembly ReadFromEmbeddedResources(Dictionary<string, string> assemblyNames, Dictionary<string, string> symbolNames, AssemblyName requestedAssemblyName)
{
var name = requestedAssemblyName.Name.ToLowerInvariant();
if (requestedAssemblyName.CultureInfo != null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name))
{
name = $"{requestedAssemblyName.CultureInfo.Name}.{name}";
}
byte[] assemblyData;
using (var assemblyStream = LoadStream(assemblyNames, name))
{
if (assemblyStream == null)
{
return null;
}
assemblyData = ReadStream(assemblyStream);
}
using (var pdbStream = LoadStream(symbolNames, name))
{
if (pdbStream != null)
{
var pdbData = ReadStream(pdbStream);
return Assembly.Load(assemblyData, pdbData);
}
}
return Assembly.Load(assemblyData);
}
static Stream LoadStream(Dictionary<string, string> resourceNames, string name)
{
if (resourceNames.TryGetValue(name, out var value))
{
return LoadStream(value);
}
return null;
}
static Stream LoadStream(string fullName)
{
var executingAssembly = Assembly.GetExecutingAssembly();
if (fullName.EndsWith(".compressed"))
{
using (var stream = executingAssembly.GetManifestResourceStream(fullName))
using (var compressStream = new DeflateStream(stream, CompressionMode.Decompress))
{
var memStream = new MemoryStream();
CopyTo(compressStream, memStream);
memStream.Position = 0;
return memStream;
}
}
return executingAssembly.GetManifestResourceStream(fullName);
}
public static void PreloadUnmanagedLibraries(string hash, string tempBasePath, List<string> libs, Dictionary<string, string> checksums)
{
// since tempBasePath is per user, the mutex can be per user
var mutexId = $"Costura{hash}";
using (var mutex = new Mutex(false, mutexId))
{
var hasHandle = false;
try
{
try
{
hasHandle = mutex.WaitOne(60000, false);
if (hasHandle == false)
{
throw new TimeoutException("Timeout waiting for exclusive access");
}
}
catch (AbandonedMutexException)
{
hasHandle = true;
}
var bittyness = IntPtr.Size == 8 ? "64" : "32";
CreateDirectory(Path.Combine(tempBasePath, bittyness));
InternalPreloadUnmanagedLibraries(tempBasePath, libs, checksums);
}
finally
{
if (hasHandle)
{
mutex.ReleaseMutex();
}
}
}
}
static void InternalPreloadUnmanagedLibraries(string tempBasePath, IList<string> libs, Dictionary<string, string> checksums)
{
string name;
foreach (var lib in libs)
{
name = ResourceNameToPath(lib);
var assemblyTempFilePath = Path.Combine(tempBasePath, name);
if (File.Exists(assemblyTempFilePath))
{
var checksum = CalculateChecksum(assemblyTempFilePath);
if (checksum != checksums[lib])
{
File.Delete(assemblyTempFilePath);
}
}
if (!File.Exists(assemblyTempFilePath))
{
using (var copyStream = LoadStream(lib))
using (var assemblyTempFile = File.OpenWrite(assemblyTempFilePath))
{
CopyTo(copyStream, assemblyTempFile);
}
}
}
SetDllDirectory(tempBasePath);
// prevent system-generated error message when LoadLibrary is called on a dll with an unmet dependency
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621(v=vs.85).aspx
//
// SEM_FAILCRITICALERRORS - The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
// SEM_NOGPFAULTERRORBOX - The system does not display the Windows Error Reporting dialog.
// SEM_NOOPENFILEERRORBOX - The OpenFile function does not display a message box when it fails to find a file. Instead, the error is returned to the caller.
//
// return value is the previous state of the error-mode bit flags.
// ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX;
uint errorModes = 32771;
var originalErrorMode = SetErrorMode(errorModes);
foreach (var lib in libs)
{
name = ResourceNameToPath(lib);
if (name.EndsWith(".dll"))
{
var assemblyTempFilePath = Path.Combine(tempBasePath, name);
LoadLibrary(assemblyTempFilePath);
}
}
// restore to previous state
SetErrorMode(originalErrorMode);
}
[DllImport("kernel32.dll")]
static extern uint SetErrorMode(uint uMode);
static string ResourceNameToPath(string lib)
{
var bittyness = IntPtr.Size == 8 ? "64" : "32";
var name = lib;
if (lib.StartsWith(string.Concat("costura", bittyness, ".")))
{
name = Path.Combine(bittyness, lib.Substring(10));
}
else if (lib.StartsWith("costura."))
{
name = lib.Substring(8);
}
if (name.EndsWith(".compressed"))
{
name = name.Substring(0, name.Length - 11);
}
return name;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Runtime.InteropServices; //used by GetFocus
namespace RE
{
internal partial class REMainForm : Form
{
public REMainForm()
{
InitializeComponent();
reLinkPanel1.LinkPointSignal += new LinkPointSignalEvent(reLinkPanel1_LinkPointSignal);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private bool ClassIsLibraryRegistry(Type m, object filterCriteria)
{
return m.IsSubclassOf(typeof(RELibraryRegistry));
}
private bool ClassIsBaseItem(Type m, object filterCriteria)
{
return m.IsSubclassOf(typeof(REBaseItem));
}
internal void AddToMenu(RELibraryMenuItem NewMenuItem, ToolStripMenuItem ParentMenuItem)
{
if (ParentMenuItem.DropDownItems.Count == 0)
ParentMenuItem.DropDownItems.Add(NewMenuItem);
else
{
int i = 0;
while (i < ParentMenuItem.DropDownItems.Count && (
!(ParentMenuItem.DropDownItems[i] is RELibraryMenuItem) ||
(NewMenuItem.Precedence > (ParentMenuItem.DropDownItems[i] as RELibraryMenuItem).Precedence))) i++;
if (i < ParentMenuItem.DropDownItems.Count)
ParentMenuItem.DropDownItems.Insert(i, NewMenuItem);
else
ParentMenuItem.DropDownItems.Add(NewMenuItem);
}
}
internal static void AddSeparators(ToolStripMenuItem MenuItem)
{
if (MenuItem.DropDownItems.Count != 0)
{
int i = 0;
int p = -1;
int q;
ToolStripItem m;
while (i < MenuItem.DropDownItems.Count)
{
m = MenuItem.DropDownItems[i];
if (m is RELibraryMenuItem)
{
q = p;
p = (m as RELibraryMenuItem).Precedence;
if (q != -1 && p / 100 > q / 100) MenuItem.DropDownItems.Insert(i++, new ToolStripSeparator());
}
i++;
}
}
}
private Hashtable KnownItemTypes = new Hashtable();
private bool PopupPointKnown;
private bool OutputDebugLog = false;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
RELibraryRegistry.ItemAdded += new RELibraryAddition(RELibraryRegistry_ItemAdded);
//TODO: other path(s) from setting?
DirectoryInfo LibraryPath = new DirectoryInfo(Path.GetDirectoryName(Application.ExecutablePath));
foreach (FileInfo f in LibraryPath.GetFiles("*.dll"))//something else than dll?
{
Assembly a = Assembly.LoadFile(f.FullName);//policy?
foreach (Module m in a.GetModules(false))
{
foreach (System.Type lregt in m.FindTypes(new TypeFilter(ClassIsLibraryRegistry), null))
{
RELibraryRegistry lreg = lregt.GetConstructor(System.Type.EmptyTypes).Invoke(new object[] { }) as RELibraryRegistry;
AddToMenu(lreg.Register(), addToolStripMenuItem);
AddToMenu(lreg.Register(), addToolStripMenuItem1);
}
foreach (System.Type rbt in m.FindTypes(new TypeFilter(ClassIsBaseItem), null))
{
foreach (REItemAttribute r in (rbt.GetCustomAttributes(typeof(REItemAttribute), true)))
{
if (KnownItemTypes.ContainsKey(r.SystemName))
throw new Exception(String.Format("Item type system names are required to be unique: \"{0}\"\r\n{1}\r\n{2}",
r.SystemName, (KnownItemTypes[r.SystemName] as REItemType).Module, f.FullName));
else
KnownItemTypes.Add(r.SystemName, new REItemType(r, rbt, f.FullName));
}
}
}
}
AddSeparators(addToolStripMenuItem);
AddSeparators(addToolStripMenuItem1);
//command line parameters
string fn = "";
string cx;
string[] cl = System.Environment.GetCommandLineArgs();
for (int i = 1; i < cl.Length; i++)
{
cx = cl[i].ToLower();
if (cx == "/debug") OutputDebugLog = true;
else
//TODO: auto start option
//TODO: close when done option
if (fn == "" && File.Exists(cl[i])) fn = cl[i];
//TODO: concatenate-load others
//TODO: message unknown parameters?
}
if (fn != "")
{
try
{
LoadFile(fn);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), "Load File", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
void RELibraryRegistry_ItemAdded(REBaseItem Item)
{
reLinkPanel1.AddItem(Item, !PopupPointKnown);
}
private void REMainForm_KeyDown(object sender, KeyEventArgs e)
{
KeyboardFlags.CtrlPressed = e.Control;
//KeyboardFlags.AltPressed = e.Alt;
}
private void REMainForm_KeyUp(object sender, KeyEventArgs e)
{
KeyboardFlags.CtrlPressed = e.Control;
//KeyboardFlags.AltPressed = e.Alt;
}
private void REMainForm_Deactivate(object sender, EventArgs e)
{
KeyboardFlags.CtrlPressed = false;
}
private void addToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
PopupPointKnown = false;
}
private void addToolStripMenuItem1_DropDownOpening(object sender, EventArgs e)
{
PopupPointKnown = true;
}
#region Loading and Saving
private string filename = "";
public string FileName
{
get
{
return filename;
}
set
{
filename = value;
if (filename == "")
Text = "Regular Expression";
else
Text = "RE - " + filename;
}
}
private bool CheckChanges()
{
bool b = reLinkPanel1.Modified;
if (!b)
foreach (REBaseItem i in reLinkPanel1.Controls)
if (i.Modified)
{
b = true;
break;
}
if (b && reLinkPanel1.Controls.Count == 0) b = false;
if (b)
{
switch (MessageBox.Show(this, "Do you want to save changes?", "Regular Expression",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
{
case DialogResult.Yes:
return SaveFile(false);
case DialogResult.No:
return true;
//case DialogResult.Cancel:
default:
return false;
}
}
else
return true;
}
private bool SaveFile(bool ForceAskFileName)
{
bool filenameok = true;
if (FileName == "" || ForceAskFileName)
{
saveFileDialog1.FileName = FileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
FileName = saveFileDialog1.FileName;
else
filenameok = false;
}
if (filenameok)
{
Cursor = Cursors.WaitCursor;
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.PreserveWhitespace = true;
xdoc.LoadXml("<reData version=\"2.0\" />");
XmlElement xroot = xdoc.DocumentElement;
xroot.SetAttribute("scrollX", reLinkPanel1.HorizontalScroll.Value.ToString());
xroot.SetAttribute("scrollY", reLinkPanel1.VerticalScroll.Value.ToString());
//TODO: bounds/maximized?
reLinkPanel1.SaveItems(xroot, false);
XmlTextWriter xwrt = new XmlTextWriter(FileName, Encoding.UTF8);
try
{
xdoc.Save(xwrt);
reLinkPanel1.Modified = false;
toolStripStatusLabel3.Text = "File saved: " + filename;
}
finally
{
xwrt.Close();
}
}
finally
{
Cursor = Cursors.Default;
}
}
return filenameok;
}
private void LoadFile(string LoadFileName)
{
FileName = LoadFileName;
Cursor = Cursors.WaitCursor;
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.PreserveWhitespace = true;
xdoc.Load(FileName);
XmlElement xroot = xdoc.DocumentElement;
//TODO: check version?
//TODO: bounds/maximized?
Point scroll = new Point(0, 0);
try
{
scroll = new Point(
Int32.Parse(xroot.GetAttribute("scrollX")),
Int32.Parse(xroot.GetAttribute("scrollY")));
}
catch (FormatException)
{
//silent, use defaults
}
reLinkPanel1.LoadItems(xroot, KnownItemTypes, false, new Point(0, 0));
if (scroll.X < reLinkPanel1.HorizontalScroll.Minimum) scroll.X = reLinkPanel1.HorizontalScroll.Minimum;
if (scroll.Y < reLinkPanel1.VerticalScroll.Minimum) scroll.Y = reLinkPanel1.VerticalScroll.Minimum;
if (scroll.X > reLinkPanel1.HorizontalScroll.Maximum) scroll.X = reLinkPanel1.HorizontalScroll.Maximum;
if (scroll.Y > reLinkPanel1.VerticalScroll.Maximum) scroll.Y = reLinkPanel1.VerticalScroll.Maximum;
reLinkPanel1.HorizontalScroll.Value = scroll.X;
reLinkPanel1.VerticalScroll.Value = scroll.Y;
}
finally
{
Cursor = Cursors.Default;
}
toolStripStatusLabel3.Text = "File loaded: " + FileName;
reLinkPanel1.Modified = false;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CheckChanges())
{
if (filename == "" && reLinkPanel1.Controls.Count == 0)
MessageBox.Show(this, "A new expression is already started, use Add to add items.", "New", MessageBoxButtons.OK, MessageBoxIcon.Information);
FileName = "";
reLinkPanel1.Visible = false;
try
{
reLinkPanel1.ClearAllItems();
}
finally
{
reLinkPanel1.Visible = true;
reLinkPanel1.Modified = false;
}
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CheckChanges())
{
openFileDialog1.FileName = FileName;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
LoadFile(openFileDialog1.FileName);
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFile(false);
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFile(true);
}
#endregion
#region Running
private RunState RunState = RunState.NotRunning;
private bool CancelPressed = false;
private bool CloseRequested = false;
private void runToolStripMenuItem_Click(object sender, EventArgs e)
{
if (RunState == RunState.NotRunning)
Run();
else
CancelPressed = true;
}
private List<RunQueueSlot> RunQueue;
private RunQueueEntry NextRunQueueEntry;
private bool FireEmitCalled;
private RELinkPoint SuspendCalled;
private StreamWriter DebugLog = null;
private static string DebugDisplay(object Data)
{
if (Data == null)
return "(null)";
else
{
string x = Data.ToString();
int y = x.IndexOf("\r\n", 0, Math.Min(x.Length, 128));
if (x.Length > 128 || y != -1)
return x.Substring(0, y == -1 ? 128 : y) + "(" + x.Length.ToString() + ")";
else
return x;
}
}
void reLinkPanel1_LinkPointSignal(RELinkPoint LinkPoint, RELinkPointSignalType Signal, object Data, bool MoreToCome)
{
if (DebugLog != null) DebugLog.WriteLine("{0}({1}{2}){3}", Signal, LinkPoint, MoreToCome ? "*" : "", DebugDisplay(Data));
switch (RunState)
{
case RunState.Starting:
switch (Signal)
{
case RELinkPointSignalType.Sending:
if (Data is RELinkPoint)
{
//another RELinkPoint is emitted to get the sequence end signalled
throw new EReException("Emitting LinkPoints on when starting is not supported.");
}
else
{
if (LinkPoint.IsConnected)
RunQueue.Add(new RunQueueSlot(
new RunQueueEntry(LinkPoint.ConnectedTo, Data,
MoreToCome ? new RunQueueEntry(LinkPoint, null, null) : null), null));
}
break;
case RELinkPointSignalType.Suspending:
//assert Data==null
if (LinkPoint.IsConnected)
RunQueue.Add(new RunQueueSlot(
new RunQueueEntry(LinkPoint, null, null), LinkPoint));
break;
case RELinkPointSignalType.Resuming:
throw new EReException("LinkPoint can't resume when starting.");
}
break;
case RunState.Running:
switch (Signal)
{
case RELinkPointSignalType.Sending:
if (Data is RELinkPoint)
{
//another RELinkPoint is emitted to get the sequence end signalled
if (NextRunQueueEntry == null)
//throw new EReException("No sequence started to signal end for.");//?
NextRunQueueEntry = new RunQueueEntry(Data as RELinkPoint, null, null);
else
NextRunQueueEntry.PostReportBack(Data as RELinkPoint, null);
}
else
{
if (FireEmitCalled)
throw new EReException("Don't call Emit more than once when processing a Signal.");
if (SuspendCalled != null)
throw new EReException("Can't Emit after Suspend.");
FireEmitCalled = true;
NextRunQueueEntry = new RunQueueEntry(LinkPoint.ConnectedTo, Data,
MoreToCome ? new RunQueueEntry(LinkPoint, null, NextRunQueueEntry) : NextRunQueueEntry);
}
break;
case RELinkPointSignalType.Suspending:
//assert Data==null
if (SuspendCalled != null)
throw new EReException("Don't call Suspend more then once when processing a Signal.");
foreach (RunQueueSlot rqs1 in RunQueue)
if (rqs1.Reserved == LinkPoint)
throw new EReException("LinkPoint is trying to suspend but was suspended already.");
SuspendCalled = LinkPoint;
break;
case RELinkPointSignalType.Resuming:
if (Data is RELinkPoint)
throw new EReException("Can't resume and send a RELinkPoint.");
if (SuspendCalled == LinkPoint)
{
SuspendCalled = null;
NextRunQueueEntry = new RunQueueEntry(LinkPoint.ConnectedTo, Data,
MoreToCome ? new RunQueueEntry(LinkPoint, null, NextRunQueueEntry) : NextRunQueueEntry);
}
else
{
RunQueueSlot rqs = null;
foreach (RunQueueSlot rqs1 in RunQueue)
if (rqs1.Reserved == LinkPoint)
{
rqs = rqs1;
break;
}
if (rqs == null)
throw new EReException("LinkPoint is trying to resume but wasn't suspended.");
rqs.Reserved = null;
if (MoreToCome && LinkPoint.IsConnected)
rqs.Entry = new RunQueueEntry(LinkPoint.ConnectedTo, Data,
new RunQueueEntry(LinkPoint, null, rqs.Entry));
else
if (rqs.Entry == null)
rqs.Entry = new RunQueueEntry(LinkPoint, null, null);
}
break;
}
break;
default:
throw new EReException("LinkPoint can't change state when not running.");
}
}
const int StateUpdateMS = 500;
private void Run()
{
//TODO: thread (or multiple threads?)
int startTC = Environment.TickCount;
int stateTC = startTC + StateUpdateMS;
int nowTC;
int qcount = 0;
RunQueue = new List<RunQueueSlot>();
CancelPressed = false;
string FailMessage = "";
if (OutputDebugLog)
{
DebugLog = new StreamWriter((filename == "" ? "debug" : filename) + ".log", false, Encoding.UTF8);
DebugLog.AutoFlush = true;//?
}
try
{
RunState = RunState.Starting;
toolStripStatusLabel3.Text = "Starting...";
if (DebugLog != null) DebugLog.WriteLine("RunState.Starting");
runToolStripMenuItem.Text = "Abort";
runToolStripMenuItem1.Text = "Abort";
foreach (REBaseItem item in reLinkPanel1.Controls) item.Start();
RunState = RunState.Running;
toolStripStatusLabel3.Text = "Running...";
if (DebugLog != null) DebugLog.WriteLine("RunState.Running");
int rindex = 0;
bool rskipactive = false;
int rlastactive = 0;
int rdone = RunQueue.Count;
while (rdone != 0 && !CancelPressed)
{
RunQueueSlot rqs = RunQueue[rindex];
if (rqs.Reserved == null && rqs.Entry != null)
{
qcount++;
RunQueueEntry rqe = rqs.Entry;
NextRunQueueEntry = rqs.Entry.ReportBack;
//Fire() signals linkpoint, action there may emit on another linkpoint, setting NextRunQueueEntry
FireEmitCalled = false;
SuspendCalled = null;
if (DebugLog != null) DebugLog.WriteLine("{0}:Fire[{1}/{2}]{3}", qcount, rindex, RunQueue.Count, rqe.DebugDisplay);
rqe.Fire();
rqs.Entry = NextRunQueueEntry;
if (SuspendCalled != null) rqs.Reserved = SuspendCalled;
if (NextRunQueueEntry == null && SuspendCalled == null) rdone--;
rlastactive = rindex;
rskipactive = false;
}
rindex++;
if (rindex >= RunQueue.Count) rindex = 0;
if (rindex == rlastactive)
if (rskipactive)
{
StringBuilder sb = new StringBuilder("Only suspended LinkPoints left, some item did not resume properly.");
foreach (RunQueueSlot rqx in RunQueue)
if (rqx.Reserved != null)
sb.Append(String.Format("\r\n{0}", rqx.Reserved.ToString()));
throw new EReException(sb.ToString());
}
else
rskipactive = true;
nowTC = Environment.TickCount;
if (nowTC >= stateTC)
{
stateTC = nowTC + StateUpdateMS;
toolStripStatusLabel1.Text = String.Format("{0} passes", qcount);
toolStripStatusLabel2.Text = String.Format("{0:F3} seconds", (nowTC - startTC) / 1000.0);
Application.DoEvents();
}
}
}
catch (Exception ex)
{
//
if (DebugLog != null) DebugLog.WriteLine(ex);
FailMessage = ex.ToString();
}
RunState = RunState.Stopping;
toolStripStatusLabel3.Text = "Stopping...";
if (DebugLog != null)
{
DebugLog.WriteLine("RunState.Stopping");
int rindex = 0;
foreach (RunQueueSlot rqs in RunQueue)
if (rqs.Entry != null && rqs.Reserved != null)
{
DebugLog.WriteLine("[{0}/{1}]{2}", rindex, RunQueue.Count, rqs.Entry.DebugDisplay);
DebugLog.WriteLine(rqs.Reserved.ToString());
rindex++;
}
}
foreach (REBaseItem item in reLinkPanel1.Controls)
{
try
{
item.Stop();
}
catch
{
//ignore!
}
}
//clean-up
NextRunQueueEntry = null;
RunState = RunState.NotRunning;
if (DebugLog != null)
{
DebugLog.WriteLine("RunState.NotRunning");
DebugLog.Close();
DebugLog = null;
}
RunQueue = null;
toolStripStatusLabel1.Text = String.Format("{0} passes", qcount);
toolStripStatusLabel2.Text = String.Format("{0:F3} seconds", (Environment.TickCount - startTC) / 1000.0);
if (CancelPressed)
toolStripStatusLabel3.Text = "Aborted by user.";
else
if (FailMessage == "")
toolStripStatusLabel3.Text = "Done.";
else
{
toolStripStatusLabel3.Text = "Failed.";
MessageBox.Show(this, FailMessage, "Run", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
runToolStripMenuItem.Text = "Run";
runToolStripMenuItem1.Text = "Run";
if (CloseRequested) Close();
}
internal class RunQueueEntry
{
private RELinkPoint _linkpoint;
private object _data;
private RunQueueEntry _reportBack;
public RunQueueEntry(RELinkPoint LinkPoint, object Data, RunQueueEntry ReportBack)
{
_data = Data;
_linkpoint = LinkPoint;
_reportBack = ReportBack;
}
public void Fire()
{
_linkpoint.FireSignal(_data);
}
public void AddReportBack(RELinkPoint LinkPoint, object Data)
{
_reportBack = new RunQueueEntry(LinkPoint, Data, _reportBack);
}
public void PostReportBack(RELinkPoint LinkPoint, object Data)
{
RunQueueEntry e = this;
while (e._reportBack != null) e = e._reportBack;
e._reportBack = new RunQueueEntry(LinkPoint, Data, null);
}
public RunQueueEntry ReportBack
{
get { return _reportBack; }
}
internal RELinkPoint LinkPoint
{
get { return _linkpoint; }
}
internal string DebugDisplay
{
get { return String.Format("({0}{2}){1}", _linkpoint, DebugDisplay(_data), _reportBack == null ? "" : "*"); }
}
}
internal class RunQueueSlot
{
private RunQueueEntry _entry;
private RELinkPoint _reserved;
public RunQueueSlot(RunQueueEntry Entry, RELinkPoint Reserved)
{
_entry = Entry;
_reserved = Reserved;
}
internal RunQueueEntry Entry
{
get { return _entry; }
set { _entry = value; }
}
internal RELinkPoint Reserved
{
get { return _reserved; }
set { _reserved = value; }
}
}
#endregion
private void REMainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (RunState != RunState.NotRunning)
{
if (MessageBox.Show(this, "Expression is still running, do you want to stop it?", "Close",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
CancelPressed = true;
CloseRequested = true;
}
e.Cancel = true;
}
else
if (!CheckChanges()) e.Cancel = true;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
internal static extern IntPtr GetFocus();
internal Control GetFocusControl()
{
Control focusControl = null;
IntPtr focusHandle = GetFocus();
if (focusHandle != IntPtr.Zero)
// returns null if handle is not to a .NET control
focusControl = Control.FromHandle(focusHandle);
return focusControl;
}
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
Control c = GetFocusControl();
if (c is TextBoxBase)
(c as TextBoxBase).SelectAll();
else
reLinkPanel1.SelectAllItems();
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO: Del shortcut and if GetFocusControl is TextBoxBase
reLinkPanel1.DeleteSelectedItems();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
Control c = GetFocusControl();
if (c is TextBoxBase)
(c as TextBoxBase).Cut();
else
{
int x = reLinkPanel1.SaveClipboard(true);
toolStripStatusLabel3.Text = String.Format("{0} items cut to clipboard", x);
}
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Control c = GetFocusControl();
if (c is TextBoxBase)
(c as TextBoxBase).Copy();
else
{
int x = reLinkPanel1.SaveClipboard(false);
toolStripStatusLabel3.Text = String.Format("{0} items copied to clipboard", x);
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
Control c = GetFocusControl();
if (c is TextBoxBase)
(c as TextBoxBase).Paste();
else
{
int x = reLinkPanel1.LoadClipboard(true, KnownItemTypes);
toolStripStatusLabel3.Text = String.Format("{0} items pasted from clipboard", x);
}
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
Control c = GetFocusControl();
if (c is TextBoxBase)
(c as TextBoxBase).Undo();
//TODO: else reLinkPanel1.Undo();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
Control c = GetFocusControl();
if (c is TextBoxBase)
(c as TextBoxBase).Undo();//TextBoxBase doesn't have Redo()?
//TODO: else reLinkPanel1.Redo();
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
pasteToolStripMenuItem2.Visible = reLinkPanel1.CanLoadClipboard();
}
private void pasteToolStripMenuItem2_Click(object sender, EventArgs e)
{
int x = reLinkPanel1.LoadClipboard(false, KnownItemTypes);
toolStripStatusLabel3.Text = String.Format("{0} items pasted from clipboard", x);
}
private void pasteFromToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Cursor = Cursors.WaitCursor;
try
{
string filename1 = openFileDialog1.FileName;
XmlDocument xdoc = new XmlDocument();
xdoc.PreserveWhitespace = true;
xdoc.Load(filename1);
XmlElement xroot = xdoc.DocumentElement;
//TODO: check version?
int i = reLinkPanel1.LoadItems(xroot, KnownItemTypes, true, new Point(0, 0));
toolStripStatusLabel3.Text = String.Format("Pasted {0} items from: {1}", i, filename1);
}
finally
{
Cursor = Cursors.Default;
}
}
}
private void copyToToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Cursor = Cursors.WaitCursor;
try
{
string filename1 = saveFileDialog1.FileName;
XmlDocument xdoc = new XmlDocument();
xdoc.PreserveWhitespace = true;
xdoc.LoadXml("<reData version=\"2.0\" />");
XmlElement xroot = xdoc.DocumentElement;
xroot.SetAttribute("scrollX", reLinkPanel1.HorizontalScroll.Value.ToString());
xroot.SetAttribute("scrollY", reLinkPanel1.VerticalScroll.Value.ToString());
//TODO: bounds/maximized?
int i = reLinkPanel1.SaveItems(xroot, true);
XmlTextWriter xwrt = new XmlTextWriter(filename1, Encoding.UTF8);
try
{
xdoc.Save(xwrt);
toolStripStatusLabel3.Text = String.Format("Copied {0} items to: {1}", i, filename1);
}
finally
{
xwrt.Close();
}
}
finally
{
Cursor = Cursors.Default;
}
}
}
private void REMainForm_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void REMainForm_DragDrop(object sender, DragEventArgs e)
{
if (CheckChanges())
LoadFile(((string[])e.Data.GetData(DataFormats.FileDrop))[0]);
}
}
internal class KeyboardFlags
{
static public bool CtrlPressed = false;
}
internal enum RunState
{
NotRunning,
Starting,
Running,
Stopping
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium
{
[TestFixture]
public class AlertsTest : DriverTestFixture
{
[Test]
public void ShouldBeAbleToOverrideTheWindowAlertMethod()
{
driver.Url = CreateAlertPage("cheese");
((IJavaScriptExecutor)driver).ExecuteScript(
"window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }");
driver.FindElement(By.Id("alert")).Click();
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertManually()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldThrowArgumentNullExceptionWhenKeysNull()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
Assert.That(() => alert.SendKeys(null), Throws.ArgumentNullException);
}
finally
{
alert.Accept();
}
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertWithNoTextManually()
{
driver.Url = CreateAlertPage("");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Edge, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.IE, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Firefox, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
[IgnoreBrowser(Browser.Safari, "This is the correct behavior, for the SwitchTo call to throw if it happens before the setTimeout call occurs in the browser and the alert is displayed.")]
public void ShouldGetTextOfAlertOpenedInSetTimeout()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithScripts(
"function slowAlert() { window.setTimeout(function(){ alert('Slow'); }, 200); }")
.WithBody(
"<a href='#' id='slow-alert' onclick='slowAlert();'>click me</a>"));
driver.FindElement(By.Id("slow-alert")).Click();
// DO NOT WAIT OR SLEEP HERE.
// This is a regression test for a bug where only the first switchTo call would throw,
// and only if it happens before the alert actually loads.
IAlert alert = driver.SwitchTo().Alert();
try
{
Assert.AreEqual("Slow", alert.Text);
}
finally
{
alert.Accept();
}
}
[Test]
public void ShouldAllowUsersToDismissAnAlertManually()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldAllowAUserToAcceptAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Prompt", driver.Title);
}
[Test]
public void ShouldAllowAUserToDismissAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Prompt", driver.Title);
}
[Test]
public void ShouldAllowAUserToSetTheValueOfAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.SendKeys("cheese");
alert.Accept();
string result = driver.FindElement(By.Id("text")).Text;
Assert.AreEqual("cheese", result);
}
[Test]
public void SettingTheValueOfAnAlertThrows()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
alert.SendKeys("cheese");
Assert.Fail("Expected exception");
}
catch (ElementNotInteractableException)
{
}
finally
{
alert.Accept();
}
}
[Test]
public void ShouldAllowTheUserToGetTheTextOfAnAlert()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("cheese", value);
}
[Test]
public void ShouldAllowTheUserToGetTheTextOfAPrompt()
{
driver.Url = CreatePromptPage(null);
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("Enter something", value);
}
[Test]
public void AlertShouldNotAllowAdditionalCommandsIfDimissed()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
string text;
Assert.That(() => text = alert.Text, Throws.InstanceOf<NoAlertPresentException>());
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertInAFrame()
{
string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody(String.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe)));
driver.SwitchTo().Frame("iframeWithAlert");
driver.FindElement(By.Id("alertInFrame")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void ShouldAllowUsersToAcceptAnAlertInANestedFrame()
{
string iframe = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody("<a href='#' id='alertInFrame' onclick='alert(\"framed cheese\");'>click me</a>"));
string iframe2 = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<iframe src='{0}' name='iframeWithAlert'></iframe>", iframe)));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody(string.Format("<iframe src='{0}' name='iframeWithIframe'></iframe>", iframe2)));
driver.SwitchTo().Frame("iframeWithIframe").SwitchTo().Frame("iframeWithAlert");
driver.FindElement(By.Id("alertInFrame")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
// If we can perform any action, we're good to go
Assert.AreEqual("Testing Alerts", driver.Title);
}
[Test]
public void SwitchingToMissingAlertThrows()
{
driver.Url = CreateAlertPage("cheese");
Assert.That(() => AlertToBePresent(), Throws.InstanceOf<NoAlertPresentException>());
}
[Test]
public void SwitchingToMissingAlertInAClosedWindowThrows()
{
string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage());
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(String.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", blank)));
string mainWindow = driver.CurrentWindowHandle;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
WaitFor(WindowHandleCountToBe(2), "Window count was not 2");
WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'");
driver.Close();
WaitFor(WindowHandleCountToBe(1), "Window count was not 1");
try
{
AlertToBePresent().Accept();
Assert.Fail("Expected exception");
}
catch (NoSuchWindowException)
{
// Expected
}
}
finally
{
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'");
}
}
[Test]
public void PromptShouldUseDefaultValueIfNoKeysSent()
{
driver.Url = CreatePromptPage("This is a default value");
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
IWebElement element = driver.FindElement(By.Id("text"));
WaitFor(ElementTextToEqual(element, "This is a default value"), "Element text was not 'This is a default value'");
Assert.AreEqual("This is a default value", element.Text);
}
[Test]
public void PromptShouldHaveNullValueIfDismissed()
{
driver.Url = CreatePromptPage("This is a default value");
driver.FindElement(By.Id("prompt")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
IWebElement element = driver.FindElement(By.Id("text"));
WaitFor(ElementTextToEqual(element, "null"), "Element text was not 'null'");
Assert.AreEqual("null", element.Text);
}
[Test]
[IgnoreBrowser(Browser.Remote)]
public void HandlesTwoAlertsFromOneInteraction()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithScripts(
"function setInnerText(id, value) {",
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
"}",
"function displayTwoPrompts() {",
" setInnerText('text1', prompt('First'));",
" setInnerText('text2', prompt('Second'));",
"}")
.WithBody(
"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",
"<div id='text1'></div>",
"<div id='text2'></div>"));
driver.FindElement(By.Id("double-prompt")).Click();
IAlert alert1 = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert1.SendKeys("brie");
alert1.Accept();
IAlert alert2 = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert2.SendKeys("cheddar");
alert2.Accept();
IWebElement element1 = driver.FindElement(By.Id("text1"));
WaitFor(ElementTextToEqual(element1, "brie"), "Element text was not 'brie'");
Assert.AreEqual("brie", element1.Text);
IWebElement element2 = driver.FindElement(By.Id("text2"));
WaitFor(ElementTextToEqual(element2, "cheddar"), "Element text was not 'cheddar'");
Assert.AreEqual("cheddar", element2.Text);
}
[Test]
public void ShouldHandleAlertOnPageLoad()
{
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<a id='open-page-with-onload-alert' href='{0}'>open new page</a>", pageWithOnLoad)));
driver.FindElement(By.Id("open-page-with-onload-alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onload", value);
IWebElement element = driver.FindElement(By.TagName("p"));
WaitFor(ElementTextToEqual(element, "Page with onload event handler"), "Element text was not 'Page with onload event handler'");
}
[Test]
public void ShouldHandleAlertOnPageLoadUsingGet()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onload", value);
WaitFor(ElementTextToEqual(driver.FindElement(By.TagName("p")), "Page with onload event handler"), "Could not find element with text 'Page with onload event handler'");
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Test with onLoad alert hangs Chrome.")]
[IgnoreBrowser(Browser.Safari, "Safari driver does not allow commands in any window when an alert is active")]
public void ShouldNotHandleAlertInAnotherWindow()
{
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithBody("<p>Page with onload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnLoad)));
string mainWindow = driver.CurrentWindowHandle;
string onloadWindow = null;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
List<String> allWindows = new List<string>(driver.WindowHandles);
allWindows.Remove(mainWindow);
Assert.AreEqual(1, allWindows.Count);
onloadWindow = allWindows[0];
try
{
IWebElement el = driver.FindElement(By.Id("open-new-window"));
WaitFor<IAlert>(AlertToBePresent, TimeSpan.FromSeconds(5), "No alert found");
Assert.Fail("Expected exception");
}
catch (WebDriverException)
{
// An operation timed out exception is expected,
// since we're using WaitFor<T>.
}
}
finally
{
driver.SwitchTo().Window(onloadWindow);
WaitFor<IAlert>(AlertToBePresent, "No alert found").Dismiss();
driver.Close();
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text 'open new window'");
}
}
[Test]
[IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Chrome, "Chrome does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Edge, "Edge does not trigger alerts on unload.")]
public void ShouldHandleAlertOnPageUnload()
{
string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnBeforeUnload("return \"onunload\";")
.WithBody("<p>Page with onbeforeunload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<a id='open-page-with-onunload-alert' href='{0}'>open new page</a>", pageWithOnBeforeUnload)));
IWebElement element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'");
element.Click();
driver.Navigate().Back();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onunload", value);
element = WaitFor<IWebElement>(ElementToBePresent(By.Id("open-page-with-onunload-alert")), "Could not find element with id 'open-page-with-onunload-alert'");
WaitFor(ElementTextToEqual(element, "open new page"), "Element text was not 'open new page'");
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome does not implicitly handle onBeforeUnload alert")]
[IgnoreBrowser(Browser.Safari, "Safari driver does not implicitly (or otherwise) handle onBeforeUnload alerts")]
[IgnoreBrowser(Browser.Edge, "Edge driver does not implicitly (or otherwise) handle onBeforeUnload alerts")]
public void ShouldImplicitlyHandleAlertOnPageBeforeUnload()
{
string blank = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage().WithTitle("Success"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Page with onbeforeunload handler")
.WithBody(String.Format(
"<a id='link' href='{0}'>Click here to navigate to another page.</a>", blank)));
SetSimpleOnBeforeUnload("onbeforeunload message");
driver.FindElement(By.Id("link")).Click();
WaitFor(() => driver.Title == "Success", "Title was not 'Success'");
}
[Test]
[IgnoreBrowser(Browser.IE, "Test as written does not trigger alert; also onbeforeunload alert on close will hang browser")]
[IgnoreBrowser(Browser.Chrome, "Test as written does not trigger alert")]
[IgnoreBrowser(Browser.Firefox, "After version 27, Firefox does not trigger alerts on unload.")]
[IgnoreBrowser(Browser.Edge, "Edge does not trigger alerts on unload.")]
public void ShouldHandleAlertOnWindowClose()
{
string pageWithOnBeforeUnload = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnBeforeUnload("javascript:alert(\"onbeforeunload\")")
.WithBody("<p>Page with onbeforeunload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format(
"<a id='open-new-window' href='{0}' target='newwindow'>open new window</a>", pageWithOnBeforeUnload)));
string mainWindow = driver.CurrentWindowHandle;
try
{
driver.FindElement(By.Id("open-new-window")).Click();
WaitFor(WindowHandleCountToBe(2), "Window count was not 2");
WaitFor(WindowWithName("newwindow"), "Could not find window with name 'newwindow'");
driver.Close();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
string value = alert.Text;
alert.Accept();
Assert.AreEqual("onbeforeunload", value);
}
finally
{
driver.SwitchTo().Window(mainWindow);
WaitFor(ElementTextToEqual(driver.FindElement(By.Id("open-new-window")), "open new window"), "Could not find element with text equal to 'open new window'");
}
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Driver chooses not to return text from unhandled alert")]
[IgnoreBrowser(Browser.Edge, "Driver chooses not to return text from unhandled alert")]
[IgnoreBrowser(Browser.Firefox, "Driver chooses not to return text from unhandled alert")]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Safari, "Safari driver does not do unhandled alerts")]
public void IncludesAlertTextInUnhandledAlertException()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
string title = driver.Title;
Assert.Fail("Expected UnhandledAlertException");
}
catch (UnhandledAlertException e)
{
Assert.AreEqual("cheese", e.AlertText);
}
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Opera)]
public void CanQuitWhenAnAlertIsPresent()
{
driver.Url = CreateAlertPage("cheese");
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
EnvironmentManager.Instance.CloseCurrentDriver();
}
[Test]
[IgnoreBrowser(Browser.Safari, "Safari driver cannot handle alert thrown via JavaScript")]
public void ShouldHandleAlertOnFormSubmit()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts").
WithBody("<form id='theForm' action='javascript:alert(\"Tasty cheese\");'>",
"<input id='unused' type='submit' value='Submit'>",
"</form>"));
IWebElement element = driver.FindElement(By.Id("theForm"));
element.Submit();
IAlert alert = driver.SwitchTo().Alert();
string text = alert.Text;
alert.Accept();
Assert.AreEqual("Tasty cheese", text);
Assert.AreEqual("Testing Alerts", driver.Title);
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
[IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")]
public void ShouldHandleAlertOnPageBeforeUnload()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html");
IWebElement element = driver.FindElement(By.Id("navigate"));
element.Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
Assert.That(driver.Url, Does.Contain("pageWithOnBeforeUnloadMessage.html"));
// Can't move forward or even quit the driver
// until the alert is accepted.
element.Click();
alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Accept();
WaitFor(() => { return driver.Url.Contains(alertsPage); }, "Browser URL does not contain " + alertsPage);
Assert.That(driver.Url, Does.Contain(alertsPage));
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Safari, "onBeforeUnload dialogs hang Safari")]
public void ShouldHandleAlertOnPageBeforeUnloadAlertAtQuit()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("pageWithOnBeforeUnloadMessage.html");
IWebElement element = driver.FindElement(By.Id("navigate"));
element.Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
// CloserCurrentDriver() contains a call to driver.Quit()
EnvironmentManager.Instance.CloseCurrentDriver();
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.IE)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldBeAbleToHandleAuthenticationDialog()
{
driver.Url = authenticationPage;
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.SetAuthenticationCredentials("test", "test");
alert.Accept();
Assert.That(driver.FindElement(By.TagName("h1")).Text, Does.Contain("authorized"));
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.IE)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldBeAbleToDismissAuthenticationDialog()
{
driver.Url = authenticationPage;
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
}
// Disabling test for all browsers. Authentication API is not supported by any driver yet.
// [Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.Edge)]
[IgnoreBrowser(Browser.Firefox)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.Remote)]
[IgnoreBrowser(Browser.Safari)]
public void ShouldThrowAuthenticatingOnStandardAlert()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("alert")).Click();
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
alert.SetAuthenticationCredentials("test", "test");
Assert.Fail("Should not be able to Authenticate");
}
catch (UnhandledAlertException)
{
// this is an expected exception
}
// but the next call should be good.
alert.Dismiss();
}
private IAlert AlertToBePresent()
{
return driver.SwitchTo().Alert();
}
private string CreateAlertPage(string alertText)
{
return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Alerts")
.WithBody("<a href='#' id='alert' onclick='alert(\"" + alertText + "\");'>click me</a>"));
}
private string CreatePromptPage(string defaultText)
{
return EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithTitle("Testing Prompt")
.WithScripts(
"function setInnerText(id, value) {",
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
"}",
defaultText == null
? "function displayPrompt() { setInnerText('text', prompt('Enter something')); }"
: "function displayPrompt() { setInnerText('text', prompt('Enter something', '" + defaultText + "')); }")
.WithBody(
"<a href='#' id='prompt' onclick='displayPrompt();'>click me</a>",
"<div id='text'>acceptor</div>"));
}
private void SetSimpleOnBeforeUnload(string returnText)
{
((IJavaScriptExecutor)driver).ExecuteScript(
"var returnText = arguments[0]; window.onbeforeunload = function() { return returnText; }",
returnText);
}
private Func<IWebElement> ElementToBePresent(By locator)
{
return () =>
{
IWebElement foundElement = null;
try
{
foundElement = driver.FindElement(By.Id("open-page-with-onunload-alert"));
}
catch (NoSuchElementException)
{
}
return foundElement;
};
}
private Func<bool> ElementTextToEqual(IWebElement element, string text)
{
return () =>
{
return element.Text == text;
};
}
private Func<bool> WindowWithName(string name)
{
return () =>
{
try
{
driver.SwitchTo().Window(name);
return true;
}
catch (NoSuchWindowException)
{
}
return false;
};
}
private Func<bool> WindowHandleCountToBe(int count)
{
return () =>
{
return driver.WindowHandles.Count == count;
};
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary writer implementation.
/// </summary>
internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Stream. */
private readonly IBinaryStream _stream;
/** Builder (used only during build). */
private BinaryObjectBuilder _builder;
/** Handles. */
private BinaryHandleDictionary<object, long> _hnds;
/** Metadatas collected during this write session. */
private IDictionary<int, BinaryType> _metas;
/** Current type ID. */
private int _curTypeId;
/** Current name converter */
private IBinaryNameMapper _curConverter;
/** Current mapper. */
private IBinaryIdMapper _curMapper;
/** Current object start position. */
private int _curPos;
/** Current raw position. */
private int _curRawPos;
/** Whether we are currently detaching an object. */
private bool _detaching;
/** Current type structure tracker, */
private BinaryStructureTracker _curStruct;
/** Schema holder. */
private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current;
/// <summary>
/// Gets the marshaller.
/// </summary>
internal Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Write named boolean value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(string fieldName, bool val)
{
WriteFieldId(fieldName, BinaryUtils.TypeBool);
WriteBooleanField(val);
}
/// <summary>
/// Writes the boolean field.
/// </summary>
/// <param name="val">if set to <c>true</c> [value].</param>
internal void WriteBooleanField(bool val)
{
_stream.WriteByte(BinaryUtils.TypeBool);
_stream.WriteBool(val);
}
/// <summary>
/// Write boolean value.
/// </summary>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(bool val)
{
_stream.WriteBool(val);
}
/// <summary>
/// Write named boolean array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(string fieldName, bool[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayBool);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write boolean array.
/// </summary>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(bool[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write named byte value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte value.</param>
public void WriteByte(string fieldName, byte val)
{
WriteFieldId(fieldName, BinaryUtils.TypeBool);
WriteByteField(val);
}
/// <summary>
/// Write byte field value.
/// </summary>
/// <param name="val">Byte value.</param>
internal void WriteByteField(byte val)
{
_stream.WriteByte(BinaryUtils.TypeByte);
_stream.WriteByte(val);
}
/// <summary>
/// Write byte value.
/// </summary>
/// <param name="val">Byte value.</param>
public void WriteByte(byte val)
{
_stream.WriteByte(val);
}
/// <summary>
/// Write named byte array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte array.</param>
public void WriteByteArray(string fieldName, byte[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayByte);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
public void WriteByteArray(byte[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write named short value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short value.</param>
public void WriteShort(string fieldName, short val)
{
WriteFieldId(fieldName, BinaryUtils.TypeShort);
WriteShortField(val);
}
/// <summary>
/// Write short field value.
/// </summary>
/// <param name="val">Short value.</param>
internal void WriteShortField(short val)
{
_stream.WriteByte(BinaryUtils.TypeShort);
_stream.WriteShort(val);
}
/// <summary>
/// Write short value.
/// </summary>
/// <param name="val">Short value.</param>
public void WriteShort(short val)
{
_stream.WriteShort(val);
}
/// <summary>
/// Write named short array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short array.</param>
public void WriteShortArray(string fieldName, short[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayShort);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="val">Short array.</param>
public void WriteShortArray(short[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write named char value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char value.</param>
public void WriteChar(string fieldName, char val)
{
WriteFieldId(fieldName, BinaryUtils.TypeChar);
WriteCharField(val);
}
/// <summary>
/// Write char field value.
/// </summary>
/// <param name="val">Char value.</param>
internal void WriteCharField(char val)
{
_stream.WriteByte(BinaryUtils.TypeChar);
_stream.WriteChar(val);
}
/// <summary>
/// Write char value.
/// </summary>
/// <param name="val">Char value.</param>
public void WriteChar(char val)
{
_stream.WriteChar(val);
}
/// <summary>
/// Write named char array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char array.</param>
public void WriteCharArray(string fieldName, char[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayChar);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="val">Char array.</param>
public void WriteCharArray(char[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write named int value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int value.</param>
public void WriteInt(string fieldName, int val)
{
WriteFieldId(fieldName, BinaryUtils.TypeInt);
WriteIntField(val);
}
/// <summary>
/// Writes the int field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteIntField(int val)
{
_stream.WriteByte(BinaryUtils.TypeInt);
_stream.WriteInt(val);
}
/// <summary>
/// Write int value.
/// </summary>
/// <param name="val">Int value.</param>
public void WriteInt(int val)
{
_stream.WriteInt(val);
}
/// <summary>
/// Write named int array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int array.</param>
public void WriteIntArray(string fieldName, int[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayInt);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="val">Int array.</param>
public void WriteIntArray(int[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write named long value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long value.</param>
public void WriteLong(string fieldName, long val)
{
WriteFieldId(fieldName, BinaryUtils.TypeLong);
WriteLongField(val);
}
/// <summary>
/// Writes the long field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteLongField(long val)
{
_stream.WriteByte(BinaryUtils.TypeLong);
_stream.WriteLong(val);
}
/// <summary>
/// Write long value.
/// </summary>
/// <param name="val">Long value.</param>
public void WriteLong(long val)
{
_stream.WriteLong(val);
}
/// <summary>
/// Write named long array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long array.</param>
public void WriteLongArray(string fieldName, long[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayLong);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="val">Long array.</param>
public void WriteLongArray(long[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write named float value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float value.</param>
public void WriteFloat(string fieldName, float val)
{
WriteFieldId(fieldName, BinaryUtils.TypeFloat);
WriteFloatField(val);
}
/// <summary>
/// Writes the float field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteFloatField(float val)
{
_stream.WriteByte(BinaryUtils.TypeFloat);
_stream.WriteFloat(val);
}
/// <summary>
/// Write float value.
/// </summary>
/// <param name="val">Float value.</param>
public void WriteFloat(float val)
{
_stream.WriteFloat(val);
}
/// <summary>
/// Write named float array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float array.</param>
public void WriteFloatArray(string fieldName, float[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayFloat);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="val">Float array.</param>
public void WriteFloatArray(float[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write named double value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double value.</param>
public void WriteDouble(string fieldName, double val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDouble);
WriteDoubleField(val);
}
/// <summary>
/// Writes the double field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteDoubleField(double val)
{
_stream.WriteByte(BinaryUtils.TypeDouble);
_stream.WriteDouble(val);
}
/// <summary>
/// Write double value.
/// </summary>
/// <param name="val">Double value.</param>
public void WriteDouble(double val)
{
_stream.WriteDouble(val);
}
/// <summary>
/// Write named double array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(string fieldName, double[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDouble);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(double[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write named decimal value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(string fieldName, decimal? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write decimal value.
/// </summary>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(decimal? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write named decimal array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(string fieldName, decimal?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write decimal array.
/// </summary>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(decimal?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write named date value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date value.</param>
public void WriteTimestamp(string fieldName, DateTime? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write date value.
/// </summary>
/// <param name="val">Date value.</param>
public void WriteTimestamp(DateTime? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write named date array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(string fieldName, DateTime?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write date array.
/// </summary>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(DateTime?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write named string value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String value.</param>
public void WriteString(string fieldName, string val)
{
WriteFieldId(fieldName, BinaryUtils.TypeString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="val">String value.</param>
public void WriteString(string val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write named string array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String array.</param>
public void WriteStringArray(string fieldName, string[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write string array.
/// </summary>
/// <param name="val">String array.</param>
public void WriteStringArray(string[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write named GUID value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID value.</param>
public void WriteGuid(string fieldName, Guid? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write GUID value.
/// </summary>
/// <param name="val">GUID value.</param>
public void WriteGuid(Guid? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write named GUID array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(string fieldName, Guid?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write GUID array.
/// </summary>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(Guid?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write named enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeEnum);
WriteEnum(val);
}
/// <summary>
/// Write enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(T val)
{
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
{
var desc = _marsh.GetDescriptor(val.GetType());
if (desc != null)
{
var metaHnd = _marsh.GetBinaryTypeHandler(desc);
_stream.WriteByte(BinaryUtils.TypeEnum);
BinaryUtils.WriteEnum(this, val);
SaveMetadata(desc, metaHnd.OnObjectWriteFinished());
}
else
{
// Unregistered enum, write as serializable
Write(new SerializableObjectHolder(val));
}
}
}
/// <summary>
/// Write named enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayEnum);
WriteEnumArray(val);
}
/// <summary>
/// Write enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(T[] val)
{
WriteEnumArrayInternal(val, null);
}
/// <summary>
/// Writes the enum array.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="elementTypeId">The element type id.</param>
public void WriteEnumArrayInternal(Array val, int? elementTypeId)
{
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayEnum);
var elTypeId = elementTypeId ?? BinaryUtils.GetEnumTypeId(val.GetType().GetElementType(), Marshaller);
BinaryUtils.WriteArray(val, this, elTypeId);
}
}
/// <summary>
/// Write named object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object value.</param>
public void WriteObject<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeObject);
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
Write(val);
}
/// <summary>
/// Write object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Object value.</param>
public void WriteObject<T>(T val)
{
Write(val);
}
/// <summary>
/// Write named object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object array.</param>
public void WriteArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArray);
WriteArray(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="val">Object array.</param>
public void WriteArray<T>(T[] val)
{
WriteArrayInternal(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <param name="val">Object array.</param>
public void WriteArrayInternal(Array val)
{
if (val == null)
WriteNullRawField();
else
{
if (WriteHandle(_stream.Position, val))
return;
_stream.WriteByte(BinaryUtils.TypeArray);
BinaryUtils.WriteArray(val, this);
}
}
/// <summary>
/// Write named collection.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Collection.</param>
public void WriteCollection(string fieldName, ICollection val)
{
WriteFieldId(fieldName, BinaryUtils.TypeCollection);
WriteCollection(val);
}
/// <summary>
/// Write collection.
/// </summary>
/// <param name="val">Collection.</param>
public void WriteCollection(ICollection val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryUtils.TypeCollection);
BinaryUtils.WriteCollection(val, this);
}
}
/// <summary>
/// Write named dictionary.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(string fieldName, IDictionary val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDictionary);
WriteDictionary(val);
}
/// <summary>
/// Write dictionary.
/// </summary>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(IDictionary val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryUtils.TypeDictionary);
BinaryUtils.WriteDictionary(val, this);
}
}
/// <summary>
/// Write NULL field.
/// </summary>
private void WriteNullField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Write NULL raw field.
/// </summary>
private void WriteNullRawField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Get raw writer.
/// </summary>
/// <returns>
/// Raw writer.
/// </returns>
public IBinaryRawWriter GetRawWriter()
{
if (_curRawPos == 0)
_curRawPos = _stream.Position;
return this;
}
/// <summary>
/// Set new builder.
/// </summary>
/// <param name="builder">Builder.</param>
/// <returns>Previous builder.</returns>
internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder)
{
BinaryObjectBuilder ret = _builder;
_builder = builder;
return ret;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Stream.</param>
internal BinaryWriter(Marshaller marsh, IBinaryStream stream)
{
_marsh = marsh;
_stream = stream;
}
/// <summary>
/// Write object.
/// </summary>
/// <param name="obj">Object.</param>
public void Write<T>(T obj)
{
// Handle special case for null.
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (obj == null)
{
_stream.WriteByte(BinaryUtils.HdrNull);
return;
}
// We use GetType() of a real object instead of typeof(T) to take advantage of
// automatic Nullable'1 unwrapping.
Type type = obj.GetType();
// Handle common case when primitive is written.
if (type.IsPrimitive)
{
WritePrimitive(obj, type);
return;
}
// Handle enums.
if (type.IsEnum)
{
WriteEnum(obj);
return;
}
// Handle special case for builder.
if (WriteBuilderSpecials(obj))
return;
// Suppose that we faced normal object and perform descriptor lookup.
IBinaryTypeDescriptor desc = _marsh.GetDescriptor(type);
if (desc != null)
{
// Writing normal object.
var pos = _stream.Position;
// Dealing with handles.
if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj))
return;
// Skip header length as not everything is known now
_stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
// Preserve old frame.
int oldTypeId = _curTypeId;
IBinaryNameMapper oldConverter = _curConverter;
IBinaryIdMapper oldMapper = _curMapper;
int oldRawPos = _curRawPos;
var oldPos = _curPos;
var oldStruct = _curStruct;
// Push new frame.
_curTypeId = desc.TypeId;
_curConverter = desc.NameMapper;
_curMapper = desc.IdMapper;
_curRawPos = 0;
_curPos = pos;
_curStruct = new BinaryStructureTracker(desc, desc.WriterTypeStructure);
var schemaIdx = _schema.PushSchema();
try
{
// Write object fields.
desc.Serializer.WriteBinary(obj, this);
// Write schema
var schemaOffset = _stream.Position - pos;
int schemaId;
var flags = desc.UserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
if (Marshaller.CompactFooter && desc.UserType)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags);
if (hasSchema)
{
flags |= BinaryObjectHeader.Flag.HasSchema;
// Calculate and write header.
if (_curRawPos > 0)
_stream.WriteInt(_curRawPos - pos); // raw offset is in the last 4 bytes
// Update schema in type descriptor
if (desc.Schema.Get(schemaId) == null)
desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx));
}
else
schemaOffset = BinaryObjectHeader.Size;
if (_curRawPos > 0)
flags |= BinaryObjectHeader.Flag.HasRaw;
var len = _stream.Position - pos;
var header = new BinaryObjectHeader(desc.TypeId, obj.GetHashCode(), len,
schemaId, schemaOffset, flags);
BinaryObjectHeader.Write(header, _stream, pos);
Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end
}
finally
{
_schema.PopSchema(schemaIdx);
}
// Apply structure updates if any.
_curStruct.UpdateWriterStructure(this);
// Restore old frame.
_curTypeId = oldTypeId;
_curConverter = oldConverter;
_curMapper = oldMapper;
_curRawPos = oldRawPos;
_curPos = oldPos;
_curStruct = oldStruct;
}
else
{
// Are we dealing with a well-known type?
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler == null) // We did our best, object cannot be marshalled.
throw BinaryUtils.GetUnsupportedTypeException(type, obj);
if (handler.SupportsHandles && WriteHandle(_stream.Position, obj))
return;
handler.Write(this, obj);
}
}
/// <summary>
/// Write primitive type.
/// </summary>
/// <param name="val">Object.</param>
/// <param name="type">Type.</param>
private unsafe void WritePrimitive<T>(T val, Type type)
{
// .Net defines 14 primitive types. We support 12 - excluding IntPtr and UIntPtr.
// Types check sequence is designed to minimize comparisons for the most frequent types.
if (type == typeof(int))
WriteIntField(TypeCaster<int>.Cast(val));
else if (type == typeof(long))
WriteLongField(TypeCaster<long>.Cast(val));
else if (type == typeof(bool))
WriteBooleanField(TypeCaster<bool>.Cast(val));
else if (type == typeof(byte))
WriteByteField(TypeCaster<byte>.Cast(val));
else if (type == typeof(short))
WriteShortField(TypeCaster<short>.Cast(val));
else if (type == typeof(char))
WriteCharField(TypeCaster<char>.Cast(val));
else if (type == typeof(float))
WriteFloatField(TypeCaster<float>.Cast(val));
else if (type == typeof(double))
WriteDoubleField(TypeCaster<double>.Cast(val));
else if (type == typeof(sbyte))
{
var val0 = TypeCaster<sbyte>.Cast(val);
WriteByteField(*(byte*)&val0);
}
else if (type == typeof(ushort))
{
var val0 = TypeCaster<ushort>.Cast(val);
WriteShortField(*(short*) &val0);
}
else if (type == typeof(uint))
{
var val0 = TypeCaster<uint>.Cast(val);
WriteIntField(*(int*)&val0);
}
else if (type == typeof(ulong))
{
var val0 = TypeCaster<ulong>.Cast(val);
WriteLongField(*(long*)&val0);
}
else
throw BinaryUtils.GetUnsupportedTypeException(type, val);
}
/// <summary>
/// Try writing object as special builder type.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>True if object was written, false otherwise.</returns>
private bool WriteBuilderSpecials<T>(T obj)
{
if (_builder != null)
{
// Special case for binary object during build.
BinaryObject portObj = obj as BinaryObject;
if (portObj != null)
{
if (!WriteHandle(_stream.Position, portObj))
_builder.ProcessBinary(_stream, portObj);
return true;
}
// Special case for builder during build.
BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder;
if (portBuilder != null)
{
if (!WriteHandle(_stream.Position, portBuilder))
_builder.ProcessBuilder(_stream, portBuilder);
return true;
}
}
return false;
}
/// <summary>
/// Add handle to handles map.
/// </summary>
/// <param name="pos">Position in stream.</param>
/// <param name="obj">Object.</param>
/// <returns><c>true</c> if object was written as handle.</returns>
private bool WriteHandle(long pos, object obj)
{
if (_hnds == null)
{
// Cache absolute handle position.
_hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance);
return false;
}
long hndPos;
if (!_hnds.TryGetValue(obj, out hndPos))
{
// Cache absolute handle position.
_hnds.Add(obj, pos);
return false;
}
_stream.WriteByte(BinaryUtils.HdrHnd);
// Handle is written as difference between position before header and handle position.
_stream.WriteInt((int)(pos - hndPos));
return true;
}
/// <summary>
/// Perform action with detached semantics.
/// </summary>
/// <param name="a"></param>
internal void WithDetach(Action<BinaryWriter> a)
{
if (_detaching)
a(this);
else
{
_detaching = true;
BinaryHandleDictionary<object, long> oldHnds = _hnds;
_hnds = null;
try
{
a(this);
}
finally
{
_detaching = false;
if (oldHnds != null)
{
// Merge newly recorded handles with old ones and restore old on the stack.
// Otherwise we can use current handles right away.
if (_hnds != null)
oldHnds.Merge(_hnds);
_hnds = oldHnds;
}
}
}
}
/// <summary>
/// Stream.
/// </summary>
internal IBinaryStream Stream
{
get { return _stream; }
}
/// <summary>
/// Gets collected metadatas.
/// </summary>
/// <returns>Collected metadatas (if any).</returns>
internal ICollection<BinaryType> GetBinaryTypes()
{
return _metas == null ? null : _metas.Values;
}
/// <summary>
/// Write field ID.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="fieldTypeId">Field type ID.</param>
private void WriteFieldId(string fieldName, byte fieldTypeId)
{
if (_curRawPos != 0)
throw new BinaryObjectException("Cannot write named fields after raw data is written.");
var fieldId = _curStruct.GetFieldId(fieldName, fieldTypeId);
_schema.PushField(fieldId, _stream.Position - _curPos);
}
/// <summary>
/// Saves metadata for this session.
/// </summary>
/// <param name="desc">The descriptor.</param>
/// <param name="fields">Fields metadata.</param>
internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, int> fields)
{
Debug.Assert(desc != null);
if (_metas == null)
{
_metas = new Dictionary<int, BinaryType>(1)
{
{desc.TypeId, new BinaryType(desc, fields)}
};
}
else
{
BinaryType meta;
if (_metas.TryGetValue(desc.TypeId, out meta))
meta.UpdateFields(fields);
else
_metas[desc.TypeId] = new BinaryType(desc, fields);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal.Windows
{
internal sealed partial class DecryptorPalWindows : DecryptorPal
{
public unsafe sealed override ContentInfo TryDecrypt(
RecipientInfo recipientInfo,
X509Certificate2 cert,
AsymmetricAlgorithm privateKey,
X509Certificate2Collection originatorCerts,
X509Certificate2Collection extraStore,
out Exception exception)
{
Debug.Assert((cert != null) ^ (privateKey != null));
if (privateKey != null)
{
RSA key = privateKey as RSA;
if (key == null)
{
exception = new CryptographicException(SR.Cryptography_Cms_Ktri_RSARequired);
return null;
}
ContentInfo contentInfo = _hCryptMsg.GetContentInfo();
byte[] cek = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore(
cert,
key,
recipientInfo.EncryptedKey,
recipientInfo.KeyEncryptionAlgorithm.Oid.Value,
out exception);
// Pin CEK to prevent it from getting copied during heap compaction.
fixed (byte* pinnedCek = cek)
{
try
{
if (exception != null)
{
return null;
}
return AnyOS.ManagedPkcsPal.ManagedDecryptorPal.TryDecryptCore(
cek,
contentInfo.ContentType.Value,
contentInfo.Content,
_contentEncryptionAlgorithm,
out exception);
}
finally
{
if (cek != null)
{
Array.Clear(cek, 0, cek.Length);
}
}
}
}
Debug.Assert(recipientInfo != null);
Debug.Assert(cert != null);
Debug.Assert(originatorCerts != null);
Debug.Assert(extraStore != null);
CryptKeySpec keySpec;
exception = TryGetKeySpecForCertificate(cert, out keySpec);
if (exception != null)
return null;
// Desktop compat: We pass false for "silent" here (thus allowing crypto providers to display UI.)
const bool Silent = false;
// Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
// because wrapping an NCrypt wrapper over CAPI keys unconditionally causes some legacy features
// (such as RC4 support) to break.
const bool PreferNCrypt = false;
using (SafeProvOrNCryptKeyHandle hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception))
{
if (hKey == null)
return null;
RecipientInfoType type = recipientInfo.Type;
switch (type)
{
case RecipientInfoType.KeyTransport:
exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec);
break;
case RecipientInfoType.KeyAgreement:
exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore);
break;
default:
// Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than
// returning to the caller.
Debug.Fail($"Unexpected RecipientInfoType: {type}");
throw new NotSupportedException();
}
if (exception != null)
return null;
// If we got here, we successfully decrypted. Return the decrypted content.
return _hCryptMsg.GetContentInfo();
}
}
private static Exception TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
{
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
int cbSize = 0;
if (Interop.Crypt32.CertGetCertificateContextProperty(
hCertContext,
CertContextPropId.CERT_NCRYPT_KEY_HANDLE_PROP_ID,
null,
ref cbSize))
{
keySpec = CryptKeySpec.CERT_NCRYPT_KEY_SPEC;
return null;
}
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
byte[] pData = new byte[cbSize];
unsafe
{
fixed (byte* pvData = pData)
{
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, pData, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
CRYPT_KEY_PROV_INFO* pCryptKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pvData;
keySpec = pCryptKeyProvInfo->dwKeySpec;
return null;
}
}
}
}
private Exception TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
{
KeyTransRecipientInfoPalWindows pal = (KeyTransRecipientInfoPalWindows)(recipientInfo.Pal);
CMSG_CTRL_DECRYPT_PARA decryptPara;
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_DECRYPT_PARA>();
decryptPara.hKey = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.dwRecipientIndex = pal.Index;
bool success = Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_DECRYPT, ref decryptPara);
if (!success)
return Marshal.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
{
unsafe
{
KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
return pal.WithCmsgCmsRecipientInfo<Exception>(
delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
{
CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_KEY_AGREE_DECRYPT_PARA>();
decryptPara.hProv = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.pKeyAgree = pKeyAgreeRecipientInfo;
decryptPara.dwRecipientIndex = pal.Index;
decryptPara.dwRecipientEncryptedKeyIndex = pal.SubIndex;
CMsgKeyAgreeOriginatorChoice originatorChoice = pKeyAgreeRecipientInfo->dwOriginatorChoice;
switch (originatorChoice)
{
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT:
{
X509Certificate2Collection candidateCerts = new X509Certificate2Collection();
candidateCerts.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, openExistingOnly: true));
candidateCerts.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.LocalMachine, openExistingOnly: true));
candidateCerts.AddRange(originatorCerts);
candidateCerts.AddRange(extraStore);
SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
if (originatorCert == null)
return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
{
CERT_CONTEXT* pOriginatorCertContext = hCertContext.DangerousGetCertContext();
decryptPara.OriginatorPublicKey = pOriginatorCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey;
// Do not factor this call out of the switch statement as leaving this "using" block will free up
// native memory that decryptPara points to.
return TryExecuteDecryptAgree(ref decryptPara);
}
}
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
{
decryptPara.OriginatorPublicKey = pKeyAgreeRecipientInfo->OriginatorPublicKeyInfo.PublicKey;
return TryExecuteDecryptAgree(ref decryptPara);
}
default:
return new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice));
}
});
}
}
private Exception TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
{
if (!Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_KEY_AGREE_DECRYPT, ref decryptPara))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetHRForLastWin32Error());
return errorCode.ToCryptographicException();
}
return null;
}
}
}
| |
namespace Microsoft.Azure.DocumentDBStudio
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.tsStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.tsProgress = new System.Windows.Forms.ToolStripProgressBar();
this.tsButtonZoom = new System.Windows.Forms.ToolStripSplitButton();
this.splitContainerOuter = new System.Windows.Forms.SplitContainer();
this.treeView1 = new System.Windows.Forms.TreeView();
this.splitContainerInner = new System.Windows.Forms.SplitContainer();
this.tabControl = new System.Windows.Forms.TabControl();
this.tabRequest = new System.Windows.Forms.TabPage();
this.tbRequest = new System.Windows.Forms.TextBox();
this.tabCrudContext = new System.Windows.Forms.TabPage();
this.splitContainerIntabPage = new System.Windows.Forms.SplitContainer();
this.labelid = new System.Windows.Forms.Label();
this.textBoxforId = new System.Windows.Forms.TextBox();
this.tbCrudContext = new System.Windows.Forms.TextBox();
this.tabResponse = new System.Windows.Forms.TabPage();
this.tbResponse = new System.Windows.Forms.TextBox();
this.tabPageRequestOptions = new System.Windows.Forms.TabPage();
this.labelPartitionKey = new System.Windows.Forms.Label();
this.tbPartitionKeyForRequestOption = new System.Windows.Forms.TextBox();
this.cbRequestOptionsApply = new System.Windows.Forms.CheckBox();
this.labelPostTrigger = new System.Windows.Forms.Label();
this.tbPostTrigger = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.tbPreTrigger = new System.Windows.Forms.TextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.rbConsistencyEventual = new System.Windows.Forms.RadioButton();
this.rbConsistencySession = new System.Windows.Forms.RadioButton();
this.rbConsistencyBound = new System.Windows.Forms.RadioButton();
this.rbConsistencyStrong = new System.Windows.Forms.RadioButton();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.rbAccessConditionIfNoneMatch = new System.Windows.Forms.RadioButton();
this.rbAccessConditionIfMatch = new System.Windows.Forms.RadioButton();
this.tbAccessConditionText = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rbIndexingExclude = new System.Windows.Forms.RadioButton();
this.rbIndexingInclude = new System.Windows.Forms.RadioButton();
this.rbIndexingDefault = new System.Windows.Forms.RadioButton();
this.tabDocumentCollection = new System.Windows.Forms.TabPage();
this.btnRemoveExcludedPath = new System.Windows.Forms.Button();
this.btnAddExcludedPath = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.rbLazy = new System.Windows.Forms.RadioButton();
this.rbConsistent = new System.Windows.Forms.RadioButton();
this.lbExcludedPath = new System.Windows.Forms.ListBox();
this.btnEdit = new System.Windows.Forms.Button();
this.btnRemovePath = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.btnAddIncludePath = new System.Windows.Forms.Button();
this.lbIncludedPath = new System.Windows.Forms.ListBox();
this.labelCollectionId = new System.Windows.Forms.Label();
this.tbCollectionId = new System.Windows.Forms.TextBox();
this.cbIndexingPolicyDefault = new System.Windows.Forms.CheckBox();
this.cbAutomatic = new System.Windows.Forms.CheckBox();
this.tabOffer = new System.Windows.Forms.TabPage();
this.label5 = new System.Windows.Forms.Label();
this.gbStandardOffer = new System.Windows.Forms.GroupBox();
this.labelThroughput = new System.Windows.Forms.Label();
this.tbThroughput = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.cbShowLegacyOffer = new System.Windows.Forms.CheckBox();
this.rbOfferS3 = new System.Windows.Forms.RadioButton();
this.rbElasticCollection = new System.Windows.Forms.RadioButton();
this.rbOfferS2 = new System.Windows.Forms.RadioButton();
this.tbPartitionKeyForCollectionCreate = new System.Windows.Forms.TextBox();
this.rbOfferS1 = new System.Windows.Forms.RadioButton();
this.rbSinglePartition = new System.Windows.Forms.RadioButton();
this.label4 = new System.Windows.Forms.Label();
this.ButtomSplitContainer = new System.Windows.Forms.SplitContainer();
this.triggerPanel = new System.Windows.Forms.Panel();
this.rbPostTrigger = new System.Windows.Forms.RadioButton();
this.rbPreTrigger = new System.Windows.Forms.RadioButton();
this.feedToolStrip = new System.Windows.Forms.ToolStrip();
this.MaxItemCount = new System.Windows.Forms.ToolStripLabel();
this.toolStripTextMaxItemCount = new System.Windows.Forms.ToolStripTextBox();
this.Separator1 = new System.Windows.Forms.ToolStripSeparator();
this.Separator2 = new System.Windows.Forms.ToolStripSeparator();
this.MaxDOP = new System.Windows.Forms.ToolStripLabel();
this.toolStripTextMaxDop = new System.Windows.Forms.ToolStripTextBox();
this.Separator3 = new System.Windows.Forms.ToolStripSeparator();
this.MaxBuffItem = new System.Windows.Forms.ToolStripLabel();
this.toolStripTextMaxBuffItem = new System.Windows.Forms.ToolStripTextBox();
this.Separator4 = new System.Windows.Forms.ToolStripSeparator();
this.btnExecuteNext = new System.Windows.Forms.ToolStripButton();
this.webBrowserResponse = new System.Windows.Forms.WebBrowser();
this.tsMenu = new System.Windows.Forms.ToolStrip();
this.btnBack = new System.Windows.Forms.ToolStripButton();
this.btnForward = new System.Windows.Forms.ToolStripButton();
this.btnHome = new System.Windows.Forms.ToolStripButton();
this.toolStripBtnExecute = new System.Windows.Forms.ToolStripButton();
this.btnRefresh = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnHeaders = new System.Windows.Forms.ToolStripButton();
this.btnEditRequests = new System.Windows.Forms.ToolStripButton();
this.tsbViewType = new System.Windows.Forms.ToolStripButton();
this.tsbHideDocumentSystemProperties = new System.Windows.Forms.ToolStripButton();
this.tsAddress = new System.Windows.Forms.ToolStrip();
this.tsLabelUrl = new System.Windows.Forms.ToolStripLabel();
this.cbUrl = new System.Windows.Forms.ToolStripComboBox();
this.btnGo = new System.Windows.Forms.ToolStripButton();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tsTablesEntities = new System.Windows.Forms.ToolStrip();
this.btnQueryTable = new System.Windows.Forms.ToolStripButton();
this.btnCreateTable = new System.Windows.Forms.ToolStripButton();
this.btnDeleteTable = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.btnQueryEntities = new System.Windows.Forms.ToolStripButton();
this.btnNextPage = new System.Windows.Forms.ToolStripButton();
this.btnInsertEntity = new System.Windows.Forms.ToolStripButton();
this.btnUpdateEntity = new System.Windows.Forms.ToolStripButton();
this.tsbMergeEntity = new System.Windows.Forms.ToolStripButton();
this.btnDeleteEntity = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.tsbEditTemplate = new System.Windows.Forms.ToolStripButton();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.statusStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainerOuter)).BeginInit();
this.splitContainerOuter.Panel1.SuspendLayout();
this.splitContainerOuter.Panel2.SuspendLayout();
this.splitContainerOuter.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainerInner)).BeginInit();
this.splitContainerInner.Panel1.SuspendLayout();
this.splitContainerInner.Panel2.SuspendLayout();
this.splitContainerInner.SuspendLayout();
this.tabControl.SuspendLayout();
this.tabRequest.SuspendLayout();
this.tabCrudContext.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainerIntabPage)).BeginInit();
this.splitContainerIntabPage.Panel1.SuspendLayout();
this.splitContainerIntabPage.Panel2.SuspendLayout();
this.splitContainerIntabPage.SuspendLayout();
this.tabResponse.SuspendLayout();
this.tabPageRequestOptions.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tabDocumentCollection.SuspendLayout();
this.groupBox4.SuspendLayout();
this.tabOffer.SuspendLayout();
this.gbStandardOffer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ButtomSplitContainer)).BeginInit();
this.ButtomSplitContainer.Panel1.SuspendLayout();
this.ButtomSplitContainer.Panel2.SuspendLayout();
this.ButtomSplitContainer.SuspendLayout();
this.triggerPanel.SuspendLayout();
this.feedToolStrip.SuspendLayout();
this.tsMenu.SuspendLayout();
this.tsAddress.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.tsTablesEntities.SuspendLayout();
this.SuspendLayout();
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsStatus,
this.tsProgress,
this.tsButtonZoom});
this.statusStrip.Location = new System.Drawing.Point(0, 843);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Padding = new System.Windows.Forms.Padding(1, 0, 19, 0);
this.statusStrip.Size = new System.Drawing.Size(1372, 22);
this.statusStrip.TabIndex = 1;
this.statusStrip.Text = "statusStrip1";
//
// tsStatus
//
this.tsStatus.Name = "tsStatus";
this.tsStatus.Size = new System.Drawing.Size(1182, 17);
this.tsStatus.Spring = true;
this.tsStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tsProgress
//
this.tsProgress.Name = "tsProgress";
this.tsProgress.Size = new System.Drawing.Size(100, 16);
//
// tsButtonZoom
//
this.tsButtonZoom.Image = global::Microsoft.Azure.DocumentDBStudio.Properties.Resources.ZoomHS;
this.tsButtonZoom.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsButtonZoom.Name = "tsButtonZoom";
this.tsButtonZoom.Size = new System.Drawing.Size(68, 20);
this.tsButtonZoom.Text = "100%";
this.tsButtonZoom.ButtonClick += new System.EventHandler(this.tsButtonZoom_ButtonClick);
//
// splitContainerOuter
//
this.splitContainerOuter.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.splitContainerOuter.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainerOuter.Location = new System.Drawing.Point(0, 50);
this.splitContainerOuter.Margin = new System.Windows.Forms.Padding(4);
this.splitContainerOuter.Name = "splitContainerOuter";
//
// splitContainerOuter.Panel1
//
this.splitContainerOuter.Panel1.Controls.Add(this.treeView1);
//
// splitContainerOuter.Panel2
//
this.splitContainerOuter.Panel2.Controls.Add(this.splitContainerInner);
this.splitContainerOuter.Size = new System.Drawing.Size(1372, 793);
this.splitContainerOuter.SplitterDistance = 457;
this.splitContainerOuter.SplitterWidth = 5;
this.splitContainerOuter.TabIndex = 2;
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.Location = new System.Drawing.Point(0, 0);
this.treeView1.Margin = new System.Windows.Forms.Padding(4);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(455, 791);
this.treeView1.TabIndex = 0;
this.treeView1.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView1_BeforeExpand);
this.treeView1.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
this.treeView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeView1_NodeKeyDown);
this.treeView1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.treeView1_NodeKeyPress);
//
// splitContainerInner
//
this.splitContainerInner.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainerInner.Location = new System.Drawing.Point(0, 0);
this.splitContainerInner.Margin = new System.Windows.Forms.Padding(4);
this.splitContainerInner.Name = "splitContainerInner";
this.splitContainerInner.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainerInner.Panel1
//
this.splitContainerInner.Panel1.Controls.Add(this.tabControl);
//
// splitContainerInner.Panel2
//
this.splitContainerInner.Panel2.Controls.Add(this.ButtomSplitContainer);
this.splitContainerInner.Size = new System.Drawing.Size(908, 791);
this.splitContainerInner.SplitterDistance = 207;
this.splitContainerInner.SplitterWidth = 5;
this.splitContainerInner.TabIndex = 0;
//
// tabControl
//
this.tabControl.Controls.Add(this.tabRequest);
this.tabControl.Controls.Add(this.tabCrudContext);
this.tabControl.Controls.Add(this.tabResponse);
this.tabControl.Controls.Add(this.tabPageRequestOptions);
this.tabControl.Controls.Add(this.tabDocumentCollection);
this.tabControl.Controls.Add(this.tabOffer);
this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Margin = new System.Windows.Forms.Padding(4);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(908, 207);
this.tabControl.TabIndex = 1;
//
// tabRequest
//
this.tabRequest.Controls.Add(this.tbRequest);
this.tabRequest.Location = new System.Drawing.Point(4, 26);
this.tabRequest.Margin = new System.Windows.Forms.Padding(4);
this.tabRequest.Name = "tabRequest";
this.tabRequest.Padding = new System.Windows.Forms.Padding(4);
this.tabRequest.Size = new System.Drawing.Size(900, 177);
this.tabRequest.TabIndex = 0;
this.tabRequest.Text = "Request Headers";
this.tabRequest.UseVisualStyleBackColor = true;
//
// tbRequest
//
this.tbRequest.Dock = System.Windows.Forms.DockStyle.Fill;
this.tbRequest.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbRequest.Location = new System.Drawing.Point(4, 4);
this.tbRequest.Margin = new System.Windows.Forms.Padding(4);
this.tbRequest.Multiline = true;
this.tbRequest.Name = "tbRequest";
this.tbRequest.ReadOnly = true;
this.tbRequest.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.tbRequest.Size = new System.Drawing.Size(892, 169);
this.tbRequest.TabIndex = 0;
//
// tabCrudContext
//
this.tabCrudContext.Controls.Add(this.splitContainerIntabPage);
this.tabCrudContext.Location = new System.Drawing.Point(4, 22);
this.tabCrudContext.Margin = new System.Windows.Forms.Padding(4);
this.tabCrudContext.Name = "tabCrudContext";
this.tabCrudContext.Padding = new System.Windows.Forms.Padding(4);
this.tabCrudContext.Size = new System.Drawing.Size(900, 182);
this.tabCrudContext.TabIndex = 2;
this.tabCrudContext.Text = "Operation Editor";
this.tabCrudContext.UseVisualStyleBackColor = true;
//
// splitContainerIntabPage
//
this.splitContainerIntabPage.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainerIntabPage.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainerIntabPage.Location = new System.Drawing.Point(4, 4);
this.splitContainerIntabPage.Margin = new System.Windows.Forms.Padding(4);
this.splitContainerIntabPage.Name = "splitContainerIntabPage";
this.splitContainerIntabPage.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainerIntabPage.Panel1
//
this.splitContainerIntabPage.Panel1.Controls.Add(this.labelid);
this.splitContainerIntabPage.Panel1.Controls.Add(this.textBoxforId);
this.splitContainerIntabPage.Panel1MinSize = 35;
//
// splitContainerIntabPage.Panel2
//
this.splitContainerIntabPage.Panel2.Controls.Add(this.tbCrudContext);
this.splitContainerIntabPage.Size = new System.Drawing.Size(892, 174);
this.splitContainerIntabPage.SplitterDistance = 35;
this.splitContainerIntabPage.SplitterWidth = 5;
this.splitContainerIntabPage.TabIndex = 0;
//
// labelid
//
this.labelid.AutoSize = true;
this.labelid.Location = new System.Drawing.Point(5, 5);
this.labelid.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelid.Name = "labelid";
this.labelid.Size = new System.Drawing.Size(19, 17);
this.labelid.TabIndex = 2;
this.labelid.Text = "Id";
//
// textBoxforId
//
this.textBoxforId.Location = new System.Drawing.Point(35, 3);
this.textBoxforId.Margin = new System.Windows.Forms.Padding(4);
this.textBoxforId.Name = "textBoxforId";
this.textBoxforId.Size = new System.Drawing.Size(389, 23);
this.textBoxforId.TabIndex = 1;
//
// tbCrudContext
//
this.tbCrudContext.Dock = System.Windows.Forms.DockStyle.Fill;
this.tbCrudContext.Location = new System.Drawing.Point(0, 0);
this.tbCrudContext.Margin = new System.Windows.Forms.Padding(4);
this.tbCrudContext.Multiline = true;
this.tbCrudContext.Name = "tbCrudContext";
this.tbCrudContext.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.tbCrudContext.Size = new System.Drawing.Size(892, 134);
this.tbCrudContext.TabIndex = 0;
this.tbCrudContext.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.tbCrudContext_PreviewKeyDown);
//
// tabResponse
//
this.tabResponse.Controls.Add(this.tbResponse);
this.tabResponse.Location = new System.Drawing.Point(4, 22);
this.tabResponse.Margin = new System.Windows.Forms.Padding(4);
this.tabResponse.Name = "tabResponse";
this.tabResponse.Padding = new System.Windows.Forms.Padding(4);
this.tabResponse.Size = new System.Drawing.Size(900, 182);
this.tabResponse.TabIndex = 1;
this.tabResponse.Text = "Response Headers";
this.tabResponse.UseVisualStyleBackColor = true;
//
// tbResponse
//
this.tbResponse.Dock = System.Windows.Forms.DockStyle.Fill;
this.tbResponse.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbResponse.Location = new System.Drawing.Point(4, 4);
this.tbResponse.Margin = new System.Windows.Forms.Padding(4);
this.tbResponse.Multiline = true;
this.tbResponse.Name = "tbResponse";
this.tbResponse.ReadOnly = true;
this.tbResponse.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.tbResponse.Size = new System.Drawing.Size(892, 174);
this.tbResponse.TabIndex = 0;
//
// tabPageRequestOptions
//
this.tabPageRequestOptions.Controls.Add(this.labelPartitionKey);
this.tabPageRequestOptions.Controls.Add(this.tbPartitionKeyForRequestOption);
this.tabPageRequestOptions.Controls.Add(this.cbRequestOptionsApply);
this.tabPageRequestOptions.Controls.Add(this.labelPostTrigger);
this.tabPageRequestOptions.Controls.Add(this.tbPostTrigger);
this.tabPageRequestOptions.Controls.Add(this.label1);
this.tabPageRequestOptions.Controls.Add(this.tbPreTrigger);
this.tabPageRequestOptions.Controls.Add(this.groupBox3);
this.tabPageRequestOptions.Controls.Add(this.groupBox2);
this.tabPageRequestOptions.Controls.Add(this.groupBox1);
this.tabPageRequestOptions.Location = new System.Drawing.Point(4, 22);
this.tabPageRequestOptions.Name = "tabPageRequestOptions";
this.tabPageRequestOptions.Padding = new System.Windows.Forms.Padding(3);
this.tabPageRequestOptions.Size = new System.Drawing.Size(900, 182);
this.tabPageRequestOptions.TabIndex = 3;
this.tabPageRequestOptions.Text = "RequestOptions";
this.tabPageRequestOptions.UseVisualStyleBackColor = true;
//
// labelPartitionKey
//
this.labelPartitionKey.AutoSize = true;
this.labelPartitionKey.Location = new System.Drawing.Point(584, 93);
this.labelPartitionKey.Name = "labelPartitionKey";
this.labelPartitionKey.Size = new System.Drawing.Size(84, 17);
this.labelPartitionKey.TabIndex = 9;
this.labelPartitionKey.Text = "PartitionKey";
//
// tbPartitionKeyForRequestOption
//
this.tbPartitionKeyForRequestOption.Location = new System.Drawing.Point(584, 111);
this.tbPartitionKeyForRequestOption.Name = "tbPartitionKeyForRequestOption";
this.tbPartitionKeyForRequestOption.Size = new System.Drawing.Size(348, 23);
this.tbPartitionKeyForRequestOption.TabIndex = 8;
//
// cbRequestOptionsApply
//
this.cbRequestOptionsApply.AutoSize = true;
this.cbRequestOptionsApply.Checked = true;
this.cbRequestOptionsApply.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbRequestOptionsApply.Location = new System.Drawing.Point(10, 10);
this.cbRequestOptionsApply.Name = "cbRequestOptionsApply";
this.cbRequestOptionsApply.Size = new System.Drawing.Size(99, 21);
this.cbRequestOptionsApply.TabIndex = 7;
this.cbRequestOptionsApply.Text = "Use default";
this.cbRequestOptionsApply.UseVisualStyleBackColor = true;
this.cbRequestOptionsApply.CheckedChanged += new System.EventHandler(this.cbRequestOptionsApply_CheckedChanged);
//
// labelPostTrigger
//
this.labelPostTrigger.AutoSize = true;
this.labelPostTrigger.Location = new System.Drawing.Point(585, 49);
this.labelPostTrigger.Name = "labelPostTrigger";
this.labelPostTrigger.Size = new System.Drawing.Size(82, 17);
this.labelPostTrigger.TabIndex = 6;
this.labelPostTrigger.Text = "PostTrigger";
//
// tbPostTrigger
//
this.tbPostTrigger.Location = new System.Drawing.Point(585, 67);
this.tbPostTrigger.Name = "tbPostTrigger";
this.tbPostTrigger.Size = new System.Drawing.Size(348, 23);
this.tbPostTrigger.TabIndex = 5;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(585, 5);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(76, 17);
this.label1.TabIndex = 4;
this.label1.Text = "PreTrigger";
//
// tbPreTrigger
//
this.tbPreTrigger.Location = new System.Drawing.Point(584, 23);
this.tbPreTrigger.Name = "tbPreTrigger";
this.tbPreTrigger.Size = new System.Drawing.Size(348, 23);
this.tbPreTrigger.TabIndex = 3;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.rbConsistencyEventual);
this.groupBox3.Controls.Add(this.rbConsistencySession);
this.groupBox3.Controls.Add(this.rbConsistencyBound);
this.groupBox3.Controls.Add(this.rbConsistencyStrong);
this.groupBox3.Location = new System.Drawing.Point(378, 6);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(200, 131);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "ConsistencyLevel";
//
// rbConsistencyEventual
//
this.rbConsistencyEventual.AutoSize = true;
this.rbConsistencyEventual.Location = new System.Drawing.Point(6, 102);
this.rbConsistencyEventual.Name = "rbConsistencyEventual";
this.rbConsistencyEventual.Size = new System.Drawing.Size(81, 21);
this.rbConsistencyEventual.TabIndex = 7;
this.rbConsistencyEventual.Text = "Eventual";
this.rbConsistencyEventual.UseVisualStyleBackColor = true;
this.rbConsistencyEventual.CheckedChanged += new System.EventHandler(this.rbConsistencyEventual_CheckedChanged);
//
// rbConsistencySession
//
this.rbConsistencySession.AutoSize = true;
this.rbConsistencySession.Checked = true;
this.rbConsistencySession.Location = new System.Drawing.Point(6, 76);
this.rbConsistencySession.Name = "rbConsistencySession";
this.rbConsistencySession.Size = new System.Drawing.Size(76, 21);
this.rbConsistencySession.TabIndex = 6;
this.rbConsistencySession.TabStop = true;
this.rbConsistencySession.Text = "Session";
this.rbConsistencySession.UseVisualStyleBackColor = true;
this.rbConsistencySession.CheckedChanged += new System.EventHandler(this.rbConsistencySession_CheckedChanged);
//
// rbConsistencyBound
//
this.rbConsistencyBound.AutoSize = true;
this.rbConsistencyBound.Location = new System.Drawing.Point(6, 49);
this.rbConsistencyBound.Name = "rbConsistencyBound";
this.rbConsistencyBound.Size = new System.Drawing.Size(145, 21);
this.rbConsistencyBound.TabIndex = 5;
this.rbConsistencyBound.Text = "BoundedStaleness";
this.rbConsistencyBound.UseVisualStyleBackColor = true;
this.rbConsistencyBound.CheckedChanged += new System.EventHandler(this.rbConsistencyBound_CheckedChanged);
//
// rbConsistencyStrong
//
this.rbConsistencyStrong.AutoSize = true;
this.rbConsistencyStrong.Location = new System.Drawing.Point(6, 22);
this.rbConsistencyStrong.Name = "rbConsistencyStrong";
this.rbConsistencyStrong.Size = new System.Drawing.Size(68, 21);
this.rbConsistencyStrong.TabIndex = 4;
this.rbConsistencyStrong.Text = "Strong";
this.rbConsistencyStrong.UseVisualStyleBackColor = true;
this.rbConsistencyStrong.CheckedChanged += new System.EventHandler(this.rbConsistencyStrong_CheckedChanged);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.rbAccessConditionIfNoneMatch);
this.groupBox2.Controls.Add(this.rbAccessConditionIfMatch);
this.groupBox2.Controls.Add(this.tbAccessConditionText);
this.groupBox2.Location = new System.Drawing.Point(161, 37);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(200, 100);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "AccessCondition";
//
// rbAccessConditionIfNoneMatch
//
this.rbAccessConditionIfNoneMatch.AutoSize = true;
this.rbAccessConditionIfNoneMatch.Location = new System.Drawing.Point(17, 46);
this.rbAccessConditionIfNoneMatch.Name = "rbAccessConditionIfNoneMatch";
this.rbAccessConditionIfNoneMatch.Size = new System.Drawing.Size(105, 21);
this.rbAccessConditionIfNoneMatch.TabIndex = 4;
this.rbAccessConditionIfNoneMatch.Text = "IfNoneMatch";
this.rbAccessConditionIfNoneMatch.UseVisualStyleBackColor = true;
this.rbAccessConditionIfNoneMatch.CheckedChanged += new System.EventHandler(this.rbAccessConditionIfNoneMatch_CheckedChanged);
//
// rbAccessConditionIfMatch
//
this.rbAccessConditionIfMatch.AutoSize = true;
this.rbAccessConditionIfMatch.Checked = true;
this.rbAccessConditionIfMatch.Location = new System.Drawing.Point(17, 22);
this.rbAccessConditionIfMatch.Name = "rbAccessConditionIfMatch";
this.rbAccessConditionIfMatch.Size = new System.Drawing.Size(71, 21);
this.rbAccessConditionIfMatch.TabIndex = 3;
this.rbAccessConditionIfMatch.TabStop = true;
this.rbAccessConditionIfMatch.Text = "IfMatch";
this.rbAccessConditionIfMatch.UseVisualStyleBackColor = true;
this.rbAccessConditionIfMatch.CheckedChanged += new System.EventHandler(this.rbAccessConditionIfMatch_CheckedChanged);
//
// tbAccessConditionText
//
this.tbAccessConditionText.Location = new System.Drawing.Point(17, 67);
this.tbAccessConditionText.Name = "tbAccessConditionText";
this.tbAccessConditionText.Size = new System.Drawing.Size(177, 23);
this.tbAccessConditionText.TabIndex = 2;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rbIndexingExclude);
this.groupBox1.Controls.Add(this.rbIndexingInclude);
this.groupBox1.Controls.Add(this.rbIndexingDefault);
this.groupBox1.Location = new System.Drawing.Point(3, 37);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(149, 94);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "IndexingDirective";
//
// rbIndexingExclude
//
this.rbIndexingExclude.AutoSize = true;
this.rbIndexingExclude.Location = new System.Drawing.Point(7, 71);
this.rbIndexingExclude.Name = "rbIndexingExclude";
this.rbIndexingExclude.Size = new System.Drawing.Size(75, 21);
this.rbIndexingExclude.TabIndex = 2;
this.rbIndexingExclude.Text = "Exclude";
this.rbIndexingExclude.UseVisualStyleBackColor = true;
this.rbIndexingExclude.CheckedChanged += new System.EventHandler(this.rbIndexingExclude_CheckedChanged);
//
// rbIndexingInclude
//
this.rbIndexingInclude.AutoSize = true;
this.rbIndexingInclude.Location = new System.Drawing.Point(7, 46);
this.rbIndexingInclude.Name = "rbIndexingInclude";
this.rbIndexingInclude.Size = new System.Drawing.Size(71, 21);
this.rbIndexingInclude.TabIndex = 1;
this.rbIndexingInclude.Text = "Include";
this.rbIndexingInclude.UseVisualStyleBackColor = true;
this.rbIndexingInclude.CheckedChanged += new System.EventHandler(this.rbIndexingInclude_CheckedChanged);
//
// rbIndexingDefault
//
this.rbIndexingDefault.AutoSize = true;
this.rbIndexingDefault.Checked = true;
this.rbIndexingDefault.Location = new System.Drawing.Point(7, 23);
this.rbIndexingDefault.Name = "rbIndexingDefault";
this.rbIndexingDefault.Size = new System.Drawing.Size(71, 21);
this.rbIndexingDefault.TabIndex = 0;
this.rbIndexingDefault.TabStop = true;
this.rbIndexingDefault.Text = "Default";
this.rbIndexingDefault.UseVisualStyleBackColor = true;
this.rbIndexingDefault.CheckedChanged += new System.EventHandler(this.rbIndexingDefault_CheckedChanged);
//
// tabDocumentCollection
//
this.tabDocumentCollection.Controls.Add(this.btnRemoveExcludedPath);
this.tabDocumentCollection.Controls.Add(this.btnAddExcludedPath);
this.tabDocumentCollection.Controls.Add(this.label3);
this.tabDocumentCollection.Controls.Add(this.groupBox4);
this.tabDocumentCollection.Controls.Add(this.lbExcludedPath);
this.tabDocumentCollection.Controls.Add(this.btnEdit);
this.tabDocumentCollection.Controls.Add(this.btnRemovePath);
this.tabDocumentCollection.Controls.Add(this.label2);
this.tabDocumentCollection.Controls.Add(this.btnAddIncludePath);
this.tabDocumentCollection.Controls.Add(this.lbIncludedPath);
this.tabDocumentCollection.Controls.Add(this.labelCollectionId);
this.tabDocumentCollection.Controls.Add(this.tbCollectionId);
this.tabDocumentCollection.Controls.Add(this.cbIndexingPolicyDefault);
this.tabDocumentCollection.Controls.Add(this.cbAutomatic);
this.tabDocumentCollection.Location = new System.Drawing.Point(4, 22);
this.tabDocumentCollection.Name = "tabDocumentCollection";
this.tabDocumentCollection.Padding = new System.Windows.Forms.Padding(3);
this.tabDocumentCollection.Size = new System.Drawing.Size(900, 182);
this.tabDocumentCollection.TabIndex = 4;
this.tabDocumentCollection.Text = "DocumentCollection";
this.tabDocumentCollection.UseVisualStyleBackColor = true;
//
// btnRemoveExcludedPath
//
this.btnRemoveExcludedPath.Enabled = false;
this.btnRemoveExcludedPath.Location = new System.Drawing.Point(688, 102);
this.btnRemoveExcludedPath.Name = "btnRemoveExcludedPath";
this.btnRemoveExcludedPath.Size = new System.Drawing.Size(75, 23);
this.btnRemoveExcludedPath.TabIndex = 13;
this.btnRemoveExcludedPath.Text = "Remove";
this.btnRemoveExcludedPath.UseVisualStyleBackColor = true;
this.btnRemoveExcludedPath.Click += new System.EventHandler(this.btnRemoveExcludedPath_Click);
//
// btnAddExcludedPath
//
this.btnAddExcludedPath.Location = new System.Drawing.Point(594, 102);
this.btnAddExcludedPath.Name = "btnAddExcludedPath";
this.btnAddExcludedPath.Size = new System.Drawing.Size(76, 23);
this.btnAddExcludedPath.TabIndex = 12;
this.btnAddExcludedPath.Text = "Add";
this.btnAddExcludedPath.UseVisualStyleBackColor = true;
this.btnAddExcludedPath.Click += new System.EventHandler(this.btnAddExcludedPath_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(591, 6);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(98, 17);
this.label3.TabIndex = 11;
this.label3.Text = "Excluded Path";
//
// groupBox4
//
this.groupBox4.Controls.Add(this.rbLazy);
this.groupBox4.Controls.Add(this.rbConsistent);
this.groupBox4.Location = new System.Drawing.Point(202, 6);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(120, 81);
this.groupBox4.TabIndex = 1;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "IndexingMode";
//
// rbLazy
//
this.rbLazy.AutoSize = true;
this.rbLazy.Location = new System.Drawing.Point(6, 49);
this.rbLazy.Name = "rbLazy";
this.rbLazy.Size = new System.Drawing.Size(56, 21);
this.rbLazy.TabIndex = 1;
this.rbLazy.Text = "Lazy";
this.rbLazy.UseVisualStyleBackColor = true;
this.rbLazy.CheckedChanged += new System.EventHandler(this.rbLazy_CheckedChanged);
//
// rbConsistent
//
this.rbConsistent.AutoSize = true;
this.rbConsistent.Checked = true;
this.rbConsistent.Location = new System.Drawing.Point(6, 22);
this.rbConsistent.Name = "rbConsistent";
this.rbConsistent.Size = new System.Drawing.Size(92, 21);
this.rbConsistent.TabIndex = 0;
this.rbConsistent.TabStop = true;
this.rbConsistent.Text = "Consistent";
this.rbConsistent.UseVisualStyleBackColor = true;
this.rbConsistent.CheckedChanged += new System.EventHandler(this.rbConsistent_CheckedChanged);
//
// lbExcludedPath
//
this.lbExcludedPath.FormattingEnabled = true;
this.lbExcludedPath.ItemHeight = 17;
this.lbExcludedPath.Location = new System.Drawing.Point(594, 24);
this.lbExcludedPath.Name = "lbExcludedPath";
this.lbExcludedPath.Size = new System.Drawing.Size(172, 72);
this.lbExcludedPath.TabIndex = 10;
this.lbExcludedPath.SelectedIndexChanged += new System.EventHandler(this.lbExcludedPath_SelectedIndexChanged);
//
// btnEdit
//
this.btnEdit.Enabled = false;
this.btnEdit.Location = new System.Drawing.Point(497, 102);
this.btnEdit.Name = "btnEdit";
this.btnEdit.Size = new System.Drawing.Size(81, 23);
this.btnEdit.TabIndex = 9;
this.btnEdit.Text = "Edit";
this.btnEdit.UseVisualStyleBackColor = true;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// btnRemovePath
//
this.btnRemovePath.Enabled = false;
this.btnRemovePath.Location = new System.Drawing.Point(416, 102);
this.btnRemovePath.Name = "btnRemovePath";
this.btnRemovePath.Size = new System.Drawing.Size(75, 23);
this.btnRemovePath.TabIndex = 8;
this.btnRemovePath.Text = "Remove";
this.btnRemovePath.UseVisualStyleBackColor = true;
this.btnRemovePath.Click += new System.EventHandler(this.btnRemovePath_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(331, 6);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(94, 17);
this.label2.TabIndex = 7;
this.label2.Text = "Included Path";
//
// btnAddIncludePath
//
this.btnAddIncludePath.Location = new System.Drawing.Point(334, 102);
this.btnAddIncludePath.Name = "btnAddIncludePath";
this.btnAddIncludePath.Size = new System.Drawing.Size(76, 23);
this.btnAddIncludePath.TabIndex = 6;
this.btnAddIncludePath.Text = "Add";
this.btnAddIncludePath.UseVisualStyleBackColor = true;
this.btnAddIncludePath.Click += new System.EventHandler(this.btnAddIncludePath_Click);
//
// lbIncludedPath
//
this.lbIncludedPath.FormattingEnabled = true;
this.lbIncludedPath.ItemHeight = 17;
this.lbIncludedPath.Location = new System.Drawing.Point(334, 24);
this.lbIncludedPath.Name = "lbIncludedPath";
this.lbIncludedPath.Size = new System.Drawing.Size(244, 72);
this.lbIncludedPath.TabIndex = 5;
this.lbIncludedPath.SelectedIndexChanged += new System.EventHandler(this.lbIncludedPath_SelectedIndexChanged);
//
// labelCollectionId
//
this.labelCollectionId.AutoSize = true;
this.labelCollectionId.Location = new System.Drawing.Point(7, 10);
this.labelCollectionId.Name = "labelCollectionId";
this.labelCollectionId.Size = new System.Drawing.Size(23, 17);
this.labelCollectionId.TabIndex = 4;
this.labelCollectionId.Text = "Id:";
//
// tbCollectionId
//
this.tbCollectionId.Location = new System.Drawing.Point(36, 7);
this.tbCollectionId.Name = "tbCollectionId";
this.tbCollectionId.Size = new System.Drawing.Size(160, 23);
this.tbCollectionId.TabIndex = 3;
this.tbCollectionId.Text = "DocumentCollection Id";
//
// cbIndexingPolicyDefault
//
this.cbIndexingPolicyDefault.AutoSize = true;
this.cbIndexingPolicyDefault.Checked = true;
this.cbIndexingPolicyDefault.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbIndexingPolicyDefault.Location = new System.Drawing.Point(10, 97);
this.cbIndexingPolicyDefault.Name = "cbIndexingPolicyDefault";
this.cbIndexingPolicyDefault.Size = new System.Drawing.Size(72, 21);
this.cbIndexingPolicyDefault.TabIndex = 2;
this.cbIndexingPolicyDefault.Text = "Default";
this.cbIndexingPolicyDefault.UseVisualStyleBackColor = true;
this.cbIndexingPolicyDefault.CheckedChanged += new System.EventHandler(this.cbIndexingPolicyDefault_CheckedChanged);
//
// cbAutomatic
//
this.cbAutomatic.AutoSize = true;
this.cbAutomatic.Checked = true;
this.cbAutomatic.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbAutomatic.Location = new System.Drawing.Point(88, 97);
this.cbAutomatic.Name = "cbAutomatic";
this.cbAutomatic.Size = new System.Drawing.Size(89, 21);
this.cbAutomatic.TabIndex = 0;
this.cbAutomatic.Text = "Automatic";
this.cbAutomatic.UseVisualStyleBackColor = true;
this.cbAutomatic.CheckedChanged += new System.EventHandler(this.cbAutomatic_CheckedChanged);
//
// tabOffer
//
this.tabOffer.Controls.Add(this.label5);
this.tabOffer.Controls.Add(this.gbStandardOffer);
this.tabOffer.Location = new System.Drawing.Point(4, 22);
this.tabOffer.Name = "tabOffer";
this.tabOffer.Padding = new System.Windows.Forms.Padding(3);
this.tabOffer.Size = new System.Drawing.Size(900, 182);
this.tabOffer.TabIndex = 5;
this.tabOffer.Text = "Offer";
this.tabOffer.UseVisualStyleBackColor = true;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 6);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(365, 17);
this.label5.TabIndex = 24;
this.label5.Text = "Please read below to understand billing on different offer";
//
// gbStandardOffer
//
this.gbStandardOffer.Controls.Add(this.labelThroughput);
this.gbStandardOffer.Controls.Add(this.tbThroughput);
this.gbStandardOffer.Controls.Add(this.label6);
this.gbStandardOffer.Controls.Add(this.cbShowLegacyOffer);
this.gbStandardOffer.Controls.Add(this.rbOfferS3);
this.gbStandardOffer.Controls.Add(this.rbElasticCollection);
this.gbStandardOffer.Controls.Add(this.rbOfferS2);
this.gbStandardOffer.Controls.Add(this.tbPartitionKeyForCollectionCreate);
this.gbStandardOffer.Controls.Add(this.rbOfferS1);
this.gbStandardOffer.Controls.Add(this.rbSinglePartition);
this.gbStandardOffer.Controls.Add(this.label4);
this.gbStandardOffer.Location = new System.Drawing.Point(15, 25);
this.gbStandardOffer.Name = "gbStandardOffer";
this.gbStandardOffer.Size = new System.Drawing.Size(733, 147);
this.gbStandardOffer.TabIndex = 23;
this.gbStandardOffer.TabStop = false;
this.gbStandardOffer.Text = "Standard Offer";
//
// labelThroughput
//
this.labelThroughput.AutoSize = true;
this.labelThroughput.Location = new System.Drawing.Point(319, 27);
this.labelThroughput.Name = "labelThroughput";
this.labelThroughput.Size = new System.Drawing.Size(222, 17);
this.labelThroughput.TabIndex = 26;
this.labelThroughput.Text = "Allowed values between 400 - 10k";
//
// tbThroughput
//
this.tbThroughput.Location = new System.Drawing.Point(114, 24);
this.tbThroughput.Name = "tbThroughput";
this.tbThroughput.Size = new System.Drawing.Size(188, 23);
this.tbThroughput.TabIndex = 25;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(16, 27);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(82, 17);
this.label6.TabIndex = 24;
this.label6.Text = "Throughput";
//
// cbShowLegacyOffer
//
this.cbShowLegacyOffer.AutoSize = true;
this.cbShowLegacyOffer.Location = new System.Drawing.Point(373, 66);
this.cbShowLegacyOffer.Name = "cbShowLegacyOffer";
this.cbShowLegacyOffer.Size = new System.Drawing.Size(147, 21);
this.cbShowLegacyOffer.TabIndex = 23;
this.cbShowLegacyOffer.Text = "Show Legacy Offer";
this.cbShowLegacyOffer.UseVisualStyleBackColor = true;
this.cbShowLegacyOffer.CheckedChanged += new System.EventHandler(this.cbShowLegacyOffer_CheckedChanged);
//
// rbOfferS3
//
this.rbOfferS3.AutoSize = true;
this.rbOfferS3.Location = new System.Drawing.Point(531, 93);
this.rbOfferS3.Name = "rbOfferS3";
this.rbOfferS3.Size = new System.Drawing.Size(43, 21);
this.rbOfferS3.TabIndex = 2;
this.rbOfferS3.Text = "S3";
this.rbOfferS3.UseVisualStyleBackColor = true;
this.rbOfferS3.Visible = false;
this.rbOfferS3.CheckedChanged += new System.EventHandler(this.rbOfferS3_CheckedChanged);
//
// rbElasticCollection
//
this.rbElasticCollection.AutoSize = true;
this.rbElasticCollection.Location = new System.Drawing.Point(19, 81);
this.rbElasticCollection.Name = "rbElasticCollection";
this.rbElasticCollection.Size = new System.Drawing.Size(94, 21);
this.rbElasticCollection.TabIndex = 2;
this.rbElasticCollection.Text = "Partitioned";
this.rbElasticCollection.UseVisualStyleBackColor = true;
this.rbElasticCollection.CheckedChanged += new System.EventHandler(this.rbElasticCollection_CheckedChanged);
//
// rbOfferS2
//
this.rbOfferS2.AutoSize = true;
this.rbOfferS2.Location = new System.Drawing.Point(466, 93);
this.rbOfferS2.Name = "rbOfferS2";
this.rbOfferS2.Size = new System.Drawing.Size(43, 21);
this.rbOfferS2.TabIndex = 1;
this.rbOfferS2.Text = "S2";
this.rbOfferS2.UseVisualStyleBackColor = true;
this.rbOfferS2.Visible = false;
this.rbOfferS2.CheckedChanged += new System.EventHandler(this.rbOfferS2_CheckedChanged);
//
// tbPartitionKeyForCollectionCreate
//
this.tbPartitionKeyForCollectionCreate.Location = new System.Drawing.Point(131, 101);
this.tbPartitionKeyForCollectionCreate.Name = "tbPartitionKeyForCollectionCreate";
this.tbPartitionKeyForCollectionCreate.Size = new System.Drawing.Size(188, 23);
this.tbPartitionKeyForCollectionCreate.TabIndex = 22;
//
// rbOfferS1
//
this.rbOfferS1.AutoSize = true;
this.rbOfferS1.Checked = true;
this.rbOfferS1.Location = new System.Drawing.Point(404, 93);
this.rbOfferS1.Name = "rbOfferS1";
this.rbOfferS1.Size = new System.Drawing.Size(43, 21);
this.rbOfferS1.TabIndex = 0;
this.rbOfferS1.TabStop = true;
this.rbOfferS1.Text = "S1";
this.rbOfferS1.UseVisualStyleBackColor = true;
this.rbOfferS1.Visible = false;
this.rbOfferS1.CheckedChanged += new System.EventHandler(this.rbOfferS1_CheckedChanged);
//
// rbSinglePartition
//
this.rbSinglePartition.AutoSize = true;
this.rbSinglePartition.Checked = true;
this.rbSinglePartition.Location = new System.Drawing.Point(19, 54);
this.rbSinglePartition.Name = "rbSinglePartition";
this.rbSinglePartition.Size = new System.Drawing.Size(121, 21);
this.rbSinglePartition.TabIndex = 0;
this.rbSinglePartition.TabStop = true;
this.rbSinglePartition.Text = "Single Partition";
this.rbSinglePartition.UseVisualStyleBackColor = true;
this.rbSinglePartition.CheckedChanged += new System.EventHandler(this.rbSinglePartition_CheckedChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(37, 105);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(88, 17);
this.label4.TabIndex = 20;
this.label4.Text = "Partition Key";
//
// ButtomSplitContainer
//
this.ButtomSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.ButtomSplitContainer.Location = new System.Drawing.Point(0, 0);
this.ButtomSplitContainer.Name = "ButtomSplitContainer";
this.ButtomSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// ButtomSplitContainer.Panel1
//
this.ButtomSplitContainer.Panel1.Controls.Add(this.triggerPanel);
this.ButtomSplitContainer.Panel1.Controls.Add(this.feedToolStrip);
this.ButtomSplitContainer.Panel1MinSize = 0;
//
// ButtomSplitContainer.Panel2
//
this.ButtomSplitContainer.Panel2.Controls.Add(this.webBrowserResponse);
this.ButtomSplitContainer.Size = new System.Drawing.Size(908, 579);
this.ButtomSplitContainer.SplitterDistance = 31;
this.ButtomSplitContainer.TabIndex = 4;
//
// triggerPanel
//
this.triggerPanel.Controls.Add(this.rbPostTrigger);
this.triggerPanel.Controls.Add(this.rbPreTrigger);
this.triggerPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.triggerPanel.Location = new System.Drawing.Point(0, 0);
this.triggerPanel.Name = "triggerPanel";
this.triggerPanel.Size = new System.Drawing.Size(908, 31);
this.triggerPanel.TabIndex = 4;
//
// rbPostTrigger
//
this.rbPostTrigger.AutoSize = true;
this.rbPostTrigger.Location = new System.Drawing.Point(119, 7);
this.rbPostTrigger.Name = "rbPostTrigger";
this.rbPostTrigger.Size = new System.Drawing.Size(100, 21);
this.rbPostTrigger.TabIndex = 1;
this.rbPostTrigger.TabStop = true;
this.rbPostTrigger.Text = "PostTrigger";
this.rbPostTrigger.UseVisualStyleBackColor = true;
//
// rbPreTrigger
//
this.rbPreTrigger.AutoSize = true;
this.rbPreTrigger.Checked = true;
this.rbPreTrigger.Location = new System.Drawing.Point(19, 7);
this.rbPreTrigger.Name = "rbPreTrigger";
this.rbPreTrigger.Size = new System.Drawing.Size(94, 21);
this.rbPreTrigger.TabIndex = 0;
this.rbPreTrigger.TabStop = true;
this.rbPreTrigger.Text = "PreTrigger";
this.rbPreTrigger.UseVisualStyleBackColor = true;
//
// feedToolStrip
//
this.feedToolStrip.Dock = System.Windows.Forms.DockStyle.Fill;
this.feedToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.feedToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.MaxItemCount,
this.toolStripTextMaxItemCount,
this.Separator1,
this.Separator2,
this.MaxDOP,
this.toolStripTextMaxDop,
this.Separator3,
this.MaxBuffItem,
this.toolStripTextMaxBuffItem,
this.Separator4,
this.btnExecuteNext});
this.feedToolStrip.Location = new System.Drawing.Point(0, 0);
this.feedToolStrip.Name = "feedToolStrip";
this.feedToolStrip.Size = new System.Drawing.Size(908, 31);
this.feedToolStrip.TabIndex = 3;
this.feedToolStrip.Text = "toolStrip1";
this.feedToolStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.feedToolStrip_ItemClicked);
//
// MaxItemCount
//
this.MaxItemCount.Name = "MaxItemCount";
this.MaxItemCount.Size = new System.Drawing.Size(78, 28);
this.MaxItemCount.Text = "MaxItemCount";
//
// toolStripTextMaxItemCount
//
this.toolStripTextMaxItemCount.Name = "toolStripTextMaxItemCount";
this.toolStripTextMaxItemCount.Size = new System.Drawing.Size(40, 31);
this.toolStripTextMaxItemCount.Text = "10";
this.toolStripTextMaxItemCount.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Separator1
//
this.Separator1.Name = "Separator1";
this.Separator1.Size = new System.Drawing.Size(6, 31);
//
// Separator2
//
this.Separator2.Name = "Separator2";
this.Separator2.Size = new System.Drawing.Size(6, 31);
//
// MaxDOP
//
this.MaxDOP.Name = "MaxDOP";
this.MaxDOP.Size = new System.Drawing.Size(48, 28);
this.MaxDOP.Text = "MaxDOP";
//
// toolStripTextMaxDop
//
this.toolStripTextMaxDop.Name = "toolStripTextMaxDop";
this.toolStripTextMaxDop.Size = new System.Drawing.Size(40, 31);
this.toolStripTextMaxDop.Text = "1";
this.toolStripTextMaxDop.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Separator3
//
this.Separator3.Name = "Separator3";
this.Separator3.Size = new System.Drawing.Size(6, 31);
//
// MaxBuffItem
//
this.MaxBuffItem.Name = "MaxBuffItem";
this.MaxBuffItem.Size = new System.Drawing.Size(69, 28);
this.MaxBuffItem.Text = "MaxBuffItem";
//
// toolStripTextMaxBuffItem
//
this.toolStripTextMaxBuffItem.Name = "toolStripTextMaxBuffItem";
this.toolStripTextMaxBuffItem.Size = new System.Drawing.Size(40, 31);
this.toolStripTextMaxBuffItem.Text = "100";
this.toolStripTextMaxBuffItem.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Separator4
//
this.Separator4.Name = "Separator4";
this.Separator4.Size = new System.Drawing.Size(6, 31);
//
// btnExecuteNext
//
this.btnExecuteNext.Image = global::Microsoft.Azure.DocumentDBStudio.Properties.Resources.NextPagepng;
this.btnExecuteNext.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnExecuteNext.MergeAction = System.Windows.Forms.MergeAction.Insert;
this.btnExecuteNext.Name = "btnExecuteNext";
this.btnExecuteNext.Size = new System.Drawing.Size(77, 28);
this.btnExecuteNext.Text = "Next Page";
this.btnExecuteNext.Click += new System.EventHandler(this.btnExecuteNext_Click);
//
// webBrowserResponse
//
this.webBrowserResponse.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowserResponse.Location = new System.Drawing.Point(0, 0);
this.webBrowserResponse.Margin = new System.Windows.Forms.Padding(4);
this.webBrowserResponse.MinimumSize = new System.Drawing.Size(27, 26);
this.webBrowserResponse.Name = "webBrowserResponse";
this.webBrowserResponse.Size = new System.Drawing.Size(908, 544);
this.webBrowserResponse.TabIndex = 0;
//
// tsMenu
//
this.tsMenu.BackColor = System.Drawing.SystemColors.Control;
this.tsMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnBack,
this.btnForward,
this.btnHome,
this.toolStripBtnExecute,
this.btnRefresh,
this.toolStripSeparator1,
this.btnHeaders,
this.btnEditRequests,
this.tsbViewType,
this.tsbHideDocumentSystemProperties});
this.tsMenu.Location = new System.Drawing.Point(0, 25);
this.tsMenu.Name = "tsMenu";
this.tsMenu.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.tsMenu.Size = new System.Drawing.Size(1372, 25);
this.tsMenu.TabIndex = 3;
this.tsMenu.Text = "toolStrip2";
//
// btnBack
//
this.btnBack.Image = global::Microsoft.Azure.DocumentDBStudio.Properties.Resources.NavBack;
this.btnBack.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnBack.Name = "btnBack";
this.btnBack.Size = new System.Drawing.Size(49, 22);
this.btnBack.Text = "Back";
//
// btnForward
//
this.btnForward.Enabled = false;
this.btnForward.Image = global::Microsoft.Azure.DocumentDBStudio.Properties.Resources.NavForward;
this.btnForward.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnForward.Name = "btnForward";
this.btnForward.Size = new System.Drawing.Size(67, 22);
this.btnForward.Text = "Forward";
//
// btnHome
//
this.btnHome.Image = global::Microsoft.Azure.DocumentDBStudio.Properties.Resources.HomeHS;
this.btnHome.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnHome.Name = "btnHome";
this.btnHome.Size = new System.Drawing.Size(54, 22);
this.btnHome.Text = "Home";
this.btnHome.Click += new System.EventHandler(this.btnHome_Click);
//
// toolStripBtnExecute
//
this.toolStripBtnExecute.Image = ((System.Drawing.Image)(resources.GetObject("toolStripBtnExecute.Image")));
this.toolStripBtnExecute.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripBtnExecute.Name = "toolStripBtnExecute";
this.toolStripBtnExecute.Size = new System.Drawing.Size(66, 22);
this.toolStripBtnExecute.Text = "Execute";
this.toolStripBtnExecute.Click += new System.EventHandler(this.toolStripBtnExecute_Click);
//
// btnRefresh
//
this.btnRefresh.Image = global::Microsoft.Azure.DocumentDBStudio.Properties.Resources.RefreshDocViewHS;
this.btnRefresh.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(65, 22);
this.btnRefresh.Text = "Refresh";
this.btnRefresh.Visible = false;
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnHeaders
//
this.btnHeaders.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnHeaders.Image = ((System.Drawing.Image)(resources.GetObject("btnHeaders.Image")));
this.btnHeaders.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnHeaders.Name = "btnHeaders";
this.btnHeaders.Size = new System.Drawing.Size(130, 22);
this.btnHeaders.Text = "Show Response Headers";
this.btnHeaders.ToolTipText = "Show response headers";
this.btnHeaders.Click += new System.EventHandler(this.btnHeaders_Click);
//
// btnEditRequests
//
this.btnEditRequests.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnEditRequests.Image = ((System.Drawing.Image)(resources.GetObject("btnEditRequests.Image")));
this.btnEditRequests.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnEditRequests.Name = "btnEditRequests";
this.btnEditRequests.Size = new System.Drawing.Size(72, 22);
this.btnEditRequests.Text = "Edit Request";
this.btnEditRequests.ToolTipText = "Edit next request (Ctrl+Click)";
this.btnEditRequests.Visible = false;
//
// tsbViewType
//
this.tsbViewType.CheckOnClick = true;
this.tsbViewType.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.tsbViewType.Image = ((System.Drawing.Image)(resources.GetObject("tsbViewType.Image")));
this.tsbViewType.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbViewType.Name = "tsbViewType";
this.tsbViewType.Size = new System.Drawing.Size(58, 22);
this.tsbViewType.Text = "Text View";
this.tsbViewType.Click += new System.EventHandler(this.tsbViewType_Click);
//
// tsbHideDocumentSystemProperties
//
this.tsbHideDocumentSystemProperties.CheckOnClick = true;
this.tsbHideDocumentSystemProperties.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.tsbHideDocumentSystemProperties.Image = ((System.Drawing.Image)(resources.GetObject("tsbHideDocumentSystemProperties.Image")));
this.tsbHideDocumentSystemProperties.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbHideDocumentSystemProperties.Name = "tsbHideDocumentSystemProperties";
this.tsbHideDocumentSystemProperties.Size = new System.Drawing.Size(125, 22);
this.tsbHideDocumentSystemProperties.Text = "Show System resources";
this.tsbHideDocumentSystemProperties.Click += new System.EventHandler(this.tsbHideDocumentSystemProperties_Click);
//
// tsAddress
//
this.tsAddress.AutoSize = false;
this.tsAddress.BackColor = System.Drawing.SystemColors.Control;
this.tsAddress.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsLabelUrl,
this.cbUrl,
this.btnGo});
this.tsAddress.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
this.tsAddress.Location = new System.Drawing.Point(0, 50);
this.tsAddress.Name = "tsAddress";
this.tsAddress.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.tsAddress.Size = new System.Drawing.Size(1428, 33);
this.tsAddress.TabIndex = 6;
this.tsAddress.Text = "toolStrip3";
this.tsAddress.Visible = false;
//
// tsLabelUrl
//
this.tsLabelUrl.Name = "tsLabelUrl";
this.tsLabelUrl.Size = new System.Drawing.Size(33, 30);
this.tsLabelUrl.Text = "URL: ";
//
// cbUrl
//
this.cbUrl.AutoSize = false;
this.cbUrl.MaxDropDownItems = 1;
this.cbUrl.Name = "cbUrl";
this.cbUrl.Size = new System.Drawing.Size(300, 21);
//
// btnGo
//
this.btnGo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnGo.Image = ((System.Drawing.Image)(resources.GetObject("btnGo.Image")));
this.btnGo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGo.Name = "btnGo";
this.btnGo.Size = new System.Drawing.Size(24, 30);
this.btnGo.Text = "Go";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Padding = new System.Windows.Forms.Padding(8, 3, 0, 3);
this.menuStrip1.Size = new System.Drawing.Size(1372, 25);
this.menuStrip1.TabIndex = 5;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.optionsToolStripMenuItem,
this.settingsToolStripMenuItem,
this.toolStripSeparator4,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 19);
this.fileToolStripMenuItem.Text = "&File";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.optionsToolStripMenuItem.Text = "&Add Account";
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 19);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.aboutToolStripMenuItem.Text = "&About";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// tsTablesEntities
//
this.tsTablesEntities.AutoSize = false;
this.tsTablesEntities.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnQueryTable,
this.btnCreateTable,
this.btnDeleteTable,
this.toolStripSeparator2,
this.btnQueryEntities,
this.btnNextPage,
this.btnInsertEntity,
this.btnUpdateEntity,
this.tsbMergeEntity,
this.btnDeleteEntity,
this.toolStripSeparator3,
this.tsbEditTemplate});
this.tsTablesEntities.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
this.tsTablesEntities.Location = new System.Drawing.Point(0, 0);
this.tsTablesEntities.Name = "tsTablesEntities";
this.tsTablesEntities.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.tsTablesEntities.Size = new System.Drawing.Size(1488, 33);
this.tsTablesEntities.TabIndex = 4;
this.tsTablesEntities.Text = "toolStrip1";
this.tsTablesEntities.Visible = false;
//
// btnQueryTable
//
this.btnQueryTable.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnQueryTable.Image = ((System.Drawing.Image)(resources.GetObject("btnQueryTable.Image")));
this.btnQueryTable.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnQueryTable.Name = "btnQueryTable";
this.btnQueryTable.Size = new System.Drawing.Size(47, 30);
this.btnQueryTable.Text = "QueryT";
this.btnQueryTable.ToolTipText = "QueryTable";
//
// btnCreateTable
//
this.btnCreateTable.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnCreateTable.Image = ((System.Drawing.Image)(resources.GetObject("btnCreateTable.Image")));
this.btnCreateTable.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCreateTable.Name = "btnCreateTable";
this.btnCreateTable.Size = new System.Drawing.Size(50, 30);
this.btnCreateTable.Text = "CreateT";
this.btnCreateTable.ToolTipText = "CreateTable";
//
// btnDeleteTable
//
this.btnDeleteTable.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnDeleteTable.Image = ((System.Drawing.Image)(resources.GetObject("btnDeleteTable.Image")));
this.btnDeleteTable.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnDeleteTable.Name = "btnDeleteTable";
this.btnDeleteTable.Size = new System.Drawing.Size(48, 30);
this.btnDeleteTable.Text = "DeleteT";
this.btnDeleteTable.ToolTipText = "DeleteTable";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 33);
//
// btnQueryEntities
//
this.btnQueryEntities.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnQueryEntities.Image = ((System.Drawing.Image)(resources.GetObject("btnQueryEntities.Image")));
this.btnQueryEntities.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnQueryEntities.Name = "btnQueryEntities";
this.btnQueryEntities.Size = new System.Drawing.Size(47, 30);
this.btnQueryEntities.Text = "QueryE";
this.btnQueryEntities.ToolTipText = "QueryEntities";
//
// btnNextPage
//
this.btnNextPage.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnNextPage.Enabled = false;
this.btnNextPage.Image = ((System.Drawing.Image)(resources.GetObject("btnNextPage.Image")));
this.btnNextPage.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnNextPage.Name = "btnNextPage";
this.btnNextPage.Size = new System.Drawing.Size(58, 30);
this.btnNextPage.Text = "NextPage";
//
// btnInsertEntity
//
this.btnInsertEntity.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnInsertEntity.Image = ((System.Drawing.Image)(resources.GetObject("btnInsertEntity.Image")));
this.btnInsertEntity.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnInsertEntity.Name = "btnInsertEntity";
this.btnInsertEntity.Size = new System.Drawing.Size(46, 30);
this.btnInsertEntity.Text = "InsertE";
this.btnInsertEntity.ToolTipText = "InsertEntity";
//
// btnUpdateEntity
//
this.btnUpdateEntity.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnUpdateEntity.Image = ((System.Drawing.Image)(resources.GetObject("btnUpdateEntity.Image")));
this.btnUpdateEntity.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnUpdateEntity.Name = "btnUpdateEntity";
this.btnUpdateEntity.Size = new System.Drawing.Size(52, 30);
this.btnUpdateEntity.Text = "UpdateE";
this.btnUpdateEntity.ToolTipText = "UpdateEntity";
//
// tsbMergeEntity
//
this.tsbMergeEntity.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.tsbMergeEntity.Image = ((System.Drawing.Image)(resources.GetObject("tsbMergeEntity.Image")));
this.tsbMergeEntity.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbMergeEntity.Name = "tsbMergeEntity";
this.tsbMergeEntity.Size = new System.Drawing.Size(47, 30);
this.tsbMergeEntity.Text = "MergeE";
//
// btnDeleteEntity
//
this.btnDeleteEntity.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnDeleteEntity.Image = ((System.Drawing.Image)(resources.GetObject("btnDeleteEntity.Image")));
this.btnDeleteEntity.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnDeleteEntity.Name = "btnDeleteEntity";
this.btnDeleteEntity.Size = new System.Drawing.Size(48, 30);
this.btnDeleteEntity.Text = "DeleteE";
this.btnDeleteEntity.ToolTipText = "DeleteEntity";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 33);
//
// tsbEditTemplate
//
this.tsbEditTemplate.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.tsbEditTemplate.Image = ((System.Drawing.Image)(resources.GetObject("tsbEditTemplate.Image")));
this.tsbEditTemplate.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbEditTemplate.Name = "tsbEditTemplate";
this.tsbEditTemplate.Size = new System.Drawing.Size(76, 30);
this.tsbEditTemplate.Text = "Edit Template";
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.settingsToolStripMenuItem.Text = "Settings...";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click_1);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(149, 6);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1372, 865);
this.Controls.Add(this.splitContainerOuter);
this.Controls.Add(this.tsAddress);
this.Controls.Add(this.tsMenu);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.tsTablesEntities);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "MainForm";
this.Text = "Azure DocumentDB Studio";
this.Load += new System.EventHandler(this.MainForm_Load);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.splitContainerOuter.Panel1.ResumeLayout(false);
this.splitContainerOuter.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainerOuter)).EndInit();
this.splitContainerOuter.ResumeLayout(false);
this.splitContainerInner.Panel1.ResumeLayout(false);
this.splitContainerInner.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainerInner)).EndInit();
this.splitContainerInner.ResumeLayout(false);
this.tabControl.ResumeLayout(false);
this.tabRequest.ResumeLayout(false);
this.tabRequest.PerformLayout();
this.tabCrudContext.ResumeLayout(false);
this.splitContainerIntabPage.Panel1.ResumeLayout(false);
this.splitContainerIntabPage.Panel1.PerformLayout();
this.splitContainerIntabPage.Panel2.ResumeLayout(false);
this.splitContainerIntabPage.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainerIntabPage)).EndInit();
this.splitContainerIntabPage.ResumeLayout(false);
this.tabResponse.ResumeLayout(false);
this.tabResponse.PerformLayout();
this.tabPageRequestOptions.ResumeLayout(false);
this.tabPageRequestOptions.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tabDocumentCollection.ResumeLayout(false);
this.tabDocumentCollection.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.tabOffer.ResumeLayout(false);
this.tabOffer.PerformLayout();
this.gbStandardOffer.ResumeLayout(false);
this.gbStandardOffer.PerformLayout();
this.ButtomSplitContainer.Panel1.ResumeLayout(false);
this.ButtomSplitContainer.Panel1.PerformLayout();
this.ButtomSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.ButtomSplitContainer)).EndInit();
this.ButtomSplitContainer.ResumeLayout(false);
this.triggerPanel.ResumeLayout(false);
this.triggerPanel.PerformLayout();
this.feedToolStrip.ResumeLayout(false);
this.feedToolStrip.PerformLayout();
this.tsMenu.ResumeLayout(false);
this.tsMenu.PerformLayout();
this.tsAddress.ResumeLayout(false);
this.tsAddress.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.tsTablesEntities.ResumeLayout(false);
this.tsTablesEntities.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.SplitContainer splitContainerOuter;
private System.Windows.Forms.SplitContainer splitContainerInner;
//private System.Windows.Forms.WebBrowser webBrowserResponse;
private System.Windows.Forms.WebBrowser webBrowserResponse;
private System.Windows.Forms.ToolStripStatusLabel tsStatus;
private System.Windows.Forms.ToolStrip tsMenu;
private System.Windows.Forms.ToolStrip tsAddress;
private System.Windows.Forms.ToolStripLabel tsLabelUrl;
private System.Windows.Forms.ToolStripButton btnGo;
private System.Windows.Forms.ToolStripSplitButton tsButtonZoom;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton btnBack;
private System.Windows.Forms.ToolStripComboBox cbUrl;
private System.Windows.Forms.ToolStripProgressBar tsProgress;
private System.Windows.Forms.ToolStripButton btnHeaders;
private System.Windows.Forms.ToolStripButton btnHome;
private System.Windows.Forms.ToolStripButton btnEditRequests;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.TabPage tabRequest;
private System.Windows.Forms.TabPage tabResponse;
private System.Windows.Forms.TextBox tbRequest;
private System.Windows.Forms.TextBox tbResponse;
private System.Windows.Forms.ToolStripButton btnForward;
private System.Windows.Forms.ToolStripButton btnRefresh;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStrip tsTablesEntities;
private System.Windows.Forms.ToolStripButton btnQueryTable;
private System.Windows.Forms.ToolStripButton btnCreateTable;
private System.Windows.Forms.ToolStripButton btnDeleteTable;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripButton btnQueryEntities;
private System.Windows.Forms.ToolStripButton btnInsertEntity;
private System.Windows.Forms.ToolStripButton btnUpdateEntity;
private System.Windows.Forms.ToolStripButton btnDeleteEntity;
private System.Windows.Forms.ToolStripButton btnNextPage;
private System.Windows.Forms.ToolStripButton tsbViewType;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripButton tsbMergeEntity;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripButton tsbEditTemplate;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.TabPage tabCrudContext;
private System.Windows.Forms.TextBox tbCrudContext;
private System.Windows.Forms.ToolStripButton toolStripBtnExecute;
private System.Windows.Forms.TextBox textBoxforId;
private System.Windows.Forms.SplitContainer splitContainerIntabPage;
private System.Windows.Forms.Label labelid;
private System.Windows.Forms.TabPage tabPageRequestOptions;
private System.Windows.Forms.ToolStrip feedToolStrip;
private System.Windows.Forms.ToolStripTextBox toolStripTextMaxItemCount;
private System.Windows.Forms.ToolStripTextBox toolStripTextMaxDop;
private System.Windows.Forms.ToolStripTextBox toolStripTextMaxBuffItem;
private System.Windows.Forms.ToolStripButton btnExecuteNext;
private System.Windows.Forms.SplitContainer ButtomSplitContainer;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox tbAccessConditionText;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.CheckBox cbRequestOptionsApply;
private System.Windows.Forms.Label labelPostTrigger;
private System.Windows.Forms.TextBox tbPostTrigger;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbPreTrigger;
private System.Windows.Forms.RadioButton rbAccessConditionIfNoneMatch;
private System.Windows.Forms.RadioButton rbAccessConditionIfMatch;
private System.Windows.Forms.RadioButton rbConsistencyEventual;
private System.Windows.Forms.RadioButton rbConsistencySession;
private System.Windows.Forms.RadioButton rbConsistencyBound;
private System.Windows.Forms.RadioButton rbConsistencyStrong;
private System.Windows.Forms.RadioButton rbIndexingExclude;
private System.Windows.Forms.RadioButton rbIndexingInclude;
private System.Windows.Forms.RadioButton rbIndexingDefault;
private System.Windows.Forms.TabPage tabDocumentCollection;
private System.Windows.Forms.CheckBox cbAutomatic;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.RadioButton rbLazy;
private System.Windows.Forms.RadioButton rbConsistent;
private System.Windows.Forms.Label labelCollectionId;
private System.Windows.Forms.TextBox tbCollectionId;
private System.Windows.Forms.CheckBox cbIndexingPolicyDefault;
private System.Windows.Forms.ListBox lbIncludedPath;
private System.Windows.Forms.Button btnEdit;
private System.Windows.Forms.Button btnRemovePath;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnAddIncludePath;
private System.Windows.Forms.ListBox lbExcludedPath;
private System.Windows.Forms.Button btnRemoveExcludedPath;
private System.Windows.Forms.Button btnAddExcludedPath;
private System.Windows.Forms.Panel triggerPanel;
private System.Windows.Forms.RadioButton rbPostTrigger;
private System.Windows.Forms.RadioButton rbPreTrigger;
private System.Windows.Forms.Label labelPartitionKey;
private System.Windows.Forms.TextBox tbPartitionKeyForRequestOption;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TabPage tabOffer;
private System.Windows.Forms.TextBox tbPartitionKeyForCollectionCreate;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.RadioButton rbOfferS3;
private System.Windows.Forms.RadioButton rbOfferS2;
private System.Windows.Forms.RadioButton rbOfferS1;
private System.Windows.Forms.GroupBox gbStandardOffer;
private System.Windows.Forms.RadioButton rbElasticCollection;
private System.Windows.Forms.RadioButton rbSinglePartition;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.CheckBox cbShowLegacyOffer;
private System.Windows.Forms.Label labelThroughput;
private System.Windows.Forms.TextBox tbThroughput;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ToolStripLabel MaxDOP;
private System.Windows.Forms.ToolStripSeparator Separator1;
private System.Windows.Forms.ToolStripSeparator Separator3;
private System.Windows.Forms.ToolStripLabel MaxBuffItem;
private System.Windows.Forms.ToolStripSeparator Separator4;
private System.Windows.Forms.ToolStripLabel MaxItemCount;
private System.Windows.Forms.ToolStripSeparator Separator2;
private System.Windows.Forms.ToolStripButton tsbHideDocumentSystemProperties;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Linq
{
internal class EnumerableRewriter : ExpressionVisitor
{
// We must ensure that if a LabelTarget is rewritten that it is always rewritten to the same new target
// or otherwise expressions using it won't match correctly.
private Dictionary<LabelTarget, LabelTarget> _targetCache;
// Finding equivalent types can be relatively expensive, and hitting with the same types repeatedly is quite likely.
private Dictionary<Type, Type> _equivalentTypeCache;
protected override Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = this.Visit(m.Object);
ReadOnlyCollection<Expression> args = Visit(m.Arguments);
// check for args changed
if (obj != m.Object || args != m.Arguments)
{
MethodInfo mInfo = m.Method;
Type[] typeArgs = (mInfo.IsGenericMethod) ? mInfo.GetGenericArguments() : null;
if ((mInfo.IsStatic || mInfo.DeclaringType.IsAssignableFrom(obj.Type))
&& ArgsMatch(mInfo, args, typeArgs))
{
// current method is still valid
return Expression.Call(obj, mInfo, args);
}
else if (mInfo.DeclaringType == typeof(Queryable))
{
// convert Queryable method to Enumerable method
MethodInfo seqMethod = FindEnumerableMethod(mInfo.Name, args, typeArgs);
args = this.FixupQuotedArgs(seqMethod, args);
return Expression.Call(obj, seqMethod, args);
}
else
{
// rebind to new method
MethodInfo method = FindMethod(mInfo.DeclaringType, mInfo.Name, args, typeArgs);
args = this.FixupQuotedArgs(method, args);
return Expression.Call(obj, method, args);
}
}
return m;
}
private ReadOnlyCollection<Expression> FixupQuotedArgs(MethodInfo mi, ReadOnlyCollection<Expression> argList)
{
ParameterInfo[] pis = mi.GetParameters();
if (pis.Length > 0)
{
List<Expression> newArgs = null;
for (int i = 0, n = pis.Length; i < n; i++)
{
Expression arg = argList[i];
ParameterInfo pi = pis[i];
arg = FixupQuotedExpression(pi.ParameterType, arg);
if (newArgs == null && arg != argList[i])
{
newArgs = new List<Expression>(argList.Count);
for (int j = 0; j < i; j++)
{
newArgs.Add(argList[j]);
}
}
if (newArgs != null)
{
newArgs.Add(arg);
}
}
if (newArgs != null)
argList = newArgs.AsReadOnly();
}
return argList;
}
private Expression FixupQuotedExpression(Type type, Expression expression)
{
Expression expr = expression;
while (true)
{
if (type.IsAssignableFrom(expr.Type))
return expr;
if (expr.NodeType != ExpressionType.Quote)
break;
expr = ((UnaryExpression)expr).Operand;
}
if (!type.IsAssignableFrom(expr.Type) && type.IsArray && expr.NodeType == ExpressionType.NewArrayInit)
{
Type strippedType = StripExpression(expr.Type);
if (type.IsAssignableFrom(strippedType))
{
Type elementType = type.GetElementType();
NewArrayExpression na = (NewArrayExpression)expr;
List<Expression> exprs = new List<Expression>(na.Expressions.Count);
for (int i = 0, n = na.Expressions.Count; i < n; i++)
{
exprs.Add(this.FixupQuotedExpression(elementType, na.Expressions[i]));
}
expression = Expression.NewArrayInit(elementType, exprs);
}
}
return expression;
}
protected override Expression VisitLambda<T>(Expression<T> node)
{
return node;
}
private static Type GetPublicType(Type t)
{
// If we create a constant explicitly typed to be a private nested type,
// such as Lookup<,>.Grouping or a compiler-generated iterator class, then
// we cannot use the expression tree in a context which has only execution
// permissions. We should endeavour to translate constants into
// new constants which have public types.
TypeInfo typeInfo = t.GetTypeInfo();
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition().GetTypeInfo().ImplementedInterfaces.Contains(typeof(IGrouping<,>)))
return typeof(IGrouping<,>).MakeGenericType(t.GetGenericArguments());
if (!typeInfo.IsNestedPrivate)
return t;
foreach (Type iType in typeInfo.ImplementedInterfaces)
{
TypeInfo iTypeInfo = iType.GetTypeInfo();
if (iTypeInfo.IsGenericType && iTypeInfo.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return iType;
}
if (typeof(IEnumerable).IsAssignableFrom(t))
return typeof(IEnumerable);
return t;
}
private Type GetEquivalentType(Type type)
{
Type equiv;
if (_equivalentTypeCache == null)
{
// Pre-loading with the non-generic IQueryable and IEnumerable not only covers this case
// without any reflection-based introspection, but also means the slightly different
// code needed to catch this case can be omitted safely.
_equivalentTypeCache = new Dictionary<Type, Type>
{
{ typeof(IQueryable), typeof(IEnumerable) },
{ typeof(IEnumerable), typeof(IEnumerable) }
};
}
if (!_equivalentTypeCache.TryGetValue(type, out equiv))
{
Type pubType = GetPublicType(type);
TypeInfo info = pubType.GetTypeInfo();
if (info.IsInterface && info.IsGenericType)
{
Type genericType = info.GetGenericTypeDefinition();
if (genericType == typeof(IOrderedEnumerable<>))
equiv = pubType;
else if (genericType == typeof(IOrderedQueryable<>))
equiv = typeof(IOrderedEnumerable<>).MakeGenericType(info.GenericTypeArguments[0]);
else if (genericType == typeof(IEnumerable<>))
equiv = pubType;
else if (genericType == typeof(IQueryable<>))
equiv = typeof(IEnumerable<>).MakeGenericType(info.GenericTypeArguments[0]);
}
if (equiv == null)
{
var interfacesWithInfo = info.ImplementedInterfaces.Select(i => new { Type = i, Info = i.GetTypeInfo() }).ToArray();
var singleTypeGenInterfacesWithGetType = interfacesWithInfo
.Where(i => i.Info.IsGenericType && i.Info.GenericTypeArguments.Length == 1)
.Select(i => new { Type = i.Type, Info = i.Info, GenType = i.Info.GetGenericTypeDefinition() });
Type typeArg = singleTypeGenInterfacesWithGetType.Where(i => i.GenType == typeof(IOrderedQueryable<>) || i.GenType == typeof(IOrderedEnumerable<>)).Select(i => i.Info.GenericTypeArguments[0]).Distinct().SingleOrDefault();
if (typeArg != null)
equiv = typeof(IOrderedEnumerable<>).MakeGenericType(typeArg);
else
{
typeArg = singleTypeGenInterfacesWithGetType.Where(i => i.GenType == typeof(IQueryable<>) || i.GenType == typeof(IEnumerable<>)).Select(i => i.Info.GenericTypeArguments[0]).Distinct().Single();
equiv = typeof(IEnumerable<>).MakeGenericType(typeArg);
}
}
_equivalentTypeCache.Add(type, equiv);
}
return equiv;
}
protected override Expression VisitConstant(ConstantExpression c)
{
EnumerableQuery sq = c.Value as EnumerableQuery;
if (sq != null)
{
if (sq.Enumerable != null)
{
Type t = GetPublicType(sq.Enumerable.GetType());
return Expression.Constant(sq.Enumerable, t);
}
Expression exp = sq.Expression;
if (exp != c)
return Visit(exp);
}
return c;
}
private static volatile ILookup<string, MethodInfo> s_seqMethods;
private static MethodInfo FindEnumerableMethod(string name, ReadOnlyCollection<Expression> args, params Type[] typeArgs)
{
if (s_seqMethods == null)
{
s_seqMethods = typeof(Enumerable).GetStaticMethods().ToLookup(m => m.Name);
}
MethodInfo mi = s_seqMethods[name].FirstOrDefault(m => ArgsMatch(m, args, typeArgs));
Debug.Assert(mi != null, "All static methods with arguments on Queryable have equivalents on Enumerable.");
if (typeArgs != null)
return mi.MakeGenericMethod(typeArgs);
return mi;
}
private static MethodInfo FindMethod(Type type, string name, ReadOnlyCollection<Expression> args, Type[] typeArgs)
{
using (IEnumerator<MethodInfo> en = type.GetStaticMethods().Where(m => m.Name == name).GetEnumerator())
{
if (!en.MoveNext())
throw Error.NoMethodOnType(name, type);
do
{
MethodInfo mi = en.Current;
if (ArgsMatch(mi, args, typeArgs))
return (typeArgs != null) ? mi.MakeGenericMethod(typeArgs) : mi;
} while (en.MoveNext());
}
throw Error.NoMethodOnTypeMatchingArguments(name, type);
}
private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection<Expression> args, Type[] typeArgs)
{
ParameterInfo[] mParams = m.GetParameters();
if (mParams.Length != args.Count)
return false;
if (!m.IsGenericMethod && typeArgs != null && typeArgs.Length > 0)
{
return false;
}
if (!m.IsGenericMethodDefinition && m.IsGenericMethod && m.ContainsGenericParameters)
{
m = m.GetGenericMethodDefinition();
}
if (m.IsGenericMethodDefinition)
{
if (typeArgs == null || typeArgs.Length == 0)
return false;
if (m.GetGenericArguments().Length != typeArgs.Length)
return false;
m = m.MakeGenericMethod(typeArgs);
mParams = m.GetParameters();
}
for (int i = 0, n = args.Count; i < n; i++)
{
Type parameterType = mParams[i].ParameterType;
if (parameterType == null)
return false;
if (parameterType.IsByRef)
parameterType = parameterType.GetElementType();
Expression arg = args[i];
if (!parameterType.IsAssignableFrom(arg.Type))
{
if (arg.NodeType == ExpressionType.Quote)
{
arg = ((UnaryExpression)arg).Operand;
}
if (!parameterType.IsAssignableFrom(arg.Type) &&
!parameterType.IsAssignableFrom(StripExpression(arg.Type)))
{
return false;
}
}
}
return true;
}
private static Type StripExpression(Type type)
{
bool isArray = type.IsArray;
Type tmp = isArray ? type.GetElementType() : type;
Type eType = TypeHelper.FindGenericType(typeof(Expression<>), tmp);
if (eType != null)
tmp = eType.GetGenericArguments()[0];
if (isArray)
{
int rank = type.GetArrayRank();
return (rank == 1) ? tmp.MakeArrayType() : tmp.MakeArrayType(rank);
}
return type;
}
protected override Expression VisitConditional(ConditionalExpression c)
{
Type type = c.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.VisitConditional(c);
Expression test = Visit(c.Test);
Expression ifTrue = Visit(c.IfTrue);
Expression ifFalse = Visit(c.IfFalse);
Type trueType = ifTrue.Type;
Type falseType = ifFalse.Type;
if (trueType.IsAssignableFrom(falseType))
return Expression.Condition(test, ifTrue, ifFalse, trueType);
if (falseType.IsAssignableFrom(trueType))
return Expression.Condition(test, ifTrue, ifFalse, falseType);
TypeInfo info = type.GetTypeInfo();
return Expression.Condition(test, ifTrue, ifFalse, GetEquivalentType(type));
}
protected override Expression VisitBlock(BlockExpression node)
{
Type type = node.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.VisitBlock(node);
ReadOnlyCollection<Expression> nodes = Visit(node.Expressions);
ReadOnlyCollection<ParameterExpression> variables = VisitAndConvert(node.Variables, "EnumerableRewriter.VisitBlock");
if (type == node.Expressions.Last().Type)
return Expression.Block(variables, nodes);
return Expression.Block(GetEquivalentType(type), variables, nodes);
}
protected override Expression VisitGoto(GotoExpression node)
{
Type type = node.Value.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
return base.VisitGoto(node);
LabelTarget target = VisitLabelTarget(node.Target);
Expression value = Visit(node.Value);
return Expression.MakeGoto(node.Kind, target, value, GetEquivalentType(typeof(EnumerableQuery).IsAssignableFrom(type) ? value.Type : type));
}
protected override LabelTarget VisitLabelTarget(LabelTarget node)
{
LabelTarget newTarget;
if (_targetCache == null)
_targetCache = new Dictionary<LabelTarget, LabelTarget>();
else if (_targetCache.TryGetValue(node, out newTarget))
return newTarget;
Type type = node.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
newTarget = base.VisitLabelTarget(node);
else
newTarget = Expression.Label(GetEquivalentType(type), node.Name);
_targetCache.Add(node, newTarget);
return newTarget;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Transactions;
using System.Web.Configuration;
using BoC.EventAggregator;
using BoC.Extensions;
using BoC.Persistence;
using BoC.Security.Model;
using BoC.Services;
using BoC.Validation;
namespace BoC.Security.Services
{
public class DefaultUserService : BaseModelService<User>, IUserService
{
private const Int32 SALT_BYTES = 16;
private readonly IRepository<Role> roleRepository;
private readonly IModelValidator modelValidator;
private readonly IRepository<User> userRepository;
public DefaultUserService(IEventAggregator eventAggregator, IRepository<User> userRepository, IRepository<Role> roleRepository, IModelValidator modelValidator) :
base(modelValidator, eventAggregator, userRepository)
{
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.modelValidator = modelValidator;
//Defuault settings:
MinRequiredPasswordLength = 5;
MinRequiredNonAlphanumericCharacters = 0;
PasswordFormat = PasswordFormat.Hashed;
PasswordAttemptWindowMinutes = 10;
MaxInvalidPasswordAttempts = 10;
RequiresUniqueEmail = false;
RequiresApproval = false;
}
#region IUserService Settings
public bool RequiresApproval { get; set; }
public bool RequiresUniqueEmail { get; set; }
public int MaxInvalidPasswordAttempts { get; set; }
public int PasswordAttemptWindowMinutes { get; set; }
public PasswordFormat PasswordFormat { get; set; }
public int MinRequiredNonAlphanumericCharacters { get; set; }
public int MinRequiredPasswordLength { get; set; }
public string PasswordStrengthRegularExpression { get; set; }
#endregion
public virtual Boolean UserExists(String login)
{
if (String.IsNullOrEmpty(login))
{
return false;
}
return (
from u in userRepository.Query()
where u.Login == login
select u
).Count() > 0;
}
public virtual Boolean ChangePassword(User user, String oldPassword, String newPassword)
{
if (user == null)
{
return false;
}
Boolean result = false;
using (var scope = new TransactionScope())
{
if (user.ChangePassword(oldPassword, newPassword))
{
userRepository.SaveOrUpdate(user);
result = true;
}
scope.Complete();
}
return result;
}
public virtual void SetPassword(User user, string password)
{
if (user == null)
{
throw new UserNotFoundException();
}
using (var scope = new TransactionScope())
{
user.Password = EncodePassword(password);
user.LastPasswordChange = DateTime.Now;
userRepository.SaveOrUpdate(user);
scope.Complete();
}
}
public override User Insert(User user)
{
return Insert(user, null);
}
public virtual User Insert(User user, string password)
{
ValidateNewUser(user);
if (password != null)
{
user.Password = EncodePassword(password);
}
user.IsApproved = user.IsApproved || RequiresApproval;
using (var scope = new TransactionScope())
{
user = base.Insert(user);
scope.Complete();
}
return user;
}
protected virtual void ValidateNewUser(User user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
if (RequiresUniqueEmail && !String.IsNullOrEmpty(user.Email) && FindByEmail(user.Email) != null)
{
throw new EmailInUseException(user.Email);
}
if (UserExists(user.Login))
{
throw new LoginInUseException(user.Login);
}
ValidateEntity(user);
}
public override User SaveOrUpdate(User user)
{
if (!String.IsNullOrEmpty(user.Email) && RequiresUniqueEmail)
{
var otheruser = FindByEmail(user.Email);
if (otheruser != null && otheruser.Id != user.Id)
{
throw new EmailInUseException(user.Email);
}
}
if (!String.IsNullOrEmpty(user.Login))
{
var otheruser = FindByLogin(user.Login);
if (otheruser != null && otheruser.Id != user.Id)
{
throw new LoginInUseException(user.Login);
}
}
return user.Id <= 0 ?
Insert(user)
: base.SaveOrUpdate(user);
}
public virtual void DeleteUser(User user)
{
if (user == null)
{
throw new UserNotFoundException();
}
using (var scope = new TransactionScope())
{
userRepository.Delete(user);
scope.Complete();
}
}
public virtual Int32 CountOnlineUsers(TimeSpan activitySpan)
{
DateTime compareTime = DateTime.Now.Subtract(activitySpan);
return
(from u in userRepository.Query()
where u.LastActivity > compareTime
select u).Count();
}
public virtual void UnlockUser(User user)
{
using (var scope = new TransactionScope())
{
if (user == null)
{
throw new UserNotFoundException();
}
else
{
user.IsLockedOut = false;
user.LastLockedOut = DateTime.Now;
userRepository.SaveOrUpdate(user);
}
scope.Complete();
}
}
public virtual void LockUser(User user)
{
using (var scope = new TransactionScope())
{
user.IsLockedOut = true;
user.LastLockedOut = DateTime.Now;
userRepository.SaveOrUpdate(user);
scope.Complete();
}
}
public virtual User FindByEmail(string email)
{
return userRepository.Query().Where(u => u.Email == email).FirstOrDefault();
}
public virtual User FindByLogin(string login)
{
if (string.IsNullOrEmpty(login))
return null;
return userRepository.Query().Where(u => u.Login == login).FirstOrDefault();
}
public virtual IEnumerable<User> FindUsersByPartialLogin(String login)
{
return from u in userRepository.Query()
where u.Login.Contains(login)
select u;
}
public virtual Int32 CountUsersByPartialLogin(String login)
{
return (from u in userRepository.Query()
where u.Login.Contains(login)
select u).Count();
}
public virtual IEnumerable<User> FindUsersByPartialEmail(String email)
{
return from u in userRepository.Query()
where u.Email.Contains(email)
select u;
}
public virtual Int32 CountUsersByPartialEmail(String email)
{
return (from u in userRepository.Query()
where u.Email.Contains(email)
select u).Count();
}
public virtual User Authenticate(String login, String password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
return null;
User user = null;
using (var scope = new TransactionScope())
{
//password = EncodePassword(password);
user = userRepository.Query().Where(u =>
u.Login == login &&
u.IsApproved && !u.IsLockedOut
).FirstOrDefault();
if (user != null)
{
if (!CheckPassword(password, user.Password))
{
UpdateFailureCount(user);
user = null;
}
else
{
user.LastLogin = DateTime.Now;
userRepository.Update(user);
}
}
scope.Complete();
}
if (user != null)
{
return user;
}
else
{
throw new RulesException("Login", "Incorrect username or password");
}
}
#region roles
public virtual void CreateRole(String roleName)
{
if (!RoleExists(roleName))
{
roleRepository.SaveOrUpdate(
new Role(roleName));
}
else
{
new RoleExistsException(roleName);
}
}
public virtual Boolean RoleExists(String roleName)
{
return (FindRole(roleName) != null);
}
public virtual Role GetRole(long id)
{
return roleRepository.Get(id);
}
public virtual Role FindRole(String roleName)
{
return
(from role in roleRepository.Query()
where role.RoleName == roleName
select role).FirstOrDefault();
}
public virtual void DeleteRole(String roleName)
{
Role role = FindRole(roleName);
if (role == null)
{
throw new RoleNotFoundException(roleName);
}
else
{
DeleteRole(role, false);
}
}
public virtual void DeleteRole(Role role)
{
if (role == null)
{
throw new RoleNotFoundException();
}
DeleteRole(role, false);
}
public virtual void DeleteRole(String roleName, Boolean throwWhenUsed)
{
Role role = FindRole(roleName);
if (role == null)
{
throw new RoleNotFoundException(roleName);
}
else
{
DeleteRole(role, throwWhenUsed);
}
}
public virtual void DeleteRole(Role role, Boolean throwWhenUsed)
{
if (role == null)
{
throw new RoleNotFoundException();
}
//TODO: optimize instead of role.users.count
if (throwWhenUsed && role.Users.Count > 0)
{
throw new RoleInUseException(role.RoleName);
}
roleRepository.Delete(role);
}
public User GetByPrincipal(IPrincipal principal)
{
if (principal is User)
return principal as User;
if (principal == null || !principal.Identity.IsAuthenticated || String.IsNullOrEmpty(principal.Identity.Name))
{
return null;
}
long userid;
if (long.TryParse(principal.Identity.Name, out userid))
{
return Get(userid);
}
return null;
}
public virtual void AddUsersToRoles(IEnumerable<User> users, IEnumerable<Role> roles)
{
if ((users == null) || (roles == null))
{
return;
}
using (var scope = new TransactionScope())
{
foreach (User u in users)
{
foreach (Role role in roles)
{
u.Roles.Add(role);
}
userRepository.SaveOrUpdate(u);
}
scope.Complete();
}
}
public virtual void AddUsersToRoles(IEnumerable<String> logins, IEnumerable<String> roleNames)
{
AddUsersToRoles(
from user in userRepository.Query()
where logins.Contains(user.Login)
select user,
from role in roleRepository.Query()
where roleNames.Contains(role.RoleName)
select role);
}
public virtual void RemoveUsersFromRoles(IEnumerable<String> logins, IEnumerable<String> roleNames)
{
RemoveUsersFromRoles(
from user in userRepository.Query()
where logins.Contains(user.Login)
select user,
from role in roleRepository.Query()
where roleNames.Contains(role.RoleName)
select role);
}
public virtual void RemoveUsersFromRoles(IEnumerable<User> users, IEnumerable<Role> roles)
{
if ((users == null) || (roles == null))
{
return;
}
using (var scope = new TransactionScope())
{
foreach (User u in users)
{
foreach (Role role in roles)
{
u.Roles.Remove(role);
}
userRepository.SaveOrUpdate(u);
}
scope.Complete();
}
}
public virtual Role[] GetAllRoles()
{
return roleRepository.Query().ToArray();
}
#endregion
//
// EncodePassword
// Encrypts, Hashes, or leaves the password clear based on the PasswordFormat.
//
public virtual String EncodePassword(String password)
{
if (password == null)
{
return null;
}
String encodedPassword = password;
switch (PasswordFormat)
{
case PasswordFormat.Clear:
break;
case PasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case PasswordFormat.Hashed:
encodedPassword = password.MD5();
break;
default:
throw new NotImplementedException("Unsupported password format.");
}
return encodedPassword;
}
//
// UnEncodePassword
// Decrypts or leaves the password clear based on the PasswordFormat.
//
private String UnEncodePassword(String encodedPassword)
{
String password = encodedPassword;
switch (PasswordFormat)
{
case PasswordFormat.Clear:
break;
case PasswordFormat.Encrypted:
password =
Encoding.Unicode.GetString(
DecryptPassword(Convert.FromBase64String(password))
);
break;
case PasswordFormat.Hashed:
throw new UserServiceException("Password", "Cannot unencode a hashed password.");
default:
throw new NotImplementedException("Unsupported password format.");
}
return password;
}
private SymmetricAlgorithm GetAlg(out byte[] decryptionKey)
{
var section = (MachineKeySection) WebConfigurationManager.GetSection("system.web/machineKey");
if (section.DecryptionKey.StartsWith("AutoGenerate"))
{
throw new UserServiceException("Password",
"You must explicitly specify a decryption key in the <machineKey> section when using encrypted passwords.");
}
String alg_type = section.Decryption;
if (alg_type == "Auto")
{
alg_type = "AES";
}
SymmetricAlgorithm alg = null;
if (alg_type == "AES")
{
alg = Rijndael.Create();
}
else if (alg_type == "3DES")
{
alg = TripleDES.Create();
}
else
{
throw new UserServiceException("Password",
String.Format("Unsupported decryption attribute '{0}' in <machineKey> configuration section",
alg_type));
}
decryptionKey = Encoding.Unicode.GetBytes(section.DecryptionKey);
return alg;
}
protected byte[] DecryptPassword(byte[] encodedPassword)
{
byte[] decryptionKey;
using (SymmetricAlgorithm alg = GetAlg(out decryptionKey))
{
alg.Key = decryptionKey;
using (ICryptoTransform decryptor = alg.CreateDecryptor())
{
byte[] buf = decryptor.TransformFinalBlock(encodedPassword, 0, encodedPassword.Length);
var rv = new byte[buf.Length - SALT_BYTES];
Array.Copy(buf, 16, rv, 0, buf.Length - 16);
return rv;
}
}
}
protected byte[] EncryptPassword(byte[] password)
{
byte[] decryptionKey;
var iv = new byte[SALT_BYTES];
Array.Copy(password, 0, iv, 0, SALT_BYTES);
Array.Clear(password, 0, SALT_BYTES);
using (SymmetricAlgorithm alg = GetAlg(out decryptionKey))
{
using (ICryptoTransform encryptor = alg.CreateEncryptor(decryptionKey, iv))
{
return encryptor.TransformFinalBlock(password, 0, password.Length);
}
}
}
//
// UpdateFailureCount
//
/// <summary>
/// A helper method that performs the checks and updates associated with
/// password failure tracking.
/// </summary>
/// <param name="username"></param>
/// <param name="isPasswordAnswer">true if the passwordanswer has failed, false if password was incorrect</param>
protected void UpdateFailureCount(User user)
{
var windowStart = new DateTime();
Int32 failureCount = 0;
if (user == null)
{
throw new UserNotFoundException();
}
failureCount = user.FailedPasswordAttemptCount;
windowStart = user.FailedPasswordAttemptWindowStart.HasValue
? user.FailedPasswordAttemptWindowStart.Value
: DateTime.MinValue;
DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindowMinutes);
using (var scope = new TransactionScope())
{
if (failureCount == 0 || DateTime.Now > windowEnd)
{
// First password failure or outside of PasswordAttemptWindow.
// Start a new password failure count from 1 and a new window starting now.
user.FailedPasswordAttemptCount = 1;
user.FailedPasswordAttemptWindowStart = DateTime.Now;
}
else
{
if (++failureCount >= MaxInvalidPasswordAttempts && MaxInvalidPasswordAttempts > 0)
{
// Password attempts have exceeded the failure threshold. Lock out
// the user.
user.IsLockedOut = true;
user.LastLockedOut = DateTime.Now;
}
else
{
// Password attempts have not exceeded the failure threshold. Update
// the failure counts. Leave the window the same.
user.FailedPasswordAttemptCount = failureCount;
}
}
userRepository.SaveOrUpdate(user);
scope.Complete();
}
}
//
// CheckPassword
// Compares password values based on the MembershipPasswordFormat.
//
public virtual Boolean CheckPassword(String password, String dbpassword)
{
switch (PasswordFormat)
{
case PasswordFormat.Encrypted:
dbpassword = UnEncodePassword(dbpassword);
break;
case PasswordFormat.Hashed:
password = EncodePassword(password);
break;
default:
break;
}
return (password == dbpassword);
}
}
}
| |
using EIDSS.Reports.Parameterized.Human.GG.DataSet;
using EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthDataSetTableAdapters;
namespace EIDSS.Reports.Parameterized.Human.GG.Report
{
partial class InfectiousDiseasesMonthV4
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InfectiousDiseasesMonthV4));
this.tableCustomHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.SpecifyDiseaseHiddenLabel = new DevExpress.XtraReports.UI.XRLabel();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.tableCustomSubheader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow23 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow21 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow24 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell71 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell73 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellNameOfrespondent = new DevExpress.XtraReports.UI.XRTableCell();
this.infectiousDiseaseDataSet1 = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthDataSet();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellActualAddress = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTelephone = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellReportedPeriod = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellMonthName = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.tableCustomFooter = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell74 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow25 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell76 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell77 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell78 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell79 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell75 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell80 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell81 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell82 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell83 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell84 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell85 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell86 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell87 = new DevExpress.XtraReports.UI.XRTableCell();
this.SpecifyDiseaseCell = new DevExpress.XtraReports.UI.XRTableCell();
this.tableBody = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.CustomDetail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow22 = new DevExpress.XtraReports.UI.XRTableRow();
this.strDiseaseName = new DevExpress.XtraReports.UI.XRTableCell();
this.cellICD10 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_0_1 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_1_4 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_5_14 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_15_19 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_20_29 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_30_59 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_60_more = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell94 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTotal = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell96 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellLabTested = new DevExpress.XtraReports.UI.XRTableCell();
this.cellLabConfirmed = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTotalConfirmed = new DevExpress.XtraReports.UI.XRTableCell();
this.CustomReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.spRepHumMonthlyInfectiousDiseaseTableAdapter1 = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthDataSetTableAdapters.spRepHumMonthlyInfectiousDiseaseTableAdapter();
this.spRepHumMonthlyInfectiousDiseaseFatalTableAdapter1 = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthDataSetTableAdapters.spRepHumMonthlyInfectiousDiseaseFatalTableAdapter();
this.DetailReport1 = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.cellLocation = new DevExpress.XtraReports.UI.XRLabel();
this.GroupFooter = new DevExpress.XtraReports.UI.GroupFooterBand();
this.SignatureTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow26 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomSubheader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.infectiousDiseaseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBody)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// tableInterval
//
resources.ApplyResources(this.tableInterval, "tableInterval");
this.tableInterval.StylePriority.UseBorders = false;
this.tableInterval.StylePriority.UseFont = false;
this.tableInterval.StylePriority.UsePadding = false;
//
// cellInputStartDate
//
resources.ApplyResources(this.cellInputStartDate, "cellInputStartDate");
this.cellInputStartDate.StylePriority.UseFont = false;
this.cellInputStartDate.StylePriority.UseTextAlignment = false;
//
// cellInputEndDate
//
resources.ApplyResources(this.cellInputEndDate, "cellInputEndDate");
this.cellInputEndDate.StylePriority.UseFont = false;
this.cellInputEndDate.StylePriority.UseTextAlignment = false;
//
// cellDefis
//
resources.ApplyResources(this.cellDefis, "cellDefis");
this.cellDefis.StylePriority.UseFont = false;
this.cellDefis.StylePriority.UseTextAlignment = false;
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Multiline = true;
this.lblReportName.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UsePadding = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.Expanded = false;
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
this.PageFooter.StylePriority.UseBorders = false;
resources.ApplyResources(this.PageFooter, "PageFooter");
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableCustomHeader});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UsePadding = false;
this.ReportHeader.Controls.SetChildIndex(this.tableCustomHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.cellLocation});
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
this.cellReportHeader.Controls.SetChildIndex(this.tableInterval, 0);
this.cellReportHeader.Controls.SetChildIndex(this.cellLocation, 0);
this.cellReportHeader.Controls.SetChildIndex(this.lblReportName, 0);
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
//
// cellBaseCountry
//
this.cellBaseCountry.StylePriority.UseFont = false;
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// tableCustomHeader
//
resources.ApplyResources(this.tableCustomHeader, "tableCustomHeader");
this.tableCustomHeader.Name = "tableCustomHeader";
this.tableCustomHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2,
this.xrTableRow3,
this.xrTableRow23,
this.xrTableRow21,
this.xrTableRow24,
this.xrTableRow8,
this.xrTableRow9,
this.xrTableRow11,
this.xrTableRow12,
this.xrTableRow13,
this.xrTableRow14,
this.xrTableRow15,
this.xrTableRow16,
this.xrTableRow17});
this.tableCustomHeader.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1});
this.xrTableRow1.Name = "xrTableRow1";
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2});
this.xrTableRow2.Name = "xrTableRow2";
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Multiline = true;
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell3});
this.xrTableRow3.Name = "xrTableRow3";
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
//
// xrTableCell5
//
this.xrTableCell5.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.SpecifyDiseaseHiddenLabel});
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Multiline = true;
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Padding = new DevExpress.XtraPrinting.PaddingInfo(44, 2, 2, 2, 100F);
this.xrTableCell5.StylePriority.UseFont = false;
this.xrTableCell5.StylePriority.UsePadding = false;
this.xrTableCell5.StylePriority.UseTextAlignment = false;
//
// SpecifyDiseaseHiddenLabel
//
resources.ApplyResources(this.SpecifyDiseaseHiddenLabel, "SpecifyDiseaseHiddenLabel");
this.SpecifyDiseaseHiddenLabel.Name = "SpecifyDiseaseHiddenLabel";
this.SpecifyDiseaseHiddenLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 96F);
//
// xrTableCell3
//
this.xrTableCell3.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableCustomSubheader});
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
//
// tableCustomSubheader
//
resources.ApplyResources(this.tableCustomSubheader, "tableCustomSubheader");
this.tableCustomSubheader.Name = "tableCustomSubheader";
this.tableCustomSubheader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow5,
this.xrTableRow6,
this.xrTableRow7});
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell6});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseFont = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7});
this.xrTableRow6.Name = "xrTableRow6";
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseFont = false;
this.xrTableCell7.StylePriority.UseTextAlignment = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell8});
this.xrTableRow7.Name = "xrTableRow7";
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Multiline = true;
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.xrTableCell8.StylePriority.UseFont = false;
this.xrTableCell8.StylePriority.UsePadding = false;
this.xrTableCell8.StylePriority.UseTextAlignment = false;
//
// xrTableRow23
//
this.xrTableRow23.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell70});
this.xrTableRow23.Name = "xrTableRow23";
resources.ApplyResources(this.xrTableRow23, "xrTableRow23");
//
// xrTableCell70
//
resources.ApplyResources(this.xrTableCell70, "xrTableCell70");
this.xrTableCell70.Multiline = true;
this.xrTableCell70.Name = "xrTableCell70";
this.xrTableCell70.StylePriority.UseFont = false;
this.xrTableCell70.StylePriority.UseTextAlignment = false;
//
// xrTableRow21
//
this.xrTableRow21.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell16,
this.xrTableCell27,
this.xrTableCell15});
this.xrTableRow21.Name = "xrTableRow21";
resources.ApplyResources(this.xrTableRow21, "xrTableRow21");
//
// xrTableCell16
//
this.xrTableCell16.Name = "xrTableCell16";
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Multiline = true;
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseFont = false;
//
// xrTableCell15
//
this.xrTableCell15.Name = "xrTableCell15";
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
//
// xrTableRow24
//
this.xrTableRow24.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell71,
this.xrTableCell72,
this.xrTableCell73});
this.xrTableRow24.Name = "xrTableRow24";
resources.ApplyResources(this.xrTableRow24, "xrTableRow24");
//
// xrTableCell71
//
this.xrTableCell71.Name = "xrTableCell71";
resources.ApplyResources(this.xrTableCell71, "xrTableCell71");
//
// xrTableCell72
//
this.xrTableCell72.Name = "xrTableCell72";
resources.ApplyResources(this.xrTableCell72, "xrTableCell72");
//
// xrTableCell73
//
this.xrTableCell73.Name = "xrTableCell73";
resources.ApplyResources(this.xrTableCell73, "xrTableCell73");
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell10,
this.cellNameOfrespondent,
this.xrTableCell11});
this.xrTableRow8.Name = "xrTableRow8";
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
//
// cellNameOfrespondent
//
resources.ApplyResources(this.cellNameOfrespondent, "cellNameOfrespondent");
this.cellNameOfrespondent.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.cellNameOfrespondent.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.infectiousDiseaseDataSet1, "spRepHumAnnualInfectiousDisease.strNameOfRespondent")});
this.cellNameOfrespondent.Name = "cellNameOfrespondent";
this.cellNameOfrespondent.StylePriority.UseBackColor = false;
this.cellNameOfrespondent.StylePriority.UseBorders = false;
this.cellNameOfrespondent.StylePriority.UseFont = false;
//
// infectiousDiseaseDataSet1
//
this.infectiousDiseaseDataSet1.DataSetName = "InfectiousDiseaseMonthDataSet";
this.infectiousDiseaseDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTableCell11
//
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseFont = false;
this.xrTableCell11.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell12,
this.cellActualAddress,
this.xrTableCell13});
this.xrTableRow9.Name = "xrTableRow9";
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
//
// cellActualAddress
//
resources.ApplyResources(this.cellActualAddress, "cellActualAddress");
this.cellActualAddress.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.cellActualAddress.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.infectiousDiseaseDataSet1, "spRepHumAnnualInfectiousDisease.strActualAddress")});
this.cellActualAddress.Name = "cellActualAddress";
this.cellActualAddress.StylePriority.UseBackColor = false;
this.cellActualAddress.StylePriority.UseBorders = false;
this.cellActualAddress.StylePriority.UseFont = false;
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseFont = false;
this.xrTableCell13.StylePriority.UseTextAlignment = false;
this.xrTableCell13.Tag = "UnchangebleFont";
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell17,
this.xrTableCell18,
this.xrTableCell19});
this.xrTableRow11.Name = "xrTableRow11";
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
//
// xrTableCell17
//
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
//
// xrTableCell18
//
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseBackColor = false;
this.xrTableCell18.StylePriority.UseBorders = false;
this.xrTableCell18.StylePriority.UseFont = false;
//
// xrTableCell19
//
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseFont = false;
this.xrTableCell19.StylePriority.UseTextAlignment = false;
this.xrTableCell19.Tag = "UnchangebleFont";
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22});
this.xrTableRow12.Name = "xrTableRow12";
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
//
// xrTableCell20
//
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseBackColor = false;
this.xrTableCell21.StylePriority.UseBorders = false;
this.xrTableCell21.StylePriority.UseFont = false;
//
// xrTableCell22
//
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
this.xrTableCell22.StylePriority.UseTextAlignment = false;
this.xrTableCell22.Tag = "UnchangebleFont";
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell23,
this.xrTableCell24,
this.xrTableCell25});
this.xrTableRow13.Name = "xrTableRow13";
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
//
// xrTableCell23
//
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
//
// xrTableCell24
//
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseBackColor = false;
this.xrTableCell24.StylePriority.UseBorders = false;
this.xrTableCell24.StylePriority.UseFont = false;
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.StylePriority.UseFont = false;
this.xrTableCell25.StylePriority.UseTextAlignment = false;
this.xrTableCell25.Tag = "UnchangebleFont";
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.cellTelephone,
this.xrTableCell28});
this.xrTableRow14.Name = "xrTableRow14";
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
//
// xrTableCell26
//
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
//
// cellTelephone
//
resources.ApplyResources(this.cellTelephone, "cellTelephone");
this.cellTelephone.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.cellTelephone.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.infectiousDiseaseDataSet1, "spRepHumAnnualInfectiousDisease.strTelephone")});
this.cellTelephone.Name = "cellTelephone";
this.cellTelephone.StylePriority.UseBackColor = false;
this.cellTelephone.StylePriority.UseBorders = false;
this.cellTelephone.StylePriority.UseFont = false;
//
// xrTableCell28
//
this.xrTableCell28.Name = "xrTableCell28";
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellReportedPeriod,
this.xrTableCell30,
this.xrTableCell31});
this.xrTableRow15.Name = "xrTableRow15";
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
//
// cellReportedPeriod
//
this.cellReportedPeriod.Name = "cellReportedPeriod";
this.cellReportedPeriod.StylePriority.UseFont = false;
resources.ApplyResources(this.cellReportedPeriod, "cellReportedPeriod");
//
// xrTableCell30
//
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell30.StylePriority.UseFont = false;
this.xrTableCell30.StylePriority.UsePadding = false;
this.xrTableCell30.Tag = "UnchangebleFont";
//
// xrTableCell31
//
this.xrTableCell31.Name = "xrTableCell31";
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
//
// xrTableRow16
//
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellMonthName,
this.xrTableCell32,
this.xrTableCell33});
this.xrTableRow16.Name = "xrTableRow16";
resources.ApplyResources(this.xrTableRow16, "xrTableRow16");
//
// cellMonthName
//
this.cellMonthName.Name = "cellMonthName";
resources.ApplyResources(this.cellMonthName, "cellMonthName");
//
// xrTableCell32
//
this.xrTableCell32.Name = "xrTableCell32";
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
//
// xrTableCell33
//
this.xrTableCell33.Name = "xrTableCell33";
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell34,
this.xrTableCell35,
this.xrTableCell36});
this.xrTableRow17.Name = "xrTableRow17";
resources.ApplyResources(this.xrTableRow17, "xrTableRow17");
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseFont = false;
//
// xrTableCell35
//
this.xrTableCell35.Name = "xrTableCell35";
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
//
// xrTableCell36
//
this.xrTableCell36.Name = "xrTableCell36";
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableCustomFooter});
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
this.ReportFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.ReportFooter.StylePriority.UseFont = false;
this.ReportFooter.StylePriority.UsePadding = false;
this.ReportFooter.StylePriority.UseTextAlignment = false;
//
// tableCustomFooter
//
resources.ApplyResources(this.tableCustomFooter, "tableCustomFooter");
this.tableCustomFooter.Name = "tableCustomFooter";
this.tableCustomFooter.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow18,
this.xrTableRow25});
this.tableCustomFooter.StylePriority.UseFont = false;
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell37,
this.xrTableCell74,
this.xrTableCell4,
this.xrTableCell39});
this.xrTableRow18.Name = "xrTableRow18";
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
//
// xrTableCell37
//
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
//
// xrTableCell74
//
this.xrTableCell74.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell74.Name = "xrTableCell74";
this.xrTableCell74.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell74, "xrTableCell74");
//
// xrTableCell4
//
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
//
// xrTableCell39
//
this.xrTableCell39.Borders = DevExpress.XtraPrinting.BorderSide.Top;
this.xrTableCell39.Name = "xrTableCell39";
this.xrTableCell39.StylePriority.UseBorders = false;
this.xrTableCell39.StylePriority.UseFont = false;
this.xrTableCell39.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
//
// xrTableRow25
//
this.xrTableRow25.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell76,
this.xrTableCell77,
this.xrTableCell78,
this.xrTableCell79});
this.xrTableRow25.Name = "xrTableRow25";
resources.ApplyResources(this.xrTableRow25, "xrTableRow25");
//
// xrTableCell76
//
this.xrTableCell76.Name = "xrTableCell76";
resources.ApplyResources(this.xrTableCell76, "xrTableCell76");
//
// xrTableCell77
//
this.xrTableCell77.Name = "xrTableCell77";
resources.ApplyResources(this.xrTableCell77, "xrTableCell77");
//
// xrTableCell78
//
this.xrTableCell78.Name = "xrTableCell78";
resources.ApplyResources(this.xrTableCell78, "xrTableCell78");
//
// xrTableCell79
//
this.xrTableCell79.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell79.Name = "xrTableCell79";
this.xrTableCell79.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell79, "xrTableCell79");
//
// xrTable2
//
this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow4});
this.xrTable2.StylePriority.UseBorders = false;
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell14,
this.xrTableCell38,
this.xrTableCell75,
this.xrTableCell80,
this.xrTableCell81,
this.xrTableCell82,
this.xrTableCell83,
this.xrTableCell84,
this.xrTableCell85,
this.xrTableCell86,
this.xrTableCell87,
this.SpecifyDiseaseCell});
this.xrTableRow4.Name = "xrTableRow4";
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseFont = false;
this.xrTableCell9.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
//
// xrTableCell14
//
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.strICD10")});
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTableCell14.StylePriority.UseFont = false;
this.xrTableCell14.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell38
//
this.xrTableCell38.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intAge_0_1")});
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
this.xrTableCell38.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell75
//
this.xrTableCell75.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intAge_1_4")});
this.xrTableCell75.Name = "xrTableCell75";
this.xrTableCell75.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell75, "xrTableCell75");
this.xrTableCell75.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell80
//
this.xrTableCell80.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intAge_5_14")});
this.xrTableCell80.Name = "xrTableCell80";
this.xrTableCell80.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell80, "xrTableCell80");
this.xrTableCell80.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell81
//
this.xrTableCell81.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intAge_15_19")});
this.xrTableCell81.Name = "xrTableCell81";
this.xrTableCell81.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell81, "xrTableCell81");
this.xrTableCell81.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell82
//
this.xrTableCell82.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intAge_20_29")});
this.xrTableCell82.Name = "xrTableCell82";
this.xrTableCell82.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell82, "xrTableCell82");
this.xrTableCell82.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell83
//
this.xrTableCell83.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intAge_30_59")});
this.xrTableCell83.Name = "xrTableCell83";
this.xrTableCell83.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell83, "xrTableCell83");
this.xrTableCell83.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell84
//
this.xrTableCell84.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intAge_60_more")});
this.xrTableCell84.Name = "xrTableCell84";
this.xrTableCell84.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell84, "xrTableCell84");
this.xrTableCell84.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell85
//
this.xrTableCell85.Name = "xrTableCell85";
resources.ApplyResources(this.xrTableCell85, "xrTableCell85");
//
// xrTableCell86
//
this.xrTableCell86.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.intLethalCases")});
this.xrTableCell86.Name = "xrTableCell86";
this.xrTableCell86.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell86, "xrTableCell86");
this.xrTableCell86.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellMainTotalBeforePrint);
//
// xrTableCell87
//
this.xrTableCell87.Name = "xrTableCell87";
resources.ApplyResources(this.xrTableCell87, "xrTableCell87");
//
// SpecifyDiseaseCell
//
this.SpecifyDiseaseCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDiseaseFatal.strSpecifyDiseases")});
this.SpecifyDiseaseCell.Name = "SpecifyDiseaseCell";
this.SpecifyDiseaseCell.StylePriority.UseFont = false;
this.SpecifyDiseaseCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.SpecifyDiseaseCell, "SpecifyDiseaseCell");
this.SpecifyDiseaseCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.SpecifyDiseaseCell_BeforePrint);
//
// tableBody
//
this.tableBody.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.tableBody, "tableBody");
this.tableBody.Name = "tableBody";
this.tableBody.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow19,
this.xrTableRow20});
this.tableBody.StylePriority.UseBorders = false;
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell43,
this.xrTableCell47,
this.xrTableCell40,
this.xrTableCell46,
this.xrTableCell44,
this.xrTableCell48,
this.xrTableCell41,
this.xrTableCell49,
this.xrTableCell52,
this.xrTableCell66,
this.xrTableCell45,
this.xrTableCell67,
this.xrTableCell51,
this.xrTableCell50,
this.xrTableCell42});
this.xrTableRow19.Name = "xrTableRow19";
resources.ApplyResources(this.xrTableRow19, "xrTableRow19");
//
// xrTableCell43
//
this.xrTableCell43.Name = "xrTableCell43";
this.xrTableCell43.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
//
// xrTableCell47
//
this.xrTableCell47.Name = "xrTableCell47";
this.xrTableCell47.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell47, "xrTableCell47");
//
// xrTableCell40
//
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
//
// xrTableCell46
//
this.xrTableCell46.Name = "xrTableCell46";
this.xrTableCell46.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell46, "xrTableCell46");
//
// xrTableCell44
//
this.xrTableCell44.Name = "xrTableCell44";
this.xrTableCell44.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
//
// xrTableCell48
//
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
//
// xrTableCell41
//
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
//
// xrTableCell49
//
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
//
// xrTableCell52
//
this.xrTableCell52.Name = "xrTableCell52";
this.xrTableCell52.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
//
// xrTableCell66
//
this.xrTableCell66.Name = "xrTableCell66";
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
//
// xrTableCell45
//
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
//
// xrTableCell67
//
this.xrTableCell67.Name = "xrTableCell67";
resources.ApplyResources(this.xrTableCell67, "xrTableCell67");
//
// xrTableCell51
//
this.xrTableCell51.Angle = 90F;
this.xrTableCell51.Name = "xrTableCell51";
this.xrTableCell51.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
//
// xrTableCell50
//
this.xrTableCell50.Angle = 90F;
this.xrTableCell50.Name = "xrTableCell50";
this.xrTableCell50.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
//
// xrTableCell42
//
this.xrTableCell42.Angle = 90F;
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell53,
this.xrTableCell54,
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57,
this.xrTableCell58,
this.xrTableCell59,
this.xrTableCell60,
this.xrTableCell61,
this.xrTableCell68,
this.xrTableCell62,
this.xrTableCell69,
this.xrTableCell63,
this.xrTableCell64,
this.xrTableCell65});
this.xrTableRow20.Name = "xrTableRow20";
this.xrTableRow20.StylePriority.UseBorders = false;
this.xrTableRow20.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableRow20, "xrTableRow20");
//
// xrTableCell53
//
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
//
// xrTableCell54
//
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
//
// xrTableCell55
//
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
//
// xrTableCell56
//
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
//
// xrTableCell57
//
this.xrTableCell57.Name = "xrTableCell57";
this.xrTableCell57.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
//
// xrTableCell58
//
this.xrTableCell58.Name = "xrTableCell58";
this.xrTableCell58.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell58, "xrTableCell58");
//
// xrTableCell59
//
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
//
// xrTableCell60
//
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
//
// xrTableCell61
//
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
//
// xrTableCell68
//
this.xrTableCell68.Name = "xrTableCell68";
resources.ApplyResources(this.xrTableCell68, "xrTableCell68");
//
// xrTableCell62
//
this.xrTableCell62.Name = "xrTableCell62";
this.xrTableCell62.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell62, "xrTableCell62");
//
// xrTableCell69
//
this.xrTableCell69.Name = "xrTableCell69";
resources.ApplyResources(this.xrTableCell69, "xrTableCell69");
//
// xrTableCell63
//
this.xrTableCell63.Name = "xrTableCell63";
this.xrTableCell63.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell63, "xrTableCell63");
//
// xrTableCell64
//
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
//
// xrTableCell65
//
this.xrTableCell65.Name = "xrTableCell65";
this.xrTableCell65.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell65, "xrTableCell65");
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.CustomDetail,
this.CustomReportHeader});
this.DetailReport.DataAdapter = this.spRepHumMonthlyInfectiousDiseaseTableAdapter1;
this.DetailReport.DataMember = "spRepHumMonthlyInfectiousDisease";
this.DetailReport.DataSource = this.infectiousDiseaseDataSet1;
resources.ApplyResources(this.DetailReport, "DetailReport");
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// CustomDetail
//
this.CustomDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.CustomDetail, "CustomDetail");
this.CustomDetail.Name = "CustomDetail";
this.CustomDetail.StylePriority.UseFont = false;
this.CustomDetail.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow22});
this.xrTable1.StylePriority.UseBorders = false;
//
// xrTableRow22
//
this.xrTableRow22.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.strDiseaseName,
this.cellICD10,
this.cellAge_0_1,
this.cellAge_1_4,
this.cellAge_5_14,
this.cellAge_15_19,
this.cellAge_20_29,
this.cellAge_30_59,
this.cellAge_60_more,
this.xrTableCell94,
this.cellTotal,
this.xrTableCell96,
this.cellLabTested,
this.cellLabConfirmed,
this.cellTotalConfirmed});
this.xrTableRow22.Name = "xrTableRow22";
this.xrTableRow22.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableRow22, "xrTableRow22");
//
// strDiseaseName
//
this.strDiseaseName.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.strDiseaseName")});
this.strDiseaseName.Name = "strDiseaseName";
this.strDiseaseName.StylePriority.UseFont = false;
this.strDiseaseName.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.strDiseaseName, "strDiseaseName");
this.strDiseaseName.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellICD10
//
this.cellICD10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.strICD10")});
this.cellICD10.Name = "cellICD10";
this.cellICD10.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.cellICD10.StylePriority.UseFont = false;
this.cellICD10.StylePriority.UsePadding = false;
resources.ApplyResources(this.cellICD10, "cellICD10");
this.cellICD10.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_0_1
//
this.cellAge_0_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_0_1")});
this.cellAge_0_1.Name = "cellAge_0_1";
this.cellAge_0_1.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_0_1, "cellAge_0_1");
this.cellAge_0_1.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_1_4
//
this.cellAge_1_4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_1_4")});
this.cellAge_1_4.Name = "cellAge_1_4";
this.cellAge_1_4.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_1_4, "cellAge_1_4");
this.cellAge_1_4.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_5_14
//
this.cellAge_5_14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_5_14")});
this.cellAge_5_14.Name = "cellAge_5_14";
this.cellAge_5_14.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_5_14, "cellAge_5_14");
this.cellAge_5_14.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_15_19
//
this.cellAge_15_19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_15_19")});
this.cellAge_15_19.Name = "cellAge_15_19";
this.cellAge_15_19.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_15_19, "cellAge_15_19");
this.cellAge_15_19.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_20_29
//
this.cellAge_20_29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_20_29")});
this.cellAge_20_29.Name = "cellAge_20_29";
this.cellAge_20_29.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_20_29, "cellAge_20_29");
this.cellAge_20_29.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_30_59
//
this.cellAge_30_59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_30_59")});
this.cellAge_30_59.Name = "cellAge_30_59";
this.cellAge_30_59.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_30_59, "cellAge_30_59");
this.cellAge_30_59.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_60_more
//
this.cellAge_60_more.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_60_more")});
this.cellAge_60_more.Name = "cellAge_60_more";
this.cellAge_60_more.StylePriority.UseFont = false;
resources.ApplyResources(this.cellAge_60_more, "cellAge_60_more");
this.cellAge_60_more.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell94
//
this.xrTableCell94.Name = "xrTableCell94";
resources.ApplyResources(this.xrTableCell94, "xrTableCell94");
//
// cellTotal
//
this.cellTotal.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intTotal")});
this.cellTotal.Name = "cellTotal";
this.cellTotal.StylePriority.UseFont = false;
resources.ApplyResources(this.cellTotal, "cellTotal");
this.cellTotal.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellMainTotalBeforePrint);
//
// xrTableCell96
//
this.xrTableCell96.Name = "xrTableCell96";
resources.ApplyResources(this.xrTableCell96, "xrTableCell96");
//
// cellLabTested
//
this.cellLabTested.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intLabTested")});
this.cellLabTested.Name = "cellLabTested";
this.cellLabTested.StylePriority.UseFont = false;
resources.ApplyResources(this.cellLabTested, "cellLabTested");
this.cellLabTested.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellLabConfirmed
//
this.cellLabConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intLabConfirmed")});
this.cellLabConfirmed.Name = "cellLabConfirmed";
this.cellLabConfirmed.StylePriority.UseFont = false;
resources.ApplyResources(this.cellLabConfirmed, "cellLabConfirmed");
this.cellLabConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellTotalConfirmed
//
this.cellTotalConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intTotalConfirmed")});
this.cellTotalConfirmed.Name = "cellTotalConfirmed";
this.cellTotalConfirmed.StylePriority.UseFont = false;
resources.ApplyResources(this.cellTotalConfirmed, "cellTotalConfirmed");
this.cellTotalConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// CustomReportHeader
//
this.CustomReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableBody});
resources.ApplyResources(this.CustomReportHeader, "CustomReportHeader");
this.CustomReportHeader.Name = "CustomReportHeader";
this.CustomReportHeader.StylePriority.UseTextAlignment = false;
//
// spRepHumMonthlyInfectiousDiseaseTableAdapter1
//
this.spRepHumMonthlyInfectiousDiseaseTableAdapter1.ClearBeforeFill = true;
//
// spRepHumMonthlyInfectiousDiseaseFatalTableAdapter1
//
this.spRepHumMonthlyInfectiousDiseaseFatalTableAdapter1.ClearBeforeFill = true;
//
// DetailReport1
//
this.DetailReport1.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1});
this.DetailReport1.DataAdapter = this.spRepHumMonthlyInfectiousDiseaseFatalTableAdapter1;
this.DetailReport1.DataMember = "spRepHumMonthlyInfectiousDiseaseFatal";
this.DetailReport1.DataSource = this.infectiousDiseaseDataSet1;
this.DetailReport1.Level = 1;
this.DetailReport1.Name = "DetailReport1";
this.DetailReport1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// Detail1
//
this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
this.Detail1.StylePriority.UseFont = false;
this.Detail1.StylePriority.UseTextAlignment = false;
//
// cellLocation
//
this.cellLocation.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.cellLocation.BorderWidth = 0F;
resources.ApplyResources(this.cellLocation, "cellLocation");
this.cellLocation.Name = "cellLocation";
this.cellLocation.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.cellLocation.StylePriority.UseBorders = false;
this.cellLocation.StylePriority.UseBorderWidth = false;
this.cellLocation.StylePriority.UseFont = false;
this.cellLocation.StylePriority.UseTextAlignment = false;
//
// GroupFooter
//
this.GroupFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.SignatureTable});
resources.ApplyResources(this.GroupFooter, "GroupFooter");
this.GroupFooter.Name = "GroupFooter";
//
// SignatureTable
//
resources.ApplyResources(this.SignatureTable, "SignatureTable");
this.SignatureTable.Name = "SignatureTable";
this.SignatureTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.SignatureTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow26});
this.SignatureTable.StylePriority.UseFont = false;
this.SignatureTable.StylePriority.UsePadding = false;
this.SignatureTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow26
//
this.xrTableRow26.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell29});
this.xrTableRow26.Name = "xrTableRow26";
resources.ApplyResources(this.xrTableRow26, "xrTableRow26");
//
// xrTableCell29
//
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
//
// InfectiousDiseasesMonthV4
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.ReportFooter,
this.DetailReport,
this.DetailReport1,
this.GroupFooter});
resources.ApplyResources(this, "$this");
this.Version = "15.1";
this.Controls.SetChildIndex(this.GroupFooter, 0);
this.Controls.SetChildIndex(this.DetailReport1, 0);
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportFooter, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomSubheader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.infectiousDiseaseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBody)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTable tableCustomHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTable tableCustomSubheader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell cellNameOfrespondent;
private DevExpress.XtraReports.UI.XRTableCell cellActualAddress;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell cellTelephone;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell cellReportedPeriod;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell cellMonthName;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell36;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRTable tableCustomFooter;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRTable tableBody;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell43;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell46;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell44;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell62;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell63;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell65;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell66;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell67;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell68;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell69;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand CustomDetail;
private DevExpress.XtraReports.UI.ReportHeaderBand CustomReportHeader;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow22;
private DevExpress.XtraReports.UI.XRTableCell strDiseaseName;
private DevExpress.XtraReports.UI.XRTableCell cellICD10;
private DevExpress.XtraReports.UI.XRTableCell cellAge_0_1;
private DevExpress.XtraReports.UI.XRTableCell cellAge_1_4;
private DevExpress.XtraReports.UI.XRTableCell cellAge_5_14;
private DevExpress.XtraReports.UI.XRTableCell cellAge_15_19;
private DevExpress.XtraReports.UI.XRTableCell cellAge_20_29;
private DevExpress.XtraReports.UI.XRTableCell cellAge_30_59;
private DevExpress.XtraReports.UI.XRTableCell cellAge_60_more;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell94;
private DevExpress.XtraReports.UI.XRTableCell cellTotal;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell96;
private DevExpress.XtraReports.UI.XRTableCell cellLabTested;
private DevExpress.XtraReports.UI.XRTableCell cellLabConfirmed;
private DevExpress.XtraReports.UI.XRTableCell cellTotalConfirmed;
private InfectiousDiseaseMonthDataSet infectiousDiseaseDataSet1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell70;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell71;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell72;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell73;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell74;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell76;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell77;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell78;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell79;
private spRepHumMonthlyInfectiousDiseaseTableAdapter spRepHumMonthlyInfectiousDiseaseTableAdapter1;
private spRepHumMonthlyInfectiousDiseaseFatalTableAdapter spRepHumMonthlyInfectiousDiseaseFatalTableAdapter1;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell75;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell80;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell81;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell82;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell83;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell84;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell85;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell86;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell87;
private DevExpress.XtraReports.UI.XRTableCell SpecifyDiseaseCell;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport1;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.XRLabel cellLocation;
private DevExpress.XtraReports.UI.XRLabel SpecifyDiseaseHiddenLabel;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooter;
private DevExpress.XtraReports.UI.XRTable SignatureTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Buffers.Text
{
public static partial class Utf8Parser
{
private static bool TryParseByteD(ReadOnlySpan<byte> source, out byte value, out int bytesConsumed)
{
if (source.Length < 1)
goto FalseExit;
int index = 0;
int num = source[index];
int answer = 0;
if (ParserHelpers.IsDigit(num))
{
if (num == '0')
{
do
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
} while (num == '0');
if (!ParserHelpers.IsDigit(num))
goto Done;
}
answer = num - '0';
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
// Potential overflow
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = answer * 10 + num - '0';
if ((uint)answer > byte.MaxValue)
goto FalseExit; // Overflow
if ((uint)index >= (uint)source.Length)
goto Done;
if (!ParserHelpers.IsDigit(source[index]))
goto Done;
// Guaranteed overflow
goto FalseExit;
}
FalseExit:
bytesConsumed = default;
value = default;
return false;
Done:
bytesConsumed = index;
value = (byte)answer;
return true;
}
private static bool TryParseUInt16D(ReadOnlySpan<byte> source, out ushort value, out int bytesConsumed)
{
if (source.Length < 1)
goto FalseExit;
int index = 0;
int num = source[index];
int answer = 0;
if (ParserHelpers.IsDigit(num))
{
if (num == '0')
{
do
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
} while (num == '0');
if (!ParserHelpers.IsDigit(num))
goto Done;
}
answer = num - '0';
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
// Potential overflow
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = answer * 10 + num - '0';
if ((uint)answer > ushort.MaxValue)
goto FalseExit; // Overflow
if ((uint)index >= (uint)source.Length)
goto Done;
if (!ParserHelpers.IsDigit(source[index]))
goto Done;
// Guaranteed overflow
goto FalseExit;
}
FalseExit:
bytesConsumed = default;
value = default;
return false;
Done:
bytesConsumed = index;
value = (ushort)answer;
return true;
}
private static bool TryParseUInt32D(ReadOnlySpan<byte> source, out uint value, out int bytesConsumed)
{
if (source.Length < 1)
goto FalseExit;
int index = 0;
int num = source[index];
int answer = 0;
if (ParserHelpers.IsDigit(num))
{
if (num == '0')
{
do
{
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
} while (num == '0');
if (!ParserHelpers.IsDigit(num))
goto Done;
}
answer = num - '0';
index++;
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
answer = 10 * answer + num - '0';
// Potential overflow
if ((uint)index >= (uint)source.Length)
goto Done;
num = source[index];
if (!ParserHelpers.IsDigit(num))
goto Done;
index++;
if (((uint)answer) > uint.MaxValue / 10 || (((uint)answer) == uint.MaxValue / 10 && num > '5'))
goto FalseExit; // Overflow
answer = answer * 10 + num - '0';
if ((uint)index >= (uint)source.Length)
goto Done;
if (!ParserHelpers.IsDigit(source[index]))
goto Done;
// Guaranteed overflow
goto FalseExit;
}
FalseExit:
bytesConsumed = default;
value = default;
return false;
Done:
bytesConsumed = index;
value = (uint)answer;
return true;
}
private static bool TryParseUInt64D(ReadOnlySpan<byte> source, out ulong value, out int bytesConsumed)
{
if (source.Length < 1)
{
bytesConsumed = 0;
value = default;
return false;
}
// Parse the first digit separately. If invalid here, we need to return false.
ulong firstDigit = source[0] - 48u; // '0'
if (firstDigit > 9)
{
bytesConsumed = 0;
value = default;
return false;
}
ulong parsedValue = firstDigit;
if (source.Length < ParserHelpers.Int64OverflowLength)
{
// Length is less than Parsers.Int64OverflowLength; overflow is not possible
for (int index = 1; index < source.Length; index++)
{
ulong nextDigit = source[index] - 48u; // '0'
if (nextDigit > 9)
{
bytesConsumed = index;
value = parsedValue;
return true;
}
parsedValue = parsedValue * 10 + nextDigit;
}
}
else
{
// Length is greater than Parsers.Int64OverflowLength; overflow is only possible after Parsers.Int64OverflowLength
// digits. There may be no overflow after Parsers.Int64OverflowLength if there are leading zeroes.
for (int index = 1; index < ParserHelpers.Int64OverflowLength - 1; index++)
{
ulong nextDigit = source[index] - 48u; // '0'
if (nextDigit > 9)
{
bytesConsumed = index;
value = parsedValue;
return true;
}
parsedValue = parsedValue * 10 + nextDigit;
}
for (int index = ParserHelpers.Int64OverflowLength - 1; index < source.Length; index++)
{
ulong nextDigit = source[index] - 48u; // '0'
if (nextDigit > 9)
{
bytesConsumed = index;
value = parsedValue;
return true;
}
// If parsedValue > (ulong.MaxValue / 10), any more appended digits will cause overflow.
// if parsedValue == (ulong.MaxValue / 10), any nextDigit greater than 5 implies overflow.
if (parsedValue > ulong.MaxValue / 10 || (parsedValue == ulong.MaxValue / 10 && nextDigit > 5))
{
bytesConsumed = 0;
value = default;
return false;
}
parsedValue = parsedValue * 10 + nextDigit;
}
}
bytesConsumed = source.Length;
value = parsedValue;
return true;
}
}
}
| |
namespace Macabresoft.Macabre2D.Framework;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Macabresoft.Core;
using Microsoft.Xna.Framework;
/// <summary>
/// The type of collider being used.
/// </summary>
public enum ColliderType {
/// <summary>
/// Circle collider.
/// </summary>
Circle,
/// <summary>
/// Polygon collider.
/// </summary>
Polygon,
/// <summary>
/// Some other type of collider. Most custom colliders will fall into this category.
/// </summary>
Other,
/// <summary>
/// Reserved for the single empty collider instance.
/// </summary>
Empty
}
/// <summary>
/// Collider to be attached to bodies in the physics engine.
/// </summary>
[DataContract]
public abstract class Collider : NotifyPropertyChanged, IBoundable {
private readonly ResettableLazy<BoundingArea> _boundingArea;
private readonly ResettableLazy<Transform> _transform;
private Vector2 _offset;
private Layers _overrideLayers = Layers.None;
/// <summary>
/// Initializes a new instance of the <see cref="Collider" /> class.
/// </summary>
protected Collider() {
this._transform = new ResettableLazy<Transform>(() => this.Body?.GetWorldTransform(this.Offset) ?? Transform.Origin);
this._boundingArea = new ResettableLazy<BoundingArea>(this.CreateBoundingArea);
}
/// <inheritdoc />
public BoundingArea BoundingArea => this._boundingArea.Value;
/// <summary>
/// Gets the type of the collider.
/// </summary>
/// <value>The type of the collider.</value>
public abstract ColliderType ColliderType { get; }
/// <summary>
/// Gets the transform.
/// </summary>
/// <value>The transform.</value>
public Transform Transform => this._transform.Value;
/// <summary>
/// Gets the body that this collider is attached to.
/// </summary>
/// <value>The body.</value>
public IPhysicsBody? Body { get; private set; }
/// <summary>
/// Gets the layers.
/// </summary>
/// <value>The layers.</value>
[DataMember(Name = "Collider Layers")]
public Layers Layers {
get => this._overrideLayers != Layers.None ? this._overrideLayers : this.Body?.Layers ?? Layers.None;
internal set => this.Set(ref this._overrideLayers, value);
}
/// <summary>
/// Gets the offset.
/// </summary>
/// <value>The offset.</value>
[DataMember]
public Vector2 Offset {
get => this._offset;
set {
if (this.Set(ref this._offset, value)) {
this.Reset();
}
}
}
/// <summary>
/// Gets a value indicating whether or not this instance collides with the specified collider.
/// </summary>
/// <param name="other">The other collider.</param>
/// <param name="collision">The collision.</param>
/// <returns>A value indicating whether or not the collision occurred.</returns>
public bool CollidesWith(Collider other, out CollisionEventArgs? collision) {
if (!this.BoundingArea.Overlaps(other.BoundingArea)) {
collision = null;
return false;
}
var overlap = float.MaxValue;
var smallestAxis = Vector2.Zero;
var axes = new List<Vector2>(this.GetAxesForSat(other));
axes.AddRange(other.GetAxesForSat(this));
var thisContainsOther = true;
var otherContainsThis = true;
foreach (var axis in axes) {
var projectionA = this.GetProjection(axis);
var projectionB = other.GetProjection(axis);
if (projectionA.OverlapsWith(projectionB)) {
var currentOverlap = projectionA.GetOverlap(projectionB);
var aContainsB = projectionA.Contains(projectionB);
var bContainsA = projectionB.Contains(projectionA);
// Information gathering for the collision
if (!aContainsB) {
thisContainsOther = false;
}
if (!bContainsA) {
otherContainsThis = false;
}
if (aContainsB || bContainsA) {
var minimum = Math.Abs(projectionA.Minimum - projectionB.Minimum);
var maximum = Math.Abs(projectionA.Maximum - projectionB.Maximum);
if (minimum < maximum) {
currentOverlap += minimum;
}
else {
currentOverlap += maximum;
}
}
if (currentOverlap < overlap) {
overlap = currentOverlap;
smallestAxis = axis;
}
}
else {
// Gap was found, return false.
collision = null;
return false;
}
}
var minimumTranslation = overlap * smallestAxis;
// This is important to determine which direction this collider has to move to be
// separated from the other collider.
if (Vector2.Dot(this.GetCenter() - other.GetCenter(), minimumTranslation) < 0) {
minimumTranslation = -minimumTranslation;
}
collision = new CollisionEventArgs(this, other, smallestAxis, minimumTranslation, thisContainsOther, otherContainsThis);
return true;
}
/// <summary>
/// Determines whether this collider contains the other collider.
/// </summary>
/// <param name="other">The other collider.</param>
/// <returns><c>true</c> if this collider contains the other collider; otherwise, <c>false</c>.</returns>
public abstract bool Contains(Collider other);
/// <summary>
/// Determines whether this collider contains the specified point.
/// </summary>
/// <param name="point">The point.</param>
/// <returns><c>true</c> if this collider contains the specified point; otherwise, <c>false</c>.</returns>
public abstract bool Contains(Vector2 point);
/// <summary>
/// Gets the axes to test for the Separating Axis Theorem.
/// </summary>
/// <param name="other">The other collider.</param>
/// <returns>The axes to test for the Separating Axis Theorem</returns>
public abstract IReadOnlyCollection<Vector2> GetAxesForSat(Collider other);
/// <summary>
/// Gets the center of the collider.
/// </summary>
/// <returns>The center of the collider.</returns>
public abstract Vector2 GetCenter();
/// <summary>
/// Gets the projection of this collider onto the specified axis.
/// </summary>
/// <param name="axis">The axis.</param>
/// <returns>The projection of this collider onto the specified axis.</returns>
public abstract Projection GetProjection(Vector2 axis);
/// <summary>
/// Initializes the specified body.
/// </summary>
/// <param name="body">The body.</param>
public void Initialize(IPhysicsBody body) {
this.Body = body;
this.Reset();
}
/// <summary>
/// Determines whether [is candidate for collision] [the specified other].
/// </summary>
/// <param name="other">The other collider.</param>
/// <returns></returns>
public bool IsCandidateForCollision(Collider other) {
return this.BoundingArea.Overlaps(other.BoundingArea);
}
/// <summary>
/// Determines whether this collider is hit by the specified ray.
/// </summary>
/// <param name="ray">The ray.</param>
/// <param name="hit">The hit.</param>
/// <returns><c>true</c> if this collider is hit by the specified ray; otherwise, <c>false</c>.</returns>
public bool IsHitBy(LineSegment ray, out RaycastHit hit) {
if (!ray.BoundingArea.Overlaps(this.BoundingArea)) {
hit = RaycastHit.Empty;
return false;
}
return this.TryHit(ray, out hit);
}
/// <summary>
/// Resets this instance.
/// </summary>
public virtual void Reset() {
this.ResetLazyFields();
}
/// <summary>
/// Creates the bounding area.
/// </summary>
/// <returns>The created bounding area.</returns>
protected abstract BoundingArea CreateBoundingArea();
/// <summary>
/// Gets the normal from the line defined by two points.
/// </summary>
/// <param name="firstPoint">The first point.</param>
/// <param name="secondPoint">The second point.</param>
/// <returns>The normal.</returns>
protected Vector2 GetNormal(Vector2 firstPoint, Vector2 secondPoint) {
var edge = firstPoint - secondPoint;
var normal = edge.GetPerpendicular();
normal.Normalize();
return normal;
}
/// <summary>
/// Resets the lazy fields.
/// </summary>
protected virtual void ResetLazyFields() {
this._transform.Reset();
this._boundingArea.Reset();
}
/// <summary>
/// Tries to process a hit between this collider and a ray.
/// </summary>
/// <param name="ray">The ray.</param>
/// <param name="result">The result.</param>
/// <returns>A value indicating whether or not a hit occurred.</returns>
protected abstract bool TryHit(LineSegment ray, out RaycastHit result);
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace STIOnboardingPortal.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CommonHelper.cs" company="CompanyName">
// Copyright info.
// </copyright>
//-----------------------------------------------------------------------
namespace Distribox.CommonLib
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
/// <summary>
/// Common helpers.
/// </summary>
public static class CommonHelper
{
/// <summary>
/// Random Generator
/// </summary>
private static Random rd = new Random();
/// <summary>
/// Gets the SHA1 hash of a file.
/// </summary>
/// <returns>The SHA1 hash.</returns>
/// <param name="pathName">Path name.</param>
public static string GetSHA1Hash(string pathName)
{
string strResult = string.Empty;
string strHashData = string.Empty;
byte[] arrbytHashValue;
System.IO.FileStream fileStream = null;
SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider();
// TODO comment for find another solution
while (true)
{
try
{
fileStream = new FileStream(pathName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
arrbytHashValue = sha1Hasher.ComputeHash(fileStream);
fileStream.Close();
break;
}
catch
{
Thread.Sleep(1);
}
}
strHashData = BitConverter.ToString(arrbytHashValue);
strHashData = strHashData.Replace("-", string.Empty);
strResult = strHashData;
return strResult;
}
/// <summary>
/// Gets a random hash.
/// </summary>
/// <returns>The random hash.</returns>
public static string GetRandomHash()
{
return rd.Next().ToString();
}
/// <summary>
/// Deserialize the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
/// <returns>Deserialize result.</returns>
public static T Deserialize<T>(this string input)
{
return JsonConvert.DeserializeObject<T>(input);
}
/// <summary>
/// Deserialize the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
/// <returns>Deserialize result.</returns>
public static T Deserialize<T>(this byte[] input)
{
return Deserialize<T>(ByteToString(input));
}
/// <summary>
/// Serialize the specified input inline.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>Serialize result.</returns>
public static string SerializeInline(this object input)
{
return JsonConvert.SerializeObject(input);
}
/// <summary>
/// Serialize the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>Serialize result.</returns>
public static string Serialize(this object input)
{
return JsonConvert.SerializeObject(input, Formatting.Indented);
}
/// <summary>
/// Serializes as bytes.
/// </summary>
/// <returns>The as bytes.</returns>
/// <param name="input">The input.</param>
/// <returns>Serialize result.</returns>
public static byte[] SerializeAsBytes(this object input)
{
return StringToByte(Serialize(input));
}
/// <summary>
/// Reads the object from file.
/// </summary>
/// <returns>The object.</returns>
/// <param name="filename">The filename.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static T ReadObject<T>(string filename)
{
string str = File.ReadAllText(filename);
return Deserialize<T>(str);
}
/// <summary>
/// Writes the object to file.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="filename">The filename.</param>
public static void WriteObject(this object input, string filename)
{
string str = input.Serialize();
File.WriteAllText(filename, str);
}
/// <summary>
/// Converts string to bytes.
/// </summary>
/// <returns>The to byte.</returns>
/// <param name="str">The string.</param>
public static byte[] StringToByte(string str)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(str);
}
/// <summary>
/// Converts bytes to string.
/// </summary>
/// <returns>The to string.</returns>
/// <param name="bytes">The bytes.</param>
/// <returns>The string.</returns>
public static string ByteToString(byte[] bytes)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetString(bytes);
}
/// <summary>
/// Initialize all the folders and files in monitored file.
/// </summary>
public static void InitializeFolder()
{
if (!Directory.Exists(Config.RootFolder))
{
Directory.CreateDirectory(Config.RootFolder);
}
if (!Directory.Exists(Config.MetaFolder))
{
Directory.CreateDirectory(Config.MetaFolder);
}
if (!Directory.Exists(Config.MetaFolderTmp))
{
Directory.CreateDirectory(Config.MetaFolderTmp);
}
if (!Directory.Exists(Config.MetaFolderData))
{
Directory.CreateDirectory(Config.MetaFolderData);
}
if (!File.Exists(Config.VersionListFilePath))
{
File.WriteAllText(Config.VersionListFilePath, "[]");
}
}
/// <summary>
/// Write all bytes to a stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="bytes">The bytes.</param>
public static void WriteAllBytes(this Stream stream, byte[] bytes)
{
stream.Write(bytes, 0, bytes.Length);
}
/// <summary>
/// Read all bytes from a stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>The bytes.</returns>
public static byte[] ReadAllBytes(this Stream stream)
{
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
return ms.ToArray();
}
/// <summary>
/// Get hash code of a list.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="list">The list.</param>
/// <returns>The hash code.</returns>
public static int GetHashCode<T>(IEnumerable<T> list)
{
unchecked
{
int hash = 0;
foreach (var item in list)
{
hash = (31 * hash) + item.GetHashCode();
}
return hash;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Net.Mail;
using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Net.Mime
{
internal static class MailBnfHelper
{
// characters allowed in atoms
internal static bool[] Atext = new bool[128];
// characters allowed in quoted strings (not including unicode)
internal static bool[] Qtext = new bool[128];
// characters allowed in domain literals
internal static bool[] Dtext = new bool[128];
// characters allowed in header names
internal static bool[] Ftext = new bool[128];
// characters allowed in tokens
internal static bool[] Ttext = new bool[128];
// characters allowed inside of comments
internal static bool[] Ctext = new bool[128];
internal static readonly int Ascii7bitMaxValue = 127;
internal static readonly char Quote = '\"';
internal static readonly char Space = ' ';
internal static readonly char Tab = '\t';
internal static readonly char CR = '\r';
internal static readonly char LF = '\n';
internal static readonly char StartComment = '(';
internal static readonly char EndComment = ')';
internal static readonly char Backslash = '\\';
internal static readonly char At = '@';
internal static readonly char EndAngleBracket = '>';
internal static readonly char StartAngleBracket = '<';
internal static readonly char StartSquareBracket = '[';
internal static readonly char EndSquareBracket = ']';
internal static readonly char Comma = ',';
internal static readonly char Dot = '.';
internal static readonly IList<char> Whitespace;
static MailBnfHelper()
{
// NOTE: See RFC 2822 for more detail. By default, every value in the array is false and only
// those values which are allowed in that particular set are then set to true. The numbers
// annotating each definition below are the range of ASCII values which are allowed in that definition.
// all allowed whitespace characters
Whitespace = new List<char>();
Whitespace.Add(Tab);
Whitespace.Add(Space);
Whitespace.Add(CR);
Whitespace.Add(LF);
// atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
for (int i = '0'; i <= '9'; i++) { Atext[i] = true; }
for (int i = 'A'; i <= 'Z'; i++) { Atext[i] = true; }
for (int i = 'a'; i <= 'z'; i++) { Atext[i] = true; }
Atext['!'] = true;
Atext['#'] = true;
Atext['$'] = true;
Atext['%'] = true;
Atext['&'] = true;
Atext['\''] = true;
Atext['*'] = true;
Atext['+'] = true;
Atext['-'] = true;
Atext['/'] = true;
Atext['='] = true;
Atext['?'] = true;
Atext['^'] = true;
Atext['_'] = true;
Atext['`'] = true;
Atext['{'] = true;
Atext['|'] = true;
Atext['}'] = true;
Atext['~'] = true;
// fqtext = %d1-9 / %d11 / %d12 / %d14-33 / %d35-91 / %d93-127
for (int i = 1; i <= 9; i++) { Qtext[i] = true; }
Qtext[11] = true;
Qtext[12] = true;
for (int i = 14; i <= 33; i++) { Qtext[i] = true; }
for (int i = 35; i <= 91; i++) { Qtext[i] = true; }
for (int i = 93; i <= 127; i++) { Qtext[i] = true; }
// fdtext = %d1-8 / %d11 / %d12 / %d14-31 / %d33-90 / %d94-127
for (int i = 1; i <= 8; i++) { Dtext[i] = true; }
Dtext[11] = true;
Dtext[12] = true;
for (int i = 14; i <= 31; i++) { Dtext[i] = true; }
for (int i = 33; i <= 90; i++) { Dtext[i] = true; }
for (int i = 94; i <= 127; i++) { Dtext[i] = true; }
// ftext = %d33-57 / %d59-126
for (int i = 33; i <= 57; i++) { Ftext[i] = true; }
for (int i = 59; i <= 126; i++) { Ftext[i] = true; }
// ttext = %d33-126 except '()<>@,;:\"/[]?='
for (int i = 33; i <= 126; i++) { Ttext[i] = true; }
Ttext['('] = false;
Ttext[')'] = false;
Ttext['<'] = false;
Ttext['>'] = false;
Ttext['@'] = false;
Ttext[','] = false;
Ttext[';'] = false;
Ttext[':'] = false;
Ttext['\\'] = false;
Ttext['"'] = false;
Ttext['/'] = false;
Ttext['['] = false;
Ttext[']'] = false;
Ttext['?'] = false;
Ttext['='] = false;
// ctext- %d1-8 / %d11 / %d12 / %d14-31 / %33-39 / %42-91 / %93-127
for (int i = 1; i <= 8; i++) { Ctext[i] = true; }
Ctext[11] = true;
Ctext[12] = true;
for (int i = 14; i <= 31; i++) { Ctext[i] = true; }
for (int i = 33; i <= 39; i++) { Ctext[i] = true; }
for (int i = 42; i <= 91; i++) { Ctext[i] = true; }
for (int i = 93; i <= 127; i++) { Ctext[i] = true; }
}
internal static bool SkipCFWS(string data, ref int offset)
{
int comments = 0;
for (; offset < data.Length; offset++)
{
if (data[offset] > 127)
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
else if (data[offset] == '\\' && comments > 0)
offset += 2;
else if (data[offset] == '(')
comments++;
else if (data[offset] == ')')
comments--;
else if (data[offset] != ' ' && data[offset] != '\t' && comments == 0)
return true;
if (comments < 0)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
}
//returns false if end of string
return false;
}
internal static void ValidateHeaderName(string data)
{
int offset = 0;
for (; offset < data.Length; offset++)
{
if (data[offset] > Ftext.Length || !Ftext[data[offset]])
throw new FormatException(SR.InvalidHeaderName);
}
if (offset == 0)
throw new FormatException(SR.InvalidHeaderName);
}
internal static string ReadQuotedString(string data, ref int offset, StringBuilder builder)
{
return ReadQuotedString(data, ref offset, builder, false, false);
}
internal static string ReadQuotedString(string data, ref int offset, StringBuilder builder, bool doesntRequireQuotes, bool permitUnicodeInDisplayName)
{
// assume first char is the opening quote
if (!doesntRequireQuotes)
{
++offset;
}
int start = offset;
StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
for (; offset < data.Length; offset++)
{
if (data[offset] == '\\')
{
localBuilder.Append(data, start, offset - start);
start = ++offset;
}
else if (data[offset] == '"')
{
localBuilder.Append(data, start, offset - start);
offset++;
return (builder != null ? null : localBuilder.ToString());
}
else if (data[offset] == '=' &&
data.Length > offset + 3 &&
data[offset + 1] == '\r' &&
data[offset + 2] == '\n' &&
(data[offset + 3] == ' ' || data[offset + 3] == '\t'))
{
//it's a soft crlf so it's ok
offset += 3;
}
else if (permitUnicodeInDisplayName)
{
//if data contains unicode and unicode is permitted, then
//it is valid in a quoted string in a header.
if (data[offset] <= Ascii7bitMaxValue && !Qtext[data[offset]])
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
//not permitting unicode, in which case unicode is a formatting error
else if (data[offset] > Ascii7bitMaxValue || !Qtext[data[offset]])
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
}
if (doesntRequireQuotes)
{
localBuilder.Append(data, start, offset - start);
return (builder != null ? null : localBuilder.ToString());
}
throw new FormatException(SR.MailHeaderFieldMalformedHeader);
}
internal static string ReadParameterAttribute(string data, ref int offset, StringBuilder builder)
{
if (!SkipCFWS(data, ref offset))
return null; //
return ReadToken(data, ref offset, null);
}
internal static string ReadToken(string data, ref int offset, StringBuilder builder)
{
int start = offset;
for (; offset < data.Length; offset++)
{
if (data[offset] > Ascii7bitMaxValue)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
else if (!Ttext[data[offset]])
{
break;
}
}
if (start == offset)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
return data.Substring(start, offset - start);
}
private static string[] s_months = new string[] { null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
internal static string GetDateTimeString(DateTime value, StringBuilder builder)
{
StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
localBuilder.Append(value.Day);
localBuilder.Append(' ');
localBuilder.Append(s_months[value.Month]);
localBuilder.Append(' ');
localBuilder.Append(value.Year);
localBuilder.Append(' ');
if (value.Hour <= 9)
{
localBuilder.Append('0');
}
localBuilder.Append(value.Hour);
localBuilder.Append(':');
if (value.Minute <= 9)
{
localBuilder.Append('0');
}
localBuilder.Append(value.Minute);
localBuilder.Append(':');
if (value.Second <= 9)
{
localBuilder.Append('0');
}
localBuilder.Append(value.Second);
string offset = TimeZoneInfo.Local.GetUtcOffset(value).ToString();
if (offset[0] != '-')
{
localBuilder.Append(" +");
}
else
{
localBuilder.Append(' ');
}
string[] offsetFields = offset.Split(':');
localBuilder.Append(offsetFields[0]);
localBuilder.Append(offsetFields[1]);
return (builder != null ? null : localBuilder.ToString());
}
internal static void GetTokenOrQuotedString(string data, StringBuilder builder, bool allowUnicode)
{
int offset = 0, start = 0;
for (; offset < data.Length; offset++)
{
if (CheckForUnicode(data[offset], allowUnicode))
{
continue;
}
if (!Ttext[data[offset]] || data[offset] == ' ')
{
builder.Append('"');
for (; offset < data.Length; offset++)
{
if (CheckForUnicode(data[offset], allowUnicode))
{
continue;
}
else if (IsFWSAt(data, offset)) // Allow FWS == "\r\n "
{
// No-op, skip these three chars
offset++;
offset++;
}
else if (!Qtext[data[offset]])
{
builder.Append(data, start, offset - start);
builder.Append('\\');
start = offset;
}
}
builder.Append(data, start, offset - start);
builder.Append('"');
return;
}
}
//always a quoted string if it was empty.
if (data.Length == 0)
{
builder.Append("\"\"");
}
// Token, no quotes needed
builder.Append(data);
}
private static bool CheckForUnicode(char ch, bool allowUnicode)
{
if (ch < Ascii7bitMaxValue)
{
return false;
}
if (!allowUnicode)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, ch));
}
return true;
}
internal static bool HasCROrLF(string data)
{
for (int i = 0; i < data.Length; i++)
{
if (data[i] == '\r' || data[i] == '\n')
{
return true;
}
}
return false;
}
// Is there a FWS ("\r\n " or "\r\n\t") starting at the given index?
internal static bool IsFWSAt(string data, int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < data.Length);
return (data[index] == MailBnfHelper.CR
&& index + 2 < data.Length
&& data[index + 1] == MailBnfHelper.LF
&& (data[index + 2] == MailBnfHelper.Space
|| data[index + 2] == MailBnfHelper.Tab));
}
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Text;
using System.Threading;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* This probably needs some throttling mechanism but
* it's wide open right now. This applies to both
* number of requests and data volume.
*
* Linden puts all kinds of header fields in the requests.
* Not doing any of that:
* User-Agent
* X-SecondLife-Shard
* X-SecondLife-Object-Name
* X-SecondLife-Object-Key
* X-SecondLife-Region
* X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
public class HttpRequestModule : IRegionModule, IHttpRequestModule
{
private object HttpListLock = new object();
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
private string m_proxyurl = "";
private string m_proxyexcepts = "";
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestClass> m_pendingRequests;
private Scene m_scene;
// private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public HttpRequestModule()
{
}
#region IHttpRequestModule Members
public UUID MakeHttpRequest(string url, string parameters, string body)
{
return UUID.Zero;
}
public UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
if (parameters != null)
{
string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length; i += 2)
{
switch (Int32.Parse(parms[i]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
htc.HttpMethod = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
// TODO implement me
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
// TODO implement me
break;
}
}
}
htc.LocalID = localID;
htc.ItemID = itemID;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = httpTimeout;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
lock (HttpListLock)
{
m_pendingRequests.Add(reqID, htc);
}
htc.Process();
return reqID;
}
public void StopHttpRequest(uint m_localID, UUID m_itemID)
{
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{
tmpReq.Stop();
m_pendingRequests.Remove(m_itemID);
}
}
}
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finsihed. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (HttpListLock)
{
foreach (UUID luid in m_pendingRequests.Keys)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
{
return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(id, out tmpReq))
{
tmpReq.Stop();
tmpReq = null;
m_pendingRequests.Remove(id);
}
}
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
}
public class HttpRequestClass: IServiceRequest
{
// Constants for parameters
// public const int HTTP_BODY_MAXLENGTH = 2;
// public const int HTTP_METHOD = 0;
// public const int HTTP_MIMETYPE = 1;
// public const int HTTP_VERIFY_CERT = 3;
private bool _finished;
public bool Finished
{
get { return _finished; }
}
// public int HttpBodyMaxLen = 2048; // not implemented
// Parameter members and default values
public string HttpMethod = "GET";
public string HttpMIMEType = "text/plain;charset=utf-8";
public int HttpTimeout;
// public bool HttpVerifyCert = true; // not implemented
private Thread httpThread;
// Request info
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
public DateTime Next;
public string proxyurl;
public string proxyexcepts;
public string OutboundBody;
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public HttpWebRequest Request;
public string ResponseBody;
public List<string> ResponseMetadata;
public Dictionary<string, string> ResponseHeaders;
public int Status;
public string Url;
public void Process()
{
httpThread = new Thread(SendRequest);
httpThread.Name = "HttpRequestThread";
httpThread.Priority = ThreadPriority.BelowNormal;
httpThread.IsBackground = true;
_finished = false;
httpThread.Start();
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
HttpWebResponse response = null;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
string tempString = null;
int count = 0;
try
{
Request = (HttpWebRequest) WebRequest.Create(Url);
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
if (proxyurl != null && proxyurl.Length > 0)
{
if (proxyexcepts != null && proxyexcepts.Length > 0)
{
string[] elist = proxyexcepts.Split(';');
Request.Proxy = new WebProxy(proxyurl, true, elist);
}
else
{
Request.Proxy = new WebProxy(proxyurl, true);
}
}
foreach (KeyValuePair<string, string> entry in ResponseHeaders)
if (entry.Key.ToLower().Equals("user-agent"))
Request.UserAgent = entry.Value;
else
Request.Headers[entry.Key] = entry.Value;
// Encode outbound data
if (OutboundBody.Length > 0)
{
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
Stream bstream = Request.GetRequestStream();
bstream.Write(data, 0, data.Length);
bstream.Close();
}
Request.Timeout = HttpTimeout;
// execute the request
response = (HttpWebResponse) Request.GetResponse();
Stream resStream = response.GetResponseStream();
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Util.UTF8.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
} while (count > 0); // any more data to read?
ResponseBody = sb.ToString();
}
catch (Exception e)
{
if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response;
Status = (int)webRsp.StatusCode;
ResponseBody = webRsp.StatusDescription;
}
else
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
}
_finished = true;
return;
}
finally
{
if (response != null)
response.Close();
}
Status = (int)OSHttpStatusCode.SuccessOk;
_finished = true;
}
public void Stop()
{
try
{
httpThread.Abort();
}
catch (Exception)
{
}
}
}
}
| |
// 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.Xml;
using System.Runtime.Serialization;
using System.Globalization;
namespace System.Runtime.Serialization.Json
{
internal class JsonReaderDelegator : XmlReaderDelegator
{
private DateTimeFormat _dateTimeFormat;
private DateTimeArrayJsonHelperWithString _dateTimeArrayHelper;
public JsonReaderDelegator(XmlReader reader)
: base(reader)
{
}
public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat)
: this(reader)
{
_dateTimeFormat = dateTimeFormat;
}
internal XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
if (this.dictionaryReader == null)
{
return null;
}
else
{
return dictionaryReader.Quotas;
}
}
}
private DateTimeArrayJsonHelperWithString DateTimeArrayHelper
{
get
{
if (_dateTimeArrayHelper == null)
{
_dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(_dateTimeFormat);
}
return _dateTimeArrayHelper;
}
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = string.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal override char ReadContentAsChar()
{
return XmlConvert.ToChar(ReadContentAsString());
}
internal override XmlQualifiedName ReadContentAsQName()
{
return ParseQualifiedName(ReadContentAsString());
}
internal override char ReadElementContentAsChar()
{
return XmlConvert.ToChar(ReadElementContentAsString());
}
public override byte[] ReadContentAsBase64()
{
if (isEndOfEmptyElement)
return Array.Empty<byte>();
byte[] buffer;
if (dictionaryReader == null)
{
XmlDictionaryReader tempDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
buffer = ByteArrayHelperWithString.Instance.ReadArray(tempDictionaryReader, JsonGlobals.itemString, string.Empty, tempDictionaryReader.Quotas.MaxArrayLength);
}
else
{
buffer = ByteArrayHelperWithString.Instance.ReadArray(dictionaryReader, JsonGlobals.itemString, string.Empty, dictionaryReader.Quotas.MaxArrayLength);
}
return buffer;
}
internal override byte[] ReadElementContentAsBase64()
{
if (isEndOfEmptyElement)
{
throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"));
}
bool isEmptyElement = reader.IsStartElement() && reader.IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
reader.Read();
buffer = Array.Empty<byte>();
}
else
{
reader.ReadStartElement();
buffer = ReadContentAsBase64();
reader.ReadEndElement();
}
return buffer;
}
internal override DateTime ReadContentAsDateTime()
{
return ParseJsonDate(ReadContentAsString(), _dateTimeFormat);
}
internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat)
{
if (dateTimeFormat == null)
{
return ParseJsonDateInDefaultFormat(originalDateTimeValue);
}
else
{
return DateTime.ParseExact(originalDateTimeValue, dateTimeFormat.FormatString, dateTimeFormat.FormatProvider, dateTimeFormat.DateTimeStyles);
}
}
internal static DateTime ParseJsonDateInDefaultFormat(string originalDateTimeValue)
{
// Dates are represented in JSON as "\/Date(number of ticks)\/".
// The number of ticks is the number of milliseconds since January 1, 1970.
string dateTimeValue;
if (!string.IsNullOrEmpty(originalDateTimeValue))
{
dateTimeValue = originalDateTimeValue.Trim();
}
else
{
dateTimeValue = originalDateTimeValue;
}
if (string.IsNullOrEmpty(dateTimeValue) ||
!dateTimeValue.StartsWith(JsonGlobals.DateTimeStartGuardReader, StringComparison.Ordinal) ||
!dateTimeValue.EndsWith(JsonGlobals.DateTimeEndGuardReader, StringComparison.Ordinal))
{
throw new FormatException(SR.Format(SR.JsonInvalidDateTimeString, originalDateTimeValue, JsonGlobals.DateTimeStartGuardWriter, JsonGlobals.DateTimeEndGuardWriter));
}
string ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8);
long millisecondsSinceUnixEpoch;
DateTimeKind dateTimeKind = DateTimeKind.Utc;
int indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1);
if (indexOfTimeZoneOffset == -1)
{
indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1);
}
if (indexOfTimeZoneOffset != -1)
{
dateTimeKind = DateTimeKind.Local;
ticksvalue = ticksvalue.Substring(0, indexOfTimeZoneOffset);
}
try
{
millisecondsSinceUnixEpoch = long.Parse(ticksvalue, CultureInfo.InvariantCulture);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
// Convert from # milliseconds since epoch to # of 100-nanosecond units, which is what DateTime understands
long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks;
try
{
DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc);
switch (dateTimeKind)
{
case DateTimeKind.Local:
return dateTime.ToLocalTime();
case DateTimeKind.Unspecified:
return DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified);
case DateTimeKind.Utc:
default:
return dateTime;
}
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception);
}
}
internal override DateTime ReadElementContentAsDateTime()
{
return ParseJsonDate(ReadElementContentAsString(), _dateTimeFormat);
}
#if USE_REFEMIT
public override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
#else
internal override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out DateTime[] array)
{
return TryReadJsonDateTimeArray(context, itemName, itemNamespace, arrayLength, out array);
}
internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context,
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out DateTime[] array)
{
if ((dictionaryReader == null) || (arrayLength != -1))
{
array = null;
return false;
}
array = this.DateTimeArrayHelper.ReadArray(dictionaryReader, XmlDictionaryString.GetString(itemName), XmlDictionaryString.GetString(itemNamespace), GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
return true;
}
private class DateTimeArrayJsonHelperWithString : ArrayHelper<string, DateTime>
{
private DateTimeFormat _dateTimeFormat;
public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat)
{
_dateTimeFormat = dateTimeFormat;
}
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
XmlJsonReader.CheckArray(array, offset, count);
int actual = 0;
while (actual < count && reader.IsStartElement(JsonGlobals.itemString, string.Empty))
{
array[offset + actual] = JsonReaderDelegator.ParseJsonDate(reader.ReadElementContentAsString(), _dateTimeFormat);
actual++;
}
return actual;
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
throw NotImplemented.ByDesign;
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
internal override ulong ReadContentAsUnsignedLong()
{
string value = reader.ReadContentAsString();
if (value == null || value.Length == 0)
{
throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64")));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
internal override ulong ReadElementContentAsUnsignedLong()
{
if (isEndOfEmptyElement)
{
throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"));
}
string value = reader.ReadElementContentAsString();
if (value == null || value.Length == 0)
{
throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64")));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public partial class ByteTests
{
[Fact]
public static void Ctor_Empty()
{
var b = new byte();
Assert.Equal(0, b);
}
[Fact]
public static void Ctor_Value()
{
byte b = 41;
Assert.Equal(41, b);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0xFF, byte.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(0, byte.MinValue);
}
[Theory]
[InlineData((byte)234, (byte)234, 0)]
[InlineData((byte)234, byte.MinValue, 1)]
[InlineData((byte)234, (byte)0, 1)]
[InlineData((byte)234, (byte)123, 1)]
[InlineData((byte)234, (byte)235, -1)]
[InlineData((byte)234, byte.MaxValue, -1)]
[InlineData((byte)234, null, 1)]
public void CompareTo_Other_ReturnsExpected(byte i, object value, int expected)
{
if (value is byte byteValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(byteValue)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData(234)]
public void CompareTo_ObjectNotByte_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => ((byte)123).CompareTo(value));
}
[Theory]
[InlineData((byte)78, (byte)78, true)]
[InlineData((byte)78, (byte)0, false)]
[InlineData((byte)0, (byte)0, true)]
[InlineData((byte)78, null, false)]
[InlineData((byte)78, "78", false)]
[InlineData((byte)78, 78, false)]
public static void Equals(byte b, object obj, bool expected)
{
if (obj is byte b2)
{
Assert.Equal(expected, b.Equals(b2));
Assert.Equal(expected, b.GetHashCode().Equals(b2.GetHashCode()));
Assert.Equal(b, b.GetHashCode());
}
Assert.Equal(expected, b.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsByte()
{
Assert.Equal(TypeCode.Byte, ((byte)1).GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
foreach (NumberFormatInfo emptyFormat in new[] { null, NumberFormatInfo.CurrentInfo })
{
yield return new object[] { (byte)0, "G", emptyFormat, "0" };
yield return new object[] { (byte)123, "G", emptyFormat, "123" };
yield return new object[] { byte.MaxValue, "G", emptyFormat, "255" };
yield return new object[] { (byte)123, "D", emptyFormat, "123" };
yield return new object[] { (byte)123, "D99", emptyFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123" };
yield return new object[] { (byte)0x24, "x", emptyFormat, "24" };
yield return new object[] { (byte)24, "N", emptyFormat, string.Format("{0:N}", 24.00) };
}
var customFormat = new NumberFormatInfo()
{
NegativeSign = "#",
NumberDecimalSeparator = "~",
NumberGroupSeparator = "*",
PositiveSign = "&",
NumberDecimalDigits = 2,
PercentSymbol = "@",
PercentGroupSeparator = ",",
PercentDecimalSeparator = ".",
PercentDecimalDigits = 5
};
yield return new object[] { (byte)24, "N", customFormat, "24~00" };
yield return new object[] { (byte)123, "E", customFormat, "1~230000E&002" };
yield return new object[] { (byte)123, "F", customFormat, "123~00" };
yield return new object[] { (byte)123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(byte b, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, b.ToString());
Assert.Equal(upperExpected, b.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, b.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, b.ToString(upperFormat));
Assert.Equal(lowerExpected, b.ToString(lowerFormat));
Assert.Equal(upperExpected, b.ToString(upperFormat, null));
Assert.Equal(lowerExpected, b.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, b.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, b.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
byte b = 123;
Assert.Throws<FormatException>(() => b.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => b.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "0", defaultStyle, null, (byte)0 };
yield return new object[] { "123", defaultStyle, null, (byte)123 };
yield return new object[] { "+123", defaultStyle, null, (byte)123 };
yield return new object[] { " 123 ", defaultStyle, null, (byte)123 };
yield return new object[] { "255", defaultStyle, null, (byte)255 };
yield return new object[] { "12", NumberStyles.HexNumber, null, (byte)0x12 };
yield return new object[] { "10", NumberStyles.AllowThousands, null, (byte)10 };
yield return new object[] { "123", defaultStyle, emptyFormat, (byte)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (byte)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (byte)0x12 };
yield return new object[] { "ab", NumberStyles.HexNumber, emptyFormat, (byte)0xab };
yield return new object[] { "AB", NumberStyles.HexNumber, null, (byte)0xab };
yield return new object[] { "$100", NumberStyles.Currency, customFormat, (byte)100 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, byte expected)
{
byte result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(byte.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, byte.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, byte.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(byte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, byte.Parse(value, style));
}
Assert.Equal(expected, byte.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "ab", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 100.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 67.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "ab", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-1", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "256", defaultStyle, null, typeof(OverflowException) }; // > max value
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, typeof(OverflowException) }; // Parentheses = negative
yield return new object[] { "2147483648", defaultStyle, null, typeof(OverflowException) }; // Internally, Parse pretends we are inputting an Int32, so this overflows
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
byte result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(byte.TryParse(value, out result));
Assert.Equal(default(byte), result);
Assert.Throws(exceptionType, () => byte.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => byte.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(byte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(byte), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => byte.Parse(value, style));
}
Assert.Throws(exceptionType, () => byte.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
byte result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => byte.TryParse("1", style, null, out result));
Assert.Equal(default(byte), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => byte.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => byte.Parse("1", style, null));
}
}
}
| |
#pragma warning disable 0168
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using nHydrate.DataImport;
namespace nHydrate.DslPackage.Forms
{
public partial class DBObjectDifferenceForm : Form
{
private int _leftPercentWidth = 50;
private bool _isLoading = false;
private SQLObject _sourceItem;
private SQLObject _targetItem;
private bool _isScrolling = false;
public DBObjectDifferenceForm()
{
InitializeComponent();
this.Size = new Size((int)(Screen.PrimaryScreen.WorkingArea.Width * 0.8), (int)(Screen.PrimaryScreen.WorkingArea.Height * 0.8));
this.ResizeEnd += DBObjectDifferenceForm_ClientSizeChanged;
this.ClientSizeChanged += DBObjectDifferenceForm_ClientSizeChanged;
this.KeyDown += DBObjectDifferenceForm_KeyDown;
pnlLeft.Width = pnlMain.Width / 2; //split screen in half
splitterField.SplitterMoved += new SplitterEventHandler(splitter1_SplitterMoved);
splitterField.DoubleClick += new EventHandler(splitter1_DoubleClick);
txtText1.CurrentLineColor = Color.FromArgb(200, 210, 210, 255);
txtText1.ChangedLineColor = Color.FromArgb(255, 230, 230, 255);
txtText1.ReadOnly = true;
txtText1.Scroll += new ScrollEventHandler(txtText1_Scroll);
txtText1.VisibleRangeChanged += txtText1_VisibleRangeChanged;
txtText2.CurrentLineColor = txtText1.CurrentLineColor;
txtText2.ChangedLineColor = txtText1.ChangedLineColor;
txtText2.TextChanged += new EventHandler<FastColoredTextBoxNS.TextChangedEventArgs>(txtText2_TextChanged);
txtText2.ReadOnly = true;
txtText2.Scroll += new ScrollEventHandler(txtText2_Scroll);
txtText2.VisibleRangeChanged += new EventHandler(txtText2_VisibleRangeChanged);
lstFields.Columns.Clear();
lstFields.Columns.Add(new ColumnHeader() { Text = string.Empty, Width = 24 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Field", Width = 150 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Datatype", Width = 150 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Length", Width = 150 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Nullable", Width = 150 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Field", Width = 150 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Datatype", Width = 150 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Length", Width = 150 });
lstFields.Columns.Add(new ColumnHeader() { Text = "Nullable", Width = 150 });
this.FormClosing += new FormClosingEventHandler(DBObjectDifferenceForm_FormClosing);
}
public DBObjectDifferenceForm(SQLObject sourceItem, SQLObject targetItem)
: this()
{
_sourceItem = sourceItem;
_targetItem = targetItem;
_isLoading = true;
var showSQL = true;
var showFields = true;
var showParameters = true;
try
{
if (_sourceItem.SQL != null && _targetItem.SQL != null)
{
nHydrate.DslPackage.Objects.Utils.CompareText(txtText1, txtText2, _sourceItem.SQL, _targetItem.SQL);
}
else
{
showSQL = false;
this.Controls.Remove(pnlMain);
this.Controls.Remove(splitterParameter);
}
txtText1.ClearUndo();
txtText2.ClearUndo();
txtText1.IsChanged = false;
txtText2.IsChanged = false;
if (sourceItem.FieldList != null)
{
//Load all source fields
foreach (var item in sourceItem.FieldList)
{
var li = new ListViewItem();
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.Name });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.DataType.ToString() });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.Length.ToString() });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.Nullable.ToString() });
var targetField = targetItem.FieldList.FirstOrDefault(x => x.Name == item.Name);
if (targetField != null)
{
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = targetField.Name });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = targetField.DataType.ToString() });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = targetField.Length.ToString() });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = targetField.Nullable.ToString() });
if (!targetField.Equals(item))
{
li.BackColor = nHydrate.DslPackage.Objects.Utils.ColorModified;
li.ImageIndex = 2;
}
}
else
{
li.BackColor = nHydrate.DslPackage.Objects.Utils.ColorDeleted;
li.ImageIndex = 1;
}
lstFields.Items.Add(li);
}
//Load all target fields NOT in source
var targetFieldList = targetItem.FieldList.Where(x => !sourceItem.FieldList.Select(z => z.Name).ToList().Contains(x.Name));
foreach (var item in targetFieldList)
{
var li = new ListViewItem();
li.BackColor = nHydrate.DslPackage.Objects.Utils.ColorInserted;
li.ImageIndex = 0;
li.SubItems[0].Text = string.Empty;
li.SubItems.Add(new ListViewItem.ListViewSubItem());
li.SubItems.Add(new ListViewItem.ListViewSubItem());
li.SubItems.Add(new ListViewItem.ListViewSubItem());
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.Name });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.DataType.ToString() });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.Length.ToString() });
li.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = item.Nullable.ToString() });
lstFields.Items.Add(li);
}
}
else
{
showFields = false;
this.Controls.Remove(pnlFields);
this.Controls.Remove(splitterField);
}
if (!showSQL)
{
//Entity
pnlFields.Dock = DockStyle.Fill;
splitterField.Visible = false;
var e1 = sourceItem as Entity;
var e2 = targetItem as Entity;
var changedText = string.Empty;
if (e1.AllowCreateAudit != e2.AllowCreateAudit)
{
if (!string.IsNullOrEmpty(changedText)) changedText += ", ";
changedText += "Create Audit: " + e1.AllowCreateAudit + " -> " + e2.AllowCreateAudit;
}
if (e1.AllowModifyAudit != e2.AllowModifyAudit)
{
if (!string.IsNullOrEmpty(changedText)) changedText += ", ";
changedText += "Modify Audit: " + e1.AllowModifyAudit + " -> " + e2.AllowModifyAudit;
}
if (e1.AllowTimestamp != e2.AllowTimestamp)
{
if (!string.IsNullOrEmpty(changedText)) changedText += ", ";
changedText += "Timestamp: " + e1.AllowTimestamp + " -> " + e2.AllowTimestamp;
}
if (e1.IsTenant != e2.IsTenant)
{
if (!string.IsNullOrEmpty(changedText)) changedText += ", ";
changedText += "IsTenant: " + e1.IsTenant + " -> " + e2.IsTenant;
}
if (!string.IsNullOrEmpty(changedText))
{
lblFieldInfo.Text = "Changed: " + changedText;
lblFieldInfo.Visible = true;
}
}
else if (showFields && !showParameters)
{
//Views
}
else if (showFields && showParameters)
{
//Functions, SP
}
this.Text += " " + _sourceItem.ObjectType + ": [" + _sourceItem.Name + "]";
this.ResizeColumns();
}
catch (Exception ex)
{
throw;
}
finally
{
this.IsDirty = false;
_isLoading = false;
}
}
private bool IsDirty { get; set; } = false;
private void ResizeColumns()
{
var colwidth = (this.Width - 70) / 8;
lstFields.Columns[0].Width = 24;
for (var ii = 1; ii < 9; ii++)
{
lstFields.Columns[ii].Width = colwidth;
}
}
#region Event Handlers
private void splitter1_DoubleClick(object sender, EventArgs e)
{
_leftPercentWidth = 50;
pnlLeft.Width = (int)(pnlMain.Width * (_leftPercentWidth / 100.0)); //split screen in half
}
private void DBObjectDifferenceForm_ClientSizeChanged(object sender, EventArgs e)
{
pnlLeft.Width = (int)(pnlMain.Width * (_leftPercentWidth / 100.0)); //split screen in half
this.ResizeColumns();
}
private void splitter1_SplitterMoved(object sender, SplitterEventArgs e)
{
_leftPercentWidth = (splitterField.Left + (splitterField.Width / 2)) * 100 / pnlMain.Width;
}
private void txtText2_TextChanged(object sender, FastColoredTextBoxNS.TextChangedEventArgs e)
{
if (!_isLoading)
{
this.IsDirty = true;
}
}
private void DBObjectDifferenceForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && this.IsDirty)
{
if (MessageBox.Show("Do you wish to ignore changes made to this object?", "Ignore Changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes)
{
e.Cancel = true;
}
}
}
private void cmdSave_Click(object sender, EventArgs e)
{
_targetItem.SQL = txtText2.Text;
this.IsDirty = false;
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
private void txtText1_VisibleRangeChanged(object sender, EventArgs e)
{
_isScrolling = true;
try
{
if (txtText1.VerticalScroll.Value <= txtText2.VerticalScroll.Maximum)
txtText2.VerticalScroll.Value = txtText1.VerticalScroll.Value;
else
txtText2.VerticalScroll.Value = txtText2.VerticalScroll.Maximum;
if (txtText1.HorizontalScroll.Value <= txtText2.HorizontalScroll.Maximum)
txtText2.HorizontalScroll.Value = txtText1.HorizontalScroll.Value;
else
txtText2.HorizontalScroll.Value = txtText2.HorizontalScroll.Maximum;
txtText2.Refresh();
}
catch (Exception ex)
{
throw;
}
finally
{
_isScrolling = false;
}
}
private void txtText1_Scroll(object sender, ScrollEventArgs e)
{
_isScrolling = true;
try
{
if (txtText1.VerticalScroll.Value <= txtText2.VerticalScroll.Maximum)
txtText2.VerticalScroll.Value = txtText1.VerticalScroll.Value;
else
txtText2.VerticalScroll.Value = txtText2.VerticalScroll.Maximum;
if (txtText1.HorizontalScroll.Value <= txtText2.HorizontalScroll.Maximum)
txtText2.HorizontalScroll.Value = txtText1.HorizontalScroll.Value;
else
txtText2.HorizontalScroll.Value = txtText2.HorizontalScroll.Maximum;
txtText2.Refresh();
}
catch (Exception ex)
{
throw;
}
finally
{
_isScrolling = false;
}
}
private void txtText2_VisibleRangeChanged(object sender, EventArgs e)
{
_isScrolling = true;
try
{
if (txtText2.VerticalScroll.Value <= txtText1.VerticalScroll.Maximum)
txtText1.VerticalScroll.Value = txtText2.VerticalScroll.Value;
else
txtText1.VerticalScroll.Value = txtText1.VerticalScroll.Maximum;
if (txtText2.HorizontalScroll.Value <= txtText1.HorizontalScroll.Maximum)
txtText1.HorizontalScroll.Value = txtText2.HorizontalScroll.Value;
else
txtText1.HorizontalScroll.Value = txtText1.HorizontalScroll.Maximum;
txtText1.Refresh();
}
catch (Exception ex)
{
throw;
}
finally
{
_isScrolling = false;
}
}
private void txtText2_Scroll(object sender, ScrollEventArgs e)
{
_isScrolling = true;
try
{
if (txtText2.VerticalScroll.Value <= txtText1.VerticalScroll.Maximum)
txtText1.VerticalScroll.Value = txtText2.VerticalScroll.Value;
else
txtText1.VerticalScroll.Value = txtText1.VerticalScroll.Maximum;
if (txtText2.HorizontalScroll.Value <= txtText1.HorizontalScroll.Maximum)
txtText1.HorizontalScroll.Value = txtText2.HorizontalScroll.Value;
else
txtText1.HorizontalScroll.Value = txtText1.HorizontalScroll.Maximum;
txtText1.Refresh();
}
catch (Exception ex)
{
throw;
}
finally
{
_isScrolling = false;
}
}
private void splitterVert_DoubleClick(object sender, EventArgs e)
{
pnlLeft.Width = (int)(pnlMain.Width * (_leftPercentWidth / 100.0)); //split screen in half
}
private void DBObjectDifferenceForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
#endregion
}
}
| |
using Permadelete.ApplicationManagement;
using Permadelete.Enums;
using Permadelete.Helpers;
using Permadelete.Mvvm;
using Permadelete.Services;
using Permadelete.Views;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Shell;
using System.Windows.Threading;
namespace Permadelete.ViewModels
{
public class QuickWindowVM : BindableBase
{
public QuickWindowVM(IEnumerable<string> paths)
{
string names;
string pronoun;
if (paths.Count() == 1)
{
names = $"\"{GetShortName(paths.First())}\"";
pronoun = string.Empty;
}
else
{
names = $"{paths.Count()} items";
pronoun = "these ";
}
QuestionTitle = $"Do you want to shred {pronoun}{names}?";
ProgressTitle = $"Shredding {names}";
QuestionVisibility = Visibility.Visible;
ProgressVisibility = Visibility.Hidden;
NotificationVisibility = Visibility.Hidden;
TimeRemaining = QuestionTitle;
TaskbarState = TaskbarItemProgressState.Indeterminate;
_progressTimer.Interval = TimeSpan.FromMilliseconds(100);
_progressTimer.Tick += _progressTimer_Tick;
(App.Operations as INotifyCollectionChanged).CollectionChanged += Operations_Changed;
CloseCommand = new DelegateCommand(p =>
{
if (App.Current.UpdateStatus != Enums.UpdateStatus.DownloadingUpdate)
{
App.Current.Shutdown();
return;
}
App.Current.MainWindow.Hide();
App.Current.UpdateStatusChanged += (sender, e) =>
{
App.Current.Dispatcher.Invoke(() =>
{
if (App.Operations.Count == 0)
App.Current.Shutdown();
else
App.Current?.MainWindow?.Show();
});
};
});
DeleteCommand = new DelegateCommand(async p =>
{
QuestionVisibility = Visibility.Collapsed;
ProgressVisibility = Visibility.Visible;
TaskbarState = TaskbarItemProgressState.Normal;
_progressTimer.Start();
await App.Current.DeleteFilesOrFolders(paths, NumberOfPasses);
if (_hasPendingNotification)
{
ProgressVisibility = Visibility.Collapsed;
NotificationVisibility = Visibility.Visible;
RaisePropertyChanged(nameof(WindowTitle));
}
else
{
CloseCommand.Execute(null);
}
});
OpenMainWindowCommand = new DelegateCommand(dialog =>
{
(App.Operations as INotifyCollectionChanged).CollectionChanged -= Operations_Changed;
CloseCommand = new DelegateCommand(p => { });
App.Current.NotificationRaised -= OnNotificationRaised;
App.Current.MainWindow = new MainWindow();
App.Current.MainWindow.Show();
(dialog as Window).Close();
});
App.Current.NotificationRaised += OnNotificationRaised;
var settings = SettingsHelper.GetSettings();
NumberOfPasses = settings.DefaultOverwritePasses;
}
#region Fields
private DispatcherTimer _progressTimer = new DispatcherTimer();
private TimeSpan _timeToComplete;
long _totalBytes = 0;
long _bytesOfCompletedOperations = 0;
long _writtenBytes = 0;
private bool _hasPendingNotification = false;
#endregion
#region Commands
public ICommand CloseCommand { get; set; }
public ICommand DeleteCommand { get; set; }
public ICommand OpenMainWindowCommand { get; set; }
#endregion
#region Properties
public string WindowTitle
{
get
{
if (QuestionVisibility == Visibility.Visible)
return QuestionTitle;
else if (ProgressVisibility == Visibility.Visible)
return TimeRemaining;
else
return "There was an error in shredding the items.";
}
}
private NotificationVM _notification;
public NotificationVM Notification
{
get { return _notification; }
set { Set(ref _notification, value); }
}
private string _progressTitle;
public string ProgressTitle
{
get { return _progressTitle; }
set { Set(ref _progressTitle, value); }
}
private string _timeRemaining;
public string TimeRemaining
{
get { return _timeRemaining; }
set
{
if (Set(ref _timeRemaining, value))
RaisePropertyChanged(nameof(WindowTitle));
}
}
private TaskbarItemProgressState _taskbarState;
public TaskbarItemProgressState TaskbarState
{
get { return _taskbarState; }
set { Set(ref _taskbarState, value); }
}
private string _questionTitle;
public string QuestionTitle
{
get { return _questionTitle; }
set
{
if (Set(ref _questionTitle, value))
RaisePropertyChanged(nameof(WindowTitle));
}
}
private string _icon;
public string Icon
{
get { return _icon; }
set { Set(ref _icon, value); }
}
private double _progress;
public double Progress
{
get { return _progress; }
set { Set(ref _progress, value); }
}
private Visibility _questionVisibility;
public Visibility QuestionVisibility
{
get { return _questionVisibility; }
set { Set(ref _questionVisibility, value); }
}
private Visibility _progressVisibility;
public Visibility ProgressVisibility
{
get { return _progressVisibility; }
set { Set(ref _progressVisibility, value); }
}
private Visibility _notificationVisibility;
public Visibility NotificationVisibility
{
get { return _notificationVisibility; }
set { Set(ref _notificationVisibility, value); }
}
private int _numberOfPasses;
public int NumberOfPasses
{
get { return _numberOfPasses; }
set { Set(ref _numberOfPasses, value); }
}
#endregion
#region Methods
private void _progressTimer_Tick(object sender, EventArgs e)
{
if (App.Operations.Count == 0)
return;
_timeToComplete = App.Operations.Max(o => o.TimeRemaining);
TimeRemaining = _timeToComplete.ToHumanLanguage();
_writtenBytes = App.Operations.Sum(o => o.BytesComplete);
Progress = (double)(_writtenBytes + _bytesOfCompletedOperations) / _totalBytes;
}
private void Operations_Changed(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems?.Count > 0)
foreach (OperationVM item in e.NewItems)
{
if (item.Bytes != -1)
_totalBytes += item.Bytes;
else
item.PropertyChanged += DeferAddingToTotalBytes;
}
if (e.OldItems?.Count > 0)
foreach (OperationVM item in e.OldItems)
{
_bytesOfCompletedOperations += item.Bytes;
item.PropertyChanged -= DeferAddingToTotalBytes;
}
}
private string GetShortName(string path, int maxLength = 25)
{
var name = Path.GetFileName(path);
if (name.Length > maxLength)
name = name.Substring(0, maxLength) + "...";
return name;
}
private void RecieveNotification(string message, MessageIcon icon)
{
if (Notification != null)
return;
Notification = new NotificationVM(message, icon);
_hasPendingNotification = true;
}
private void DeferAddingToTotalBytes(object sender, PropertyChangedEventArgs e)
{
var item = (OperationVM)sender;
if (item != null && e.PropertyName == nameof(item.Bytes) && item.Bytes != -1)
{
_totalBytes += item.Bytes;
item.PropertyChanged -= DeferAddingToTotalBytes;
}
}
private void OnNotificationRaised(object sender, NotificationEventArgs e)
{
switch (e.NotificationType)
{
case NotificationType.FailedToShredItem:
RecieveNotification(e.Message, MessageIcon.Error);
break;
case NotificationType.IncompleteFolderShred:
RecieveNotification(e.Message, MessageIcon.Exclamation);
break;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* This probably needs some throttling mechanism but
* it's wide open right now. This applies to both
* number of requests and data volume.
*
* Linden puts all kinds of header fields in the requests.
* Not doing any of that:
* User-Agent
* X-SecondLife-Shard
* X-SecondLife-Object-Name
* X-SecondLife-Object-Key
* X-SecondLife-Region
* X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule
{
private object HttpListLock = new object();
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
private string m_proxyurl = "";
private string m_proxyexcepts = "";
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestClass> m_pendingRequests;
private Scene m_scene;
// private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public HttpRequestModule()
{
ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate;
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// If this is a web request we need to check the headers first
// We may want to ignore SSL
if (sender is HttpWebRequest)
{
HttpWebRequest Request = (HttpWebRequest)sender;
ServicePoint sp = Request.ServicePoint;
// We don't case about encryption, get out of here
if (Request.Headers.Get("NoVerifyCert") != null)
{
return true;
}
// If there was an upstream cert verification error, bail
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
// Check for policy and execute it if defined
if (ServicePointManager.CertificatePolicy != null)
{
return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
}
return true;
}
// If it's not HTTP, trust .NET to check it
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
return true;
}
#region IHttpRequestModule Members
public UUID MakeHttpRequest(string url, string parameters, string body)
{
return UUID.Zero;
}
public UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
if (parameters != null)
{
string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length; i += 2)
{
switch (Int32.Parse(parms[i]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
htc.HttpMethod = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
// TODO implement me
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
break;
}
}
}
htc.LocalID = localID;
htc.ItemID = itemID;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = httpTimeout;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
lock (HttpListLock)
{
m_pendingRequests.Add(reqID, htc);
}
htc.Process();
return reqID;
}
public void StopHttpRequest(uint m_localID, UUID m_itemID)
{
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{
tmpReq.Stop();
m_pendingRequests.Remove(m_itemID);
}
}
}
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finished. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (HttpListLock)
{
foreach (UUID luid in m_pendingRequests.Keys)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
{
return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(id, out tmpReq))
{
tmpReq.Stop();
tmpReq = null;
m_pendingRequests.Remove(id);
}
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
}
public void RemoveRegion(Scene scene)
{
scene.UnregisterModuleInterface<IHttpRequestModule>(this);
if (scene == m_scene)
m_scene = null;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
}
public class HttpRequestClass: IServiceRequest
{
// Constants for parameters
// public const int HTTP_BODY_MAXLENGTH = 2;
// public const int HTTP_METHOD = 0;
// public const int HTTP_MIMETYPE = 1;
// public const int HTTP_VERIFY_CERT = 3;
private bool _finished;
public bool Finished
{
get { return _finished; }
}
// public int HttpBodyMaxLen = 2048; // not implemented
// Parameter members and default values
public string HttpMethod = "GET";
public string HttpMIMEType = "text/plain;charset=utf-8";
public int HttpTimeout;
public bool HttpVerifyCert = true;
private Thread httpThread;
// Request info
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
public DateTime Next;
public string proxyurl;
public string proxyexcepts;
public string OutboundBody;
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public HttpWebRequest Request;
public string ResponseBody;
public List<string> ResponseMetadata;
public Dictionary<string, string> ResponseHeaders;
public int Status;
public string Url;
public void Process()
{
httpThread = new Thread(SendRequest);
httpThread.Name = "HttpRequestThread";
httpThread.Priority = ThreadPriority.BelowNormal;
httpThread.IsBackground = true;
_finished = false;
httpThread.Start();
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
HttpWebResponse response = null;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
string tempString = null;
int count = 0;
try
{
Request = (HttpWebRequest) WebRequest.Create(Url);
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
if(!HttpVerifyCert)
{
// We could hijack Connection Group Name to identify
// a desired security exception. But at the moment we'll use a dummy header instead.
// Request.ConnectionGroupName = "NoVerify";
Request.Headers.Add("NoVerifyCert", "true");
}
// else
// {
// Request.ConnectionGroupName="Verify";
// }
if (proxyurl != null && proxyurl.Length > 0)
{
if (proxyexcepts != null && proxyexcepts.Length > 0)
{
string[] elist = proxyexcepts.Split(';');
Request.Proxy = new WebProxy(proxyurl, true, elist);
}
else
{
Request.Proxy = new WebProxy(proxyurl, true);
}
}
foreach (KeyValuePair<string, string> entry in ResponseHeaders)
if (entry.Key.ToLower().Equals("user-agent"))
Request.UserAgent = entry.Value;
else
Request.Headers[entry.Key] = entry.Value;
// Encode outbound data
if (OutboundBody.Length > 0)
{
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
Stream bstream = Request.GetRequestStream();
bstream.Write(data, 0, data.Length);
bstream.Close();
}
Request.Timeout = HttpTimeout;
try
{
// execute the request
response = (HttpWebResponse) Request.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
throw;
}
response = (HttpWebResponse)e.Response;
}
Status = (int)response.StatusCode;
Stream resStream = response.GetResponseStream();
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Util.UTF8.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
} while (count > 0); // any more data to read?
ResponseBody = sb.ToString();
}
catch (Exception e)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
_finished = true;
return;
}
finally
{
if (response != null)
response.Close();
}
_finished = true;
}
public void Stop()
{
try
{
httpThread.Abort();
}
catch (Exception)
{
}
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace ZXing.Common
{
/// <summary> Implementations of this class can, given locations of finder patterns for a QR code in an
/// image, sample the right points in the image to reconstruct the QR code, accounting for
/// perspective distortion. It is abstracted since it is relatively expensive and should be allowed
/// to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
/// Imaging library, but which may not be available in other environments such as J2ME, and vice
/// versa.
///
/// The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
/// with an instance of a class which implements this interface.
/// </summary>
/// <author> Sean Owen</author>
public abstract class GridSampler
{
/// <returns> the current implementation of <see cref="GridSampler"/>
/// </returns>
public static GridSampler Instance
{
get
{
return gridSampler;
}
}
private static GridSampler gridSampler = new DefaultGridSampler();
/// <summary> Sets the implementation of <see cref="GridSampler"/> used by the library. One global
/// instance is stored, which may sound problematic. But, the implementation provided
/// ought to be appropriate for the entire platform, and all uses of this library
/// in the whole lifetime of the JVM. For instance, an Android activity can swap in
/// an implementation that takes advantage of native platform libraries.
/// </summary>
/// <param name="newGridSampler">The platform-specific object to install.</param>
public static void setGridSampler(GridSampler newGridSampler)
{
if (newGridSampler == null)
{
throw new System.ArgumentException();
}
gridSampler = newGridSampler;
}
/// <summary>
/// <p>Samples an image for a square matrix of bits of the given dimension. This is used to extract
/// the black/white modules of a 2D barcode like a QR Code found in an image. Because this barcode
/// may be rotated or perspective-distorted, the caller supplies four points in the source image
/// that define known points in the barcode, so that the image may be sampled appropriately.</p>
/// <p>The last eight "from" parameters are four X/Y coordinate pairs of locations of points in
/// the image that define some significant points in the image to be sample. For example,
/// these may be the location of finder pattern in a QR Code.</p>
/// <p>The first eight "to" parameters are four X/Y coordinate pairs measured in the destination
/// <see cref="BitMatrix"/>, from the top left, where the known points in the image given by the "from"
/// parameters map to.</p>
/// <p>These 16 parameters define the transformation needed to sample the image.</p>
/// </summary>
/// <param name="image">image to sample</param>
/// <param name="dimensionX">The dimension X.</param>
/// <param name="dimensionY">The dimension Y.</param>
/// <param name="p1ToX">The p1 preimage X.</param>
/// <param name="p1ToY">The p1 preimage Y.</param>
/// <param name="p2ToX">The p2 preimage X.</param>
/// <param name="p2ToY">The p2 preimage Y.</param>
/// <param name="p3ToX">The p3 preimage X.</param>
/// <param name="p3ToY">The p3 preimage Y.</param>
/// <param name="p4ToX">The p4 preimage X.</param>
/// <param name="p4ToY">The p4 preimage Y.</param>
/// <param name="p1FromX">The p1 image X.</param>
/// <param name="p1FromY">The p1 image Y.</param>
/// <param name="p2FromX">The p2 image X.</param>
/// <param name="p2FromY">The p2 image Y.</param>
/// <param name="p3FromX">The p3 image X.</param>
/// <param name="p3FromY">The p3 image Y.</param>
/// <param name="p4FromX">The p4 image X.</param>
/// <param name="p4FromY">The p4 image Y.</param>
/// <returns>
/// <see cref="BitMatrix"/> representing a grid of points sampled from the image within a region
/// defined by the "from" parameters
/// </returns>
/// <throws> ReaderException if image can't be sampled, for example, if the transformation defined </throws>
public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY);
/// <summary>
///
/// </summary>
/// <param name="image"></param>
/// <param name="dimensionX"></param>
/// <param name="dimensionY"></param>
/// <param name="transform"></param>
/// <returns></returns>
public virtual BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform)
{
throw new System.NotSupportedException();
}
/// <summary> <p>Checks a set of points that have been transformed to sample points on an image against
/// the image's dimensions to see if the point are even within the image.</p>
///
/// <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
/// barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
/// patterns in an image where the QR Code runs all the way to the image border.</p>
///
/// <p>For efficiency, the method will check points from either end of the line until one is found
/// to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
///
/// </summary>
/// <param name="image">image into which the points should map
/// </param>
/// <param name="points">actual points in x1,y1,...,xn,yn form
/// </param>
protected internal static bool checkAndNudgePoints(BitMatrix image, float[] points)
{
int width = image.Width;
int height = image.Height;
// Check and nudge points from start until we see some that are OK:
bool nudged = true;
for (int offset = 0; offset < points.Length && nudged; offset += 2)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int x = (int)points[offset];
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int y = (int)points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height)
{
return false;
}
nudged = false;
if (x == -1)
{
points[offset] = 0.0f;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == -1)
{
points[offset + 1] = 0.0f;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
// Check and nudge points from end:
nudged = true;
for (int offset = points.Length - 2; offset >= 0 && nudged; offset -= 2)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int x = (int)points[offset];
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int y = (int)points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height)
{
return false;
}
nudged = false;
if (x == -1)
{
points[offset] = 0.0f;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == -1)
{
points[offset + 1] = 0.0f;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
return true;
}
}
}
| |
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.TestingHost;
using Tester;
using TestExtensions;
using Xunit;
namespace UnitTests.StreamingTests
{
public class PubSubRendezvousGrainTests : OrleansTestingBase, IClassFixture<PubSubRendezvousGrainTests.Fixture>
{
private readonly Fixture fixture;
public class Fixture : BaseTestClusterFixture
{
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddSiloBuilderConfigurator<SiloHostConfigurator>();
}
public class SiloHostConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddFaultInjectionMemoryStorage("PubSubStore");
}
}
}
public PubSubRendezvousGrainTests(Fixture fixture)
{
this.fixture = fixture;
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task RegisterConsumerFaultTest()
{
this.fixture.Logger.Info("************************ RegisterConsumerFaultTest *********************************");
var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace");
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(
streamId.Guid,
keyExtension: streamId.ProviderName + "_" + streamId.Namespace);
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
// clean call, to make sure everything is happy and pubsub has state.
await pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null, null);
int consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(1, consumers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when registering a new consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null, null));
// pubsub grain should recover and still function
await pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null, null);
consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(2, consumers);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task UnregisterConsumerFaultTest()
{
this.fixture.Logger.Info("************************ UnregisterConsumerFaultTest *********************************");
var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace");
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(
streamId.Guid,
keyExtension: streamId.ProviderName + "_" + streamId.Namespace);
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
// Add two consumers so when we remove the first it does a storage write, not a storage clear.
GuidId subscriptionId1 = GuidId.GetGuidId(Guid.NewGuid());
GuidId subscriptionId2 = GuidId.GetGuidId(Guid.NewGuid());
await pubSubGrain.RegisterConsumer(subscriptionId1, streamId, null, null);
await pubSubGrain.RegisterConsumer(subscriptionId2, streamId, null, null);
int consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(2, consumers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterConsumer(subscriptionId1, streamId));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterConsumer(subscriptionId1, streamId);
consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(1, consumers);
// inject clear fault, because removing last consumer should trigger a clear storage call.
await faultGrain.AddFaultOnClear(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterConsumer(subscriptionId2, streamId));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterConsumer(subscriptionId2, streamId);
consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(0, consumers);
}
/// <summary>
/// This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension in the producer management calls.
/// TODO: Fix rendezvous implementation.
/// </summary>
/// <returns></returns>
[Fact(Skip = "This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task RegisterProducerFaultTest()
{
this.fixture.Logger.Info("************************ RegisterProducerFaultTest *********************************");
var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace");
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(
streamId.Guid,
keyExtension: streamId.ProviderName + "_" + streamId.Namespace);
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
// clean call, to make sure everything is happy and pubsub has state.
await pubSubGrain.RegisterProducer(streamId, null);
int producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(1, producers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when registering a new producer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.RegisterProducer(streamId, null));
// pubsub grain should recover and still function
await pubSubGrain.RegisterProducer(streamId, null);
producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(2, producers);
}
/// <summary>
/// This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension in the producer management calls.
/// TODO: Fix rendezvous implementation.
/// </summary>
[Fact(Skip = "This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task UnregisterProducerFaultTest()
{
this.fixture.Logger.Info("************************ UnregisterProducerFaultTest *********************************");
var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace");
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(
streamId.Guid,
keyExtension: streamId.ProviderName + "_" + streamId.Namespace);
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
IStreamProducerExtension firstProducer = new DummyStreamProducerExtension();
IStreamProducerExtension secondProducer = new DummyStreamProducerExtension();
// Add two producers so when we remove the first it does a storage write, not a storage clear.
await pubSubGrain.RegisterProducer(streamId, firstProducer);
await pubSubGrain.RegisterProducer(streamId, secondProducer);
int producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(2, producers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a producer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterProducer(streamId, firstProducer));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterProducer(streamId, firstProducer);
producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(1, producers);
// inject clear fault, because removing last producers should trigger a clear storage call.
await faultGrain.AddFaultOnClear(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterProducer(streamId, secondProducer));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterProducer(streamId, secondProducer);
producers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(0, producers);
}
[Serializable]
private class DummyStreamProducerExtension : IStreamProducerExtension
{
private readonly Guid id;
public DummyStreamProducerExtension()
{
id = Guid.NewGuid();
}
public Task AddSubscriber(GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer,
IStreamFilterPredicateWrapper filter)
{
return Task.CompletedTask;
}
public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId)
{
return Task.CompletedTask;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((DummyStreamProducerExtension)obj);
}
public override int GetHashCode()
{
return id.GetHashCode();
}
private bool Equals(DummyStreamProducerExtension other)
{
return id.Equals(other.id);
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Xml;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for DialogDataSourceRef.
/// </summary>
internal class DialogNewMatrix : System.Windows.Forms.Form
{
private DesignXmlDraw _Draw;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox cbDataSets;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ListBox lbFields;
private System.Windows.Forms.CheckedListBox lbMatrixColumns;
private System.Windows.Forms.Button bColumnUp;
private System.Windows.Forms.Button bColumnDown;
private System.Windows.Forms.Button bColumn;
private System.Windows.Forms.Button bRowSelect;
private System.Windows.Forms.CheckedListBox lbMatrixRows;
private System.Windows.Forms.Button bColumnDelete;
private System.Windows.Forms.Button bRowDelete;
private System.Windows.Forms.Button bRowDown;
private System.Windows.Forms.Button bRowUp;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.ComboBox cbMatrixCell;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DialogNewMatrix(DesignXmlDraw dxDraw, XmlNode container)
{
_Draw = dxDraw;
//
// Required for Windows Form Designer support
//
InitializeComponent();
InitValues(container);
}
private void InitValues(XmlNode container)
{
this.bOK.Enabled = false;
//
// Obtain the existing DataSets info
//
object[] datasets = _Draw.DataSetNames;
if (datasets == null)
return; // not much to do if no DataSets
if (_Draw.IsDataRegion(container))
{
string s = _Draw.GetDataSetNameValue(container);
if (s == null)
return;
this.cbDataSets.Items.Add(s);
this.cbDataSets.Enabled = false;
}
else
this.cbDataSets.Items.AddRange(datasets);
cbDataSets.SelectedIndex = 0;
}
internal string MatrixXml
{
get
{
StringBuilder matrix = new StringBuilder("<Matrix>");
matrix.AppendFormat("<DataSetName>{0}</DataSetName>", this.cbDataSets.Text);
matrix.Append("<NoRows>Query returned no rows!</NoRows><Style>"+
"<BorderStyle><Default>Solid</Default></BorderStyle></Style>");
matrix.Append("<Corner><ReportItems><Textbox Name=\"Corner\"><Value>Corner</Value>" +
"<Style><BorderStyle><Default>Solid</Default></BorderStyle><BorderWidth>"+
"<Left>1pt</Left><Right>1pt</Right><Top>1pt</Top><Bottom>1pt</Bottom>"+
"</BorderWidth><FontWeight>bold</FontWeight></Style>"+
"</Textbox></ReportItems></Corner>");
// do the column groupings
matrix.Append("<ColumnGroupings>");
foreach (string cname in this.lbMatrixColumns.Items)
{
matrix.Append("<ColumnGrouping><Height>12pt</Height>");
matrix.Append("<DynamicColumns>");
matrix.AppendFormat("<Grouping><GroupExpressions>"+
"<GroupExpression>=Fields!{0}.Value</GroupExpression>"+
"</GroupExpressions></Grouping>", cname);
matrix.AppendFormat("<ReportItems><Textbox>"+
"<Value>=Fields!{0}.Value</Value>"+
"<Style><BorderStyle><Default>Solid</Default></BorderStyle></Style>"+
"</Textbox></ReportItems>", cname);
int iChecked = this.lbMatrixColumns.CheckedItems.IndexOf(cname);
if (iChecked >= 0)
{
matrix.AppendFormat("<Subtotal><ReportItems><Textbox>"+
"<Value>{0} Subtotal</Value>"+
"<Style><BorderStyle><Default>Solid</Default></BorderStyle></Style>"+
"</Textbox></ReportItems></Subtotal>", cname);
}
matrix.Append("</DynamicColumns>");
matrix.Append("</ColumnGrouping>");
}
matrix.Append("</ColumnGroupings>");
// do the row groupings
matrix.Append("<RowGroupings>");
foreach (string rname in this.lbMatrixRows.Items)
{
matrix.Append("<RowGrouping><Width>1in</Width>");
matrix.Append("<DynamicRows>");
matrix.AppendFormat("<Grouping><GroupExpressions>"+
"<GroupExpression>=Fields!{0}.Value</GroupExpression>"+
"</GroupExpressions></Grouping>", rname);
matrix.AppendFormat("<ReportItems><Textbox>"+
"<Value>=Fields!{0}.Value</Value>"+
"<Style><BorderStyle><Default>Solid</Default></BorderStyle></Style>"+
"</Textbox></ReportItems>", rname);
int iChecked = this.lbMatrixRows.CheckedItems.IndexOf(rname);
if (iChecked >= 0)
{
matrix.AppendFormat("<Subtotal><ReportItems><Textbox>"+
"<Value>{0} Subtotal</Value>"+
"<Style><BorderStyle><Default>Solid</Default></BorderStyle></Style>"+
"</Textbox></ReportItems></Subtotal>", rname);
}
matrix.Append("</DynamicRows>");
matrix.Append("</RowGrouping>");
}
matrix.Append("</RowGroupings>");
// Matrix Columns
matrix.Append("<MatrixColumns><MatrixColumn><Width>1in</Width></MatrixColumn></MatrixColumns>");
// Matrix Rows
matrix.AppendFormat("<MatrixRows><MatrixRow><Height>12pt</Height>"+
"<MatrixCells><MatrixCell><ReportItems>"+
"<Textbox><Value>{0}</Value>"+
"<Style><BorderStyle><Default>Solid</Default></BorderStyle></Style></Textbox>"+
"</ReportItems></MatrixCell></MatrixCells>"+
"</MatrixRow></MatrixRows>", this.cbMatrixCell.Text);
// end of matrix defintion
matrix.Append("</Matrix>");
return matrix.ToString();
}
}
/// <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.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.cbDataSets = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.lbFields = new System.Windows.Forms.ListBox();
this.lbMatrixColumns = new System.Windows.Forms.CheckedListBox();
this.bColumnUp = new System.Windows.Forms.Button();
this.bColumnDown = new System.Windows.Forms.Button();
this.bColumn = new System.Windows.Forms.Button();
this.bRowSelect = new System.Windows.Forms.Button();
this.lbMatrixRows = new System.Windows.Forms.CheckedListBox();
this.bColumnDelete = new System.Windows.Forms.Button();
this.bRowDelete = new System.Windows.Forms.Button();
this.bRowDown = new System.Windows.Forms.Button();
this.bRowUp = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.cbMatrixCell = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// bOK
//
this.bOK.Location = new System.Drawing.Point(272, 368);
this.bOK.Name = "bOK";
this.bOK.TabIndex = 13;
this.bOK.Text = "OK";
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(368, 368);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 14;
this.bCancel.Text = "Cancel";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(48, 23);
this.label1.TabIndex = 11;
this.label1.Text = "DataSet";
//
// cbDataSets
//
this.cbDataSets.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDataSets.Location = new System.Drawing.Point(80, 16);
this.cbDataSets.Name = "cbDataSets";
this.cbDataSets.Size = new System.Drawing.Size(360, 21);
this.cbDataSets.TabIndex = 0;
this.cbDataSets.SelectedIndexChanged += new System.EventHandler(this.cbDataSets_SelectedIndexChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 56);
this.label2.Name = "label2";
this.label2.TabIndex = 13;
this.label2.Text = "DataSet Fields";
//
// label3
//
this.label3.Location = new System.Drawing.Point(224, 56);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(184, 23);
this.label3.TabIndex = 14;
this.label3.Text = "Matrix Columns (check to subtotal)";
//
// lbFields
//
this.lbFields.Location = new System.Drawing.Point(16, 80);
this.lbFields.Name = "lbFields";
this.lbFields.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lbFields.Size = new System.Drawing.Size(152, 225);
this.lbFields.TabIndex = 1;
//
// lbMatrixColumns
//
this.lbMatrixColumns.Location = new System.Drawing.Point(232, 80);
this.lbMatrixColumns.Name = "lbMatrixColumns";
this.lbMatrixColumns.Size = new System.Drawing.Size(152, 94);
this.lbMatrixColumns.TabIndex = 3;
//
// bColumnUp
//
this.bColumnUp.Location = new System.Drawing.Point(392, 80);
this.bColumnUp.Name = "bColumnUp";
this.bColumnUp.Size = new System.Drawing.Size(48, 24);
this.bColumnUp.TabIndex = 4;
this.bColumnUp.Text = "Up";
this.bColumnUp.Click += new System.EventHandler(this.bColumnUp_Click);
//
// bColumnDown
//
this.bColumnDown.Location = new System.Drawing.Point(392, 112);
this.bColumnDown.Name = "bColumnDown";
this.bColumnDown.Size = new System.Drawing.Size(48, 24);
this.bColumnDown.TabIndex = 5;
this.bColumnDown.Text = "Down";
this.bColumnDown.Click += new System.EventHandler(this.bColumnDown_Click);
//
// bColumn
//
this.bColumn.Location = new System.Drawing.Point(184, 88);
this.bColumn.Name = "bColumn";
this.bColumn.Size = new System.Drawing.Size(32, 24);
this.bColumn.TabIndex = 2;
this.bColumn.Text = ">";
this.bColumn.Click += new System.EventHandler(this.bColumn_Click);
//
// bRowSelect
//
this.bRowSelect.Location = new System.Drawing.Point(184, 216);
this.bRowSelect.Name = "bRowSelect";
this.bRowSelect.Size = new System.Drawing.Size(32, 24);
this.bRowSelect.TabIndex = 7;
this.bRowSelect.Text = ">";
this.bRowSelect.Click += new System.EventHandler(this.bRow_Click);
//
// lbMatrixRows
//
this.lbMatrixRows.Location = new System.Drawing.Point(232, 208);
this.lbMatrixRows.Name = "lbMatrixRows";
this.lbMatrixRows.Size = new System.Drawing.Size(152, 94);
this.lbMatrixRows.TabIndex = 8;
//
// bColumnDelete
//
this.bColumnDelete.Location = new System.Drawing.Point(392, 144);
this.bColumnDelete.Name = "bColumnDelete";
this.bColumnDelete.Size = new System.Drawing.Size(48, 24);
this.bColumnDelete.TabIndex = 6;
this.bColumnDelete.Text = "Delete";
this.bColumnDelete.Click += new System.EventHandler(this.bColumnDelete_Click);
//
// bRowDelete
//
this.bRowDelete.Location = new System.Drawing.Point(392, 272);
this.bRowDelete.Name = "bRowDelete";
this.bRowDelete.Size = new System.Drawing.Size(48, 24);
this.bRowDelete.TabIndex = 11;
this.bRowDelete.Text = "Delete";
this.bRowDelete.Click += new System.EventHandler(this.bRowDelete_Click);
//
// bRowDown
//
this.bRowDown.Location = new System.Drawing.Point(392, 240);
this.bRowDown.Name = "bRowDown";
this.bRowDown.Size = new System.Drawing.Size(48, 24);
this.bRowDown.TabIndex = 10;
this.bRowDown.Text = "Down";
this.bRowDown.Click += new System.EventHandler(this.bRowDown_Click);
//
// bRowUp
//
this.bRowUp.Location = new System.Drawing.Point(392, 208);
this.bRowUp.Name = "bRowUp";
this.bRowUp.Size = new System.Drawing.Size(48, 24);
this.bRowUp.TabIndex = 9;
this.bRowUp.Text = "Up";
this.bRowUp.Click += new System.EventHandler(this.bRowUp_Click);
//
// label4
//
this.label4.Location = new System.Drawing.Point(224, 184);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(184, 23);
this.label4.TabIndex = 31;
this.label4.Text = "Matrix Rows (check to subtotal)";
//
// label5
//
this.label5.Location = new System.Drawing.Point(16, 320);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(120, 23);
this.label5.TabIndex = 32;
this.label5.Text = "Matrix Cell Expression";
//
// cbMatrixCell
//
this.cbMatrixCell.Location = new System.Drawing.Point(16, 336);
this.cbMatrixCell.Name = "cbMatrixCell";
this.cbMatrixCell.Size = new System.Drawing.Size(368, 21);
this.cbMatrixCell.TabIndex = 12;
this.cbMatrixCell.TextChanged += new System.EventHandler(this.cbMatrixCell_TextChanged);
this.cbMatrixCell.Enter += new System.EventHandler(this.cbMatrixCell_Enter);
//
// DialogNewMatrix
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(456, 400);
this.Controls.Add(this.cbMatrixCell);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.bRowDelete);
this.Controls.Add(this.bRowDown);
this.Controls.Add(this.bRowUp);
this.Controls.Add(this.bColumnDelete);
this.Controls.Add(this.lbMatrixRows);
this.Controls.Add(this.bRowSelect);
this.Controls.Add(this.bColumn);
this.Controls.Add(this.bColumnDown);
this.Controls.Add(this.bColumnUp);
this.Controls.Add(this.lbMatrixColumns);
this.Controls.Add(this.lbFields);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.cbDataSets);
this.Controls.Add(this.label1);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogNewMatrix";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "New Matrix";
this.ResumeLayout(false);
}
#endregion
private void bOK_Click(object sender, System.EventArgs e)
{
// apply the result
DialogResult = DialogResult.OK;
}
private void cbDataSets_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.lbMatrixColumns.Items.Clear();
this.lbMatrixRows.Items.Clear();
bOK.Enabled = false;
this.lbFields.Items.Clear();
string [] fields = _Draw.GetFields(cbDataSets.Text, false);
if (fields != null)
lbFields.Items.AddRange(fields);
}
private void bColumn_Click(object sender, System.EventArgs e)
{
ICollection sic = lbFields.SelectedIndices;
int count=sic.Count;
foreach (int i in sic)
{
string fname = (string) lbFields.Items[i];
if (this.lbMatrixColumns.Items.IndexOf(fname) < 0)
lbMatrixColumns.Items.Add(fname);
}
OkEnable();
}
private void bRow_Click(object sender, System.EventArgs e)
{
ICollection sic = lbFields.SelectedIndices;
int count=sic.Count;
foreach (int i in sic)
{
string fname = (string) lbFields.Items[i];
if (this.lbMatrixRows.Items.IndexOf(fname) < 0)
lbMatrixRows.Items.Add(fname);
}
OkEnable();
}
private void bColumnUp_Click(object sender, System.EventArgs e)
{
int index = lbMatrixColumns.SelectedIndex;
if (index <= 0)
return;
string prename = (string) lbMatrixColumns.Items[index-1];
lbMatrixColumns.Items.RemoveAt(index-1);
lbMatrixColumns.Items.Insert(index, prename);
}
private void bColumnDown_Click(object sender, System.EventArgs e)
{
int index = lbMatrixColumns.SelectedIndex;
if (index < 0 || index + 1 == lbMatrixColumns.Items.Count)
return;
string postname = (string) lbMatrixColumns.Items[index+1];
lbMatrixColumns.Items.RemoveAt(index+1);
lbMatrixColumns.Items.Insert(index, postname);
}
private void bColumnDelete_Click(object sender, System.EventArgs e)
{
int index = lbMatrixColumns.SelectedIndex;
if (index < 0)
return;
lbMatrixColumns.Items.RemoveAt(index);
OkEnable();
}
private void bRowUp_Click(object sender, System.EventArgs e)
{
int index = lbMatrixRows.SelectedIndex;
if (index <= 0)
return;
string prename = (string) lbMatrixRows.Items[index-1];
lbMatrixRows.Items.RemoveAt(index-1);
lbMatrixRows.Items.Insert(index, prename);
}
private void bRowDown_Click(object sender, System.EventArgs e)
{
int index = lbMatrixRows.SelectedIndex;
if (index < 0 || index + 1 == lbMatrixRows.Items.Count)
return;
string postname = (string) lbMatrixRows.Items[index+1];
lbMatrixRows.Items.RemoveAt(index+1);
lbMatrixRows.Items.Insert(index, postname);
}
private void bRowDelete_Click(object sender, System.EventArgs e)
{
int index = lbMatrixRows.SelectedIndex;
if (index < 0)
return;
lbMatrixRows.Items.RemoveAt(index);
OkEnable();
}
private void OkEnable()
{
// We need values in datasets, rows, columns, and matrix cells for OK to work correctly
bOK.Enabled = this.lbMatrixColumns.Items.Count > 0 &&
this.lbMatrixRows.Items.Count > 0 &&
this.cbMatrixCell.Text != null &&
this.cbMatrixCell.Text.Length > 0 &&
this.cbDataSets.Text != null &&
this.cbDataSets.Text.Length > 0;
}
private void cbMatrixCell_Enter(object sender, System.EventArgs e)
{
cbMatrixCell.Items.Clear();
foreach (string field in this.lbFields.Items)
{
if (this.lbMatrixColumns.Items.IndexOf(field) >= 0 ||
this.lbMatrixRows.Items.IndexOf(field) >= 0)
continue;
// Field selected in columns and rows
this.cbMatrixCell.Items.Add(string.Format("=Sum(Fields!{0}.Value)", field));
}
}
private void cbMatrixCell_TextChanged(object sender, System.EventArgs e)
{
OkEnable();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Microsoft.ApplicationBlocks.Data;
using ILPathways.Business;
namespace ILPathways.DAL
{
/// <summary>
/// Summary description for OrganizationManager
/// </summary>
///<remarks></remarks>
public class OrganizationManager : BaseDataManager
{
static string className = "OrganizationManager";
public static int K12_SCHOOL_ORG_TYPE = 1;
public static int K12_SCHOOL_DIV_ORG_TYPE = 2;
public static int STATE_AGENCY_ORG_TYPE = 3;
#region Constants for database procedures
// Gets an organization
const string GET_PROC = "OrganizationGet";
// Creates an organization
const string INSERT_PROC = "OrganizationInsert";
// Updates an organization
const string UPDATE_PROC = "OrganizationUpdate";
// Deletes an organization
const string OrganizationDelete_PROC = "OrganizationDelete";
const string SEARCH_PROC = "[OrganizationSearch]";
#endregion
public OrganizationManager()
{ }
#region organization Core methods
/// <summary>
/// Create an organization
/// </summary>
/// <param name="org"></param>
/// <returns></returns>
[Obsolete]
private static Organization Create( Organization org, string pathway )
{
org.IsValid = true;
org.Message = "";
try
{
#region parameters
SqlParameter[] sqlParameters = new SqlParameter[ 17 ];
sqlParameters[ 0 ] = new SqlParameter( "@Name", org.Name );
sqlParameters[ 1 ] = new SqlParameter( "@OrgTypeId", org.OrgTypeId );
sqlParameters[ 2 ] = new SqlParameter( "@parentId", org.ParentId );
sqlParameters[ 3 ] = new SqlParameter( "@IsActive", org.IsActive );
sqlParameters[ 4 ] = new SqlParameter( "@MainPhone", org.MainPhone );
sqlParameters[ 5 ] = new SqlParameter( "@MainExtension", org.MainExtension );
sqlParameters[ 6 ] = new SqlParameter( "@Fax", org.Fax );
sqlParameters[ 7 ] = new SqlParameter( "@TTY", org.TTY );
sqlParameters[ 8 ] = new SqlParameter( "@WebSite", org.WebSite );
sqlParameters[ 9 ] = new SqlParameter( "@email", org.Email );
sqlParameters[ 10 ] = new SqlParameter( "@LogoUrl", org.LogoUrl );
sqlParameters[ 11 ] = new SqlParameter( "@Address", org.Address1 );
sqlParameters[ 12 ] = new SqlParameter( "@Address2", org.Address2 );
sqlParameters[ 13 ] = new SqlParameter( "@City", org.City );
sqlParameters[ 14 ] = new SqlParameter( "@State", org.State );
sqlParameters[ 15 ] = new SqlParameter( "@Zipcode", org.Zipcode );
sqlParameters[ 16 ] = new SqlParameter( "@ZipCode4", org.ZipCode4 );
sqlParameters[ 17 ] = new SqlParameter( "@CreatedById", org.CreatedById );
#endregion
//Add the organization to the Organization table, returning the id of the record just added
SqlDataReader dr = SqlHelper.ExecuteReader( GatewayConnection(), INSERT_PROC, sqlParameters );
if ( dr.HasRows )
{
dr.Read();
org.Id = int.Parse( dr[ 0 ].ToString() );
}
dr.Close();
dr = null;
return Get( org.Id );
} catch ( Exception e )
{
LogError( "OrganizationManager.Create(): " + e.ToString() );
org.IsValid = false;
//TODO: should improve messages returned from a proc!!
org.Message = e.ToString();
return org;
}
}//
/// <summary>
/// Update an organization
/// </summary>
/// <param name="org"></param>
/// <returns></returns>
[Obsolete]
private static Organization Update( Organization org )
{
//alternate may be to pass organization as reference and use a bool to indicate success or failure
try
{
#region parameters
SqlParameter[] sqlParameters = new SqlParameter[ 17 ];
sqlParameters[ 0 ] = new SqlParameter( "@id", org.Id );
sqlParameters[ 1 ] = new SqlParameter( "@Name", org.Name );
sqlParameters[ 2 ] = new SqlParameter( "@IsActive", org.IsActive );
sqlParameters[ 3 ] = new SqlParameter( "@MainPhone", org.MainPhone );
sqlParameters[ 4 ] = new SqlParameter( "@MainExtension", org.MainExtension );
sqlParameters[ 5 ] = new SqlParameter( "@Fax", org.Fax );
sqlParameters[ 6 ] = new SqlParameter( "@TTY", org.TTY );
sqlParameters[ 7 ] = new SqlParameter( "@WebSite", org.WebSite );
sqlParameters[ 8 ] = new SqlParameter( "@email", org.Email );
sqlParameters[ 9 ] = new SqlParameter( "@LogoUrl", org.LogoUrl );
sqlParameters[ 10 ] = new SqlParameter( "@Address", org.Address1 );
sqlParameters[ 11 ] = new SqlParameter( "@Address2", org.Address2 );
sqlParameters[ 12 ] = new SqlParameter( "@City", org.City );
sqlParameters[ 13 ] = new SqlParameter( "@State", org.State );
sqlParameters[ 14 ] = new SqlParameter( "@Zipcode", org.Zipcode );
sqlParameters[ 15 ] = new SqlParameter( "@ZipCode4", org.ZipCode4 );
sqlParameters[ 16 ] = new SqlParameter( "@LastUpdatedById", org.LastUpdatedById );
#endregion
SqlHelper.ExecuteNonQuery( GatewayConnection(), UPDATE_PROC, sqlParameters );
org.Message = "successful";
return org;
} catch ( Exception e )
{
LogError( string.Format("OrganizationManager.Update(): id={0}, \rName:{1}\r\n ", org.Id, org.Name ) + e.ToString() );
org.IsValid = false;
org.Message = e.ToString();
return org;
}
}//
/// <summary>
/// Delete a site
/// </summary>
/// <param name="id"></param>
/// <param name="deletedBy">Perhaps use for logging??</param>
/// <param name="statusMessage"></param>
/// <returns></returns>
[Obsolete]
private static bool Delete( int id, string deletedBy, ref string statusMessage )
{
bool successful;
SqlParameter[] sqlParameters = new SqlParameter[ 1 ];
sqlParameters[ 0 ] = new SqlParameter( "@id", SqlDbType.Int );
sqlParameters[ 0 ].Value = id;
try
{
SqlHelper.ExecuteNonQuery( GatewayConnection(), CommandType.StoredProcedure, OrganizationDelete_PROC, sqlParameters );
successful = true;
} catch ( Exception ex )
{
LogError( ex, "OrganizationManager.Delete() " );
statusMessage = "Unsuccessful: OrganizationManager.Delete(): " + ex.Message.ToString();
successful = false;
}
return successful;
}
#endregion
#region organization retrieval methods
/// <summary>
/// Get an organization ONLY
/// NOTE: Use GetOrganization() to just get the organization and all services and funding sources
/// </summary>
/// <param name="id">organization id</param>
/// <returns></returns>
public static Organization Get( int id )
{
return Get( id, "" );
}//
public static Organization GetByRowId( string rowId )
{
return Get( 0, rowId );
}//
/// <summary>
/// Get an organization ONLY
/// NOTE: Use GetOrganization() to just get the organization and all services and funding sources
/// </summary>
/// <param name="id">organization id</param>
/// <returns></returns>
private static Organization Get( int id, string rowId )
{
Organization entity = new Organization();
try
{
//NOTE need to address other calls to this method, webservices, etc.
//So using a second proc
SqlParameter[] sqlParameters = new SqlParameter[1];
sqlParameters[0] = new SqlParameter("@id", id);
//sqlParameters[ 1 ] = new SqlParameter( "@RowId", rowId );
SqlDataReader dr = SqlHelper.ExecuteReader( GatewayConnectionRO(), GET_PROC, sqlParameters );
if (dr.HasRows)
{
while (dr.Read())
{
entity = Fill( dr );
//should only have one row returned, so do a break just in case
break;
}
}
dr.Close();
dr = null;
return entity;
}
catch (Exception e)
{
LogError("OrganizationManager.Get(): " + e.ToString());
return entity;
//throw e;
}
}//
/// <summary>
/// Retrieve organization by name - will need to handle dups in the future, or generate a unique name?
/// </summary>
/// <param name="orgName"></param>
/// <returns></returns>
public static Organization GetByName( string orgName)
{
Organization entity = new Organization();
try
{
SqlParameter[] sqlParameters = new SqlParameter[ 1 ];
sqlParameters[ 0 ] = new SqlParameter( "@Name", orgName );
SqlDataReader dr = SqlHelper.ExecuteReader( GatewayConnectionRO(), "[OrganizationGetByName]", sqlParameters );
if ( dr.HasRows )
{
while ( dr.Read() )
{
entity = Fill( dr );
//should only have one row returned, so do a break just in case
break;
}
}
dr.Close();
dr = null;
return entity;
}
catch ( Exception e )
{
LogError( "OrganizationManager.GetByName(): " + e.ToString() );
return entity;
//throw e;
}
}//
public static DataSet GetTopLevelOrganzations()
{
string filter = " (IsActive = 1 AND parentId is null)";
return SearchProxy( filter, "Name");
}//
/// <summary>
/// Get all active children of passed organization
/// The parent is not returned
/// </summary>
/// <param name="parentId">parentId for the org</param>
/// <returns>DataSet of child organizations</returns>
/// <remarks>This should probably be a call to an appropriate method within the organization manager</remarks>
public static DataSet GetChildOrganizations( int parentId )
{
//return GetChildOrganizations( parentId, false );
string filter = string.Format(" (IsActive = 1 AND parentId = {0}) ", parentId);
return SearchProxy( filter );
}//
public static DataSet GetRTTTOrganzations()
{
string filter = " (IsActive = 1 AND (parentId is null OR parentId in (2,3)))";
return SearchProxy( filter, "Name" );
}//
/// <summary>
/// Get all active children of passed organization
/// </summary>
/// <param name="id">id for the org</param>
/// <param name="includeParent">True if parent should be returned as well</param>///
/// <returns>DataSet of child organizations (and parent organization if includeParent = true</returns>
/// <remarks>This should probably be a call to an appropriate method within the organization manager</remarks>
public static DataSet GetChildOrganizations(int parentId, bool includeParent)
{
DataSet ds = new DataSet();
try
{
SqlParameter[] sqlParameters = new SqlParameter[3];
sqlParameters[ 0 ] = new SqlParameter( "@id", parentId );
sqlParameters[1] = new SqlParameter("@IsActive", 1);
sqlParameters[2] = new SqlParameter("@IncludeParent", includeParent);
ds = SqlHelper.ExecuteDataset(GatewayConnectionRO(), "TBD", sqlParameters);
if (ds.HasErrors)
{
ds = null;
return null;
}
return ds;
}
catch (Exception e)
{
LogError("ReportingManager.GetChildOrganizations(): " + e.ToString());
return null;
}
}//
private static DataSet SearchProxy( string filter )
{
int pTotalRows = 0;
int pMaximumRows = 500;
return Search( filter, "Name", 1, pMaximumRows, ref pTotalRows );
}//
private static DataSet SearchProxy( string filter, string orderBy )
{
int pTotalRows = 0;
int pMaximumRows = 500;
return Search( filter, orderBy, 1, pMaximumRows, ref pTotalRows );
}//
/// <summary>
/// Search for organization related data using passed parameters
/// </summary>
/// <param name="pFilter"></param>
/// <param name="pOrderBy">Sort order of results. If blank, the proc should have a default sort order</param>
/// <param name="pStartPageIndex"></param>
/// <param name="pMaximumRows"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
public static List<Organization> SearchAsList( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
List<Organization> list = new List<Organization>();
DataSet ds = Search( pFilter, pOrderBy, pStartPageIndex, pMaximumRows, ref pTotalRows );
if ( DatabaseManager.DoesDataSetHaveRows( ds ) )
{
foreach ( DataRow dr in ds.Tables[ 0 ].DefaultView.Table.Rows )
{
Organization org = Fill( dr );
list.Add( org );
} //end foreach
}
return list;
}//
/// <summary>
/// Search for organization related data using passed parameters
/// - uses custom paging
/// - only requested range of rows will be returned
/// </summary>
/// <param name="pFilter"></param>
/// <param name="pOrderBy">Sort order of results. If blank, the proc should have a default sort order</param>
/// <param name="pStartPageIndex"></param>
/// <param name="pMaximumRows"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
public static DataSet Search( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
int outputCol = 4;
SqlParameter[] sqlParameters = new SqlParameter[ 5 ];
sqlParameters[ 0 ] = new SqlParameter( "@Filter", pFilter );
sqlParameters[ 1 ] = new SqlParameter( "@SortOrder", pOrderBy );
sqlParameters[ 2 ] = new SqlParameter( "@StartPageIndex", pStartPageIndex);
sqlParameters[ 3 ] = new SqlParameter( "@PageSize", pMaximumRows);
sqlParameters[ outputCol ] = new SqlParameter( "@TotalRows", SqlDbType.Int );
sqlParameters[ outputCol ].Direction = ParameterDirection.Output;
using ( SqlConnection conn = new SqlConnection( GatewayConnectionRO() ) )
{
DataSet ds = new DataSet();
try
{
ds = SqlHelper.ExecuteDataset( conn, CommandType.StoredProcedure, SEARCH_PROC, sqlParameters );
string rows = sqlParameters[ outputCol ].Value.ToString();
try
{
pTotalRows = Int32.Parse( rows );
}
catch
{
pTotalRows = 0;
}
if ( ds.HasErrors )
{
return null;
}
return ds;
}
catch ( Exception ex )
{
LogError( ex, className + ".Search() " );
return null;
}
}
}
/// <summary>
/// Fill an Organization object from a SqlDataReader
/// </summary>
/// <param name="dr">SqlDataReader</param>
/// <returns>Policy</returns>
public static Organization Fill( SqlDataReader dr )
{
Organization entity = new Organization();
entity.Id = GetRowColumn( dr, "id", 0 );
entity.Name = dr[ "name" ].ToString();
entity.OrgTypeId = GetRowColumn( dr, "OrgTypeId", 0 );
entity.OrgType = GetRowPossibleColumn( dr, "OrgType", entity.OrgTypeId.ToString() );
entity.ParentId = GetRowColumn( dr, "parentId", 0 );
//entity.PrimaryContactId = GetRowColumn( dr, "primaryContactId", 0 );
entity.IsActive = GetRowColumn( dr, "IsActive", false );
entity.IsIsleMember = GetRowPossibleColumn( dr, "IsIsleMember", false );
entity.MainPhone = GetRowColumn( dr, "MainPhone", "" );
entity.MainExtension = GetRowColumn( dr, "MainExtension", "" );
entity.Fax = GetRowColumn( dr, "Fax", "" );
entity.TTY = GetRowColumn( dr, "TTY", "" );
entity.WebSite = GetRowPossibleColumn( dr, "WebSite", "" );
entity.Email = GetRowPossibleColumn( dr, "Email", "" );
entity.EmailDomain = GetRowPossibleColumn( dr, "EmailDomain", "" );
entity.LogoUrl = GetRowPossibleColumn( dr, "LogoUrl", "" );
entity.Address1 = GetRowColumn( dr, "Address", "" );
entity.Address2 = GetRowColumn( dr, "Address2", "" );
entity.City = GetRowColumn( dr, "City", "" );
entity.State = GetRowColumn( dr, "State", "" );
entity.Zipcode = GetRowColumn( dr, "Zipcode", "" );
entity.ZipCode4 = GetRowPossibleColumn( dr, "ZipCode4", "" );
entity.IsContentApprovalRequired = GetRowPossibleColumn( dr, "IsContentApprovalRequired", false );
entity.Created = DateTime.Parse( dr[ "Created" ].ToString() );
entity.CreatedById = GetRowColumn( dr, "CreatedById", 0 );
//entity.CreatedBy = dr[ "CreatedBy" ].ToString();
entity.LastUpdated = DateTime.Parse( dr[ "LastUpdated" ].ToString() );
entity.LastUpdatedById = GetRowColumn( dr, "LastUpdatedById", 0 );
//entity.LastUpdatedBy = dr[ "LastUpdatedBy" ].ToString();
string rowId = GetRowColumn( dr, "RowId", "" );
if ( rowId.Length > 35 )
entity.RowId = new Guid( rowId );
return entity;
}//
/// <summary>
/// Fill an Organization object from a SqlDataReader
/// </summary>
/// <param name="dr">SqlDataReader</param>
/// <returns>Policy</returns>
public static Organization Fill( DataRow dr )
{
Organization entity = new Organization();
entity.Id = GetRowColumn( dr, "id", 0 );
entity.Name = dr[ "name" ].ToString();
entity.OrgTypeId = GetRowColumn( dr, "OrgTypeId", 0 );
entity.OrgType = GetRowPossibleColumn( dr, "OrgType", entity.OrgTypeId.ToString());
entity.ParentId = GetRowColumn( dr, "parentId", 0 );
//entity.PrimaryContactId = GetRowColumn( dr, "primaryContactId", 0 );
entity.IsActive = GetRowColumn( dr, "IsActive", false );
entity.IsIsleMember = GetRowColumn( dr, "IsIsleMember", false );
entity.MainPhone = GetRowColumn( dr, "MainPhone", "" );
entity.MainExtension = GetRowColumn( dr, "MainExtension", "" );
entity.Fax = GetRowColumn( dr, "Fax", "" );
entity.TTY = GetRowColumn( dr, "TTY", "" );
entity.WebSite = GetRowPossibleColumn( dr, "WebSite", "" );
entity.Email = GetRowPossibleColumn( dr, "Email", "" );
entity.EmailDomain = GetRowColumn( dr, "EmailDomain", "" );
entity.LogoUrl = GetRowPossibleColumn( dr, "LogoUrl", "" );
entity.Address1 = GetRowColumn( dr, "Address", "" );
entity.Address2 = GetRowColumn( dr, "Address2", "" );
entity.City = GetRowColumn( dr, "City", "" );
entity.State = GetRowColumn( dr, "State", "" );
entity.Zipcode = GetRowColumn( dr, "Zipcode", "" );
entity.ZipCode4 = GetRowPossibleColumn( dr, "ZipCode4", "" );
entity.IsContentApprovalRequired = GetRowPossibleColumn( dr, "IsContentApprovalRequired", false );
entity.Created = DateTime.Parse( dr[ "Created" ].ToString() );
entity.CreatedById = GetRowColumn( dr, "CreatedById", 0 );
//entity.CreatedBy = dr[ "CreatedBy" ].ToString();
entity.LastUpdated = DateTime.Parse( dr[ "LastUpdated" ].ToString() );
entity.LastUpdatedById = GetRowColumn( dr, "LastUpdatedById", 0 );
//entity.LastUpdatedBy = dr[ "LastUpdatedBy" ].ToString();
string rowId = GetRowColumn( dr, "RowId", "" );
if ( rowId.Length > 35 )
entity.RowId = new Guid( rowId );
return entity;
}//
public static string[] OrganzationsAutoComplete( string prefixText )
{
//int count = 10;
string sql = "SELECT [Name], [Name] + ' [' + convert(varchar, [Id]) + '] ' As Combined FROM [Gateway].[dbo].[Organization] where [IsActive]= 1 And Name like @prefixText order by 1";
try
{
DataSet ds = DatabaseManager.DoQuery( sql );
SqlDataAdapter da = new SqlDataAdapter( sql, GatewayConnectionRO() );
da.SelectCommand.Parameters.Add( "@prefixText", SqlDbType.VarChar, 100 ).Value = "%" + prefixText + "%";
DataTable dt = new DataTable();
da.Fill( dt );
string[] items = new string[ dt.Rows.Count ];
int i = 0;
foreach ( DataRow dr in dt.Rows )
{
items.SetValue( dr[ "Combined" ].ToString(), i );
i++;
}
return items;
}
catch ( Exception ex )
{
LogError( ex, className + ".OrganzationsAutoComplete() - Unexpected error encountered while attempting search. " );
return null;
}
}//
#endregion
#region organization Contacts
/// <summary>
/// Get all ACTIVE LWIA contacts for an organization
/// </summary>
/// <param name="orgId">id for the org</param>
/// <param name="includeChildSiteUsers">If True, then also retrieve all users from child organizations (ie. where an organization's parentId equals the passed orgId</param>
/// <returns></returns>
public static DataSet GetOrgUsers( int orgId, bool includeChildSiteUsers )
{
DataSet ds = new DataSet();
try
{
SqlParameter[] sqlParameters = new SqlParameter[ 2 ];
sqlParameters[ 0 ] = new SqlParameter( "@orgId", orgId );
if ( includeChildSiteUsers )
sqlParameters[ 1 ] = new SqlParameter( "@parentId", orgId );
else
sqlParameters[ 1 ] = new SqlParameter( "@parentId", 0 );
ds = SqlHelper.ExecuteDataset( GatewayConnectionRO(), "TBD", sqlParameters );
if ( ds.HasErrors )
{
ds = null;
return null;
}
return ds;
} catch ( Exception e )
{
LogError( className + ".GetOrgUsers(): " + e.ToString() );
return null;
}
}//
#endregion
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//***************************************************
using System;
using System.Collections.Generic;
using SharpKit.JavaScript;
namespace Y_
{
/// <summary>
/// Loader dynamically loads script and css files. It includes the dependency
/// info for the version of the library in use, and will automatically pull in
/// dependencies for the modules requested. It can load the
/// files from the Yahoo! CDN, and it can utilize the combo service provided on
/// this network to reduce the number of http connections required to download
/// YUI files. You can also specify an external, custom combo service to host
/// your modules as well.
/// var Y = YUI();
/// var loader = new Y.Loader({
/// filter: 'debug',
/// base: '../../',
/// root: 'build/',
/// combine: true,
/// require: ['node', 'dd', 'console']
/// });
/// var out = loader.resolve(true);
/// </summary>
public partial class Loader
{
/// <summary>
/// Adds an alias module to the system
/// </summary>
public void addAlias(Y_.Array use, object name){}
/// <summary>
/// Add a new module group
/// </summary>
public void addGroup(object config, object name){}
/// <summary>
/// Add a new module to the component metadata.
/// </summary>
public object addModule(object config){return null;}
/// <summary>
/// Add a new module to the component metadata.
/// </summary>
public object addModule(object config, object name){return null;}
/// <summary>
/// Calculates the dependency tree, the result is stored in the sorted
/// property.
/// </summary>
public void calculate(object o, object type){}
/// <summary>
/// Explodes the required array to remove aliases and replace them with real modules
/// </summary>
public Y_.Array filterRequires(Y_.Array r){return null;}
/// <summary>
/// Returns the skin module name for the specified skin name. If a
/// module name is supplied, the returned skin module name is
/// specific to the module passed in.
/// </summary>
public object formatSkin(object skin, object mod){return null;}
/// <summary>
/// Builds a module name for a language pack
/// </summary>
public object getLangPackName(object lang, object mname){return null;}
/// <summary>
/// Get's the loader meta data for the requested module
/// </summary>
public object getModule(object mname){return null;}
/// <summary>
/// Returns a hash of module names the supplied module satisfies.
/// </summary>
public object getProvides(object name){return null;}
/// <summary>
/// Returns an object containing properties for all modules required
/// in order to load the requested module
/// </summary>
public Y_.Array getRequires(object mod){return null;}
/// <summary>
/// inserts the requested modules and their dependencies.
/// <code>type</code> can be "js" or "css". Both script and
/// css are inserted if type is not provided.
/// </summary>
public void insert(object o, object type){}
/// <summary>
/// Check to see if named css module is already loaded on the page
/// </summary>
public object isCSSLoaded(object name){return null;}
/// <summary>
/// Shortcut to calculate, resolve and load all modules.
/// var loader = new Y.Loader({
/// ignoreRegistered: true,
/// modules: {
/// mod: {
/// path: 'mod.js'
/// }
/// },
/// requires: [ 'mod' ]
/// });
/// loader.load(function() {
/// console.log('All modules have loaded..');
/// });
/// </summary>
public void load(object cb){}
/// <summary>
/// Executed every time a module is loaded, and if we are in a load
/// cycle, we attempt to load the next script. Public so that it
/// is possible to call this if using a method other than
/// Y.register to determine when scripts are fully loaded
/// </summary>
public void loadNext(object mname){}
/// <summary>
/// Callback for the 'CSSComplete' event. When loading YUI components
/// with CSS the CSS is loaded first, then the script. This provides
/// a moment you can tie into to improve the presentation of the page
/// while the script is loading.
/// </summary>
public void onCSS(){}
/// <summary>
/// Callback that will be executed if there is a failure
/// </summary>
public void onFailure(){}
/// <summary>
/// Callback executed each time a script or css file is loaded
/// </summary>
public void onProgress(){}
/// <summary>
/// Callback that will be executed when the loader is finished
/// with an insert
/// </summary>
public void onSuccess(){}
/// <summary>
/// Callback that will be executed if a timeout occurs
/// </summary>
public void onTimeout(){}
/// <summary>
/// Add a requirement for one or more module
/// </summary>
public void require(object what){}
/// <summary>
/// Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules.
/// </summary>
public object resolve(){return null;}
/// <summary>
/// Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules.
/// </summary>
public object resolve(Y_.Array s){return null;}
/// <summary>
/// Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules.
/// </summary>
public object resolve(object calc){return null;}
/// <summary>
/// Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules.
/// </summary>
public object resolve(object calc, Y_.Array s){return null;}
/// <summary>
/// The base directory.
/// </summary>
public string @base{get;set;}
/// <summary>
/// The charset attribute for inserted nodes
/// </summary>
public string charset{get;set;}
/// <summary>
/// Base path for the combo service
/// </summary>
public string comboBase{get;set;}
/// <summary>
/// The execution context for all callbacks
/// </summary>
public object context{get;set;}
/// <summary>
/// An object literal containing attributes to add to link nodes
/// </summary>
public object cssAttributes{get;set;}
/// <summary>
/// Data that is passed to all callbacks
/// </summary>
public object data{get;set;}
/// <summary>
/// Default filters for raw and debug
/// </summary>
protected object FILTER_DEFS{get;set;}
/// <summary>
/// per-component filter specification. If specified for a given
/// component, this overrides the filter config.
/// </summary>
public object filters{get;set;}
/// <summary>
/// Ignore modules registered on the YUI global
/// </summary>
public object ignoreRegistered{get;set;}
/// <summary>
/// An object literal containing attributes to add to script nodes
/// </summary>
public object jsAttributes{get;set;}
/// <summary>
/// Max url length for combo urls. The default is 2048. This is the URL
/// limit for the Yahoo! hosted combo servers. If consuming
/// a different combo service that has a different URL limit
/// it is possible to override this default by supplying
/// the maxURLLength config option. The config option will
/// only take effect if lower than the default.
/// </summary>
public int maxURLLength{get;set;}
/// <summary>
/// The library metadata
/// </summary>
public object moduleInfo{get;set;}
/// <summary>
/// If a module name is predefined when requested, it is checked againsts
/// the patterns provided in this property. If there is a match, the
/// module is added with the default configuration.
/// At the moment only supporting module prefixes, but anticipate
/// supporting at least regular expressions.
/// </summary>
public object patterns{get;set;}
/// <summary>
/// List of rollup files found in the library metadata
/// </summary>
public object rollups{get;set;}
/// <summary>
/// Root path to prepend to module path for the combo
/// service
/// </summary>
public string root{get;set;}
/// <summary>
/// List of skipped modules during insert() because the module
/// was not defined
/// </summary>
public object skipped{get;set;}
/// <summary>
/// Timeout value in milliseconds. If set, self value will be used by
/// the get utility. the timeout event will fire if
/// a timeout occurs.
/// </summary>
public int timeout{get;set;}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlDataSourceView.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing.Design;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
using ConflictOptions = System.Web.UI.ConflictOptions;
/// <devdoc>
/// Represents a single view of a SqlDataSource.
/// </devdoc>
public class SqlDataSourceView : DataSourceView, IStateManager {
private const int MustDeclareVariableSqlExceptionNumber = 137;
private const int ProcedureExpectsParameterSqlExceptionNumber = 201;
private static readonly object EventDeleted = new object();
private static readonly object EventDeleting = new object();
private static readonly object EventFiltering = new object();
private static readonly object EventInserted = new object();
private static readonly object EventInserting = new object();
private static readonly object EventSelected = new object();
private static readonly object EventSelecting = new object();
private static readonly object EventUpdated = new object();
private static readonly object EventUpdating = new object();
private HttpContext _context;
private SqlDataSource _owner;
private bool _tracking;
private bool _cancelSelectOnNullParameter = true;
private ConflictOptions _conflictDetection = ConflictOptions.OverwriteChanges;
private string _deleteCommand;
private SqlDataSourceCommandType _deleteCommandType = SqlDataSourceCommandType.Text;
private ParameterCollection _deleteParameters;
private string _filterExpression;
private ParameterCollection _filterParameters;
private string _insertCommand;
private SqlDataSourceCommandType _insertCommandType = SqlDataSourceCommandType.Text;
private ParameterCollection _insertParameters;
private string _oldValuesParameterFormatString;
private string _selectCommand;
private SqlDataSourceCommandType _selectCommandType = SqlDataSourceCommandType.Text;
private ParameterCollection _selectParameters;
private string _sortParameterName;
private string _updateCommand;
private SqlDataSourceCommandType _updateCommandType = SqlDataSourceCommandType.Text;
private ParameterCollection _updateParameters;
/// <devdoc>
/// Creates a new instance of SqlDataSourceView.
/// </devdoc>
public SqlDataSourceView(SqlDataSource owner, string name, HttpContext context) : base(owner, name) {
_owner = owner;
_context = context;
}
public bool CancelSelectOnNullParameter {
get {
return _cancelSelectOnNullParameter;
}
set {
if (CancelSelectOnNullParameter != value) {
_cancelSelectOnNullParameter = value;
OnDataSourceViewChanged(EventArgs.Empty);
}
}
}
/// <devdoc>
/// Indicates that the view can delete rows.
/// </devdoc>
public override bool CanDelete {
get {
return (DeleteCommand.Length != 0);
}
}
/// <devdoc>
/// Indicates that the view can add new rows.
/// </devdoc>
public override bool CanInsert {
get {
return (InsertCommand.Length != 0);
}
}
/// <devdoc>
/// Indicates that the view can page the datasource on the server.
/// </devdoc>
public override bool CanPage {
get {
return false;
}
}
/// <devdoc>
/// Indicates that the view can return the total number of rows returned by the query.
/// </devdoc>
public override bool CanRetrieveTotalRowCount {
get {
return false;
}
}
/// <devdoc>
/// Indicates that the view can sort rows.
/// </devdoc>
public override bool CanSort {
get {
return (_owner.DataSourceMode == SqlDataSourceMode.DataSet) || (SortParameterName.Length > 0);
}
}
/// <devdoc>
/// Indicates that the view can update rows.
/// </devdoc>
public override bool CanUpdate {
get {
return (UpdateCommand.Length != 0);
}
}
/// <devdoc>
/// Whether commands pass old values in the parameter collection.
/// </devdoc>
public ConflictOptions ConflictDetection {
get {
return _conflictDetection;
}
set {
if ((value < ConflictOptions.OverwriteChanges) || (value > ConflictOptions.CompareAllValues)) {
throw new ArgumentOutOfRangeException("value");
}
_conflictDetection = value;
OnDataSourceViewChanged(EventArgs.Empty);
}
}
/// <devdoc>
/// The command to execute when Delete() is called on the SqlDataSourceView.
/// </devdoc>
public string DeleteCommand {
get {
if (_deleteCommand == null) {
return String.Empty;
}
return _deleteCommand;
}
set {
_deleteCommand = value;
}
}
public SqlDataSourceCommandType DeleteCommandType {
get {
return _deleteCommandType;
}
set {
if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
throw new ArgumentOutOfRangeException("value");
}
_deleteCommandType = value;
}
}
/// <devdoc>
/// Collection of parameters used in Delete().
/// </devdoc>
[
DefaultValue(null),
Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerProperty),
WebSysDescription(SR.SqlDataSource_DeleteParameters),
]
public ParameterCollection DeleteParameters {
get {
if (_deleteParameters == null) {
_deleteParameters = new ParameterCollection();
}
return _deleteParameters;
}
}
/// <devdoc>
/// The filter to apply when Select() is called on the SqlDataSourceView.
/// </devdoc>
public string FilterExpression {
get {
if (_filterExpression == null) {
return String.Empty;
}
return _filterExpression;
}
set {
if (FilterExpression != value) {
_filterExpression = value;
OnDataSourceViewChanged(EventArgs.Empty);
}
}
}
/// <devdoc>
/// Collection of parameters used in the FilterExpression property.
/// </devdoc>
[
DefaultValue(null),
Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerProperty),
WebSysDescription(SR.SqlDataSource_FilterParameters),
]
public ParameterCollection FilterParameters {
get {
if (_filterParameters == null) {
_filterParameters = new ParameterCollection();
_filterParameters.ParametersChanged += new EventHandler(SelectParametersChangedEventHandler);
if (_tracking) {
((IStateManager)_filterParameters).TrackViewState();
}
}
return _filterParameters;
}
}
/// <devdoc>
/// The command to execute when Insert() is called on the SqlDataSourceView.
/// </devdoc>
public string InsertCommand {
get {
if (_insertCommand == null) {
return String.Empty;
}
return _insertCommand;
}
set {
_insertCommand = value;
}
}
public SqlDataSourceCommandType InsertCommandType {
get {
return _insertCommandType;
}
set {
if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
throw new ArgumentOutOfRangeException("value");
}
_insertCommandType = value;
}
}
/// <devdoc>
/// Collection of values used in Insert().
/// </devdoc>
[
DefaultValue(null),
Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerProperty),
WebSysDescription(SR.SqlDataSource_InsertParameters),
]
public ParameterCollection InsertParameters {
get {
if (_insertParameters == null) {
_insertParameters = new ParameterCollection();
}
return _insertParameters;
}
}
/// <devdoc>
/// Returns whether this object is tracking view state.
/// </devdoc>
protected bool IsTrackingViewState {
get {
return _tracking;
}
}
/// <devdoc>
/// The format string applied to the names of the old values parameters
/// </devdoc>
[
DefaultValue("{0}"),
WebCategory("Data"),
WebSysDescription(SR.DataSource_OldValuesParameterFormatString),
]
public string OldValuesParameterFormatString {
get {
if (_oldValuesParameterFormatString == null) {
return "{0}";
}
return _oldValuesParameterFormatString;
}
set {
_oldValuesParameterFormatString = value;
OnDataSourceViewChanged(EventArgs.Empty);
}
}
/// <devdoc>
/// Indicates the prefix for parameters.
/// </devdoc>
protected virtual string ParameterPrefix {
get {
if (String.IsNullOrEmpty(_owner.ProviderName) ||
String.Equals(_owner.ProviderName, "System.Data.SqlClient", StringComparison.OrdinalIgnoreCase)) {
return "@";
}
else {
return String.Empty;
}
}
}
/// <devdoc>
/// The command to execute when Select() is called on the SqlDataSourceView.
/// </devdoc>
public string SelectCommand {
get {
if (_selectCommand == null) {
return String.Empty;
}
return _selectCommand;
}
set {
if (SelectCommand != value) {
_selectCommand = value;
OnDataSourceViewChanged(EventArgs.Empty);
}
}
}
public SqlDataSourceCommandType SelectCommandType {
get {
return _selectCommandType;
}
set {
if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
throw new ArgumentOutOfRangeException("value");
}
_selectCommandType = value;
}
}
/// <devdoc>
/// The command to execute when Select is called on the SqlDataSourceView and the total rows is requested.
/// </devdoc>
/*public string SelectCountCommand {
get {
if (_selectCountCommand == null) {
return String.Empty;
}
return _selectCountCommand;
}
set {
if (SelectCountCommand != value) {
_selectCountCommand = value;
OnDataSourceViewChanged(EventArgs.Empty);
}
}
}*/
/// <devdoc>
/// Collection of parameters used in Select().
/// </devdoc>
public ParameterCollection SelectParameters {
get {
if (_selectParameters == null) {
_selectParameters = new ParameterCollection();
_selectParameters.ParametersChanged += new EventHandler(SelectParametersChangedEventHandler);
if (_tracking) {
((IStateManager)_selectParameters).TrackViewState();
}
}
return _selectParameters;
}
}
/// <devdoc>
/// The name of the parameter in the SelectCommand that specifies the
/// sort expression. This parameter's value will be automatically set
/// at runtime with the appropriate sort expression. This is only
/// supported for stored procedure commands.
/// </devdoc>
public string SortParameterName {
get {
if (_sortParameterName == null) {
return String.Empty;
}
return _sortParameterName;
}
set {
if (SortParameterName != value) {
_sortParameterName = value;
OnDataSourceViewChanged(EventArgs.Empty);
}
}
}
/// <devdoc>
/// The command to execute when Update() is called on the SqlDataSourceView.
/// </devdoc>
public string UpdateCommand {
get {
if (_updateCommand == null) {
return String.Empty;
}
return _updateCommand;
}
set {
_updateCommand = value;
}
}
public SqlDataSourceCommandType UpdateCommandType {
get {
return _updateCommandType;
}
set {
if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
throw new ArgumentOutOfRangeException("value");
}
_updateCommandType = value;
}
}
/// <devdoc>
/// Collection of parameters used in Update().
/// </devdoc>
[
DefaultValue(null),
Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerProperty),
WebSysDescription(SR.SqlDataSource_UpdateParameters),
]
public ParameterCollection UpdateParameters {
get {
if (_updateParameters == null) {
_updateParameters = new ParameterCollection();
}
return _updateParameters;
}
}
/// <devdoc>
/// This event is raised after the Delete operation has completed.
/// Handle this event if you need to examine the values of output parameters.
/// </devdoc>
public event SqlDataSourceStatusEventHandler Deleted {
add {
Events.AddHandler(EventDeleted, value);
}
remove {
Events.RemoveHandler(EventDeleted, value);
}
}
/// <devdoc>
/// This event is raised before the Delete operation has been executed.
/// Handle this event if you want to perform additional initialization operations
/// that are specific to your application. You can also handle this event if you
/// need to validate the values of parameters or change their values.
/// When this event is raised, the database connection is not open yet, and you
/// can cancel the event by setting the Cancel property of the DataCommandEventArgs
/// to true.
/// </devdoc>
public event SqlDataSourceCommandEventHandler Deleting {
add {
Events.AddHandler(EventDeleting, value);
}
remove {
Events.RemoveHandler(EventDeleting, value);
}
}
public event SqlDataSourceFilteringEventHandler Filtering {
add {
Events.AddHandler(EventFiltering, value);
}
remove {
Events.RemoveHandler(EventFiltering, value);
}
}
/// <devdoc>
/// This event is raised after the Insert operation has completed.
/// Handle this event if you need to examine the values of output parameters.
/// </devdoc>
public event SqlDataSourceStatusEventHandler Inserted {
add {
Events.AddHandler(EventInserted, value);
}
remove {
Events.RemoveHandler(EventInserted, value);
}
}
/// <devdoc>
/// This event is raised before the Insert operation has been executed.
/// Handle this event if you want to perform additional initialization operations
/// that are specific to your application. You can also handle this event if you
/// need to validate the values of parameters or change their values.
/// When this event is raised, the database connection is not open yet, and you
/// can cancel the event by setting the Cancel property of the DataCommandEventArgs
/// to true.
/// </devdoc>
public event SqlDataSourceCommandEventHandler Inserting {
add {
Events.AddHandler(EventInserting, value);
}
remove {
Events.RemoveHandler(EventInserting, value);
}
}
/// <devdoc>
/// This event is raised after the Select operation has completed.
/// Handle this event if you need to examine the values of output parameters.
/// </devdoc>
public event SqlDataSourceStatusEventHandler Selected {
add {
Events.AddHandler(EventSelected, value);
}
remove {
Events.RemoveHandler(EventSelected, value);
}
}
/// <devdoc>
/// This event is raised before the Select operation has been executed.
/// Handle this event if you want to perform additional initialization operations
/// that are specific to your application. You can also handle this event if you
/// need to validate the values of parameters or change their values.
/// When this event is raised, the database connection is not open yet, and you
/// can cancel the event by setting the Cancel property of the DataCommandEventArgs
/// to true.
/// </devdoc>
public event SqlDataSourceSelectingEventHandler Selecting {
add {
Events.AddHandler(EventSelecting, value);
}
remove {
Events.RemoveHandler(EventSelecting, value);
}
}
/// <devdoc>
/// This event is raised after the Update operation has completed.
/// Handle this event if you need to examine the values of output parameters.
/// </devdoc>
public event SqlDataSourceStatusEventHandler Updated {
add {
Events.AddHandler(EventUpdated, value);
}
remove {
Events.RemoveHandler(EventUpdated, value);
}
}
/// <devdoc>
/// This event is raised before the Update operation has been executed.
/// Handle this event if you want to perform additional initialization operations
/// that are specific to your application. You can also handle this event if you
/// need to validate the values of parameters or change their values.
/// When this event is raised, the database connection is not open yet, and you
/// can cancel the event by setting the Cancel property of the DataCommandEventArgs
/// to true.
/// </devdoc>
public event SqlDataSourceCommandEventHandler Updating {
add {
Events.AddHandler(EventUpdating, value);
}
remove {
Events.RemoveHandler(EventUpdating, value);
}
}
/// <devdoc>
/// Adds parameters to an DbCommand from an IOrderedDictionary.
/// The exclusion list contains parameter names that should not be added
/// to the command's parameter collection.
/// </devdoc>
private void AddParameters(DbCommand command, ParameterCollection reference, IDictionary parameters, IDictionary exclusionList, string oldValuesParameterFormatString) {
Debug.Assert(command != null);
IDictionary caseInsensitiveExclusionList = null;
if (exclusionList != null) {
caseInsensitiveExclusionList = new ListDictionary(StringComparer.OrdinalIgnoreCase);
foreach (DictionaryEntry de in exclusionList) {
caseInsensitiveExclusionList.Add(de.Key, de.Value);
}
}
if (parameters != null) {
string parameterPrefix = ParameterPrefix;
foreach (DictionaryEntry de in parameters) {
string rawParamName = (string)de.Key;
if ((caseInsensitiveExclusionList != null) && (caseInsensitiveExclusionList.Contains(rawParamName))) {
// If we have an exclusion list and it contains this parameter, skip it
continue;
}
string formattedParamName;
if (oldValuesParameterFormatString == null) {
formattedParamName = rawParamName;
}
else {
formattedParamName = String.Format(CultureInfo.InvariantCulture, oldValuesParameterFormatString, rawParamName);
}
object value = de.Value;
// If the reference collection contains this parameter, we will use
// the Parameter's settings to format the value
Parameter parameter = reference[formattedParamName];
if (parameter != null) {
value = parameter.GetValue(de.Value, false);
}
formattedParamName = parameterPrefix + formattedParamName;
if (command.Parameters.Contains(formattedParamName)) {
// We never overwrite an existing value with a null value
if (value != null) {
command.Parameters[formattedParamName].Value = value;
}
}
else {
// Parameter does not exist, add a new one
DbParameter dbParameter = _owner.CreateParameter(formattedParamName, value);
command.Parameters.Add(dbParameter);
}
}
}
}
/// <devdoc>
/// Builds a custom exception for specific database errors.
/// Currently the only custom exception text supported is for SQL Server
/// when a parameter is present in the command but not in the parameters
/// collection.
/// The isCustomException parameter indicates whether a custom exception
/// was created or not. This way the caller can determine whether it wants
/// to rethrow the original exception or throw the new custom exception.
/// </devdoc>
private Exception BuildCustomException(Exception ex, DataSourceOperation operation, DbCommand command, out bool isCustomException) {
System.Data.SqlClient.SqlException sqlException = ex as System.Data.SqlClient.SqlException;
if (sqlException != null) {
if ((sqlException.Number == MustDeclareVariableSqlExceptionNumber) ||
(sqlException.Number == ProcedureExpectsParameterSqlExceptionNumber)) {
string parameterNames;
if (command.Parameters.Count > 0) {
StringBuilder sb = new StringBuilder();
bool firstParameter = true;
foreach (DbParameter p in command.Parameters) {
if (!firstParameter) {
sb.Append(", ");
}
sb.Append(p.ParameterName);
firstParameter = false;
}
parameterNames = sb.ToString();
}
else {
parameterNames = SR.GetString(SR.SqlDataSourceView_NoParameters);
}
isCustomException = true;
return new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_MissingParameters, operation, _owner.ID, parameterNames));
}
}
isCustomException = false;
return ex;
}
public int Delete(IDictionary keys, IDictionary oldValues) {
return ExecuteDelete(keys, oldValues);
}
/// <devdoc>
/// Executes a DbCommand and returns the number of rows affected.
/// </devdoc>
private int ExecuteDbCommand(DbCommand command, DataSourceOperation operation) {
int rowsAffected = 0;
bool eventRaised = false;
try {
if (command.Connection.State != ConnectionState.Open) {
command.Connection.Open();
}
rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0) {
OnDataSourceViewChanged(EventArgs.Empty);
DataSourceCache cache = _owner.Cache;
if ((cache != null) && (cache.Enabled)) {
_owner.InvalidateCacheEntry();
}
}
// Raise appropriate event
eventRaised = true;
SqlDataSourceStatusEventArgs eventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, null);
switch (operation) {
case DataSourceOperation.Delete:
OnDeleted(eventArgs);
break;
case DataSourceOperation.Insert:
OnInserted(eventArgs);
break;
case DataSourceOperation.Update:
OnUpdated(eventArgs);
break;
}
}
catch (Exception ex) {
if (!eventRaised) {
// Raise appropriate event
SqlDataSourceStatusEventArgs eventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, ex);
switch (operation) {
case DataSourceOperation.Delete:
OnDeleted(eventArgs);
break;
case DataSourceOperation.Insert:
OnInserted(eventArgs);
break;
case DataSourceOperation.Update:
OnUpdated(eventArgs);
break;
}
if (!eventArgs.ExceptionHandled) {
throw;
}
}
else {
bool isCustomException;
ex = BuildCustomException(ex, operation, command, out isCustomException);
if (isCustomException) {
throw ex;
}
else {
throw;
}
}
}
finally {
if (command.Connection.State == ConnectionState.Open) {
command.Connection.Close();
}
}
return rowsAffected;
}
/// <devdoc>
/// Deletes rows from the data source with given parameters.
/// </devdoc>
protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues) {
if (!CanDelete) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_DeleteNotSupported, _owner.ID));
}
DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);
if (connection == null) {
throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
}
// Create command and add parameters
string oldValuesParameterFormatString = OldValuesParameterFormatString;
DbCommand command = _owner.CreateCommand(DeleteCommand, connection);
InitializeParameters(command, DeleteParameters, oldValues);
AddParameters(command, DeleteParameters, keys, null, oldValuesParameterFormatString);
if (ConflictDetection == ConflictOptions.CompareAllValues) {
if (oldValues == null || oldValues.Count == 0) {
throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_Pessimistic, SR.GetString(SR.DataSourceView_delete), _owner.ID, "values"));
}
AddParameters(command, DeleteParameters, oldValues, null, oldValuesParameterFormatString);
}
command.CommandType = GetCommandType(DeleteCommandType);
// Raise event to allow customization and cancellation
SqlDataSourceCommandEventArgs eventArgs = new SqlDataSourceCommandEventArgs(command);
OnDeleting(eventArgs);
// If the operation was cancelled, exit immediately
if (eventArgs.Cancel) {
return 0;
}
// Replace null values in parameters with DBNull.Value
ReplaceNullValues(command);
return ExecuteDbCommand(command, DataSourceOperation.Delete);
}
/// <devdoc>
/// Inserts a new row with data from a name/value collection.
/// </devdoc>
protected override int ExecuteInsert(IDictionary values) {
if (!CanInsert) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_InsertNotSupported, _owner.ID));
}
DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);
if (connection == null) {
throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
}
// Create command and add parameters
DbCommand command = _owner.CreateCommand(InsertCommand, connection);
InitializeParameters(command, InsertParameters, null);
AddParameters(command, InsertParameters, values, null, null);
command.CommandType = GetCommandType(InsertCommandType);
// Raise event to allow customization and cancellation
SqlDataSourceCommandEventArgs eventArgs = new SqlDataSourceCommandEventArgs(command);
OnInserting(eventArgs);
// If the operation was cancelled, exit immediately
if (eventArgs.Cancel) {
return 0;
}
// Replace null values in parameters with DBNull.Value
ReplaceNullValues(command);
return ExecuteDbCommand(command, DataSourceOperation.Insert);
}
/// <devdoc>
/// Returns all the rows of the datasource.
/// Parameters are taken from the SqlDataSource.Parameters property collection.
/// If DataSourceMode is set to DataSet then a DataView is returned.
/// If DataSourceMode is set to DataReader then a DataReader is returned, and it must be closed when done.
/// </devdoc>
protected internal override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) {
if (SelectCommand.Length == 0) {
return null;
}
DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);
if (connection == null) {
throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
}
DataSourceCache cache = _owner.Cache;
bool cacheEnabled = (cache != null) && (cache.Enabled);
//int startRowIndex = arguments.StartRowIndex;
//int maximumRows = arguments.MaximumRows;
string sortExpression = arguments.SortExpression;
if (CanPage) {
arguments.AddSupportedCapabilities(DataSourceCapabilities.Page);
}
if (CanSort) {
arguments.AddSupportedCapabilities(DataSourceCapabilities.Sort);
}
if (CanRetrieveTotalRowCount) {
arguments.AddSupportedCapabilities(DataSourceCapabilities.RetrieveTotalRowCount);
}
// If caching is enabled, load DataSet from cache
if (cacheEnabled) {
if (_owner.DataSourceMode != SqlDataSourceMode.DataSet) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_CacheNotSupported, _owner.ID));
}
arguments.RaiseUnsupportedCapabilitiesError(this);
DataSet dataSet = _owner.LoadDataFromCache(0, -1) as DataSet;
if (dataSet != null) {
/*if (arguments.RetrieveTotalRowCount) {
int cachedTotalRowCount = _owner.LoadTotalRowCountFromCache();
if (cachedTotalRowCount >= 0) {
arguments.TotalRowCount = cachedTotalRowCount;
}
else {
// query for row count and then save it in cache
cachedTotalRowCount = QueryTotalRowCount(connection, arguments);
arguments.TotalRowCount = cachedTotalRowCount;
_owner.SaveTotalRowCountToCache(cachedTotalRowCount);
}
}*/
IOrderedDictionary parameterValues = FilterParameters.GetValues(_context, _owner);
if (FilterExpression.Length > 0) {
SqlDataSourceFilteringEventArgs filterArgs = new SqlDataSourceFilteringEventArgs(parameterValues);
OnFiltering(filterArgs);
if (filterArgs.Cancel) {
return null;
}
}
return FilteredDataSetHelper.CreateFilteredDataView(dataSet.Tables[0], sortExpression, FilterExpression, parameterValues);
}
}
// Create command and add parameters
DbCommand command = _owner.CreateCommand(SelectCommand, connection);
InitializeParameters(command, SelectParameters, null);
command.CommandType = GetCommandType(SelectCommandType);
// Raise event to allow customization and cancellation
SqlDataSourceSelectingEventArgs selectingEventArgs = new SqlDataSourceSelectingEventArgs(command, arguments);
OnSelecting(selectingEventArgs);
// If the operation was cancelled, exit immediately
if (selectingEventArgs.Cancel) {
return null;
}
// Add the sort parameter to allow for custom stored procedure sorting, if necessary
string sortParameterName = SortParameterName;
if (sortParameterName.Length > 0) {
if (command.CommandType != CommandType.StoredProcedure) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_SortParameterRequiresStoredProcedure, _owner.ID));
}
command.Parameters.Add(_owner.CreateParameter(ParameterPrefix + sortParameterName, sortExpression));
// We reset the sort expression here so that we pretend as
// though we're not really sorting (since the developer is
// worrying about it instead of us).
arguments.SortExpression = String.Empty;
}
arguments.RaiseUnsupportedCapabilitiesError(this);
// reset these values, since they might have changed in the OnSelecting event
sortExpression = arguments.SortExpression;
//startRowIndex = arguments.StartRowIndex;
//maximumRows = arguments.MaximumRows;
// Perform null check if user wants to cancel on any null parameter value
if (CancelSelectOnNullParameter) {
int paramCount = command.Parameters.Count;
for (int i = 0; i < paramCount; i++) {
DbParameter parameter = command.Parameters[i];
if ((parameter != null) &&
(parameter.Value == null) &&
((parameter.Direction == ParameterDirection.Input) || (parameter.Direction == ParameterDirection.InputOutput))) {
return null;
}
}
}
// Replace null values in parameters with DBNull.Value
ReplaceNullValues(command);
/*if (arguments.RetrieveTotalRowCount && SelectCountCommand.Length > 0) {
int cachedTotalRowCount = -1;
if (cacheEnabled) {
cachedTotalRowCount = _owner.LoadTotalRowCountFromCache();
if (cachedTotalRowCount >= 0) {
arguments.TotalRowCount = cachedTotalRowCount;
}
}
if (cachedTotalRowCount < 0) {
cachedTotalRowCount = QueryTotalRowCount(connection, arguments);
arguments.TotalRowCount = cachedTotalRowCount;
if (cacheEnabled) {
_owner.SaveTotalRowCountToCache(cachedTotalRowCount);
}
}
}*/
IEnumerable selectResult = null;
switch (_owner.DataSourceMode) {
case SqlDataSourceMode.DataSet:
{
SqlCacheDependency cacheDependency = null;
if (cacheEnabled && cache is SqlDataSourceCache) {
SqlDataSourceCache sqlCache = (SqlDataSourceCache)cache;
if (String.Equals(sqlCache.SqlCacheDependency, SqlDataSourceCache.Sql9CacheDependencyDirective, StringComparison.OrdinalIgnoreCase)) {
if (!(command is System.Data.SqlClient.SqlCommand)) {
throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CommandNotificationNotSupported, _owner.ID));
}
cacheDependency = new SqlCacheDependency((System.Data.SqlClient.SqlCommand)command);
}
}
DbDataAdapter adapter = _owner.CreateDataAdapter(command);
DataSet dataSet = new DataSet();
int rowsAffected = 0;
bool eventRaised = false;
try {
rowsAffected = adapter.Fill(dataSet, Name);
// Raise the Selected event
eventRaised = true;
SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, null);
OnSelected(selectedEventArgs);
}
catch (Exception ex) {
if (!eventRaised) {
// Raise the Selected event
SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, ex);
OnSelected(selectedEventArgs);
if (!selectedEventArgs.ExceptionHandled) {
throw;
}
}
else {
bool isCustomException;
ex = BuildCustomException(ex, DataSourceOperation.Select, command, out isCustomException);
if (isCustomException) {
throw ex;
}
else {
throw;
}
}
}
finally {
if (connection.State == ConnectionState.Open) {
connection.Close();
}
}
// If caching is enabled, save DataSet to cache
DataTable dataTable = (dataSet.Tables.Count > 0 ? dataSet.Tables[0] : null);
if (cacheEnabled && dataTable != null) {
_owner.SaveDataToCache(0, -1, dataSet, cacheDependency);
}
if (dataTable != null) {
IOrderedDictionary parameterValues = FilterParameters.GetValues(_context, _owner);
if (FilterExpression.Length > 0) {
SqlDataSourceFilteringEventArgs filterArgs = new SqlDataSourceFilteringEventArgs(parameterValues);
OnFiltering(filterArgs);
if (filterArgs.Cancel) {
return null;
}
}
selectResult = FilteredDataSetHelper.CreateFilteredDataView(dataTable, sortExpression, FilterExpression, parameterValues);
}
break;
}
case SqlDataSourceMode.DataReader:
{
if (FilterExpression.Length > 0) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_FilterNotSupported, _owner.ID));
}
if (sortExpression.Length > 0) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_SortNotSupported, _owner.ID));
}
bool eventRaised = false;
try {
if (connection.State != ConnectionState.Open) {
connection.Open();
}
selectResult = command.ExecuteReader(CommandBehavior.CloseConnection);
// Raise the Selected event
eventRaised = true;
SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, 0, null);
OnSelected(selectedEventArgs);
}
catch (Exception ex) {
if (!eventRaised) {
// Raise the Selected event
SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, 0, ex);
OnSelected(selectedEventArgs);
if (!selectedEventArgs.ExceptionHandled) {
throw;
}
}
else {
bool isCustomException;
ex = BuildCustomException(ex, DataSourceOperation.Select, command, out isCustomException);
if (isCustomException) {
throw ex;
}
else {
throw;
}
}
}
break;
}
}
return selectResult;
}
/// <devdoc>
/// Updates rows matching the parameter collection and setting new values from the name/value values collection.
/// </devdoc>
protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) {
if (!CanUpdate) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_UpdateNotSupported, _owner.ID));
}
DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);
if (connection == null) {
throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
}
// Create command and add parameters
string oldValuesParameterFormatString = OldValuesParameterFormatString;
DbCommand command = _owner.CreateCommand(UpdateCommand, connection);
InitializeParameters(command, UpdateParameters, keys);
AddParameters(command, UpdateParameters, values, null, null);
AddParameters(command, UpdateParameters, keys, null, oldValuesParameterFormatString);
if (ConflictDetection == ConflictOptions.CompareAllValues) {
if (oldValues == null || oldValues.Count == 0) {
throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_Pessimistic, SR.GetString(SR.DataSourceView_update), _owner.ID, "oldValues"));
}
AddParameters(command, UpdateParameters, oldValues, null, oldValuesParameterFormatString);
}
command.CommandType = GetCommandType(UpdateCommandType);
// Raise event to allow customization and cancellation
SqlDataSourceCommandEventArgs eventArgs = new SqlDataSourceCommandEventArgs(command);
OnUpdating(eventArgs);
// If the operation was cancelled, exit immediately
if (eventArgs.Cancel) {
return 0;
}
// Replace null values in parameters with DBNull.Value
ReplaceNullValues(command);
return ExecuteDbCommand(command, DataSourceOperation.Update);
}
/// <devdoc>
/// Converts a SqlDataSourceCommandType to a System.Data.CommandType.
/// </devdoc>
private static CommandType GetCommandType(SqlDataSourceCommandType commandType) {
if (commandType == SqlDataSourceCommandType.Text) {
return CommandType.Text;
}
return CommandType.StoredProcedure;
}
/// <devdoc>
/// Initializes a DbCommand with parameters from a ParameterCollection.
/// The exclusion list contains parameter names that should not be added
/// to the command's parameter collection.
/// </devdoc>
private void InitializeParameters(DbCommand command, ParameterCollection parameters, IDictionary exclusionList) {
Debug.Assert(command != null);
Debug.Assert(parameters != null);
string parameterPrefix = ParameterPrefix;
IDictionary caseInsensitiveExclusionList = null;
if (exclusionList != null) {
caseInsensitiveExclusionList = new ListDictionary(StringComparer.OrdinalIgnoreCase);
foreach (DictionaryEntry de in exclusionList) {
caseInsensitiveExclusionList.Add(de.Key, de.Value);
}
}
IOrderedDictionary values = parameters.GetValues(_context, _owner);
for (int i = 0; i < parameters.Count; i++) {
Parameter parameter = parameters[i];
if ((caseInsensitiveExclusionList == null) || (!caseInsensitiveExclusionList.Contains(parameter.Name))) {
DbParameter dbParameter = _owner.CreateParameter(parameterPrefix + parameter.Name, values[i]);
dbParameter.Direction = parameter.Direction;
dbParameter.Size = parameter.Size;
if (parameter.DbType != DbType.Object || (parameter.Type != TypeCode.Empty && parameter.Type != TypeCode.DBNull)) {
SqlParameter sqlParameter = dbParameter as SqlParameter;
if (sqlParameter == null) {
dbParameter.DbType = parameter.GetDatabaseType();
}
else {
// In Whidbey, the DbType Date and Time members mapped to SqlDbType.DateTime since there
// were no SqlDbType equivalents. SqlDbType has since been modified to include the new
// Katmai types, including Date and Time. For backwards compatability SqlParameter's DbType
// setter doesn't support Date and Time, so the SqlDbType property should be used instead.
// Other new SqlServer 2008 types (DateTime2, DateTimeOffset) can be set using DbType.
DbType dbType = parameter.GetDatabaseType();
switch (dbType) {
case DbType.Time:
sqlParameter.SqlDbType = SqlDbType.Time;
break;
case DbType.Date:
sqlParameter.SqlDbType = SqlDbType.Date;
break;
default:
dbParameter.DbType = parameter.GetDatabaseType();
break;
}
}
}
command.Parameters.Add(dbParameter);
}
}
}
public int Insert(IDictionary values) {
return ExecuteInsert(values);
}
/// <devdoc>
/// Loads view state.
/// </devdoc>
protected virtual void LoadViewState(object savedState) {
if (savedState == null)
return;
Pair myState = (Pair)savedState;
if (myState.First != null)
((IStateManager)SelectParameters).LoadViewState(myState.First);
if (myState.Second != null)
((IStateManager)FilterParameters).LoadViewState(myState.Second);
}
/// <devdoc>
/// Raises the Deleted event.
/// </devdoc>
protected virtual void OnDeleted(SqlDataSourceStatusEventArgs e) {
SqlDataSourceStatusEventHandler handler = Events[EventDeleted] as SqlDataSourceStatusEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the Deleting event.
/// </devdoc>
protected virtual void OnDeleting(SqlDataSourceCommandEventArgs e) {
SqlDataSourceCommandEventHandler handler = Events[EventDeleting] as SqlDataSourceCommandEventHandler;
if (handler != null) {
handler(this, e);
}
}
protected virtual void OnFiltering(SqlDataSourceFilteringEventArgs e) {
SqlDataSourceFilteringEventHandler handler = Events[EventFiltering] as SqlDataSourceFilteringEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the Inserted event.
/// </devdoc>
protected virtual void OnInserted(SqlDataSourceStatusEventArgs e) {
SqlDataSourceStatusEventHandler handler = Events[EventInserted] as SqlDataSourceStatusEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the Inserting event.
/// </devdoc>
protected virtual void OnInserting(SqlDataSourceCommandEventArgs e) {
SqlDataSourceCommandEventHandler handler = Events[EventInserting] as SqlDataSourceCommandEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the Selected event.
/// </devdoc>
protected virtual void OnSelected(SqlDataSourceStatusEventArgs e) {
SqlDataSourceStatusEventHandler handler = Events[EventSelected] as SqlDataSourceStatusEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the Selecting event.
/// </devdoc>
protected virtual void OnSelecting(SqlDataSourceSelectingEventArgs e) {
SqlDataSourceSelectingEventHandler handler = Events[EventSelecting] as SqlDataSourceSelectingEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the Updated event.
/// </devdoc>
protected virtual void OnUpdated(SqlDataSourceStatusEventArgs e) {
SqlDataSourceStatusEventHandler handler = Events[EventUpdated] as SqlDataSourceStatusEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the Updating event.
/// </devdoc>
protected virtual void OnUpdating(SqlDataSourceCommandEventArgs e) {
SqlDataSourceCommandEventHandler handler = Events[EventUpdating] as SqlDataSourceCommandEventHandler;
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Executes the SelectCountCommand to retrieve the total row count.
/// </devdoc>
/*protected virtual int QueryTotalRowCount(DbConnection connection, DataSourceSelectArguments arguments) {
int totalRowCount = 0;
bool eventRaised = false;
if (SelectCountCommand.Length > 0) {
// Create command and add parameters
DbCommand command = _owner.CreateCommand(SelectCountCommand, connection);
InitializeParameters(command, SelectParameters);
command.CommandType = GetCommandType(SelectCountCommand, SelectCompareString);
// Raise event to allow customization and cancellation
SqlDataSourceSelectingEventArgs selectCountingEventArgs = new SqlDataSourceSelectingEventArgs(command, arguments, true);
OnSelecting(selectCountingEventArgs);
// If the operation was cancelled, exit immediately
if (selectCountingEventArgs.Cancel) {
return totalRowCount;
}
// the arguments may have been changed
arguments.RaiseUnsupportedCapabilitiesError(this);
//
*/
protected internal override void RaiseUnsupportedCapabilityError(DataSourceCapabilities capability) {
if (!CanPage && ((capability & DataSourceCapabilities.Page) != 0)) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_NoPaging, _owner.ID));
}
if (!CanSort && ((capability & DataSourceCapabilities.Sort) != 0)) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_NoSorting, _owner.ID));
}
if (!CanRetrieveTotalRowCount && ((capability & DataSourceCapabilities.RetrieveTotalRowCount) != 0)) {
throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_NoRowCount, _owner.ID));
}
base.RaiseUnsupportedCapabilityError(capability);
}
/// <devdoc>
/// Replace null values in parameters with DBNull.Value.
/// </devdoc>
private void ReplaceNullValues(DbCommand command) {
int paramCount = command.Parameters.Count;
foreach (DbParameter parameter in command.Parameters) {
if (parameter.Value == null) {
parameter.Value = DBNull.Value;
}
}
}
/// <devdoc>
/// Saves view state.
/// </devdoc>
protected virtual object SaveViewState() {
Pair myState = new Pair();
myState.First = (_selectParameters != null) ? ((IStateManager)_selectParameters).SaveViewState() : null;
myState.Second = (_filterParameters != null) ? ((IStateManager)_filterParameters).SaveViewState() : null;
if ((myState.First == null) &&
(myState.Second == null)) {
return null;
}
return myState;
}
public IEnumerable Select(DataSourceSelectArguments arguments) {
return ExecuteSelect(arguments);
}
/// <devdoc>
/// Event handler for SelectParametersChanged event.
/// </devdoc>
private void SelectParametersChangedEventHandler(object o, EventArgs e) {
OnDataSourceViewChanged(EventArgs.Empty);
}
/// <devdoc>
/// Starts tracking view state.
/// </devdoc>
protected virtual void TrackViewState() {
_tracking = true;
if (_selectParameters != null) {
((IStateManager)_selectParameters).TrackViewState();
}
if (_filterParameters != null) {
((IStateManager)_filterParameters).TrackViewState();
}
}
public int Update(IDictionary keys, IDictionary values, IDictionary oldValues) {
return ExecuteUpdate(keys, values, oldValues);
}
#region IStateManager implementation
bool IStateManager.IsTrackingViewState {
get {
return IsTrackingViewState;
}
}
void IStateManager.LoadViewState(object savedState) {
LoadViewState(savedState);
}
object IStateManager.SaveViewState() {
return SaveViewState();
}
void IStateManager.TrackViewState() {
TrackViewState();
}
#endregion
}
}
| |
// Copyright (c) 2009 DotNetAnywhere
//
// 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;
namespace System.Drawing {
public static class Pens {
private static Pen aliceblue;
private static Pen antiquewhite;
private static Pen aqua;
private static Pen aquamarine;
private static Pen azure;
private static Pen beige;
private static Pen bisque;
private static Pen black;
private static Pen blanchedalmond;
private static Pen blue;
private static Pen blueviolet;
private static Pen brown;
private static Pen burlywood;
private static Pen cadetblue;
private static Pen chartreuse;
private static Pen chocolate;
private static Pen coral;
private static Pen cornflowerblue;
private static Pen cornsilk;
private static Pen crimson;
private static Pen cyan;
private static Pen darkblue;
private static Pen darkcyan;
private static Pen darkgoldenrod;
private static Pen darkgray;
private static Pen darkgreen;
private static Pen darkkhaki;
private static Pen darkmagenta;
private static Pen darkolivegreen;
private static Pen darkorange;
private static Pen darkorchid;
private static Pen darkred;
private static Pen darksalmon;
private static Pen darkseagreen;
private static Pen darkslateblue;
private static Pen darkslategray;
private static Pen darkturquoise;
private static Pen darkviolet;
private static Pen deeppink;
private static Pen deepskyblue;
private static Pen dimgray;
private static Pen dodgerblue;
private static Pen firebrick;
private static Pen floralwhite;
private static Pen forestgreen;
private static Pen fuchsia;
private static Pen gainsboro;
private static Pen ghostwhite;
private static Pen gold;
private static Pen goldenrod;
private static Pen gray;
private static Pen green;
private static Pen greenyellow;
private static Pen honeydew;
private static Pen hotpink;
private static Pen indianred;
private static Pen indigo;
private static Pen ivory;
private static Pen khaki;
private static Pen lavender;
private static Pen lavenderblush;
private static Pen lawngreen;
private static Pen lemonchiffon;
private static Pen lightblue;
private static Pen lightcoral;
private static Pen lightcyan;
private static Pen lightgoldenrodyellow;
private static Pen lightgray;
private static Pen lightgreen;
private static Pen lightpink;
private static Pen lightsalmon;
private static Pen lightseagreen;
private static Pen lightskyblue;
private static Pen lightslategray;
private static Pen lightsteelblue;
private static Pen lightyellow;
private static Pen lime;
private static Pen limegreen;
private static Pen linen;
private static Pen magenta;
private static Pen maroon;
private static Pen mediumaquamarine;
private static Pen mediumblue;
private static Pen mediumorchid;
private static Pen mediumpurple;
private static Pen mediumseagreen;
private static Pen mediumslateblue;
private static Pen mediumspringgreen;
private static Pen mediumturquoise;
private static Pen mediumvioletred;
private static Pen midnightblue;
private static Pen mintcream;
private static Pen mistyrose;
private static Pen moccasin;
private static Pen navajowhite;
private static Pen navy;
private static Pen oldlace;
private static Pen olive;
private static Pen olivedrab;
private static Pen orange;
private static Pen orangered;
private static Pen orchid;
private static Pen palegoldenrod;
private static Pen palegreen;
private static Pen paleturquoise;
private static Pen palevioletred;
private static Pen papayawhip;
private static Pen peachpuff;
private static Pen peru;
private static Pen pink;
private static Pen plum;
private static Pen powderblue;
private static Pen purple;
private static Pen red;
private static Pen rosybrown;
private static Pen royalblue;
private static Pen saddlebrown;
private static Pen salmon;
private static Pen sandybrown;
private static Pen seagreen;
private static Pen seashell;
private static Pen sienna;
private static Pen silver;
private static Pen skyblue;
private static Pen slateblue;
private static Pen slategray;
private static Pen snow;
private static Pen springgreen;
private static Pen steelblue;
private static Pen tan;
private static Pen teal;
private static Pen thistle;
private static Pen tomato;
private static Pen transparent;
private static Pen turquoise;
private static Pen violet;
private static Pen wheat;
private static Pen white;
private static Pen whitesmoke;
private static Pen yellow;
private static Pen yellowgreen;
public static Pen AliceBlue {
get {
if (aliceblue == null) {
aliceblue = new Pen(Color.AliceBlue);
aliceblue.canChange = false;
}
return aliceblue;
}
}
public static Pen AntiqueWhite {
get {
if (antiquewhite == null) {
antiquewhite = new Pen(Color.AntiqueWhite);
antiquewhite.canChange = false;
}
return antiquewhite;
}
}
public static Pen Aqua {
get {
if (aqua == null) {
aqua = new Pen(Color.Aqua);
aqua.canChange = false;
}
return aqua;
}
}
public static Pen Aquamarine {
get {
if (aquamarine == null) {
aquamarine = new Pen(Color.Aquamarine);
aquamarine.canChange = false;
}
return aquamarine;
}
}
public static Pen Azure {
get {
if (azure == null) {
azure = new Pen(Color.Azure);
azure.canChange = false;
}
return azure;
}
}
public static Pen Beige {
get {
if (beige == null) {
beige = new Pen(Color.Beige);
beige.canChange = false;
}
return beige;
}
}
public static Pen Bisque {
get {
if (bisque == null) {
bisque = new Pen(Color.Bisque);
bisque.canChange = false;
}
return bisque;
}
}
public static Pen Black {
get {
if (black == null) {
black = new Pen(Color.Black);
black.canChange = false;
}
return black;
}
}
public static Pen BlanchedAlmond {
get {
if (blanchedalmond == null) {
blanchedalmond = new Pen(Color.BlanchedAlmond);
blanchedalmond.canChange = false;
}
return blanchedalmond;
}
}
public static Pen Blue {
get {
if (blue == null) {
blue = new Pen(Color.Blue);
blue.canChange = false;
}
return blue;
}
}
public static Pen BlueViolet {
get {
if (blueviolet == null) {
blueviolet = new Pen(Color.BlueViolet);
blueviolet.canChange = false;
}
return blueviolet;
}
}
public static Pen Brown {
get {
if (brown == null) {
brown = new Pen(Color.Brown);
brown.canChange = false;
}
return brown;
}
}
public static Pen BurlyWood {
get {
if (burlywood == null) {
burlywood = new Pen(Color.BurlyWood);
burlywood.canChange = false;
}
return burlywood;
}
}
public static Pen CadetBlue {
get {
if (cadetblue == null) {
cadetblue = new Pen(Color.CadetBlue);
cadetblue.canChange = false;
}
return cadetblue;
}
}
public static Pen Chartreuse {
get {
if (chartreuse == null) {
chartreuse = new Pen(Color.Chartreuse);
chartreuse.canChange = false;
}
return chartreuse;
}
}
public static Pen Chocolate {
get {
if (chocolate == null) {
chocolate = new Pen(Color.Chocolate);
chocolate.canChange = false;
}
return chocolate;
}
}
public static Pen Coral {
get {
if (coral == null) {
coral = new Pen(Color.Coral);
coral.canChange = false;
}
return coral;
}
}
public static Pen CornflowerBlue {
get {
if (cornflowerblue == null) {
cornflowerblue = new Pen(Color.CornflowerBlue);
cornflowerblue.canChange = false;
}
return cornflowerblue;
}
}
public static Pen Cornsilk {
get {
if (cornsilk == null) {
cornsilk = new Pen(Color.Cornsilk);
cornsilk.canChange = false;
}
return cornsilk;
}
}
public static Pen Crimson {
get {
if (crimson == null) {
crimson = new Pen(Color.Crimson);
crimson.canChange = false;
}
return crimson;
}
}
public static Pen Cyan {
get {
if (cyan == null) {
cyan = new Pen(Color.Cyan);
cyan.canChange = false;
}
return cyan;
}
}
public static Pen DarkBlue {
get {
if (darkblue == null) {
darkblue = new Pen(Color.DarkBlue);
darkblue.canChange = false;
}
return darkblue;
}
}
public static Pen DarkCyan {
get {
if (darkcyan == null) {
darkcyan = new Pen(Color.DarkCyan);
darkcyan.canChange = false;
}
return darkcyan;
}
}
public static Pen DarkGoldenrod {
get {
if (darkgoldenrod == null) {
darkgoldenrod = new Pen(Color.DarkGoldenrod);
darkgoldenrod.canChange = false;
}
return darkgoldenrod;
}
}
public static Pen DarkGray {
get {
if (darkgray == null) {
darkgray = new Pen(Color.DarkGray);
darkgray.canChange = false;
}
return darkgray;
}
}
public static Pen DarkGreen {
get {
if (darkgreen == null) {
darkgreen = new Pen(Color.DarkGreen);
darkgreen.canChange = false;
}
return darkgreen;
}
}
public static Pen DarkKhaki {
get {
if (darkkhaki == null) {
darkkhaki = new Pen(Color.DarkKhaki);
darkkhaki.canChange = false;
}
return darkkhaki;
}
}
public static Pen DarkMagenta {
get {
if (darkmagenta == null) {
darkmagenta = new Pen(Color.DarkMagenta);
darkmagenta.canChange = false;
}
return darkmagenta;
}
}
public static Pen DarkOliveGreen {
get {
if (darkolivegreen == null) {
darkolivegreen = new Pen(Color.DarkOliveGreen);
darkolivegreen.canChange = false;
}
return darkolivegreen;
}
}
public static Pen DarkOrange {
get {
if (darkorange == null) {
darkorange = new Pen(Color.DarkOrange);
darkorange.canChange = false;
}
return darkorange;
}
}
public static Pen DarkOrchid {
get {
if (darkorchid == null) {
darkorchid = new Pen(Color.DarkOrchid);
darkorchid.canChange = false;
}
return darkorchid;
}
}
public static Pen DarkRed {
get {
if (darkred == null) {
darkred = new Pen(Color.DarkRed);
darkred.canChange = false;
}
return darkred;
}
}
public static Pen DarkSalmon {
get {
if (darksalmon == null) {
darksalmon = new Pen(Color.DarkSalmon);
darksalmon.canChange = false;
}
return darksalmon;
}
}
public static Pen DarkSeaGreen {
get {
if (darkseagreen == null) {
darkseagreen = new Pen(Color.DarkSeaGreen);
darkseagreen.canChange = false;
}
return darkseagreen;
}
}
public static Pen DarkSlateBlue {
get {
if (darkslateblue == null) {
darkslateblue = new Pen(Color.DarkSlateBlue);
darkslateblue.canChange = false;
}
return darkslateblue;
}
}
public static Pen DarkSlateGray {
get {
if (darkslategray == null) {
darkslategray = new Pen(Color.DarkSlateGray);
darkslategray.canChange = false;
}
return darkslategray;
}
}
public static Pen DarkTurquoise {
get {
if (darkturquoise == null) {
darkturquoise = new Pen(Color.DarkTurquoise);
darkturquoise.canChange = false;
}
return darkturquoise;
}
}
public static Pen DarkViolet {
get {
if (darkviolet == null) {
darkviolet = new Pen(Color.DarkViolet);
darkviolet.canChange = false;
}
return darkviolet;
}
}
public static Pen DeepPink {
get {
if (deeppink == null) {
deeppink = new Pen(Color.DeepPink);
deeppink.canChange = false;
}
return deeppink;
}
}
public static Pen DeepSkyBlue {
get {
if (deepskyblue == null) {
deepskyblue = new Pen(Color.DeepSkyBlue);
deepskyblue.canChange = false;
}
return deepskyblue;
}
}
public static Pen DimGray {
get {
if (dimgray == null) {
dimgray = new Pen(Color.DimGray);
dimgray.canChange = false;
}
return dimgray;
}
}
public static Pen DodgerBlue {
get {
if (dodgerblue == null) {
dodgerblue = new Pen(Color.DodgerBlue);
dodgerblue.canChange = false;
}
return dodgerblue;
}
}
public static Pen Firebrick {
get {
if (firebrick == null) {
firebrick = new Pen(Color.Firebrick);
firebrick.canChange = false;
}
return firebrick;
}
}
public static Pen FloralWhite {
get {
if (floralwhite == null) {
floralwhite = new Pen(Color.FloralWhite);
floralwhite.canChange = false;
}
return floralwhite;
}
}
public static Pen ForestGreen {
get {
if (forestgreen == null) {
forestgreen = new Pen(Color.ForestGreen);
forestgreen.canChange = false;
}
return forestgreen;
}
}
public static Pen Fuchsia {
get {
if (fuchsia == null) {
fuchsia = new Pen(Color.Fuchsia);
fuchsia.canChange = false;
}
return fuchsia;
}
}
public static Pen Gainsboro {
get {
if (gainsboro == null) {
gainsboro = new Pen(Color.Gainsboro);
gainsboro.canChange = false;
}
return gainsboro;
}
}
public static Pen GhostWhite {
get {
if (ghostwhite == null) {
ghostwhite = new Pen(Color.GhostWhite);
ghostwhite.canChange = false;
}
return ghostwhite;
}
}
public static Pen Gold {
get {
if (gold == null) {
gold = new Pen(Color.Gold);
gold.canChange = false;
}
return gold;
}
}
public static Pen Goldenrod {
get {
if (goldenrod == null) {
goldenrod = new Pen(Color.Goldenrod);
goldenrod.canChange = false;
}
return goldenrod;
}
}
public static Pen Gray {
get {
if (gray == null) {
gray = new Pen(Color.Gray);
gray.canChange = false;
}
return gray;
}
}
public static Pen Green {
get {
if (green == null) {
green = new Pen(Color.Green);
green.canChange = false;
}
return green;
}
}
public static Pen GreenYellow {
get {
if (greenyellow == null) {
greenyellow = new Pen(Color.GreenYellow);
greenyellow.canChange = false;
}
return greenyellow;
}
}
public static Pen Honeydew {
get {
if (honeydew == null) {
honeydew = new Pen(Color.Honeydew);
honeydew.canChange = false;
}
return honeydew;
}
}
public static Pen HotPink {
get {
if (hotpink == null) {
hotpink = new Pen(Color.HotPink);
hotpink.canChange = false;
}
return hotpink;
}
}
public static Pen IndianRed {
get {
if (indianred == null) {
indianred = new Pen(Color.IndianRed);
indianred.canChange = false;
}
return indianred;
}
}
public static Pen Indigo {
get {
if (indigo == null) {
indigo = new Pen(Color.Indigo);
indigo.canChange = false;
}
return indigo;
}
}
public static Pen Ivory {
get {
if (ivory == null) {
ivory = new Pen(Color.Ivory);
ivory.canChange = false;
}
return ivory;
}
}
public static Pen Khaki {
get {
if (khaki == null) {
khaki = new Pen(Color.Khaki);
khaki.canChange = false;
}
return khaki;
}
}
public static Pen Lavender {
get {
if (lavender == null) {
lavender = new Pen(Color.Lavender);
lavender.canChange = false;
}
return lavender;
}
}
public static Pen LavenderBlush {
get {
if (lavenderblush == null) {
lavenderblush = new Pen(Color.LavenderBlush);
lavenderblush.canChange = false;
}
return lavenderblush;
}
}
public static Pen LawnGreen {
get {
if (lawngreen == null) {
lawngreen = new Pen(Color.LawnGreen);
lawngreen.canChange = false;
}
return lawngreen;
}
}
public static Pen LemonChiffon {
get {
if (lemonchiffon == null) {
lemonchiffon = new Pen(Color.LemonChiffon);
lemonchiffon.canChange = false;
}
return lemonchiffon;
}
}
public static Pen LightBlue {
get {
if (lightblue == null) {
lightblue = new Pen(Color.LightBlue);
lightblue.canChange = false;
}
return lightblue;
}
}
public static Pen LightCoral {
get {
if (lightcoral == null) {
lightcoral = new Pen(Color.LightCoral);
lightcoral.canChange = false;
}
return lightcoral;
}
}
public static Pen LightCyan {
get {
if (lightcyan == null) {
lightcyan = new Pen(Color.LightCyan);
lightcyan.canChange = false;
}
return lightcyan;
}
}
public static Pen LightGoldenrodYellow {
get {
if (lightgoldenrodyellow == null) {
lightgoldenrodyellow = new Pen(Color.LightGoldenrodYellow);
lightgoldenrodyellow.canChange = false;
}
return lightgoldenrodyellow;
}
}
public static Pen LightGray {
get {
if (lightgray == null) {
lightgray = new Pen(Color.LightGray);
lightgray.canChange = false;
}
return lightgray;
}
}
public static Pen LightGreen {
get {
if (lightgreen == null) {
lightgreen = new Pen(Color.LightGreen);
lightgreen.canChange = false;
}
return lightgreen;
}
}
public static Pen LightPink {
get {
if (lightpink == null) {
lightpink = new Pen(Color.LightPink);
lightpink.canChange = false;
}
return lightpink;
}
}
public static Pen LightSalmon {
get {
if (lightsalmon == null) {
lightsalmon = new Pen(Color.LightSalmon);
lightsalmon.canChange = false;
}
return lightsalmon;
}
}
public static Pen LightSeaGreen {
get {
if (lightseagreen == null) {
lightseagreen = new Pen(Color.LightSeaGreen);
lightseagreen.canChange = false;
}
return lightseagreen;
}
}
public static Pen LightSkyBlue {
get {
if (lightskyblue == null) {
lightskyblue = new Pen(Color.LightSkyBlue);
lightskyblue.canChange = false;
}
return lightskyblue;
}
}
public static Pen LightSlateGray {
get {
if (lightslategray == null) {
lightslategray = new Pen(Color.LightSlateGray);
lightslategray.canChange = false;
}
return lightslategray;
}
}
public static Pen LightSteelBlue {
get {
if (lightsteelblue == null) {
lightsteelblue = new Pen(Color.LightSteelBlue);
lightsteelblue.canChange = false;
}
return lightsteelblue;
}
}
public static Pen LightYellow {
get {
if (lightyellow == null) {
lightyellow = new Pen(Color.LightYellow);
lightyellow.canChange = false;
}
return lightyellow;
}
}
public static Pen Lime {
get {
if (lime == null) {
lime = new Pen(Color.Lime);
lime.canChange = false;
}
return lime;
}
}
public static Pen LimeGreen {
get {
if (limegreen == null) {
limegreen = new Pen(Color.LimeGreen);
limegreen.canChange = false;
}
return limegreen;
}
}
public static Pen Linen {
get {
if (linen == null) {
linen = new Pen(Color.Linen);
linen.canChange = false;
}
return linen;
}
}
public static Pen Magenta {
get {
if (magenta == null) {
magenta = new Pen(Color.Magenta);
magenta.canChange = false;
}
return magenta;
}
}
public static Pen Maroon {
get {
if (maroon == null) {
maroon = new Pen(Color.Maroon);
maroon.canChange = false;
}
return maroon;
}
}
public static Pen MediumAquamarine {
get {
if (mediumaquamarine == null) {
mediumaquamarine = new Pen(Color.MediumAquamarine);
mediumaquamarine.canChange = false;
}
return mediumaquamarine;
}
}
public static Pen MediumBlue {
get {
if (mediumblue == null) {
mediumblue = new Pen(Color.MediumBlue);
mediumblue.canChange = false;
}
return mediumblue;
}
}
public static Pen MediumOrchid {
get {
if (mediumorchid == null) {
mediumorchid = new Pen(Color.MediumOrchid);
mediumorchid.canChange = false;
}
return mediumorchid;
}
}
public static Pen MediumPurple {
get {
if (mediumpurple == null) {
mediumpurple = new Pen(Color.MediumPurple);
mediumpurple.canChange = false;
}
return mediumpurple;
}
}
public static Pen MediumSeaGreen {
get {
if (mediumseagreen == null) {
mediumseagreen = new Pen(Color.MediumSeaGreen);
mediumseagreen.canChange = false;
}
return mediumseagreen;
}
}
public static Pen MediumSlateBlue {
get {
if (mediumslateblue == null) {
mediumslateblue = new Pen(Color.MediumSlateBlue);
mediumslateblue.canChange = false;
}
return mediumslateblue;
}
}
public static Pen MediumSpringGreen {
get {
if (mediumspringgreen == null) {
mediumspringgreen = new Pen(Color.MediumSpringGreen);
mediumspringgreen.canChange = false;
}
return mediumspringgreen;
}
}
public static Pen MediumTurquoise {
get {
if (mediumturquoise == null) {
mediumturquoise = new Pen(Color.MediumTurquoise);
mediumturquoise.canChange = false;
}
return mediumturquoise;
}
}
public static Pen MediumVioletRed {
get {
if (mediumvioletred == null) {
mediumvioletred = new Pen(Color.MediumVioletRed);
mediumvioletred.canChange = false;
}
return mediumvioletred;
}
}
public static Pen MidnightBlue {
get {
if (midnightblue == null) {
midnightblue = new Pen(Color.MidnightBlue);
midnightblue.canChange = false;
}
return midnightblue;
}
}
public static Pen MintCream {
get {
if (mintcream == null) {
mintcream = new Pen(Color.MintCream);
mintcream.canChange = false;
}
return mintcream;
}
}
public static Pen MistyRose {
get {
if (mistyrose == null) {
mistyrose = new Pen(Color.MistyRose);
mistyrose.canChange = false;
}
return mistyrose;
}
}
public static Pen Moccasin {
get {
if (moccasin == null) {
moccasin = new Pen(Color.Moccasin);
moccasin.canChange = false;
}
return moccasin;
}
}
public static Pen NavajoWhite {
get {
if (navajowhite == null) {
navajowhite = new Pen(Color.NavajoWhite);
navajowhite.canChange = false;
}
return navajowhite;
}
}
public static Pen Navy {
get {
if (navy == null) {
navy = new Pen(Color.Navy);
navy.canChange = false;
}
return navy;
}
}
public static Pen OldLace {
get {
if (oldlace == null) {
oldlace = new Pen(Color.OldLace);
oldlace.canChange = false;
}
return oldlace;
}
}
public static Pen Olive {
get {
if (olive == null) {
olive = new Pen(Color.Olive);
olive.canChange = false;
}
return olive;
}
}
public static Pen OliveDrab {
get {
if (olivedrab == null) {
olivedrab = new Pen(Color.OliveDrab);
olivedrab.canChange = false;
}
return olivedrab;
}
}
public static Pen Orange {
get {
if (orange == null) {
orange = new Pen(Color.Orange);
orange.canChange = false;
}
return orange;
}
}
public static Pen OrangeRed {
get {
if (orangered == null) {
orangered = new Pen(Color.OrangeRed);
orangered.canChange = false;
}
return orangered;
}
}
public static Pen Orchid {
get {
if (orchid == null) {
orchid = new Pen(Color.Orchid);
orchid.canChange = false;
}
return orchid;
}
}
public static Pen PaleGoldenrod {
get {
if (palegoldenrod == null) {
palegoldenrod = new Pen(Color.PaleGoldenrod);
palegoldenrod.canChange = false;
}
return palegoldenrod;
}
}
public static Pen PaleGreen {
get {
if (palegreen == null) {
palegreen = new Pen(Color.PaleGreen);
palegreen.canChange = false;
}
return palegreen;
}
}
public static Pen PaleTurquoise {
get {
if (paleturquoise == null) {
paleturquoise = new Pen(Color.PaleTurquoise);
paleturquoise.canChange = false;
}
return paleturquoise;
}
}
public static Pen PaleVioletRed {
get {
if (palevioletred == null) {
palevioletred = new Pen(Color.PaleVioletRed);
palevioletred.canChange = false;
}
return palevioletred;
}
}
public static Pen PapayaWhip {
get {
if (papayawhip == null) {
papayawhip = new Pen(Color.PapayaWhip);
papayawhip.canChange = false;
}
return papayawhip;
}
}
public static Pen PeachPuff {
get {
if (peachpuff == null) {
peachpuff = new Pen(Color.PeachPuff);
peachpuff.canChange = false;
}
return peachpuff;
}
}
public static Pen Peru {
get {
if (peru == null) {
peru = new Pen(Color.Peru);
peru.canChange = false;
}
return peru;
}
}
public static Pen Pink {
get {
if (pink == null) {
pink = new Pen(Color.Pink);
pink.canChange = false;
}
return pink;
}
}
public static Pen Plum {
get {
if (plum == null) {
plum = new Pen(Color.Plum);
plum.canChange = false;
}
return plum;
}
}
public static Pen PowderBlue {
get {
if (powderblue == null) {
powderblue = new Pen(Color.PowderBlue);
powderblue.canChange = false;
}
return powderblue;
}
}
public static Pen Purple {
get {
if (purple == null) {
purple = new Pen(Color.Purple);
purple.canChange = false;
}
return purple;
}
}
public static Pen Red {
get {
if (red == null) {
red = new Pen(Color.Red);
red.canChange = false;
}
return red;
}
}
public static Pen RosyBrown {
get {
if (rosybrown == null) {
rosybrown = new Pen(Color.RosyBrown);
rosybrown.canChange = false;
}
return rosybrown;
}
}
public static Pen RoyalBlue {
get {
if (royalblue == null) {
royalblue = new Pen(Color.RoyalBlue);
royalblue.canChange = false;
}
return royalblue;
}
}
public static Pen SaddleBrown {
get {
if (saddlebrown == null) {
saddlebrown = new Pen(Color.SaddleBrown);
saddlebrown.canChange = false;
}
return saddlebrown;
}
}
public static Pen Salmon {
get {
if (salmon == null) {
salmon = new Pen(Color.Salmon);
salmon.canChange = false;
}
return salmon;
}
}
public static Pen SandyBrown {
get {
if (sandybrown == null) {
sandybrown = new Pen(Color.SandyBrown);
sandybrown.canChange = false;
}
return sandybrown;
}
}
public static Pen SeaGreen {
get {
if (seagreen == null) {
seagreen = new Pen(Color.SeaGreen);
seagreen.canChange = false;
}
return seagreen;
}
}
public static Pen SeaShell {
get {
if (seashell == null) {
seashell = new Pen(Color.SeaShell);
seashell.canChange = false;
}
return seashell;
}
}
public static Pen Sienna {
get {
if (sienna == null) {
sienna = new Pen(Color.Sienna);
sienna.canChange = false;
}
return sienna;
}
}
public static Pen Silver {
get {
if (silver == null) {
silver = new Pen(Color.Silver);
silver.canChange = false;
}
return silver;
}
}
public static Pen SkyBlue {
get {
if (skyblue == null) {
skyblue = new Pen(Color.SkyBlue);
skyblue.canChange = false;
}
return skyblue;
}
}
public static Pen SlateBlue {
get {
if (slateblue == null) {
slateblue = new Pen(Color.SlateBlue);
slateblue.canChange = false;
}
return slateblue;
}
}
public static Pen SlateGray {
get {
if (slategray == null) {
slategray = new Pen(Color.SlateGray);
slategray.canChange = false;
}
return slategray;
}
}
public static Pen Snow {
get {
if (snow == null) {
snow = new Pen(Color.Snow);
snow.canChange = false;
}
return snow;
}
}
public static Pen SpringGreen {
get {
if (springgreen == null) {
springgreen = new Pen(Color.SpringGreen);
springgreen.canChange = false;
}
return springgreen;
}
}
public static Pen SteelBlue {
get {
if (steelblue == null) {
steelblue = new Pen(Color.SteelBlue);
steelblue.canChange = false;
}
return steelblue;
}
}
public static Pen Tan {
get {
if (tan == null) {
tan = new Pen(Color.Tan);
tan.canChange = false;
}
return tan;
}
}
public static Pen Teal {
get {
if (teal == null) {
teal = new Pen(Color.Teal);
teal.canChange = false;
}
return teal;
}
}
public static Pen Thistle {
get {
if (thistle == null) {
thistle = new Pen(Color.Thistle);
thistle.canChange = false;
}
return thistle;
}
}
public static Pen Tomato {
get {
if (tomato == null) {
tomato = new Pen(Color.Tomato);
tomato.canChange = false;
}
return tomato;
}
}
public static Pen Transparent {
get {
if (transparent == null) {
transparent = new Pen(Color.Transparent);
transparent.canChange = false;
}
return transparent;
}
}
public static Pen Turquoise {
get {
if (turquoise == null) {
turquoise = new Pen(Color.Turquoise);
turquoise.canChange = false;
}
return turquoise;
}
}
public static Pen Violet {
get {
if (violet == null) {
violet = new Pen(Color.Violet);
violet.canChange = false;
}
return violet;
}
}
public static Pen Wheat {
get {
if (wheat == null) {
wheat = new Pen(Color.Wheat);
wheat.canChange = false;
}
return wheat;
}
}
public static Pen White {
get {
if (white == null) {
white = new Pen(Color.White);
white.canChange = false;
}
return white;
}
}
public static Pen WhiteSmoke {
get {
if (whitesmoke == null) {
whitesmoke = new Pen(Color.WhiteSmoke);
whitesmoke.canChange = false;
}
return whitesmoke;
}
}
public static Pen Yellow {
get {
if (yellow == null) {
yellow = new Pen(Color.Yellow);
yellow.canChange = false;
}
return yellow;
}
}
public static Pen YellowGreen {
get {
if (yellowgreen == null) {
yellowgreen = new Pen(Color.YellowGreen);
yellowgreen.canChange = false;
}
return yellowgreen;
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Collections;
//
// Now define the set of commands for manipulating modules.
//
namespace Microsoft.PowerShell.Commands
{
#region Test-ModuleManifest
/// <summary>
/// This cmdlet takes a module manifest and validates the contents...
/// </summary>
[Cmdlet("Test", "ModuleManifest", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=141557")]
[OutputType(typeof(PSModuleInfo))]
public sealed class TestModuleManifestCommand : ModuleCmdletBase
{
/// <summary>
/// The output path for the generated file...
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0, ValueFromPipelineByPropertyName = true)]
public string Path
{
get { return _path; }
set { _path = value; }
}
private string _path;
/// <summary>
/// Implements the record processing for this cmdlet
/// </summary>
protected override void ProcessRecord()
{
ProviderInfo provider = null;
Collection<string> filePaths;
try
{
if (Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem))
{
filePaths =
SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider);
}
else
{
filePaths = new Collection<string>();
filePaths.Add(_path);
}
}
catch (ItemNotFoundException)
{
string message = StringUtil.Format(Modules.ModuleNotFound, _path);
FileNotFoundException fnf = new FileNotFoundException(message);
ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound",
ErrorCategory.ResourceUnavailable, _path);
WriteError(er);
return;
}
// Make sure that the path is in the file system - that's all we can handle currently...
if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
{
// "The current provider ({0}) cannot open a file"
throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException),
null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName);
}
// Make sure at least one file was found...
if (filePaths == null || filePaths.Count < 1)
{
string message = StringUtil.Format(Modules.ModuleNotFound, _path);
FileNotFoundException fnf = new FileNotFoundException(message);
ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound",
ErrorCategory.ResourceUnavailable, _path);
WriteError(er);
return;
}
if (filePaths.Count > 1)
{
// "The path resolved to more than one file; can only process one file at a time."
throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException),
null, "AmbiguousPath", ParserStrings.AmbiguousPath);
}
string filePath = filePaths[0];
ExternalScriptInfo scriptInfo = null;
string ext = System.IO.Path.GetExtension(filePath);
if (ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
// Create a script info for loading the file...
string scriptName;
scriptInfo = GetScriptInfoForFile(filePath, out scriptName, false);
// we should reserve the Context.ModuleBeingProcessed unchanged after loadModuleManifest(), otherwise the module won't be importable next time.
PSModuleInfo module;
string _origModuleBeingProcessed = Context.ModuleBeingProcessed;
try
{
module = LoadModuleManifest(
scriptInfo,
ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings /* but don't stop on first error and don't load elements */,
null,
null,
null,
null);
if (module != null)
{
//Validate file existence
if (module.RequiredAssemblies != null)
{
foreach (string requiredAssembliespath in module.RequiredAssemblies)
{
if (!IsValidFilePath(requiredAssembliespath, module, true) && !IsValidGacAssembly(requiredAssembliespath))
{
string errorMsg = StringUtil.Format(Modules.InvalidRequiredAssembliesInModuleManifest, requiredAssembliespath, filePath);
var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredAssembliesInModuleManifest",
ErrorCategory.ObjectNotFound, _path);
WriteError(errorRecord);
}
}
}
Hashtable data = null;
Hashtable localizedData = null;
bool containerErrors = false;
LoadModuleManifestData(scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out data, out localizedData, ref containerErrors);
ModuleSpecification[] nestedModules;
GetScalarFromData(data, scriptInfo.Path, "NestedModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out nestedModules);
if (nestedModules != null)
{
foreach (ModuleSpecification nestedModule in nestedModules)
{
if (!IsValidFilePath(nestedModule.Name, module, true)
&& !IsValidFilePath(nestedModule.Name + StringLiterals.DependentWorkflowAssemblyExtension, module, true)
&& !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellNgenAssemblyExtension, module, true)
&& !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellModuleFileExtension, module, true)
&& !IsValidGacAssembly(nestedModule.Name))
{
// The nested module could be dependencies. We compare if it can be loaded by loadmanifest
bool isDependency = false;
foreach (PSModuleInfo loadedNestedModule in module.NestedModules)
{
if (string.Equals(loadedNestedModule.Name, nestedModule.Name, StringComparison.OrdinalIgnoreCase))
{
isDependency = true;
break;
}
}
if (!isDependency)
{
string errorMsg = StringUtil.Format(Modules.InvalidNestedModuleinModuleManifest, nestedModule.Name, filePath);
var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidNestedModuleinModuleManifest",
ErrorCategory.ObjectNotFound, _path);
WriteError(errorRecord);
}
}
}
}
ModuleSpecification[] requiredModules;
GetScalarFromData(data, scriptInfo.Path, "RequiredModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out requiredModules);
if (requiredModules != null)
{
foreach (ModuleSpecification requiredModule in requiredModules)
{
var modules = GetModule(new[] { requiredModule.Name }, false, true);
if (modules.Count == 0)
{
string errorMsg = StringUtil.Format(Modules.InvalidRequiredModulesinModuleManifest, requiredModule.Name, filePath);
var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredModulesinModuleManifest",
ErrorCategory.ObjectNotFound, _path);
WriteError(errorRecord);
}
}
}
string[] fileListPaths;
GetScalarFromData(data, scriptInfo.Path, "FileList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out fileListPaths);
if (fileListPaths != null)
{
foreach (string fileListPath in fileListPaths)
{
if (!IsValidFilePath(fileListPath, module, true))
{
string errorMsg = StringUtil.Format(Modules.InvalidFilePathinModuleManifest, fileListPath, filePath);
var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidFilePathinModuleManifest",
ErrorCategory.ObjectNotFound, _path);
WriteError(errorRecord);
}
}
}
ModuleSpecification[] moduleListModules;
GetScalarFromData(data, scriptInfo.Path, "ModuleList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out moduleListModules);
if (moduleListModules != null)
{
foreach (ModuleSpecification moduleListModule in moduleListModules)
{
var modules = GetModule(new[] { moduleListModule.Name }, true, true);
if (modules.Count == 0)
{
string errorMsg = StringUtil.Format(Modules.InvalidModuleListinModuleManifest, moduleListModule.Name, filePath);
var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidModuleListinModuleManifest",
ErrorCategory.ObjectNotFound, _path);
WriteError(errorRecord);
}
}
}
if (module.CompatiblePSEditions.Any())
{
// The CompatiblePSEditions module manifest key is supported only on PowerShell version '5.1' or higher.
// Ensure that PowerShellVersion module manifest key value is '5.1' or higher.
//
var minimumRequiredPowerShellVersion = new Version(5, 1);
if ((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion)
{
string errorMsg = StringUtil.Format(Modules.InvalidPowerShellVersionInModuleManifest, filePath);
var errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidPowerShellVersionInModuleManifest", ErrorCategory.InvalidArgument, _path);
WriteError(errorRecord);
}
}
}
}
finally
{
Context.ModuleBeingProcessed = _origModuleBeingProcessed;
}
DirectoryInfo parent = null;
try
{
parent = Directory.GetParent(filePath);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
catch (ArgumentException) { }
Version version;
if (parent != null && Version.TryParse(parent.Name, out version))
{
if (!version.Equals(module.Version))
{
string message = StringUtil.Format(Modules.InvalidModuleManifestVersion, filePath, module.Version.ToString(), parent.FullName);
var ioe = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestVersion",
ErrorCategory.InvalidArgument, _path);
ThrowTerminatingError(er);
}
WriteVerbose(Modules.ModuleVersionEqualsToVersionFolder);
}
if (module != null)
{
WriteObject(module);
}
}
else
{
string message = StringUtil.Format(Modules.InvalidModuleManifestPath, filePath);
InvalidOperationException ioe = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath",
ErrorCategory.InvalidArgument, _path);
ThrowTerminatingError(er);
}
}
/// <summary>
/// Check if the given path is valid.
/// </summary>
/// <param name="path"></param>
/// <param name="module"></param>
/// <param name="verifyPathScope"></param>
/// <returns></returns>
private bool IsValidFilePath(string path, PSModuleInfo module, bool verifyPathScope)
{
try
{
if (!System.IO.Path.IsPathRooted(path))
{
// we assume the relative path is under module scope, otherwise we will throw error anyway.
path = System.IO.Path.GetFullPath(module.ModuleBase + "\\" + path);
}
// First, we validate if the path does exist.
if (!File.Exists(path) && !Directory.Exists(path))
{
return false;
}
//Then, we validate if the path is under module scope
if (verifyPathScope && !System.IO.Path.GetFullPath(path).StartsWith(System.IO.Path.GetFullPath(module.ModuleBase), StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
catch (Exception exception)
{
if (exception is ArgumentException || exception is ArgumentNullException || exception is NotSupportedException || exception is PathTooLongException)
{
return false;
}
}
return true;
}
/// <summary>
/// Check if the given string is a valid gac assembly.
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
private bool IsValidGacAssembly(string assemblyName)
{
string gacPath = System.Environment.GetEnvironmentVariable("windir") + "\\Microsoft.NET\\assembly";
string assemblyFile = assemblyName;
string ngenAssemblyFile = assemblyName;
if (!assemblyName.EndsWith(StringLiterals.DependentWorkflowAssemblyExtension, StringComparison.OrdinalIgnoreCase))
{
assemblyFile = assemblyName + StringLiterals.DependentWorkflowAssemblyExtension;
ngenAssemblyFile = assemblyName + StringLiterals.PowerShellNgenAssemblyExtension;
}
try
{
var allFiles = Directory.GetFiles(gacPath, assemblyFile, SearchOption.AllDirectories);
if (allFiles.Length == 0)
{
var allNgenFiles = Directory.GetFiles(gacPath, ngenAssemblyFile, SearchOption.AllDirectories);
if (allNgenFiles.Length == 0)
{
return false;
}
}
}
catch
{
return false;
}
return true;
}
}
#endregion
} // Microsoft.PowerShell.Commands
| |
namespace UserInterface {
partial class MainForm {
/// <summary>
/// Required designer variable.
/// </summary>
public System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
public void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.menu = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.indexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.panel1 = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.chooseFeedButton = new System.Windows.Forms.Button();
this.feedComboBox = new System.Windows.Forms.ComboBox();
this.flowPanel = new System.Windows.Forms.FlowLayoutPanel();
this.menu.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// menu
//
this.menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.menu.Location = new System.Drawing.Point(0, 0);
this.menu.Name = "menu";
this.menu.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.menu.Size = new System.Drawing.Size(599, 24);
this.menu.TabIndex = 0;
this.menu.Text = "menu";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.toolStripSeparator1,
this.printToolStripMenuItem,
this.printPreviewToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
this.newToolStripMenuItem.Text = "&New";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
this.openToolStripMenuItem.Text = "&Open";
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(148, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
this.saveToolStripMenuItem.Text = "&Save";
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
this.saveAsToolStripMenuItem.Text = "Save &As";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(148, 6);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image")));
this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.printToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
this.printToolStripMenuItem.Text = "&Print";
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image")));
this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
this.printPreviewToolStripMenuItem.Text = "Print Pre&view";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(148, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(151, 22);
this.exitToolStripMenuItem.Text = "E&xit";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.undoToolStripMenuItem.Text = "&Undo";
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.redoToolStripMenuItem.Text = "&Redo";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(147, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.copyToolStripMenuItem.Text = "&Copy";
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(147, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.selectAllToolStripMenuItem.Text = "Select &All";
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.customizeToolStripMenuItem,
this.optionsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// customizeToolStripMenuItem
//
this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem";
this.customizeToolStripMenuItem.Size = new System.Drawing.Size(134, 22);
this.customizeToolStripMenuItem.Text = "&Customize";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(134, 22);
this.optionsToolStripMenuItem.Text = "&Options";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.indexToolStripMenuItem,
this.searchToolStripMenuItem,
this.toolStripSeparator5,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
this.contentsToolStripMenuItem.Size = new System.Drawing.Size(129, 22);
this.contentsToolStripMenuItem.Text = "&Contents";
//
// indexToolStripMenuItem
//
this.indexToolStripMenuItem.Name = "indexToolStripMenuItem";
this.indexToolStripMenuItem.Size = new System.Drawing.Size(129, 22);
this.indexToolStripMenuItem.Text = "&Index";
//
// searchToolStripMenuItem
//
this.searchToolStripMenuItem.Name = "searchToolStripMenuItem";
this.searchToolStripMenuItem.Size = new System.Drawing.Size(129, 22);
this.searchToolStripMenuItem.Text = "&Search";
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(126, 6);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(129, 22);
this.aboutToolStripMenuItem.Text = "&About...";
//
// panel1
//
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.chooseFeedButton);
this.panel1.Controls.Add(this.feedComboBox);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 24);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(599, 72);
this.panel1.TabIndex = 3;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(14, 21);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(82, 13);
this.label1.TabIndex = 2;
this.label1.Text = "&Choose a Feed:";
//
// chooseFeedButton
//
this.chooseFeedButton.Location = new System.Drawing.Point(337, 16);
this.chooseFeedButton.Name = "chooseFeedButton";
this.chooseFeedButton.Size = new System.Drawing.Size(75, 23);
this.chooseFeedButton.TabIndex = 1;
this.chooseFeedButton.Text = "&Go";
this.chooseFeedButton.UseVisualStyleBackColor = true;
//
// feedComboBox
//
this.feedComboBox.DisplayMember = "name";
this.feedComboBox.FormattingEnabled = true;
this.feedComboBox.Location = new System.Drawing.Point(118, 17);
this.feedComboBox.Name = "feedComboBox";
this.feedComboBox.Size = new System.Drawing.Size(210, 21);
this.feedComboBox.TabIndex = 0;
this.feedComboBox.ValueMember = "link";
//
// flowPanel
//
this.flowPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowPanel.Location = new System.Drawing.Point(0, 96);
this.flowPanel.Name = "flowPanel";
this.flowPanel.Size = new System.Drawing.Size(599, 224);
this.flowPanel.TabIndex = 4;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(599, 320);
this.Controls.Add(this.flowPanel);
this.Controls.Add(this.panel1);
this.Controls.Add(this.menu);
this.Name = "MainForm";
this.Text = "Ruby RSS Reader";
this.menu.ResumeLayout(false);
this.menu.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public System.Windows.Forms.MenuStrip menu;
public System.Windows.Forms.Panel panel1;
public System.Windows.Forms.Label label1;
public System.Windows.Forms.Button chooseFeedButton;
public System.Windows.Forms.ComboBox feedComboBox;
public System.Windows.Forms.FlowLayoutPanel flowPanel;
public System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
public System.Windows.Forms.ToolStripSeparator toolStripSeparator;
public System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
public System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
public System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
public System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
public System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
public System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
public System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
public System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
public System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem indexToolStripMenuItem;
public System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem;
public System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
public System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using AstUtils = System.Linq.Expressions.Utils;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Dynamic
{
/// <summary>
/// Provides a simple class that can be inherited from to create an object with dynamic behavior
/// at runtime. Subclasses can override the various binder methods (<see cref="TryGetMember"/>,
/// <see cref="TrySetMember"/>, <see cref="TryInvokeMember"/>, etc.) to provide custom behavior
/// that will be invoked at runtime.
///
/// If a method is not overridden then the <see cref="DynamicObject"/> does not directly support
/// that behavior and the call site will determine how the binding should be performed.
/// </summary>
public class DynamicObject : IDynamicMetaObjectProvider
{
/// <summary>
/// Enables derived types to create a new instance of <see cref="DynamicObject"/>.
/// </summary>
/// <remarks>
/// <see cref="DynamicObject"/> instances cannot be directly instantiated because they have no
/// implementation of dynamic behavior.
/// </remarks>
protected DynamicObject()
{
}
#region Public Virtual APIs
/// <summary>
/// Provides the implementation of getting a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="result">The result of the get operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of setting a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="value">The value to set.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
public virtual bool TrySetMember(SetMemberBinder binder, object value) => false;
/// <summary>
/// Provides the implementation of deleting a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
public virtual bool TryDeleteMember(DeleteMemberBinder binder) => false;
/// <summary>
/// Provides the implementation of calling a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="args">The arguments to be used for the invocation.</param>
/// <param name="result">The result of the invocation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of converting the <see cref="DynamicObject"/> to another type.
/// Derived classes can override this method to customize behavior. When not overridden the
/// call site requesting the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="result">The result of the conversion.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of creating an instance of the <see cref="DynamicObject"/>.
/// Derived classes can override this method to customize behavior. When not overridden the
/// call site requesting the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="args">The arguments used for creation.</param>
/// <param name="result">The created instance.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of invoking the <see cref="DynamicObject"/>. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="args">The arguments to be used for the invocation.</param>
/// <param name="result">The result of the invocation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a binary operation. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="arg">The right operand for the operation.</param>
/// <param name="result">The result of the operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a unary operation. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="result">The result of the operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryUnaryOperation(UnaryOperationBinder binder, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a get index operation. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="indexes">The indexes to be used.</param>
/// <param name="result">The result of the operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a set index operation. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="indexes">The indexes to be used.</param>
/// <param name="value">The value to set.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) => false;
/// <summary>
/// Provides the implementation of performing a delete index operation. Derived classes
/// can override this method to customize behavior. When not overridden the call site
/// requesting the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="indexes">The indexes to be deleted.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
public virtual bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes) => false;
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>The list of dynamic member names.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual IEnumerable<string> GetDynamicMemberNames() => Array.Empty<string>();
#endregion
#region MetaDynamic
private sealed class MetaDynamic : DynamicMetaObject
{
internal MetaDynamic(Expression expression, DynamicObject value)
: base(expression, BindingRestrictions.Empty, value)
{
}
public override IEnumerable<string> GetDynamicMemberNames() => Value.GetDynamicMemberNames();
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
if (IsOverridden(DynamicObject_TryGetMember))
{
return CallMethodWithResult(
DynamicObject_TryGetMember,
binder,
s_noArgs,
(MetaDynamic @this, GetMemberBinder b, DynamicMetaObject e) => b.FallbackGetMember(@this, e)
);
}
return base.BindGetMember(binder);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
if (IsOverridden(DynamicObject_TrySetMember))
{
DynamicMetaObject localValue = value;
return CallMethodReturnLast(
DynamicObject_TrySetMember,
binder,
s_noArgs,
value.Expression,
(MetaDynamic @this, SetMemberBinder b, DynamicMetaObject e) => b.FallbackSetMember(@this, localValue, e)
);
}
return base.BindSetMember(binder, value);
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder)
{
if (IsOverridden(DynamicObject_TryDeleteMember))
{
return CallMethodNoResult(
DynamicObject_TryDeleteMember,
binder,
s_noArgs,
(MetaDynamic @this, DeleteMemberBinder b, DynamicMetaObject e) => b.FallbackDeleteMember(@this, e)
);
}
return base.BindDeleteMember(binder);
}
public override DynamicMetaObject BindConvert(ConvertBinder binder)
{
if (IsOverridden(DynamicObject_TryConvert))
{
return CallMethodWithResult(
DynamicObject_TryConvert,
binder,
s_noArgs,
(MetaDynamic @this, ConvertBinder b, DynamicMetaObject e) => b.FallbackConvert(@this, e)
);
}
return base.BindConvert(binder);
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
// Generate a tree like:
//
// {
// object result;
// TryInvokeMember(payload, out result)
// ? result
// : TryGetMember(payload, out result)
// ? FallbackInvoke(result)
// : fallbackResult
// }
//
// Then it calls FallbackInvokeMember with this tree as the
// "error", giving the language the option of using this
// tree or doing .NET binding.
//
DynamicMetaObject call = BuildCallMethodWithResult(
DynamicObject_TryInvokeMember,
binder,
GetExpressions(args),
BuildCallMethodWithResult<GetMemberBinder>(
DynamicObject_TryGetMember,
new GetBinderAdapter(binder),
s_noArgs,
binder.FallbackInvokeMember(this, args, null),
(MetaDynamic @this, GetMemberBinder ignored, DynamicMetaObject e) => binder.FallbackInvoke(e, args, null)
),
null
);
return binder.FallbackInvokeMember(this, args, call);
}
public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args)
{
if (IsOverridden(DynamicObject_TryCreateInstance))
{
DynamicMetaObject[] localArgs = args;
return CallMethodWithResult(
DynamicObject_TryCreateInstance,
binder,
GetExpressions(args),
(MetaDynamic @this, CreateInstanceBinder b, DynamicMetaObject e) => b.FallbackCreateInstance(@this, localArgs, e)
);
}
return base.BindCreateInstance(binder, args);
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args)
{
if (IsOverridden(DynamicObject_TryInvoke))
{
DynamicMetaObject[] localArgs = args;
return CallMethodWithResult(
DynamicObject_TryInvoke,
binder,
GetExpressions(args),
(MetaDynamic @this, InvokeBinder b, DynamicMetaObject e) => b.FallbackInvoke(@this, localArgs, e)
);
}
return base.BindInvoke(binder, args);
}
public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg)
{
if (IsOverridden(DynamicObject_TryBinaryOperation))
{
DynamicMetaObject localArg = arg;
return CallMethodWithResult(
DynamicObject_TryBinaryOperation,
binder,
new[] { arg.Expression },
(MetaDynamic @this, BinaryOperationBinder b, DynamicMetaObject e) => b.FallbackBinaryOperation(@this, localArg, e)
);
}
return base.BindBinaryOperation(binder, arg);
}
public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder)
{
if (IsOverridden(DynamicObject_TryUnaryOperation))
{
return CallMethodWithResult(
DynamicObject_TryUnaryOperation,
binder,
s_noArgs,
(MetaDynamic @this, UnaryOperationBinder b, DynamicMetaObject e) => b.FallbackUnaryOperation(@this, e)
);
}
return base.BindUnaryOperation(binder);
}
public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
if (IsOverridden(DynamicObject_TryGetIndex))
{
DynamicMetaObject[] localIndexes = indexes;
return CallMethodWithResult(
DynamicObject_TryGetIndex,
binder,
GetExpressions(indexes),
(MetaDynamic @this, GetIndexBinder b, DynamicMetaObject e) => b.FallbackGetIndex(@this, localIndexes, e)
);
}
return base.BindGetIndex(binder, indexes);
}
public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
if (IsOverridden(DynamicObject_TrySetIndex))
{
DynamicMetaObject[] localIndexes = indexes;
DynamicMetaObject localValue = value;
return CallMethodReturnLast(
DynamicObject_TrySetIndex,
binder,
GetExpressions(indexes),
value.Expression,
(MetaDynamic @this, SetIndexBinder b, DynamicMetaObject e) => b.FallbackSetIndex(@this, localIndexes, localValue, e)
);
}
return base.BindSetIndex(binder, indexes, value);
}
public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes)
{
if (IsOverridden(DynamicObject_TryDeleteIndex))
{
DynamicMetaObject[] localIndexes = indexes;
return CallMethodNoResult(
DynamicObject_TryDeleteIndex,
binder,
GetExpressions(indexes),
(MetaDynamic @this, DeleteIndexBinder b, DynamicMetaObject e) => b.FallbackDeleteIndex(@this, localIndexes, e)
);
}
return base.BindDeleteIndex(binder, indexes);
}
private delegate DynamicMetaObject Fallback<TBinder>(MetaDynamic @this, TBinder binder, DynamicMetaObject errorSuggestion);
private static readonly Expression[] s_noArgs = new Expression[0]; // used in reference comparison, requires unique object identity
private static ReadOnlyCollection<Expression> GetConvertedArgs(params Expression[] args)
{
var paramArgs = new Expression[args.Length];
for (int i = 0; i < args.Length; i++)
{
paramArgs[i] = Expression.Convert(args[i], typeof(object));
}
return new TrueReadOnlyCollection<Expression>(paramArgs);
}
/// <summary>
/// Helper method for generating expressions that assign byRef call
/// parameters back to their original variables.
/// </summary>
private static Expression ReferenceArgAssign(Expression callArgs, Expression[] args)
{
ReadOnlyCollectionBuilder<Expression> block = null;
for (int i = 0; i < args.Length; i++)
{
ParameterExpression variable = args[i] as ParameterExpression;
ContractUtils.Requires(variable != null, nameof(args));
if (variable.IsByRef)
{
if (block == null)
block = new ReadOnlyCollectionBuilder<Expression>();
block.Add(
Expression.Assign(
variable,
Expression.Convert(
Expression.ArrayIndex(
callArgs,
AstUtils.Constant(i)
),
variable.Type
)
)
);
}
}
if (block != null)
return Expression.Block(block);
else
return AstUtils.Empty;
}
/// <summary>
/// Helper method for generating arguments for calling methods
/// on DynamicObject. parameters is either a list of ParameterExpressions
/// to be passed to the method as an object[], or NoArgs to signify that
/// the target method takes no object[] parameter.
/// </summary>
private static Expression[] BuildCallArgs<TBinder>(TBinder binder, Expression[] parameters, Expression arg0, Expression arg1)
where TBinder : DynamicMetaObjectBinder
{
if (!object.ReferenceEquals(parameters, s_noArgs))
return arg1 != null ? new Expression[] { Constant(binder), arg0, arg1 } : new Expression[] { Constant(binder), arg0 };
else
return arg1 != null ? new Expression[] { Constant(binder), arg1 } : new Expression[] { Constant(binder) };
}
private static ConstantExpression Constant<TBinder>(TBinder binder)
{
return Expression.Constant(binder, typeof(TBinder));
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic that returns a result
/// </summary>
private DynamicMetaObject CallMethodWithResult<TBinder>(MethodInfo method, TBinder binder, Expression[] args, Fallback<TBinder> fallback)
where TBinder : DynamicMetaObjectBinder
{
return CallMethodWithResult(method, binder, args, fallback, null);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic that returns a result
/// </summary>
private DynamicMetaObject CallMethodWithResult<TBinder>(MethodInfo method, TBinder binder, Expression[] args, Fallback<TBinder> fallback, Fallback<TBinder> fallbackInvoke)
where TBinder : DynamicMetaObjectBinder
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(this, binder, null);
DynamicMetaObject callDynamic = BuildCallMethodWithResult(method, binder, args, fallbackResult, fallbackInvoke);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback(this, binder, callDynamic);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on DynamicObject that returns a result.
///
/// args is either an array of arguments to be passed
/// to the method as an object[] or NoArgs to signify that
/// the target method takes no parameters.
/// </summary>
private DynamicMetaObject BuildCallMethodWithResult<TBinder>(MethodInfo method, TBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback<TBinder> fallbackInvoke)
where TBinder : DynamicMetaObjectBinder
{
if (!IsOverridden(method))
{
return fallbackResult;
}
//
// Build a new expression like:
// {
// object result;
// TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
ParameterExpression callArgs = method != DynamicObject_TryBinaryOperation ? Expression.Parameter(typeof(object[]), null) : Expression.Parameter(typeof(object), null);
ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs(args);
var resultMO = new DynamicMetaObject(result, BindingRestrictions.Empty);
// Need to add a conversion if calling TryConvert
if (binder.ReturnType != typeof(object))
{
Debug.Assert(binder is ConvertBinder && fallbackInvoke == null);
UnaryExpression convert = Expression.Convert(resultMO.Expression, binder.ReturnType);
// will always be a cast or unbox
Debug.Assert(convert.Method == null);
// Prepare a good exception message in case the convert will fail
string convertFailed = System.Linq.Expressions.Strings.DynamicObjectResultNotAssignable(
"{0}",
this.Value.GetType(),
binder.GetType(),
binder.ReturnType
);
Expression condition;
// If the return type can not be assigned null then just check for type assignability otherwise allow null.
if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType(binder.ReturnType) == null)
{
condition = Expression.TypeIs(resultMO.Expression, binder.ReturnType);
}
else
{
condition = Expression.OrElse(
Expression.Equal(resultMO.Expression, AstUtils.Null),
Expression.TypeIs(resultMO.Expression, binder.ReturnType));
}
Expression checkedConvert = Expression.Condition(
condition,
convert,
Expression.Throw(
Expression.New(
InvalidCastException_Ctor_String,
new TrueReadOnlyCollection<Expression>(
Expression.Call(
String_Format_String_ObjectArray,
Expression.Constant(convertFailed),
Expression.NewArrayInit(
typeof(object),
new TrueReadOnlyCollection<Expression>(
Expression.Condition(
Expression.Equal(resultMO.Expression, AstUtils.Null),
Expression.Constant("null"),
Expression.Call(
resultMO.Expression,
Object_GetType
),
typeof(object)
)
)
)
)
)
),
binder.ReturnType
),
binder.ReturnType
);
resultMO = new DynamicMetaObject(checkedConvert, resultMO.Restrictions);
}
if (fallbackInvoke != null)
{
resultMO = fallbackInvoke(this, binder, resultMO);
}
var callDynamic = new DynamicMetaObject(
Expression.Block(
new TrueReadOnlyCollection<ParameterExpression>(result, callArgs),
new TrueReadOnlyCollection<Expression>(
method != DynamicObject_TryBinaryOperation ? Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)) : Expression.Assign(callArgs, callArgsValue[0]),
Expression.Condition(
Expression.Call(
GetLimitedSelf(),
method,
BuildCallArgs(
binder,
args,
callArgs,
result
)
),
Expression.Block(
method != DynamicObject_TryBinaryOperation ? ReferenceArgAssign(callArgs, args) : AstUtils.Empty,
resultMO.Expression
),
fallbackResult.Expression,
binder.ReturnType
)
)
),
GetRestrictions().Merge(resultMO.Restrictions).Merge(fallbackResult.Restrictions)
);
return callDynamic;
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
///
/// args is either an array of arguments to be passed
/// to the method as an object[] or NoArgs to signify that
/// the target method takes no parameters.
/// </summary>
private DynamicMetaObject CallMethodReturnLast<TBinder>(MethodInfo method, TBinder binder, Expression[] args, Expression value, Fallback<TBinder> fallback)
where TBinder : DynamicMetaObjectBinder
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(this, binder, null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
ParameterExpression callArgs = Expression.Parameter(typeof(object[]), null);
ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs(args);
var callDynamic = new DynamicMetaObject(
Expression.Block(
new TrueReadOnlyCollection<ParameterExpression>(result, callArgs),
new TrueReadOnlyCollection<Expression>(
Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)),
Expression.Condition(
Expression.Call(
GetLimitedSelf(),
method,
BuildCallArgs(
binder,
args,
callArgs,
Expression.Assign(result, Expression.Convert(value, typeof(object)))
)
),
Expression.Block(
ReferenceArgAssign(callArgs, args),
result
),
fallbackResult.Expression,
typeof(object)
)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback(this, binder, callDynamic);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
///
/// args is either an array of arguments to be passed
/// to the method as an object[] or NoArgs to signify that
/// the target method takes no parameters.
/// </summary>
private DynamicMetaObject CallMethodNoResult<TBinder>(MethodInfo method, TBinder binder, Expression[] args, Fallback<TBinder> fallback)
where TBinder : DynamicMetaObjectBinder
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(this, binder, null);
ParameterExpression callArgs = Expression.Parameter(typeof(object[]), null);
ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs(args);
//
// Build a new expression like:
// if (TryDeleteMember(payload)) { } else { fallbackResult }
//
var callDynamic = new DynamicMetaObject(
Expression.Block(
new TrueReadOnlyCollection<ParameterExpression>(callArgs),
new TrueReadOnlyCollection<Expression>(
Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)),
Expression.Condition(
Expression.Call(
GetLimitedSelf(),
method,
BuildCallArgs(
binder,
args,
callArgs,
null
)
),
Expression.Block(
ReferenceArgAssign(callArgs, args),
AstUtils.Empty
),
fallbackResult.Expression,
typeof(void)
)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback(this, binder, callDynamic);
}
/// <summary>
/// Checks if the derived type has overridden the specified method. If there is no
/// implementation for the method provided then Dynamic falls back to the base class
/// behavior which lets the call site determine how the binder is performed.
/// </summary>
private bool IsOverridden(MethodInfo method)
{
MemberInfo[] methods = Value.GetType().GetMember(method.Name, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance);
foreach (MethodInfo mi in methods)
{
if (mi.DeclaringType != typeof(DynamicObject) && mi.GetBaseDefinition() == method)
{
return true;
}
}
return false;
}
/// <summary>
/// Returns a Restrictions object which includes our current restrictions merged
/// with a restriction limiting our type
/// </summary>
private BindingRestrictions GetRestrictions()
{
Debug.Assert(Restrictions == BindingRestrictions.Empty, "We don't merge, restrictions are always empty");
return BindingRestrictions.GetTypeRestriction(this);
}
/// <summary>
/// Returns our Expression converted to DynamicObject
/// </summary>
private Expression GetLimitedSelf()
{
// Convert to DynamicObject rather than LimitType, because
// the limit type might be non-public.
if (TypeUtils.AreEquivalent(Expression.Type, typeof(DynamicObject)))
{
return Expression;
}
return Expression.Convert(Expression, typeof(DynamicObject));
}
private new DynamicObject Value => (DynamicObject)base.Value;
// It is okay to throw NotSupported from this binder. This object
// is only used by DynamicObject.GetMember--it is not expected to
// (and cannot) implement binding semantics. It is just so the DO
// can use the Name and IgnoreCase properties.
private sealed class GetBinderAdapter : GetMemberBinder
{
internal GetBinderAdapter(InvokeMemberBinder binder)
: base(binder.Name, binder.IgnoreCase)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotSupportedException();
}
}
}
#endregion
#region IDynamicMetaObjectProvider Members
/// <summary>
/// Returns the <see cref="DynamicMetaObject" /> responsible for binding operations performed on this object,
/// using the virtual methods provided by this class.
/// </summary>
/// <param name="parameter">The expression tree representation of the runtime value.</param>
/// <returns>
/// The <see cref="DynamicMetaObject" /> to bind this object. The object can be encapsulated inside of another
/// <see cref="DynamicMetaObject"/> to provide custom behavior for individual actions.
/// </returns>
public virtual DynamicMetaObject GetMetaObject(Expression parameter) => new MetaDynamic(parameter, this);
#endregion
}
}
| |
using System;
using System.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace ShareLink.Converters
{
/// <summary>
/// Value converter that translates true to <see cref="Visibility.Visible"/> and false to
/// <see cref="Visibility.Collapsed"/>.
/// </summary>
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is bool);
return (value is bool && (bool) value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is Visibility);
return value is Visibility && (Visibility) value == Visibility.Visible;
}
}
/// <summary>
/// Provides inverse value of the BooleanToVisibilityConverter
/// </summary>
public sealed class InvertedBooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is bool);
return (value is bool && (bool) value) ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is Visibility);
return value is Visibility && (Visibility) value != Visibility.Visible;
}
}
public sealed class InvertedBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is bool);
return (!(value is bool) || !(bool) value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is bool);
return value is bool && (bool) value;
}
}
/// <summary>
/// Value converter that translates an integer count to visibility (0 for hiding, non 0 for showing).
/// </summary>
public sealed class CountToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is int);
return value is int && (int) value != 0 ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Provides the inverse value of CountToVisibilityConverter
/// </summary>
public sealed class InvertedCountToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is int);
return value is int && (int) value == 0 ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Provides the inverse value of Visibility
/// </summary>
public sealed class InvertedVisibilityToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is Visibility);
return value is Visibility && (Visibility) value == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Value converter that translates an empty string to hidden and non empty to a shown.
/// </summary>
public sealed class StringToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return string.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
public sealed class StringToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return !string.IsNullOrEmpty(value as string);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
public sealed class InvertedStringToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return string.IsNullOrEmpty(value as string);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Value converter that translates an empty string to shown and non empty to hidden.
/// </summary>
public sealed class InvertedStringToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return string.IsNullOrEmpty(value as string) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
public sealed class ObjectToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return IsVisible(value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
internal static bool IsVisible(object value)
{
var str = value as string;
if (str != null)
{
return !string.IsNullOrEmpty(str);
}
return value != null;
}
}
public sealed class InvertedObjectToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return ObjectToVisibilityConverter.IsVisible(value) ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
public sealed class GreaterThanVisibilityConverter : IValueConverter
{
public int GreaterThan { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.Assert(value is int);
return value is int && (int) value > GreaterThan ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
}
| |
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Threading.Atomics
{
/// <summary>
/// A wrapper for structs with atomic operations
/// </summary>
/// <typeparam name="T">The underlying struct's type</typeparam>
[DebuggerDisplay("{Value}")]
public sealed class Atomic<T> : IAtomicRef<T>,
IEquatable<T>,
IAtomicCASProvider<T>,
IEquatable<Atomic<T>> where T : struct, IEquatable<T>
{
private T _value;
//private static readonly IAtomicCASProvider<T> Intrinsics = new PrimitiveAtomics() as IAtomicCASProvider<T>;
private readonly IAtomicRef<T> _storage;
private readonly MemoryOrder _order;
/// <summary>
/// Creates new instance of <see cref="Atomic{T}"/>
/// </summary>
/// <param name="order">Affects the way store operation occur. Default is <see cref="MemoryOrder.SeqCst"/> semantics which hurt performance</param>
/// <param name="align">True to store the underlying value aligned, otherwise False</param>
public Atomic(MemoryOrder order = MemoryOrder.SeqCst, bool align = false)
:this (default(T), order, align)
{
}
/// <summary>
/// Creates new instance of <see cref="Atomic{T}"/>
/// </summary>
/// <param name="value">The value to store</param>
/// <param name="order">Affects the way store operation occur. Default is <see cref="MemoryOrder.SeqCst"/> semantics which hurt performance</param>
/// <param name="align">True to store the underlying value aligned, otherwise False</param>
public Atomic(T value, MemoryOrder order = MemoryOrder.SeqCst, bool align = false)
{
order.ThrowIfNotSupported();
_storage = GetStorage(order, align);
_order = order;
_storage.Value = value;
}
private IAtomicRef<T> GetStorage(MemoryOrder order, bool align)
{
if (typeof(T) == typeof(bool))
{
return (IAtomicRef<T>)(IAtomicRef<bool>)new AtomicBoolean(order, align);
}
if (typeof(T) == typeof(int))
{
return (IAtomicRef<T>)(IAtomicRef<int>)new AtomicInteger(order, align);
}
if (typeof(T) == typeof(long))
{
return (IAtomicRef<T>)(IAtomicRef<long>)new AtomicLong(order, align);
}
if (Pod<T>.Size == sizeof (int))
{
return new Boxed32Bit();
}
if (Pod<T>.Size <= sizeof(int))
{
return new LockBasedAtomic(new Boxed32Bit());
}
if (Pod<T>.Size == sizeof(long))
{
return new Boxed64Bit();
}
if (Pod<T>.Size <= sizeof(long))
{
return new LockBasedAtomic(new Boxed64Bit());
}
if (Pod<T>.AtomicRWSupported() || Pod<T>.Size <= IntPtr.Size)
return this;
return new LockBasedAtomic(this);
}
/*
* We use lock(this) to have lower memory footprint
* Additional instance lock (i.e. object) is redundant
* LockBasedAtomic is used only as a storage and doesn't get exposed
*/
class LockBasedAtomic : IAtomicRef<T>
{
private readonly IAtomic<T> _atomic;
public LockBasedAtomic(IAtomic<T> atomic)
{
_atomic = atomic;
}
public T Value
{
get { lock (this) return _atomic.Value; }
set { lock (this) _atomic.Value = value; }
}
public void Store(T value, MemoryOrder order)
{
lock (this)
_atomic.Store(value, order);
}
public T Load(MemoryOrder order)
{
lock (this)
return _atomic.Load(order);
}
public void Store(ref T value, MemoryOrder order)
{
lock (this)
_atomic.Store(value, order);
}
public bool IsLockFree { get { return false; } }
public T CompareExchange(T value, T comparand)
{
lock (this)
return _atomic.CompareExchange(value, comparand);
}
}
/// <summary>
/// Gets or sets atomically the underlying value
/// </summary>
/// <remarks>This method does use CAS approach for value setting. To avoid this use <see cref="Load"/> and <see cref="Store"/> methods pair for get/set operations respectively</remarks>
public T Value
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _storage.Value; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set { _storage.Value = value; }
}
T IAtomic<T>.Value
{
get { return Load(_order == MemoryOrder.SeqCst ? MemoryOrder.SeqCst : MemoryOrder.Acquire); }
set
{
if (_order == MemoryOrder.SeqCst)
{
Platform.WriteSeqCst(ref _value, ref value);
return;
}
T currentValue = this._value;
T tempValue;
do
{
tempValue = _storage.CompareExchange(value, currentValue);
} while (!tempValue.Equals(currentValue));
}
}
class Boxed32Bit : IAtomicCASProvider<byte>,
IAtomicCASProvider<sbyte>,
IAtomicCASProvider<Int16>,
IAtomicCASProvider<UInt16>,
IAtomicCASProvider<Int32>,
IAtomicCASProvider<UInt32>,
IAtomicCASProvider<float>,
IAtomicRef<T>
{
public Platform.Data32 AcqRelValue;
public void Store(ref T value, MemoryOrder order)
{
switch (order)
{
case MemoryOrder.Relaxed:
this.AcqRelValue.Int32Value = Platform.reinterpret_cast<T, int>(ref value);
break;
case MemoryOrder.Consume:
throw new NotSupportedException();
case MemoryOrder.Acquire:
throw new InvalidOperationException("Cannot set (store) value with Acquire semantics");
case MemoryOrder.Release:
case MemoryOrder.AcqRel:
this.AcqRelValue.Int32Value = Platform.reinterpret_cast<T, int>(ref value);
break;
case MemoryOrder.SeqCst:
#if ARM_CPU
Platform.MemoryBarrier();
this.AcqRelValue.Int32Value = Platform.reinterpret_cast<T, int>(ref value);
#else
Interlocked.Exchange(ref AcqRelValue.Int32Value, Platform.reinterpret_cast<T, int>(ref value));
#endif
break;
default:
throw new ArgumentOutOfRangeException("order");
}
}
public T Value
{
get { return Load(MemoryOrder.SeqCst); }
set { Store(value, MemoryOrder.SeqCst); }
}
public void Store(T value, MemoryOrder order)
{
Store(ref value, order);
}
public T Load(MemoryOrder order)
{
switch (order)
{
case MemoryOrder.Relaxed:
return Platform.reinterpret_cast<int, T>(ref AcqRelValue.Int32Value);
case MemoryOrder.Consume:
throw new NotSupportedException();
case MemoryOrder.Acquire:
return Platform.reinterpret_cast<int, T>(ref AcqRelValue.Int32Value);
case MemoryOrder.Release:
throw new InvalidOperationException("Cannot get (load) value with Release semantics");
case MemoryOrder.AcqRel:
return Platform.reinterpret_cast<int, T>(ref AcqRelValue.Int32Value);
case MemoryOrder.SeqCst:
#if ARM_CPU
var tmp = Platform.reinterpret_cast<int, T>(ref AcqRelValue.Int32Value);
Platform.MemoryBarrier();
return tmp;
#else
return Platform.reinterpret_cast<int, T>(ref AcqRelValue.Int32Value);
#endif
default:
throw new ArgumentOutOfRangeException("order");
}
}
public bool IsLockFree
{
get { return true; }
}
public T CompareExchange(T value, T comparand)
{
return (this as IAtomicCASProvider<T>).CompareExchange(value, comparand);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
byte IAtomicCASProvider<byte>.CompareExchange(byte value, byte comparand)
{
return (byte)Interlocked.CompareExchange(ref AcqRelValue.Int32Value, value, comparand);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
sbyte IAtomicCASProvider<sbyte>.CompareExchange(sbyte value, sbyte comparand)
{
return (sbyte)Interlocked.CompareExchange(ref AcqRelValue.Int32Value, value, comparand);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
short IAtomicCASProvider<short>.CompareExchange(short value, short comparand)
{
return (short)Interlocked.CompareExchange(ref AcqRelValue.Int32Value, value, comparand);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
ushort IAtomicCASProvider<ushort>.CompareExchange(ushort value, ushort comparand)
{
return (ushort)Interlocked.CompareExchange(ref AcqRelValue.Int32Value, value, comparand);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int IAtomicCASProvider<int>.CompareExchange(int value, int comparand)
{
return Interlocked.CompareExchange(ref AcqRelValue.Int32Value, value, comparand);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe uint IAtomicCASProvider<uint>.CompareExchange(uint value, uint comparand)
{
var result = Interlocked.CompareExchange(ref AcqRelValue.Int32Value, *(int*)&value, *(int*)&comparand);
return *(uint*)&result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
float IAtomicCASProvider<float>.CompareExchange(float value, float comparand)
{
return Interlocked.CompareExchange(ref AcqRelValue.SingleValue, value, comparand);
}
}
class Boxed64Bit : IAtomicCASProvider<long>,
IAtomicCASProvider<ulong>,
IAtomicCASProvider<double>,
IAtomicRef<T>
{
public Platform.Data64 AcqRelValue;
long IAtomicCASProvider<long>.CompareExchange(long value, long comparand)
{
return Interlocked.CompareExchange(ref AcqRelValue.Int64Value, value, comparand);
}
unsafe ulong IAtomicCASProvider<ulong>.CompareExchange(ulong value, ulong comparand)
{
var result = Interlocked.CompareExchange(ref AcqRelValue.Int64Value, *(long*)&value, *(long*)&comparand);
return *(ulong*) &result;
}
double IAtomicCASProvider<double>.CompareExchange(double value, double comparand)
{
return Interlocked.CompareExchange(ref AcqRelValue.DoubleValue, value, comparand);
}
public T CompareExchange(T value, T comparand)
{
return ((IAtomicCASProvider<T>) this).CompareExchange(value, comparand);
}
public bool IsLockFree
{
get { return true; }
}
public void Store(ref T value, MemoryOrder order)
{
switch (order)
{
case MemoryOrder.Relaxed:
this.AcqRelValue.Int64Value = Platform.reinterpret_cast<T, long>(ref value);
break;
case MemoryOrder.Consume:
throw new NotSupportedException();
case MemoryOrder.Acquire:
throw new InvalidOperationException("Cannot set (store) value with Acquire semantics");
case MemoryOrder.Release:
case MemoryOrder.AcqRel:
#if ARM_CPU
Platform.MemoryBarrier();
this.AcqRelValue.Int64Value = Platform.reinterpret_cast<T, long>(ref value);
#else
Volatile.Write(ref AcqRelValue.Int64Value, Platform.reinterpret_cast<T, long>(ref value));
#endif
break;
case MemoryOrder.SeqCst:
#if ARM_CPU
Platform.MemoryBarrier();
this.AcqRelValue.Int64Value = Platform.reinterpret_cast<T, long>(ref value);
Platform.MemoryBarrier();
#else
Interlocked.Exchange(ref AcqRelValue.Int64Value, Platform.reinterpret_cast<T, long>(ref value));
#endif
break;
default:
throw new ArgumentOutOfRangeException("order");
}
}
public T Value
{
get { return Load(MemoryOrder.SeqCst); }
set { Store(value, MemoryOrder.SeqCst); }
}
public void Store(T value, MemoryOrder order)
{
Store(ref value, order);
}
public T Load(MemoryOrder order)
{
if (order == MemoryOrder.Consume)
throw new NotSupportedException();
if (order == MemoryOrder.Release)
throw new InvalidOperationException("Cannot get (load) value with Release semantics");
switch (order)
{
case MemoryOrder.Relaxed:
return Platform.reinterpret_cast<long, T>(ref AcqRelValue.Int64Value);
case MemoryOrder.Acquire:
case MemoryOrder.AcqRel:
case MemoryOrder.SeqCst:
#if ARM_CPU
var tmp = Platform.reinterpret_cast<long, T>(ref AcqRelValue.Int64Value);
Platform.MemoryBarrier();
return tmp;
#else
long value = Volatile.Read(ref AcqRelValue.Int64Value);
return Platform.reinterpret_cast<long, T>(ref value);
#endif
default:
throw new ArgumentOutOfRangeException("order");
}
}
}
/// <summary>
/// Gets value whether the object is lock-free
/// </summary>
public bool IsLockFree
{
get
{
if (object.ReferenceEquals(_storage, this))
return Pod<T>.AtomicRWSupported() || Pod<T>.Size <= IntPtr.Size;
return _storage.IsLockFree;
}
}
/// <summary>
/// Atomically compares underlying value with <paramref name="comparand"/> for equality and, if they are equal, replaces the first value.
/// </summary>
/// <param name="value">The value that replaces the underlying value if the comparison results in equality</param>
/// <param name="comparand">The value that is compared to the underlying value.</param>
/// <returns>The original underlying value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T CompareExchange(T value, T comparand)
{
return _storage.CompareExchange(value, comparand);
}
T IAtomic<T>.CompareExchange(T value, T comparand)
{
T temp = _value;
if (!temp.Equals(comparand))
{
Platform.MemoryBarrier();
_value = value;
}
Platform.MemoryBarrier();
return temp;
}
void IAtomic<T>.Store(T value, MemoryOrder order)
{
((IAtomicRef<T>)this).Store(ref value, order);
}
void IAtomicRef<T>.Store(ref T value, MemoryOrder order)
{
switch (order)
{
case MemoryOrder.Relaxed:
Platform.Write(ref _value, ref value);
break;
case MemoryOrder.Consume:
throw new NotSupportedException();
case MemoryOrder.Acquire:
throw new InvalidOperationException("Cannot set (store) value with Acquire semantics");
case MemoryOrder.Release:
case MemoryOrder.AcqRel:
Platform.WriteRelease(ref _value, ref value);
break;
case MemoryOrder.SeqCst:
Platform.WriteSeqCst(ref _value, ref value);
break;
default:
throw new ArgumentOutOfRangeException("order");
}
}
/// <summary>
/// Sets the underlying value with provided <paramref name="order"/>
/// </summary>
/// <param name="value">The value to store</param>
/// <param name="order">The <see cref="MemoryOrder"/> to achieve</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Store(ref T value, MemoryOrder order)
{
_storage.Store(ref value, order);
}
/// <summary>
/// Sets the underlying value with provided <paramref name="order"/>
/// </summary>
/// <param name="value">The value to store</param>
/// <param name="order">The <see cref="MemoryOrder"/> to achieve</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Store(T value, MemoryOrder order)
{
_storage.Store(value, order);
}
T IAtomic<T>.Load(MemoryOrder order)
{
switch (order)
{
case MemoryOrder.Relaxed:
return Platform.Read(ref _value);
case MemoryOrder.Consume:
throw new NotSupportedException();
case MemoryOrder.Acquire:
return Platform.ReadAcquire(ref _value);
case MemoryOrder.Release:
throw new InvalidOperationException("Cannot get (load) value with Release semantics");
case MemoryOrder.AcqRel:
return Platform.ReadAcquire(ref _value);
case MemoryOrder.SeqCst:
return Platform.ReadSeqCst(ref _value);
default:
throw new ArgumentOutOfRangeException("order");
}
}
/// <summary>
/// Gets the underlying value with provided <paramref name="order"/>
/// </summary>
/// <param name="order">The <see cref="MemoryOrder"/> to achieve</param>
/// <returns>The underlying value with provided <paramref name="order"/></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Load(MemoryOrder order)
{
return _storage.Load(order);
}
/// <summary>
/// Defines an implicit conversion of a <see cref="AtomicInteger"/> to a <typeparamref name="T"/>.
/// </summary>
/// <param name="atomic">The <see cref="Atomic{T}"/> to convert.</param>
/// <returns>The converted <see cref="Atomic{T}"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator T(Atomic<T> atomic)
{
return atomic == null ? default(T) : atomic.Value;
}
/// <summary>
/// Defines an implicit conversion of a <typeparamref name="T"/> to a <see cref="AtomicInteger"/>.
/// </summary>
/// <param name="value">The <typeparamref name="T"/> to convert.</param>
/// <returns>The converted <typeparamref name="T"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Atomic<T>(T value)
{
return new Atomic<T>(value);
}
/// <summary>
/// Serves as the default hash function
/// </summary>
/// <returns>A hash code for the current <see cref="Atomic{T}"/></returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Returns a value indicating whether this instance and a specified Object represent the same type and value.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><c>true</c> if <paramref name="obj"/> is a <see cref="Atomic{T}"/> and equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
Atomic<T> other = obj as Atomic<T>;
if (other == null) return false;
return object.ReferenceEquals(this, other) || this.Value.Equals(other.Value);
}
/// <summary>
/// Returns a value indicating whether this instance and a specified <paramref name="other"/> represent the same value.
/// </summary>
/// <param name="other">An object to compare to this instance.</param>
/// <returns><c>true</c> if <paramref name="other"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public bool Equals(T other)
{
return this.Value.Equals(other);
}
/// <summary>
/// Returns a value indicating whether this instance and a specified <see cref="Atomic{T}"/> object represent the same value.
/// </summary>
/// <param name="other">An object to compare to this instance.</param>
/// <returns><c>true</c> if <paramref name="other"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public bool Equals(Atomic<T> other)
{
return !object.ReferenceEquals(other, null) && (object.ReferenceEquals(this, other) || this.Value.Equals(other.Value));
}
/// <summary>
/// Returns a value that indicates whether <see cref="Atomic{T}"/> and <typeparamref name="T"/> are equal.
/// </summary>
/// <param name="x">The first value (<see cref="Atomic{T}"/>) to compare.</param>
/// <param name="y">The second value (<typeparamref name="T"/>) to compare.</param>
/// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are equal; otherwise, <c>false</c>.</returns>
public static bool operator ==(Atomic<T> x, T y)
{
return (!object.ReferenceEquals(x, null) && x.Value.Equals(y));
}
/// <summary>
/// Returns a value that indicates whether <see cref="Atomic{T}"/> and <see cref="Atomic{T}"/> are equal.
/// </summary>
/// <param name="x">The first value (<see cref="AtomicInteger"/>) to compare.</param>
/// <param name="y">The second value (<see cref="int"/>) to compare.</param>
/// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are equal; otherwise, <c>false</c>.</returns>
public static bool operator ==(Atomic<T> x, Atomic<T> y)
{
return !object.ReferenceEquals(x, null) && !object.ReferenceEquals(y, null) && x.Equals(y);
}
/// <summary>
/// Returns a value that indicates whether <see cref="Atomic{T}"/> and <typeparamref name="T"/> have different values.
/// </summary>
/// <param name="x">The first value (<see cref="Atomic{T}"/>) to compare.</param>
/// <param name="y">The second value (<typeparamref name="T"/>) to compare.</param>
/// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are not equal; otherwise, <c>false</c>.</returns>
public static bool operator !=(Atomic<T> x, T y)
{
return !object.ReferenceEquals(x, null) && !x.Equals(y);
}
/// <summary>
/// Returns a value that indicates whether <see cref="Atomic{T}"/> and <typeparamref name="T"/> have different values.
/// </summary>
/// <param name="x">The first value (<see cref="Atomic{T}"/>) to compare.</param>
/// <param name="y">The second value (<see cref="Atomic{T}"/>) to compare.</param>
/// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are not equal; otherwise, <c>false</c>.</returns>
public static bool operator !=(Atomic<T> x, Atomic<T> y)
{
return !object.ReferenceEquals(x, null) && !object.ReferenceEquals(y, null) && !x.Equals(y);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class OfTypeTests
{
public class OfType011
{
private static int OfType001()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst1 = q.OfType<int>();
var rst2 = q.OfType<int>();
return Verification.Allequal(rst1, rst2);
}
private static int OfType002()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where String.IsNullOrEmpty(x)
select x;
var rst1 = q.OfType<string>();
var rst2 = q.OfType<string>();
return Verification.Allequal(rst1, rst2);
}
public static int Main()
{
int ret = RunTest(OfType001) + RunTest(OfType002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType1
{
// source is empty
public static int Test1()
{
Object[] source = { };
int[] expected = { };
IEnumerable<int> actual = source.OfType<int>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test1();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType10
{
// source is an int and type is long
public static int Test10()
{
int[] source = { 99, 45, 81 };
long[] expected = { };
IEnumerable<long> actual = source.OfType<long>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test10();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType2
{
// source does NOT have any object of type int
public static int Test2()
{
Object[] source = { "Hello", 3.5, "Test" };
int[] expected = { };
IEnumerable<int> actual = source.OfType<int>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType3
{
// only the first element in source is of type int
public static int Test3()
{
Object[] source = { 10, "Hello", 3.5, "Test" };
int[] expected = { 10 };
IEnumerable<int> actual = source.OfType<int>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test3();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType4
{
// All elements in source is of type int?
public static int Test4()
{
Object[] source = { 10, -4, null, null, 4, 9 };
int?[] expected = { 10, -4, 4, 9 };
IEnumerable<int?> actual = source.OfType<int?>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test4();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType5
{
// When 2nd, 5th and the last element is of type int
public static int Test5()
{
Object[] source = { 3.5m, -4, "Test", "Check", 4, 8.0, 10.5, 9 };
int[] expected = { -4, 4, 9 };
IEnumerable<int> actual = source.OfType<int>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test5();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType6
{
// source is an int and type is int?
public static int Test6()
{
int[] source = { -4, 4, 9 };
int?[] expected = { -4, 4, 9 };
IEnumerable<int?> actual = source.OfType<int?>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test6();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType7
{
// source is an int? and type is int
public static int Test7()
{
int?[] source = { null, -4, 4, null, 9 };
int[] expected = { -4, 4, 9 };
IEnumerable<int> actual = source.OfType<int>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test7();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType8
{
// source is an string and type is decimal?
public static int Test8()
{
string[] source = { "Test1", "Test2", "Test9" };
decimal?[] expected = { };
IEnumerable<decimal?> actual = source.OfType<decimal?>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test8();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OfType9
{
// source is an long and type is double
public static int Test9()
{
long[] source = { 99L, 45L, 81L };
double[] expected = { };
IEnumerable<double> actual = source.OfType<double>();
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test9();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RemoteWebConfigurationHostServer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration {
using System.Collections;
using System.Configuration;
using System.Security;
using System.IO;
using System.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Web.Util;
using System.Collections.Specialized;
using System.Xml;
using System.Security.Cryptography;
#if !FEATURE_PAL // FEATURE_PAL does not enable access control
using System.Security.AccessControl;
#endif // !FEATURE_PAL
using System.Security.Permissions;
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual),
#if WIN64
Guid("DFD0D215-72C0-450d-92B5-10971FC24625"), ProgId("System.Web.Configuration.RemoteWebConfigurationHostServerV4_64")]
#else
Guid("9FDB6D2C-90EA-4e42-99E6-38B96E28698E"), ProgId("System.Web.Configuration.RemoteWebConfigurationHostServerV4_32")]
#endif
#endif // FEATURE_PAL does not enable COM
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
public class RemoteWebConfigurationHostServer : IRemoteWebConfigurationHostServer
{
internal const char FilePathsSeparatorChar = '<';
static internal readonly char[] FilePathsSeparatorParams = new char[] {FilePathsSeparatorChar};
public byte[] GetData(string fileName, bool getReadTimeOnly, out long readTime)
{
if (!fileName.ToLowerInvariant().EndsWith(".config", StringComparison.Ordinal))
throw new Exception(SR.GetString(SR.Can_not_access_files_other_than_config));
byte [] buf;
if (File.Exists(fileName)) {
if (getReadTimeOnly) {
buf = new byte[0];
}
else {
buf = File.ReadAllBytes(fileName);
}
DateTime lastWrite = File.GetLastWriteTimeUtc(fileName);
readTime = (DateTime.UtcNow > lastWrite ? DateTime.UtcNow.Ticks : lastWrite.Ticks);
} else {
buf = new byte[0];
readTime = DateTime.UtcNow.Ticks;
}
return buf;
}
public void WriteData(string fileName, string templateFileName, byte[] data, ref long readTime)
{
if (!fileName.ToLowerInvariant().EndsWith(".config", StringComparison.Ordinal))
throw new Exception(SR.GetString(SR.Can_not_access_files_other_than_config));
bool fileExists = File.Exists(fileName);
FileInfo fileInfo = null;
FileAttributes fileAttributes = FileAttributes.Normal;
string tempFile = null;
Exception createStreamExcep = null;
FileStream tempFileStream = null;
long lastWriteTicks = 0;
long utcNowTicks = 0;
/////////////////////////////////////////////////////////////////////
// Step 1: If the file exists, then make sure it hasn't been written to since it was read
if (fileExists && File.GetLastWriteTimeUtc(fileName).Ticks > readTime) {
throw new Exception(SR.GetString(SR.File_changed_since_read, fileName));
}
/////////////////////////////////////////////////////////////////////
// Step 2: Get the security-descriptor and attributes of the file
if (fileExists) {
try {
fileInfo = new FileInfo(fileName);
fileAttributes = fileInfo.Attributes;
} catch { }
if (((int)(fileAttributes & (FileAttributes.ReadOnly | FileAttributes.Hidden))) != 0)
throw new Exception(SR.GetString(SR.File_is_read_only, fileName));
}
/////////////////////////////////////////////////////////////////////
// Step 3: Generate a temp file name. Make sure that the temp file doesn't exist
tempFile = fileName + "." + GetRandomFileExt() + ".tmp";
for (int iter = 0; File.Exists(tempFile); iter++) { // if it exists, then use a different random name
if (iter > 100) // don't try more than 100 times
throw new Exception(SR.GetString(SR.Unable_to_create_temp_file));
else
tempFile = fileName + "." + GetRandomFileExt() + ".tmp";
}
/////////////////////////////////////////////////////////////////////
// Step 4: Write the buffer to the temp file, and move it to the actual file
try {
tempFileStream = new FileStream(tempFile, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite, data.Length, FileOptions.WriteThrough);
tempFileStream.Write(data, 0, data.Length);
} catch (Exception e) {
createStreamExcep = e;
} finally {
if (tempFileStream != null)
tempFileStream.Close();
}
if (createStreamExcep != null) {
try {
File.Delete(tempFile);
} catch { }
throw createStreamExcep;
}
if (fileExists) {
try {
DuplicateFileAttributes(fileName, tempFile);
} catch { }
}
else if ( templateFileName != null ) {
try {
DuplicateTemplateAttributes(fileName, templateFileName);
} catch { }
}
/////////////////////////////////////////////////////////////////////
// Step 4: Move the temp filt to the actual file
if (!UnsafeNativeMethods.MoveFileEx(tempFile, fileName, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
try {
File.Delete(tempFile);
} catch { }
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
/////////////////////////////////////////////////////////////////////
// Step 5: Set the attributes of the file
if (fileExists) {
fileInfo = new FileInfo(fileName);
fileInfo.Attributes = fileAttributes;
}
/////////////////////////////////////////////////////////////////////
// Step 6: Record the current time as the read-time
lastWriteTicks = File.GetLastWriteTimeUtc(fileName).Ticks;
utcNowTicks = DateTime.UtcNow.Ticks;
readTime = (utcNowTicks > lastWriteTicks ? utcNowTicks : lastWriteTicks);
}
public string GetFilePaths(int webLevelAsInt, string path, string site, string locationSubPath)
{
WebLevel webLevel = (WebLevel) webLevelAsInt;
IConfigMapPath configMapPath = IISMapPath.GetInstance();
// Get the configuration paths and application information
string appSiteName, appSiteID;
VirtualPath appPath;
string configPath, locationConfigPath;
WebConfigurationHost.GetConfigPaths(configMapPath, webLevel, VirtualPath.CreateNonRelativeAllowNull(path), site, locationSubPath,
out appPath, out appSiteName, out appSiteID, out configPath, out locationConfigPath);
//
// Format of filePaths:
// appPath < appSiteName < appSiteID < configPath < locationConfigPath [< configPath < fileName]+
//
ArrayList filePaths = new ArrayList();
filePaths.Add(VirtualPath.GetVirtualPathString(appPath));
filePaths.Add(appSiteName);
filePaths.Add(appSiteID);
filePaths.Add(configPath);
filePaths.Add(locationConfigPath);
string dummySiteID;
VirtualPath virtualPath;
WebConfigurationHost.GetSiteIDAndVPathFromConfigPath(configPath, out dummySiteID, out virtualPath);
// pathmap for machine.config
filePaths.Add(WebConfigurationHost.MachineConfigPath);
filePaths.Add(HttpConfigurationSystem.MachineConfigurationFilePath);
// pathmap for root web.config
if (webLevel != WebLevel.Machine) {
filePaths.Add(WebConfigurationHost.RootWebConfigPath);
filePaths.Add(HttpConfigurationSystem.RootWebConfigurationFilePath);
// pathmap for other paths
for (VirtualPath currentVirtualPath = virtualPath; currentVirtualPath != null; currentVirtualPath = currentVirtualPath.Parent)
{
string currentConfigPath = WebConfigurationHost.GetConfigPathFromSiteIDAndVPath(appSiteID, currentVirtualPath);
string currentFilePath = configMapPath.MapPath(appSiteID, currentVirtualPath.VirtualPathString);
currentFilePath = System.IO.Path.Combine(currentFilePath, HttpConfigurationSystem.WebConfigFileName);
filePaths.Add(currentConfigPath);
filePaths.Add(currentFilePath);
}
}
// join into a single string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < filePaths.Count; i++) {
if (i > 0) {
sb.Append(FilePathsSeparatorChar);
}
string part = (string) filePaths[i];
sb.Append(part);
}
return sb.ToString();
}
public string DoEncryptOrDecrypt(bool doEncrypt, string xmlString, string protectionProviderName, string protectionProviderType, string[] paramKeys, string[] paramValues)
{
Type t = Type.GetType(protectionProviderType, true);
if (!typeof(ProtectedConfigurationProvider).IsAssignableFrom(t)) {
throw new Exception(SR.GetString(SR.WrongType_of_Protected_provider));
}
ProtectedConfigurationProvider provider = (ProtectedConfigurationProvider)Activator.CreateInstance(t);
NameValueCollection cloneParams = new NameValueCollection(paramKeys.Length);
XmlNode node;
for(int iter=0; iter<paramKeys.Length; iter++)
cloneParams.Add(paramKeys[iter], paramValues[iter]);
provider.Initialize(protectionProviderName, cloneParams);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
xmlDocument.LoadXml(xmlString);
if (doEncrypt) {
node = provider.Encrypt(xmlDocument.DocumentElement);
} else {
node = provider.Decrypt(xmlDocument.DocumentElement);
}
return node.OuterXml;
}
public void GetFileDetails(string name, out bool exists, out long size, out long createDate, out long lastWriteDate) {
if (!name.ToLowerInvariant().EndsWith(".config", StringComparison.Ordinal))
throw new Exception(SR.GetString(SR.Can_not_access_files_other_than_config));
UnsafeNativeMethods.WIN32_FILE_ATTRIBUTE_DATA data;
if (UnsafeNativeMethods.GetFileAttributesEx(name, UnsafeNativeMethods.GetFileExInfoStandard, out data) && (data.fileAttributes & (int)FileAttributes.Directory) == 0) {
exists = true;
size = (long)(uint)data.fileSizeHigh << 32 | (long)(uint)data.fileSizeLow;
createDate = (((long)data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow);
lastWriteDate = (((long)data.ftLastWriteTimeHigh) << 32) | ((long)data.ftLastWriteTimeLow);
} else {
exists = false;
size = 0;
createDate = 0;
lastWriteDate = 0;
}
}
private static string GetRandomFileExt() {
byte[] buf = new byte[2];
(new RNGCryptoServiceProvider()).GetBytes(buf);
return buf[1].ToString("X", CultureInfo.InvariantCulture) + buf[0].ToString("X", CultureInfo.InvariantCulture);
}
private void DuplicateFileAttributes(string oldFileName, string newFileName) {
#if !FEATURE_PAL // FEATURE_PAL does not enable access control
FileAttributes attributes;
DateTime creationTime;
// Copy File Attributes, ie. Hidden, Readonly, etc.
attributes = File.GetAttributes(oldFileName);
File.SetAttributes(newFileName, attributes);
// Copy Creation Time
creationTime = File.GetCreationTimeUtc(oldFileName);
File.SetCreationTimeUtc(newFileName, creationTime);
DuplicateTemplateAttributes( oldFileName, newFileName);
}
private void DuplicateTemplateAttributes(string oldFileName, string newFileName) {
FileSecurity fileSecurity;
// Copy Security information
// If we don't have the privelege to get the Audit information,
// then just persist the DACL
try {
fileSecurity = File.GetAccessControl(oldFileName,
AccessControlSections.Access |
AccessControlSections.Audit);
// Mark dirty, so effective for write
fileSecurity.SetAuditRuleProtection(fileSecurity.AreAuditRulesProtected, true);
} catch (UnauthorizedAccessException) {
fileSecurity = File.GetAccessControl(oldFileName,
AccessControlSections.Access);
}
// Mark dirty, so effective for write
fileSecurity.SetAccessRuleProtection(fileSecurity.AreAccessRulesProtected, true);
File.SetAccessControl(newFileName, fileSecurity);
#endif // !FEATURE_PAL
}
const int MOVEFILE_REPLACE_EXISTING = 0x00000001;
const int MOVEFILE_COPY_ALLOWED = 0x00000002;
const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004;
const int MOVEFILE_WRITE_THROUGH = 0x00000008;
}
}
| |
using System;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.IO;
using FluentMigrator.Builders.Execute;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Generators.SqlServer;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.SqlServer;
using FluentMigrator.Tests.Helpers;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Integration.Processors
{
[TestFixture]
[Category("Integration")]
public class SqlServerCeProcessorTests
{
public string DatabaseFilename { get; set; }
public SqlCeConnection Connection { get; set; }
public SqlServerCeProcessor Processor { get; set; }
[SetUp]
public void SetUp()
{
DatabaseFilename = "TestDatabase.sdf";
RecreateDatabase();
Connection = new SqlCeConnection(IntegrationTestOptions.SqlServerCe.ConnectionString);
Processor = new SqlServerCeProcessor(Connection, new SqlServerCeGenerator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerCeDbFactory());
Connection.Open();
Processor.BeginTransaction();
}
[TearDown]
public void TearDown()
{
Processor.CommitTransaction();
Processor.Dispose();
}
[Test]
public void CallingTableExistsReturnsTrueIfTableExists()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
Processor.TableExists(null, table.Name).ShouldBeTrue();
}
[Test]
public void CallingTableExistsReturnsFalseIfTableDoesNotExist()
{
Processor.TableExists(null, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsTrueIfColumnExists()
{
using (var table = new SqlServerCeTestTable(Processor, "\"id\" int"))
Processor.ColumnExists(null, table.Name, "id").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsReturnsTrueIfConstraintExist()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithUniqueConstraintOn("id");
Processor.ConstraintExists(null, table.Name, "UC_id").ShouldBeTrue();
}
}
[Test]
public void CallingIndexExistsReturnsTrueIfIndexExist()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithIndexOn("id");
Processor.IndexExists(null, table.Name, "UI_id").ShouldBeTrue();
}
}
[Test]
public void CallingColumnExistsReturnsFalseIfTableDoesNotExist()
{
Processor.ColumnExists(null, "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsFalseIfColumnDoesNotExist()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
Processor.ColumnExists(null, table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingConstraintExistsReturnsFalseIfConstraintDoesNotExist()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithUniqueConstraintOn("id");
Processor.ConstraintExists(null, table.Name, "DoesNotExist").ShouldBeFalse();
}
}
[Test]
public void CallingIndexExistsReturnsFalseIfIndexDoesNotExist()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithIndexOn("id");
Processor.IndexExists(null, table.Name, "DoesNotExist").ShouldBeFalse();
}
}
[Test]
public void CallingTableExistsReturnsTrueIfTableExistsWithSchema()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
Processor.TableExists("NOTUSED", table.Name).ShouldBeTrue();
}
[Test]
public void CallingTableExistsReturnsFalseIfTableDoesNotExistWithSchema()
{
Processor.TableExists("NOTUSED", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsTrueIfColumnExistsWithSchema()
{
using (var table = new SqlServerCeTestTable(Processor, "\"id\" int"))
Processor.ColumnExists("NOTUSED", table.Name, "id").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsReturnsTrueIfConstraintExistWithSchema()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithUniqueConstraintOn("id");
Processor.ConstraintExists("NOTUSED", table.Name, "UC_id").ShouldBeTrue();
}
}
[Test]
public void CallingIndexExistsReturnsTrueIfIndexExistWithSchema()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithIndexOn("id");
Processor.IndexExists("NOTUSED", table.Name, "UI_id").ShouldBeTrue();
}
}
[Test]
public void CallingColumnExistsReturnsFalseIfTableDoesNotExistWithSchema()
{
Processor.ColumnExists("NOTUSED", "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsFalseIfColumnDoesNotExistWithSchema()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
Processor.ColumnExists("NOTUSED", table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingConstraintExistsReturnsFalseIfConstraintDoesNotExistWithSchema()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithUniqueConstraintOn("id");
Processor.ConstraintExists("NotUsed", table.Name, "DoesNotExist").ShouldBeFalse();
}
}
[Test]
public void CallingIndexExistsReturnsFalseIfIndexDoesNotExistWithSchema()
{
using (var table = new SqlServerCeTestTable(Processor, "id int"))
{
table.WithIndexOn("id");
Processor.IndexExists("NOTUSED", table.Name, "DoesNotExist").ShouldBeFalse();
}
}
[Test]
public void CallingSchemaExistsReturnsTrueAllways()
{
Processor.SchemaExists("NOTUSED").ShouldBeTrue();
}
[Test]
public void CallingExecuteWithMultilineSqlShouldExecuteInBatches()
{
Processor.Execute("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL);" + Environment.NewLine +
"GO"+ Environment.NewLine +
"INSERT INTO TestTable1 VALUES('abc', 1);");
Processor.TableExists("NOTUSED", "TestTable1");
var dataset = Processor.ReadTableData("NOTUSED", "TestTable1");
dataset.Tables[0].Rows.Count.ShouldBe(1);
}
[Test]
public void CallingExecuteWithMultilineSqlAsLowercaseShouldExecuteInBatches()
{
Processor.Execute("create table [TestTable1] ([TestColumn1] nvarchar(255) not null, [TestColumn2] int not null);" + Environment.NewLine +
"go" + Environment.NewLine +
"insert into testtable1 values('abc', 1);");
Processor.TableExists("NOTUSED", "TestTable1");
var dataset = Processor.ReadTableData("NOTUSED", "TestTable1");
dataset.Tables[0].Rows.Count.ShouldBe(1);
}
[Test]
public void CallingExecuteWithMultilineSqlWithNoTrailingSemicolonShouldExecuteInBatches()
{
Processor.Execute("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL);" + Environment.NewLine +
"GO" + Environment.NewLine +
"INSERT INTO TestTable1 VALUES('abc', 1)");
Processor.TableExists("NOTUSED", "TestTable1");
var dataset = Processor.ReadTableData("NOTUSED", "TestTable1");
dataset.Tables[0].Rows.Count.ShouldBe(1);
}
private void RecreateDatabase()
{
if (File.Exists(DatabaseFilename))
{
File.Delete(DatabaseFilename);
}
new SqlCeEngine(IntegrationTestOptions.SqlServerCe.ConnectionString).CreateDatabase();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
//using Common.Logging;
using SharpBrake.Serialization;
namespace SharpBrake
{
/// <summary>
/// Responsible for building the notice that is sent to Airbrake.
/// </summary>
public class AirbrakeNoticeBuilder
{
private readonly AirbrakeConfiguration configuration;
//private readonly ILog log;
private AirbrakeServerEnvironment environment;
private AirbrakeNotifier notifier;
/// <summary>
/// Initializes a new instance of the <see cref="AirbrakeNoticeBuilder"/> class.
/// </summary>
public AirbrakeNoticeBuilder()
: this(new AirbrakeConfiguration())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AirbrakeNoticeBuilder"/> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
public AirbrakeNoticeBuilder(AirbrakeConfiguration configuration)
{
if (configuration == null)
throw new ArgumentNullException("configuration");
this.configuration = configuration;
//this.log = LogManager.GetLogger(GetType());
}
/// <summary>
/// Gets the configuration.
/// </summary>
public AirbrakeConfiguration Configuration
{
get { return this.configuration; }
}
/// <summary>
/// Gets the notifier.
/// </summary>
public AirbrakeNotifier Notifier
{
get
{
return this.notifier ?? (this.notifier = new AirbrakeNotifier
{
Name = "SharpBrake",
Url = "https://github.com/asbjornu/SharpBrake",
Version = typeof(AirbrakeNotice).Assembly.GetName().Version.ToString()
});
}
}
/// <summary>
/// Gets the server environment.
/// </summary>
public AirbrakeServerEnvironment ServerEnvironment
{
get
{
string env = this.configuration.EnvironmentName;
return this.environment ?? (this.environment = new AirbrakeServerEnvironment(env)
{
ProjectRoot = this.configuration.ProjectRoot,
AppVersion = this.configuration.AppVersion,
});
}
}
/// <summary>
/// Creates a <see cref="AirbrakeError"/> from the the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
/// <returns>
/// A <see cref="AirbrakeError"/>, created from the the specified exception.
/// </returns>
public AirbrakeError ErrorFromException(Exception exception)
{
if (exception == null)
throw new ArgumentNullException("exception");
//this.log.Debug(f => f("{0}.Notice({1})", GetType(), exception.GetType()), exception);
MethodBase catchingMethod;
var backtrace = BuildBacktrace(exception, out catchingMethod);
var error = Activator.CreateInstance<AirbrakeError>();
error.CatchingMethod = catchingMethod;
error.Class = exception.GetType().FullName;
error.Message = exception.GetType().Name + ": " + exception.Message;
error.Backtrace = backtrace;
return error;
}
/// <summary>
/// Creates a <see cref="AirbrakeNotice"/> from the the specified error.
/// </summary>
/// <param name="error">The error.</param>
/// <returns></returns>
public AirbrakeNotice Notice(AirbrakeError error)
{
//this.log.Debug(f => f("{0}.Notice({1})", GetType(), error));
var notice = new AirbrakeNotice
{
ApiKey = Configuration.ApiKey,
Error = error,
Notifier = Notifier,
ServerEnvironment = ServerEnvironment,
};
MethodBase catchingMethod = (error != null)
? error.CatchingMethod
: null;
AddContextualInformation(notice, catchingMethod);
return notice;
}
/// <summary>
/// Creates a <see cref="AirbrakeNotice"/> from the the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
/// <returns>
/// A <see cref="AirbrakeNotice"/>, created from the the specified exception.
/// </returns>
public AirbrakeNotice Notice(Exception exception)
{
if (exception == null)
throw new ArgumentNullException("exception");
//this.log.Info(f => f("{0}.Notice({1})", GetType(), exception.GetType()), exception);
AirbrakeError error = ErrorFromException(exception);
return Notice(error);
}
private void AddContextualInformation(AirbrakeNotice notice, MethodBase catchingMethod)
{
var component = String.Empty;
var action = String.Empty;
if ((notice.Error != null) && (notice.Error.Backtrace != null) && (notice.Error.Backtrace.Length > 0))
{
// TODO: We should perhaps check whether the topmost back trace is in fact a Controller+Action by performing some sort of heuristic (searching for "Controller" etc.). @asbjornu
var backtrace = notice.Error.Backtrace[0];
action = backtrace.Method;
component = backtrace.File;
}
else if (catchingMethod != null)
{
action = catchingMethod.Name;
if (catchingMethod.DeclaringType != null)
component = catchingMethod.DeclaringType.FullName;
}
var request = new AirbrakeRequest("http://example.com/", component)
{
Action = action
};
var cgiData = new List<AirbrakeVar>
{
new AirbrakeVar("Environment.MachineName", Environment.MachineName),
new AirbrakeVar("Environment.OSversion", Environment.OSVersion),
new AirbrakeVar("Environment.Version", Environment.Version)
};
var parameters = new List<AirbrakeVar>();
var session = new List<AirbrakeVar>();
var httpContext = HttpContext.Current;
if (httpContext != null)
{
var httpRequest = httpContext.Request;
request.Url = httpRequest.Url.ToString();
cgiData.AddRange(BuildVars(httpRequest.Headers));
cgiData.AddRange(BuildVars(httpRequest.Cookies));
parameters.AddRange(BuildVars(httpRequest.Params));
session.AddRange(BuildVars(httpContext.Session));
if (httpContext.User != null)
cgiData.Add(new AirbrakeVar("User.Identity.Name", httpContext.User.Identity.Name));
var browser = httpRequest.Browser;
if (browser != null)
{
cgiData.Add(new AirbrakeVar("Browser.Browser", browser.Browser));
cgiData.Add(new AirbrakeVar("Browser.ClrVersion", browser.ClrVersion));
cgiData.Add(new AirbrakeVar("Browser.Cookies", browser.Cookies));
cgiData.Add(new AirbrakeVar("Browser.Crawler", browser.Crawler));
cgiData.Add(new AirbrakeVar("Browser.EcmaScriptVersion", browser.EcmaScriptVersion));
cgiData.Add(new AirbrakeVar("Browser.JavaApplets", browser.JavaApplets));
cgiData.Add(new AirbrakeVar("Browser.MajorVersion", browser.MajorVersion));
cgiData.Add(new AirbrakeVar("Browser.MinorVersion", browser.MinorVersion));
cgiData.Add(new AirbrakeVar("Browser.Platform", browser.Platform));
cgiData.Add(new AirbrakeVar("Browser.W3CDomVersion", browser.W3CDomVersion));
}
}
request.CgiData = cgiData.ToArray();
request.Params = parameters.Count > 0 ? parameters.ToArray() : null;
request.Session = session.Count > 0 ? session.ToArray() : null;
notice.Request = request;
}
private AirbrakeTraceLine[] BuildBacktrace(Exception exception, out MethodBase catchingMethod)
{
Assembly assembly = Assembly.GetExecutingAssembly();
if (assembly.EntryPoint == null)
assembly = Assembly.GetCallingAssembly();
if (assembly.EntryPoint == null)
assembly = Assembly.GetEntryAssembly();
catchingMethod = assembly == null
? null
: assembly.EntryPoint;
List<AirbrakeTraceLine> lines = new List<AirbrakeTraceLine>();
var stackTrace = new StackTrace(exception);
StackFrame[] frames = stackTrace.GetFrames();
if (frames == null || frames.Length == 0)
{
// Airbrake requires that at least one line is present in the XML.
AirbrakeTraceLine line = new AirbrakeTraceLine("none", 0);
lines.Add(line);
return lines.ToArray();
}
foreach (StackFrame frame in frames)
{
MethodBase method = frame.GetMethod();
catchingMethod = method;
int lineNumber = frame.GetFileLineNumber();
if (lineNumber == 0)
{
//this.log.Debug(f => f("No line number found in {0}, using IL offset instead.", method));
lineNumber = frame.GetILOffset();
}
if (lineNumber == -1)
{
lineNumber = frame.GetNativeOffset();
}
// AirBrake doesn't allow for negative line numbers which can happen with lambdas
if (lineNumber < 0)
{
lineNumber = 0;
}
string file = frame.GetFileName();
if (String.IsNullOrEmpty(file))
{
// ReSharper disable ConditionIsAlwaysTrueOrFalse
file = method.ReflectedType != null
? method.ReflectedType.FullName
: "(unknown)";
// ReSharper restore ConditionIsAlwaysTrueOrFalse
}
AirbrakeTraceLine line = new AirbrakeTraceLine(file, lineNumber)
{
Method = method.Name
};
lines.Add(line);
}
return lines.ToArray();
}
private IEnumerable<AirbrakeVar> BuildVars(HttpCookieCollection cookies)
{
if ((cookies == null) || (cookies.Count == 0))
{
// this.log.Debug(f => f("No cookies to build vars from."));
return new AirbrakeVar[0];
}
List<AirbrakeVar> airBrakeVars = new List<AirbrakeVar>();
foreach (String key in cookies.Keys)
{
HttpCookie cookie = cookies[key];
if (cookie == null || String.IsNullOrEmpty(cookie.Value)) { continue; }
airBrakeVars.Add(new AirbrakeVar(key, cookie.Value));
}
return airBrakeVars;
}
private IEnumerable<AirbrakeVar> BuildVars(NameValueCollection formData)
{
if ((formData == null) || (formData.Count == 0))
{
//this.log.Debug(f => f("No form data to build vars from."));
return new AirbrakeVar[0];
}
List<AirbrakeVar> airBrakeVars = new List<AirbrakeVar>();
foreach (string key in formData.AllKeys)
{
String var = formData[key];
if (!String.IsNullOrEmpty(key))
{
airBrakeVars.Add(new AirbrakeVar(key, var));
}
}
return airBrakeVars;
}
private IEnumerable<AirbrakeVar> BuildVars(HttpSessionState session)
{
if ((session == null) || (session.Count == 0))
{
//this.log.Debug(f => f("No session to build vars from."));
return new AirbrakeVar[0];
}
List<AirbrakeVar> airBrakeVars = new List<AirbrakeVar>();
foreach (string key in session.Keys)
{
String var = session[key] as String;
if (!String.IsNullOrEmpty(var))
{
airBrakeVars.Add(new AirbrakeVar(key, var));
}
}
return airBrakeVars;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.DDF
{
using System;
using System.Collections;
/// <summary>
/// Provides a list of all known escher properties including the description and
/// type.
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
internal class EscherProperties
{
#region Property constants
public const short TRANSFORM__ROTATION = 4;
public const short PROTECTION__LOCKROTATION = 119;
public const short PROTECTION__LOCKASPECTRATIO = 120;
public const short PROTECTION__LOCKPOSITION = 121;
public const short PROTECTION__LOCKAGAINSTSELECT = 122;
public const short PROTECTION__LOCKCROPPING = 123;
public const short PROTECTION__LOCKVERTICES = 124;
public const short PROTECTION__LOCKTEXT = 125;
public const short PROTECTION__LOCKADJUSTHANDLES = 126;
public const short PROTECTION__LOCKAGAINSTGROUPING = 127;
public const short TEXT__TEXTID = 128;
public const short TEXT__TEXTLEFT = 129;
public const short TEXT__TEXTTOP = 130;
public const short TEXT__TEXTRIGHT = 131;
public const short TEXT__TEXTBOTTOM = 132;
public const short TEXT__WRAPTEXT = 133;
public const short TEXT__SCALETEXT = 134;
public const short TEXT__ANCHORTEXT = 135;
public const short TEXT__TEXTFLOW = 136;
public const short TEXT__FONTROTATION = 137;
public const short TEXT__IDOFNEXTSHAPE = 138;
public const short TEXT__BIDIR = 139;
public const short TEXT__SINGLECLICKSELECTS = 187;
public const short TEXT__USEHOSTMARGINS = 188;
public const short TEXT__ROTATETEXTWITHSHAPE = 189;
public const short TEXT__SIZESHAPETOFITTEXT = 190;
public const short TEXT__SIZE_TEXT_TO_FIT_SHAPE = 191;
public const short GEOTEXT__UNICODE = 192;
public const short GEOTEXT__RTFTEXT = 193;
public const short GEOTEXT__ALIGNMENTONCURVE = 194;
public const short GEOTEXT__DEFAULTPOINTSIZE = 195;
public const short GEOTEXT__TEXTSPACING = 196;
public const short GEOTEXT__FONTFAMILYNAME = 197;
public const short GEOTEXT__REVERSEROWORDER = 240;
public const short GEOTEXT__HASTEXTEFFECT = 241;
public const short GEOTEXT__ROTATECHARACTERS = 242;
public const short GEOTEXT__KERNCHARACTERS = 243;
public const short GEOTEXT__TIGHTORTRACK = 244;
public const short GEOTEXT__STRETCHTOFITSHAPE = 245;
public const short GEOTEXT__CHARBOUNDINGBOX = 246;
public const short GEOTEXT__SCALETEXTONPATH = 247;
public const short GEOTEXT__STRETCHCHARHEIGHT = 248;
public const short GEOTEXT__NOMEASUREALONGPATH = 249;
public const short GEOTEXT__BOLDFONT = 250;
public const short GEOTEXT__ITALICFONT = 251;
public const short GEOTEXT__UNDERLINEFONT = 252;
public const short GEOTEXT__SHADOWFONT = 253;
public const short GEOTEXT__SMALLCAPSFONT = 254;
public const short GEOTEXT__STRIKETHROUGHFONT = 255;
public const short BLIP__CROPFROMTOP = 256;
public const short BLIP__CROPFROMBOTTOM = 257;
public const short BLIP__CROPFROMLEFT = 258;
public const short BLIP__CROPFROMRIGHT = 259;
public const short BLIP__BLIPTODISPLAY = 260;
public const short BLIP__BLIPFILENAME = 261;
public const short BLIP__BLIPFLAGS = 262;
public const short BLIP__TRANSPARENTCOLOR = 263;
public const short BLIP__CONTRASTSetTING = 264;
public const short BLIP__BRIGHTNESSSetTING = 265;
public const short BLIP__GAMMA = 266;
public const short BLIP__PICTUREID = 267;
public const short BLIP__DOUBLEMOD = 268;
public const short BLIP__PICTUREFillMOD = 269;
public const short BLIP__PICTURELINE = 270;
public const short BLIP__PRINTBLIP = 271;
public const short BLIP__PRINTBLIPFILENAME = 272;
public const short BLIP__PRINTFLAGS = 273;
public const short BLIP__NOHITTESTPICTURE = 316;
public const short BLIP__PICTUREGRAY = 317;
public const short BLIP__PICTUREBILEVEL = 318;
public const short BLIP__PICTUREACTIVE = 319;
public const short GEOMETRY__LEFT = 320;
public const short GEOMETRY__TOP = 321;
public const short GEOMETRY__RIGHT = 322;
public const short GEOMETRY__BOTTOM = 323;
public const short GEOMETRY__SHAPEPATH = 324;
public const short GEOMETRY__VERTICES = 325;
public const short GEOMETRY__SEGMENTINFO = 326;
public const short GEOMETRY__ADJUSTVALUE = 327;
public const short GEOMETRY__ADJUST2VALUE = 328;
public const short GEOMETRY__ADJUST3VALUE = 329;
public const short GEOMETRY__ADJUST4VALUE = 330;
public const short GEOMETRY__ADJUST5VALUE = 331;
public const short GEOMETRY__ADJUST6VALUE = 332;
public const short GEOMETRY__ADJUST7VALUE = 333;
public const short GEOMETRY__ADJUST8VALUE = 334;
public const short GEOMETRY__ADJUST9VALUE = 335;
public const short GEOMETRY__ADJUST10VALUE = 336;
public const short GEOMETRY__SHADOWok = 378;
public const short GEOMETRY__3DOK = 379;
public const short GEOMETRY__LINEOK = 380;
public const short GEOMETRY__GEOTEXTOK = 381;
public const short GEOMETRY__FillSHADESHAPEOK = 382;
public const short GEOMETRY__FillOK = 383;
public const short Fill__FillTYPE = 384;
public const short Fill__FillCOLOR = 385;
public const short Fill__FillOPACITY = 386;
public const short Fill__FillBACKCOLOR = 387;
public const short Fill__BACKOPACITY = 388;
public const short Fill__CRMOD = 389;
public const short Fill__PATTERNTEXTURE = 390;
public const short Fill__BLIPFILENAME = 391;
public const short Fill__BLIPFLAGS = 392;
public const short Fill__WIDTH = 393;
public const short Fill__HEIGHT = 394;
public const short Fill__ANGLE = 395;
public const short Fill__FOCUS = 396;
public const short Fill__TOLEFT = 397;
public const short Fill__TOTOP = 398;
public const short Fill__TORIGHT = 399;
public const short Fill__TOBOTTOM = 400;
public const short Fill__RECTLEFT = 401;
public const short Fill__RECTTOP = 402;
public const short Fill__RECTRIGHT = 403;
public const short Fill__RECTBOTTOM = 404;
public const short Fill__DZTYPE = 405;
public const short Fill__SHADEPRESet = 406;
public const short Fill__SHADECOLORS = 407;
public const short Fill__ORIGINX = 408;
public const short Fill__ORIGINY = 409;
public const short Fill__SHAPEORIGINX = 410;
public const short Fill__SHAPEORIGINY = 411;
public const short Fill__SHADETYPE = 412;
public const short Fill__FillED = 443;
public const short Fill__HITTESTFill = 444;
public const short Fill__SHAPE = 445;
public const short Fill__USERECT = 446;
public const short Fill__NOFillHITTEST = 447;
public const short LINESTYLE__COLOR = 448;
public const short LINESTYLE__OPACITY = 449;
public const short LINESTYLE__BACKCOLOR = 450;
public const short LINESTYLE__CRMOD = 451;
public const short LINESTYLE__LINETYPE = 452;
public const short LINESTYLE__FillBLIP = 453;
public const short LINESTYLE__FillBLIPNAME = 454;
public const short LINESTYLE__FillBLIPFLAGS = 455;
public const short LINESTYLE__FillWIDTH = 456;
public const short LINESTYLE__FillHEIGHT = 457;
public const short LINESTYLE__FillDZTYPE = 458;
public const short LINESTYLE__LINEWIDTH = 459;
public const short LINESTYLE__LINEMITERLIMIT = 460;
public const short LINESTYLE__LINESTYLE = 461;
public const short LINESTYLE__LINEDASHING = 462;
public const short LINESTYLE__LINEDASHSTYLE = 463;
public const short LINESTYLE__LINESTARTARROWHEAD = 464;
public const short LINESTYLE__LINEENDARROWHEAD = 465;
public const short LINESTYLE__LINESTARTARROWWIDTH = 466;
public const short LINESTYLE__LINEESTARTARROWLength = 467;
public const short LINESTYLE__LINEENDARROWWIDTH = 468;
public const short LINESTYLE__LINEENDARROWLength = 469;
public const short LINESTYLE__LINEJOINSTYLE = 470;
public const short LINESTYLE__LINEENDCAPSTYLE = 471;
public const short LINESTYLE__ARROWHEADSOK = 507;
public const short LINESTYLE__ANYLINE = 508;
public const short LINESTYLE__HITLINETEST = 509;
public const short LINESTYLE__LINEFillSHAPE = 510;
public const short LINESTYLE__NOLINEDRAWDASH = 511;
public const short SHADOWSTYLE__TYPE = 512;
public const short SHADOWSTYLE__COLOR = 513;
public const short SHADOWSTYLE__HIGHLIGHT = 514;
public const short SHADOWSTYLE__CRMOD = 515;
public const short SHADOWSTYLE__OPACITY = 516;
public const short SHADOWSTYLE__OFFSetX = 517;
public const short SHADOWSTYLE__OFFSetY = 518;
public const short SHADOWSTYLE__SECONDOFFSetX = 519;
public const short SHADOWSTYLE__SECONDOFFSetY = 520;
public const short SHADOWSTYLE__SCALEXTOX = 521;
public const short SHADOWSTYLE__SCALEYTOX = 522;
public const short SHADOWSTYLE__SCALEXTOY = 523;
public const short SHADOWSTYLE__SCALEYTOY = 524;
public const short SHADOWSTYLE__PERSPECTIVEX = 525;
public const short SHADOWSTYLE__PERSPECTIVEY = 526;
public const short SHADOWSTYLE__WEIGHT = 527;
public const short SHADOWSTYLE__ORIGINX = 528;
public const short SHADOWSTYLE__ORIGINY = 529;
public const short SHADOWSTYLE__SHADOW = 574;
public const short SHADOWSTYLE__SHADOWOBSURED = 575;
public const short PERSPECTIVE__TYPE = 576;
public const short PERSPECTIVE__OFFSetX = 577;
public const short PERSPECTIVE__OFFSetY = 578;
public const short PERSPECTIVE__SCALEXTOX = 579;
public const short PERSPECTIVE__SCALEYTOX = 580;
public const short PERSPECTIVE__SCALEXTOY = 581;
public const short PERSPECTIVE__SCALEYTOY = 582;
public const short PERSPECTIVE__PERSPECTIVEX = 583;
public const short PERSPECTIVE__PERSPECTIVEY = 584;
public const short PERSPECTIVE__WEIGHT = 585;
public const short PERSPECTIVE__ORIGINX = 586;
public const short PERSPECTIVE__ORIGINY = 587;
public const short PERSPECTIVE__PERSPECTIVEON = 639;
public const short THREED__SPECULARAMOUNT = 640;
public const short THREED__DIFFUSEAMOUNT = 661;
public const short THREED__SHININESS = 662;
public const short THREED__EDGetHICKNESS = 663;
public const short THREED__EXTRUDEFORWARD = 664;
public const short THREED__EXTRUDEBACKWARD = 665;
public const short THREED__EXTRUDEPLANE = 666;
public const short THREED__EXTRUSIONCOLOR = 667;
public const short THREED__CRMOD = 648;
public const short THREED__3DEFFECT = 700;
public const short THREED__METALLIC = 701;
public const short THREED__USEEXTRUSIONCOLOR = 702;
public const short THREED__LIGHTFACE = 703;
public const short THREEDSTYLE__YROTATIONANGLE = 704;
public const short THREEDSTYLE__XROTATIONANGLE = 705;
public const short THREEDSTYLE__ROTATIONAXISX = 706;
public const short THREEDSTYLE__ROTATIONAXISY = 707;
public const short THREEDSTYLE__ROTATIONAXISZ = 708;
public const short THREEDSTYLE__ROTATIONANGLE = 709;
public const short THREEDSTYLE__ROTATIONCENTERX = 710;
public const short THREEDSTYLE__ROTATIONCENTERY = 711;
public const short THREEDSTYLE__ROTATIONCENTERZ = 712;
public const short THREEDSTYLE__RENDERMODE = 713;
public const short THREEDSTYLE__TOLERANCE = 714;
public const short THREEDSTYLE__XVIEWPOINT = 715;
public const short THREEDSTYLE__YVIEWPOINT = 716;
public const short THREEDSTYLE__ZVIEWPOINT = 717;
public const short THREEDSTYLE__ORIGINX = 718;
public const short THREEDSTYLE__ORIGINY = 719;
public const short THREEDSTYLE__SKEWANGLE = 720;
public const short THREEDSTYLE__SKEWAMOUNT = 721;
public const short THREEDSTYLE__AMBIENTINTENSITY = 722;
public const short THREEDSTYLE__KEYX = 723;
public const short THREEDSTYLE__KEYY = 724;
public const short THREEDSTYLE__KEYZ = 725;
public const short THREEDSTYLE__KEYINTENSITY = 726;
public const short THREEDSTYLE__FillX = 727;
public const short THREEDSTYLE__FillY = 728;
public const short THREEDSTYLE__FillZ = 729;
public const short THREEDSTYLE__FillINTENSITY = 730;
public const short THREEDSTYLE__CONSTRAINROTATION = 763;
public const short THREEDSTYLE__ROTATIONCENTERAUTO = 764;
public const short THREEDSTYLE__PARALLEL = 765;
public const short THREEDSTYLE__KEYHARSH = 766;
public const short THREEDSTYLE__FillHARSH = 767;
public const short SHAPE__MASTER = 769;
public const short SHAPE__CONNECTORSTYLE = 771;
public const short SHAPE__BLACKANDWHITESetTINGS = 772;
public const short SHAPE__WMODEPUREBW = 773;
public const short SHAPE__WMODEBW = 774;
public const short SHAPE__OLEICON = 826;
public const short SHAPE__PREFERRELATIVERESIZE = 827;
public const short SHAPE__LOCKSHAPETYPE = 828;
public const short SHAPE__DELETEATTACHEDOBJECT = 830;
public const short SHAPE__BACKGROUNDSHAPE = 831;
public const short CALLOUT__CALLOUTTYPE = 832;
public const short CALLOUT__XYCALLOUTGAP = 833;
public const short CALLOUT__CALLOUTANGLE = 834;
public const short CALLOUT__CALLOUTDROPTYPE = 835;
public const short CALLOUT__CALLOUTDROPSPECIFIED = 836;
public const short CALLOUT__CALLOUTLengthSPECIFIED = 837;
public const short CALLOUT__ISCALLOUT = 889;
public const short CALLOUT__CALLOUTACCENTBAR = 890;
public const short CALLOUT__CALLOUTTEXTBORDER = 891;
public const short CALLOUT__CALLOUTMINUSX = 892;
public const short CALLOUT__CALLOUTMINUSY = 893;
public const short CALLOUT__DROPAUTO = 894;
public const short CALLOUT__LengthSPECIFIED = 895;
public const short GROUPSHAPE__SHAPENAME = 0x0380;
public const short GROUPSHAPE__DESCRIPTION = 0x0381;
public const short GROUPSHAPE__HYPERLINK = 0x0382;
public const short GROUPSHAPE__WRAPPOLYGONVERTICES = 0x0383;
public const short GROUPSHAPE__WRAPDISTLEFT = 0x0384;
public const short GROUPSHAPE__WRAPDISTTOP = 0x0385;
public const short GROUPSHAPE__WRAPDISTRIGHT = 0x0386;
public const short GROUPSHAPE__WRAPDISTBOTTOM = 0x0387;
public const short GROUPSHAPE__REGROUPID = 0x0388;
public const short GROUPSHAPE__UNUSED906 = 0x038A;
public const short GROUPSHAPE__TOOLTIP = 0x038D;
public const short GROUPSHAPE__SCRIPT = 0x038E;
public const short GROUPSHAPE__POSH = 0x038F;
public const short GROUPSHAPE__POSRELH = 0x0390;
public const short GROUPSHAPE__POSV = 0x0391;
public const short GROUPSHAPE__POSRELV = 0x0392;
public const short GROUPSHAPE__HR_PCT = 0x0393;
public const short GROUPSHAPE__HR_ALIGN = 0x0394;
public const short GROUPSHAPE__HR_HEIGHT = 0x0395;
public const short GROUPSHAPE__HR_WIDTH = 0x0396;
public const short GROUPSHAPE__SCRIPTEXT = 0x0397;
public const short GROUPSHAPE__SCRIPTLANG = 0x0398;
public const short GROUPSHAPE__BORDERTOPCOLOR = 0x039B;
public const short GROUPSHAPE__BORDERLEFTCOLOR = 0x039C;
public const short GROUPSHAPE__BORDERBOTTOMCOLOR = 0x039D;
public const short GROUPSHAPE__BORDERRIGHTCOLOR = 0x039E;
public const short GROUPSHAPE__TABLEPROPERTIES = 0x039F;
public const short GROUPSHAPE__TABLEROWPROPERTIES = 0x03A0;
public const short GROUPSHAPE__WEBBOT = 0x03A5;
public const short GROUPSHAPE__METROBLOB = 0x03A9;
public const short GROUPSHAPE__ZORDER = 0x03AA;
public const short GROUPSHAPE__FLAGS = 0x03BF;
public const short GROUPSHAPE__EDITEDWRAP = 953;
public const short GROUPSHAPE__BEHINDDOCUMENT = 954;
public const short GROUPSHAPE__ONDBLCLICKNOTIFY = 955;
public const short GROUPSHAPE__ISBUTTON = 956;
public const short GROUPSHAPE__1DADJUSTMENT = 957;
public const short GROUPSHAPE__HIDDEN = 958;
public const short GROUPSHAPE__PRINT = 959;
#endregion
private static Hashtable properties;
/// <summary>
/// Inits the props.
/// </summary>
private static void InitProps()
{
if (properties == null)
{
properties = new Hashtable();
AddProp(TRANSFORM__ROTATION, GetData("transform.rotation"));
AddProp(PROTECTION__LOCKROTATION, GetData("protection.lockrotation"));
AddProp(PROTECTION__LOCKASPECTRATIO, GetData("protection.lockaspectratio"));
AddProp(PROTECTION__LOCKPOSITION, GetData("protection.lockposition"));
AddProp(PROTECTION__LOCKAGAINSTSELECT, GetData("protection.lockagainstselect"));
AddProp(PROTECTION__LOCKCROPPING, GetData("protection.lockcropping"));
AddProp(PROTECTION__LOCKVERTICES, GetData("protection.lockvertices"));
AddProp(PROTECTION__LOCKTEXT, GetData("protection.locktext"));
AddProp(PROTECTION__LOCKADJUSTHANDLES, GetData("protection.lockadjusthandles"));
AddProp(PROTECTION__LOCKAGAINSTGROUPING, GetData("protection.lockagainstgrouping", EscherPropertyMetaData.TYPE_bool));
AddProp(TEXT__TEXTID, GetData("text.textid"));
AddProp(TEXT__TEXTLEFT, GetData("text.textleft"));
AddProp(TEXT__TEXTTOP, GetData("text.texttop"));
AddProp(TEXT__TEXTRIGHT, GetData("text.textright"));
AddProp(TEXT__TEXTBOTTOM, GetData("text.textbottom"));
AddProp(TEXT__WRAPTEXT, GetData("text.wraptext"));
AddProp(TEXT__SCALETEXT, GetData("text.scaletext"));
AddProp(TEXT__ANCHORTEXT, GetData("text.anchortext"));
AddProp(TEXT__TEXTFLOW, GetData("text.textflow"));
AddProp(TEXT__FONTROTATION, GetData("text.fontrotation"));
AddProp(TEXT__IDOFNEXTSHAPE, GetData("text.idofnextshape"));
AddProp(TEXT__BIDIR, GetData("text.bidir"));
AddProp(TEXT__SINGLECLICKSELECTS, GetData("text.singleclickselects"));
AddProp(TEXT__USEHOSTMARGINS, GetData("text.usehostmargins"));
AddProp(TEXT__ROTATETEXTWITHSHAPE, GetData("text.rotatetextwithshape"));
AddProp(TEXT__SIZESHAPETOFITTEXT, GetData("text.sizeshapetofittext"));
AddProp(TEXT__SIZE_TEXT_TO_FIT_SHAPE, GetData("text.sizetexttofitshape", EscherPropertyMetaData.TYPE_bool));
AddProp(GEOTEXT__UNICODE, GetData("geotext.unicode"));
AddProp(GEOTEXT__RTFTEXT, GetData("geotext.rtftext"));
AddProp(GEOTEXT__ALIGNMENTONCURVE, GetData("geotext.alignmentoncurve"));
AddProp(GEOTEXT__DEFAULTPOINTSIZE, GetData("geotext.defaultpointsize"));
AddProp(GEOTEXT__TEXTSPACING, GetData("geotext.textspacing"));
AddProp(GEOTEXT__FONTFAMILYNAME, GetData("geotext.fontfamilyname"));
AddProp(GEOTEXT__REVERSEROWORDER, GetData("geotext.reverseroworder"));
AddProp(GEOTEXT__HASTEXTEFFECT, GetData("geotext.hastexteffect"));
AddProp(GEOTEXT__ROTATECHARACTERS, GetData("geotext.rotatecharacters"));
AddProp(GEOTEXT__KERNCHARACTERS, GetData("geotext.kerncharacters"));
AddProp(GEOTEXT__TIGHTORTRACK, GetData("geotext.tightortrack"));
AddProp(GEOTEXT__STRETCHTOFITSHAPE, GetData("geotext.stretchtofitshape"));
AddProp(GEOTEXT__CHARBOUNDINGBOX, GetData("geotext.charboundingbox"));
AddProp(GEOTEXT__SCALETEXTONPATH, GetData("geotext.scaletextonpath"));
AddProp(GEOTEXT__STRETCHCHARHEIGHT, GetData("geotext.stretchcharheight"));
AddProp(GEOTEXT__NOMEASUREALONGPATH, GetData("geotext.nomeasurealongpath"));
AddProp(GEOTEXT__BOLDFONT, GetData("geotext.boldfont"));
AddProp(GEOTEXT__ITALICFONT, GetData("geotext.italicfont"));
AddProp(GEOTEXT__UNDERLINEFONT, GetData("geotext.underlinefont"));
AddProp(GEOTEXT__SHADOWFONT, GetData("geotext.shadowfont"));
AddProp(GEOTEXT__SMALLCAPSFONT, GetData("geotext.smallcapsfont"));
AddProp(GEOTEXT__STRIKETHROUGHFONT, GetData("geotext.strikethroughfont"));
AddProp(BLIP__CROPFROMTOP, GetData("blip.cropfromtop"));
AddProp(BLIP__CROPFROMBOTTOM, GetData("blip.cropfrombottom"));
AddProp(BLIP__CROPFROMLEFT, GetData("blip.cropfromleft"));
AddProp(BLIP__CROPFROMRIGHT, GetData("blip.cropfromright"));
AddProp(BLIP__BLIPTODISPLAY, GetData("blip.bliptodisplay"));
AddProp(BLIP__BLIPFILENAME, GetData("blip.blipfilename"));
AddProp(BLIP__BLIPFLAGS, GetData("blip.blipflags"));
AddProp(BLIP__TRANSPARENTCOLOR, GetData("blip.transparentcolor"));
AddProp(BLIP__CONTRASTSetTING, GetData("blip.contrastSetting"));
AddProp(BLIP__BRIGHTNESSSetTING, GetData("blip.brightnessSetting"));
AddProp(BLIP__GAMMA, GetData("blip.gamma"));
AddProp(BLIP__PICTUREID, GetData("blip.pictureid"));
AddProp(BLIP__DOUBLEMOD, GetData("blip.doublemod"));
AddProp(BLIP__PICTUREFillMOD, GetData("blip.pictureFillmod"));
AddProp(BLIP__PICTURELINE, GetData("blip.pictureline"));
AddProp(BLIP__PRINTBLIP, GetData("blip.printblip"));
AddProp(BLIP__PRINTBLIPFILENAME, GetData("blip.printblipfilename"));
AddProp(BLIP__PRINTFLAGS, GetData("blip.printflags"));
AddProp(BLIP__NOHITTESTPICTURE, GetData("blip.nohittestpicture"));
AddProp(BLIP__PICTUREGRAY, GetData("blip.picturegray"));
AddProp(BLIP__PICTUREBILEVEL, GetData("blip.picturebilevel"));
AddProp(BLIP__PICTUREACTIVE, GetData("blip.pictureactive"));
AddProp(GEOMETRY__LEFT, GetData("geometry.left"));
AddProp(GEOMETRY__TOP, GetData("geometry.top"));
AddProp(GEOMETRY__RIGHT, GetData("geometry.right"));
AddProp(GEOMETRY__BOTTOM, GetData("geometry.bottom"));
AddProp(GEOMETRY__SHAPEPATH, GetData("geometry.shapepath", EscherPropertyMetaData.TYPE_SHAPEPATH));
AddProp(GEOMETRY__VERTICES, GetData("geometry.vertices", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(GEOMETRY__SEGMENTINFO, GetData("geometry.segmentinfo", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(GEOMETRY__ADJUSTVALUE, GetData("geometry.adjustvalue"));
AddProp(GEOMETRY__ADJUST2VALUE, GetData("geometry.adjust2value"));
AddProp(GEOMETRY__ADJUST3VALUE, GetData("geometry.adjust3value"));
AddProp(GEOMETRY__ADJUST4VALUE, GetData("geometry.adjust4value"));
AddProp(GEOMETRY__ADJUST5VALUE, GetData("geometry.adjust5value"));
AddProp(GEOMETRY__ADJUST6VALUE, GetData("geometry.adjust6value"));
AddProp(GEOMETRY__ADJUST7VALUE, GetData("geometry.adjust7value"));
AddProp(GEOMETRY__ADJUST8VALUE, GetData("geometry.adjust8value"));
AddProp(GEOMETRY__ADJUST9VALUE, GetData("geometry.adjust9value"));
AddProp(GEOMETRY__ADJUST10VALUE, GetData("geometry.adjust10value"));
AddProp(GEOMETRY__SHADOWok, GetData("geometry.shadowOK"));
AddProp(GEOMETRY__3DOK, GetData("geometry.3dok"));
AddProp(GEOMETRY__LINEOK, GetData("geometry.lineok"));
AddProp(GEOMETRY__GEOTEXTOK, GetData("geometry.geotextok"));
AddProp(GEOMETRY__FillSHADESHAPEOK, GetData("geometry.Fillshadeshapeok"));
AddProp(GEOMETRY__FillOK, GetData("geometry.Fillok", EscherPropertyMetaData.TYPE_bool));
AddProp(Fill__FillTYPE, GetData("Fill.Filltype"));
AddProp(Fill__FillCOLOR, GetData("Fill.Fillcolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(Fill__FillOPACITY, GetData("Fill.Fillopacity"));
AddProp(Fill__FillBACKCOLOR, GetData("Fill.Fillbackcolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(Fill__BACKOPACITY, GetData("Fill.backopacity"));
AddProp(Fill__CRMOD, GetData("Fill.crmod"));
AddProp(Fill__PATTERNTEXTURE, GetData("Fill.patterntexture"));
AddProp(Fill__BLIPFILENAME, GetData("Fill.blipfilename"));
AddProp(Fill__BLIPFLAGS, GetData("Fill.blipflags"));
AddProp(Fill__WIDTH, GetData("Fill.width"));
AddProp(Fill__HEIGHT, GetData("Fill.height"));
AddProp(Fill__ANGLE, GetData("Fill.angle"));
AddProp(Fill__FOCUS, GetData("Fill.focus"));
AddProp(Fill__TOLEFT, GetData("Fill.toleft"));
AddProp(Fill__TOTOP, GetData("Fill.totop"));
AddProp(Fill__TORIGHT, GetData("Fill.toright"));
AddProp(Fill__TOBOTTOM, GetData("Fill.tobottom"));
AddProp(Fill__RECTLEFT, GetData("Fill.rectleft"));
AddProp(Fill__RECTTOP, GetData("Fill.recttop"));
AddProp(Fill__RECTRIGHT, GetData("Fill.rectright"));
AddProp(Fill__RECTBOTTOM, GetData("Fill.rectbottom"));
AddProp(Fill__DZTYPE, GetData("Fill.dztype"));
AddProp(Fill__SHADEPRESet, GetData("Fill.shadepReset"));
AddProp(Fill__SHADECOLORS, GetData("Fill.shadecolors", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(Fill__ORIGINX, GetData("Fill.originx"));
AddProp(Fill__ORIGINY, GetData("Fill.originy"));
AddProp(Fill__SHAPEORIGINX, GetData("Fill.shapeoriginx"));
AddProp(Fill__SHAPEORIGINY, GetData("Fill.shapeoriginy"));
AddProp(Fill__SHADETYPE, GetData("Fill.shadetype"));
AddProp(Fill__FillED, GetData("Fill.Filled"));
AddProp(Fill__HITTESTFill, GetData("Fill.hittestFill"));
AddProp(Fill__SHAPE, GetData("Fill.shape"));
AddProp(Fill__USERECT, GetData("Fill.userect"));
AddProp(Fill__NOFillHITTEST, GetData("Fill.noFillhittest", EscherPropertyMetaData.TYPE_bool));
AddProp(LINESTYLE__COLOR, GetData("linestyle.color", EscherPropertyMetaData.TYPE_RGB));
AddProp(LINESTYLE__OPACITY, GetData("linestyle.opacity"));
AddProp(LINESTYLE__BACKCOLOR, GetData("linestyle.backcolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(LINESTYLE__CRMOD, GetData("linestyle.crmod"));
AddProp(LINESTYLE__LINETYPE, GetData("linestyle.linetype"));
AddProp(LINESTYLE__FillBLIP, GetData("linestyle.Fillblip"));
AddProp(LINESTYLE__FillBLIPNAME, GetData("linestyle.Fillblipname"));
AddProp(LINESTYLE__FillBLIPFLAGS, GetData("linestyle.Fillblipflags"));
AddProp(LINESTYLE__FillWIDTH, GetData("linestyle.Fillwidth"));
AddProp(LINESTYLE__FillHEIGHT, GetData("linestyle.Fillheight"));
AddProp(LINESTYLE__FillDZTYPE, GetData("linestyle.Filldztype"));
AddProp(LINESTYLE__LINEWIDTH, GetData("linestyle.linewidth"));
AddProp(LINESTYLE__LINEMITERLIMIT, GetData("linestyle.linemiterlimit"));
AddProp(LINESTYLE__LINESTYLE, GetData("linestyle.linestyle"));
AddProp(LINESTYLE__LINEDASHING, GetData("linestyle.linedashing"));
AddProp(LINESTYLE__LINEDASHSTYLE, GetData("linestyle.linedashstyle", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(LINESTYLE__LINESTARTARROWHEAD, GetData("linestyle.linestartarrowhead"));
AddProp(LINESTYLE__LINEENDARROWHEAD, GetData("linestyle.lineendarrowhead"));
AddProp(LINESTYLE__LINESTARTARROWWIDTH, GetData("linestyle.linestartarrowwidth"));
AddProp(LINESTYLE__LINEESTARTARROWLength, GetData("linestyle.lineestartarrowLength"));
AddProp(LINESTYLE__LINEENDARROWWIDTH, GetData("linestyle.lineendarrowwidth"));
AddProp(LINESTYLE__LINEENDARROWLength, GetData("linestyle.lineendarrowLength"));
AddProp(LINESTYLE__LINEJOINSTYLE, GetData("linestyle.linejoinstyle"));
AddProp(LINESTYLE__LINEENDCAPSTYLE, GetData("linestyle.lineendcapstyle"));
AddProp(LINESTYLE__ARROWHEADSOK, GetData("linestyle.arrowheadsok"));
AddProp(LINESTYLE__ANYLINE, GetData("linestyle.anyline"));
AddProp(LINESTYLE__HITLINETEST, GetData("linestyle.hitlinetest"));
AddProp(LINESTYLE__LINEFillSHAPE, GetData("linestyle.lineFillshape"));
AddProp(LINESTYLE__NOLINEDRAWDASH, GetData("linestyle.nolinedrawdash", EscherPropertyMetaData.TYPE_bool));
AddProp(SHADOWSTYLE__TYPE, GetData("shadowstyle.type"));
AddProp(SHADOWSTYLE__COLOR, GetData("shadowstyle.color", EscherPropertyMetaData.TYPE_RGB));
AddProp(SHADOWSTYLE__HIGHLIGHT, GetData("shadowstyle.highlight"));
AddProp(SHADOWSTYLE__CRMOD, GetData("shadowstyle.crmod"));
AddProp(SHADOWSTYLE__OPACITY, GetData("shadowstyle.opacity"));
AddProp(SHADOWSTYLE__OFFSetX, GetData("shadowstyle.offsetx"));
AddProp(SHADOWSTYLE__OFFSetY, GetData("shadowstyle.offsety"));
AddProp(SHADOWSTYLE__SECONDOFFSetX, GetData("shadowstyle.secondoffsetx"));
AddProp(SHADOWSTYLE__SECONDOFFSetY, GetData("shadowstyle.secondoffsety"));
AddProp(SHADOWSTYLE__SCALEXTOX, GetData("shadowstyle.scalextox"));
AddProp(SHADOWSTYLE__SCALEYTOX, GetData("shadowstyle.scaleytox"));
AddProp(SHADOWSTYLE__SCALEXTOY, GetData("shadowstyle.scalextoy"));
AddProp(SHADOWSTYLE__SCALEYTOY, GetData("shadowstyle.scaleytoy"));
AddProp(SHADOWSTYLE__PERSPECTIVEX, GetData("shadowstyle.perspectivex"));
AddProp(SHADOWSTYLE__PERSPECTIVEY, GetData("shadowstyle.perspectivey"));
AddProp(SHADOWSTYLE__WEIGHT, GetData("shadowstyle.weight"));
AddProp(SHADOWSTYLE__ORIGINX, GetData("shadowstyle.originx"));
AddProp(SHADOWSTYLE__ORIGINY, GetData("shadowstyle.originy"));
AddProp(SHADOWSTYLE__SHADOW, GetData("shadowstyle.shadow"));
AddProp(SHADOWSTYLE__SHADOWOBSURED, GetData("shadowstyle.shadowobsured"));
AddProp(PERSPECTIVE__TYPE, GetData("perspective.type"));
AddProp(PERSPECTIVE__OFFSetX, GetData("perspective.offsetx"));
AddProp(PERSPECTIVE__OFFSetY, GetData("perspective.offsety"));
AddProp(PERSPECTIVE__SCALEXTOX, GetData("perspective.scalextox"));
AddProp(PERSPECTIVE__SCALEYTOX, GetData("perspective.scaleytox"));
AddProp(PERSPECTIVE__SCALEXTOY, GetData("perspective.scalextoy"));
AddProp(PERSPECTIVE__SCALEYTOY, GetData("perspective.scaleytoy"));
AddProp(PERSPECTIVE__PERSPECTIVEX, GetData("perspective.perspectivex"));
AddProp(PERSPECTIVE__PERSPECTIVEY, GetData("perspective.perspectivey"));
AddProp(PERSPECTIVE__WEIGHT, GetData("perspective.weight"));
AddProp(PERSPECTIVE__ORIGINX, GetData("perspective.originx"));
AddProp(PERSPECTIVE__ORIGINY, GetData("perspective.originy"));
AddProp(PERSPECTIVE__PERSPECTIVEON, GetData("perspective.perspectiveon"));
AddProp(THREED__SPECULARAMOUNT, GetData("3d.specularamount"));
AddProp(THREED__DIFFUSEAMOUNT, GetData("3d.diffuseamount"));
AddProp(THREED__SHININESS, GetData("3d.shininess"));
AddProp(THREED__EDGetHICKNESS, GetData("3d.edGethickness"));
AddProp(THREED__EXTRUDEFORWARD, GetData("3d.extrudeforward"));
AddProp(THREED__EXTRUDEBACKWARD, GetData("3d.extrudebackward"));
AddProp(THREED__EXTRUDEPLANE, GetData("3d.extrudeplane"));
AddProp(THREED__EXTRUSIONCOLOR, GetData("3d.extrusioncolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(THREED__CRMOD, GetData("3d.crmod"));
AddProp(THREED__3DEFFECT, GetData("3d.3deffect"));
AddProp(THREED__METALLIC, GetData("3d.metallic"));
AddProp(THREED__USEEXTRUSIONCOLOR, GetData("3d.useextrusioncolor", EscherPropertyMetaData.TYPE_RGB));
AddProp(THREED__LIGHTFACE, GetData("3d.lightface"));
AddProp(THREEDSTYLE__YROTATIONANGLE, GetData("3dstyle.yrotationangle"));
AddProp(THREEDSTYLE__XROTATIONANGLE, GetData("3dstyle.xrotationangle"));
AddProp(THREEDSTYLE__ROTATIONAXISX, GetData("3dstyle.rotationaxisx"));
AddProp(THREEDSTYLE__ROTATIONAXISY, GetData("3dstyle.rotationaxisy"));
AddProp(THREEDSTYLE__ROTATIONAXISZ, GetData("3dstyle.rotationaxisz"));
AddProp(THREEDSTYLE__ROTATIONANGLE, GetData("3dstyle.rotationangle"));
AddProp(THREEDSTYLE__ROTATIONCENTERX, GetData("3dstyle.rotationcenterx"));
AddProp(THREEDSTYLE__ROTATIONCENTERY, GetData("3dstyle.rotationcentery"));
AddProp(THREEDSTYLE__ROTATIONCENTERZ, GetData("3dstyle.rotationcenterz"));
AddProp(THREEDSTYLE__RENDERMODE, GetData("3dstyle.rendermode"));
AddProp(THREEDSTYLE__TOLERANCE, GetData("3dstyle.tolerance"));
AddProp(THREEDSTYLE__XVIEWPOINT, GetData("3dstyle.xviewpoint"));
AddProp(THREEDSTYLE__YVIEWPOINT, GetData("3dstyle.yviewpoint"));
AddProp(THREEDSTYLE__ZVIEWPOINT, GetData("3dstyle.zviewpoint"));
AddProp(THREEDSTYLE__ORIGINX, GetData("3dstyle.originx"));
AddProp(THREEDSTYLE__ORIGINY, GetData("3dstyle.originy"));
AddProp(THREEDSTYLE__SKEWANGLE, GetData("3dstyle.skewangle"));
AddProp(THREEDSTYLE__SKEWAMOUNT, GetData("3dstyle.skewamount"));
AddProp(THREEDSTYLE__AMBIENTINTENSITY, GetData("3dstyle.ambientintensity"));
AddProp(THREEDSTYLE__KEYX, GetData("3dstyle.keyx"));
AddProp(THREEDSTYLE__KEYY, GetData("3dstyle.keyy"));
AddProp(THREEDSTYLE__KEYZ, GetData("3dstyle.keyz"));
AddProp(THREEDSTYLE__KEYINTENSITY, GetData("3dstyle.keyintensity"));
AddProp(THREEDSTYLE__FillX, GetData("3dstyle.Fillx"));
AddProp(THREEDSTYLE__FillY, GetData("3dstyle.Filly"));
AddProp(THREEDSTYLE__FillZ, GetData("3dstyle.Fillz"));
AddProp(THREEDSTYLE__FillINTENSITY, GetData("3dstyle.Fillintensity"));
AddProp(THREEDSTYLE__CONSTRAINROTATION, GetData("3dstyle.constrainrotation"));
AddProp(THREEDSTYLE__ROTATIONCENTERAUTO, GetData("3dstyle.rotationcenterauto"));
AddProp(THREEDSTYLE__PARALLEL, GetData("3dstyle.parallel"));
AddProp(THREEDSTYLE__KEYHARSH, GetData("3dstyle.keyharsh"));
AddProp(THREEDSTYLE__FillHARSH, GetData("3dstyle.Fillharsh"));
AddProp(SHAPE__MASTER, GetData("shape.master"));
AddProp(SHAPE__CONNECTORSTYLE, GetData("shape.connectorstyle"));
AddProp(SHAPE__BLACKANDWHITESetTINGS, GetData("shape.blackandwhiteSettings"));
AddProp(SHAPE__WMODEPUREBW, GetData("shape.wmodepurebw"));
AddProp(SHAPE__WMODEBW, GetData("shape.wmodebw"));
AddProp(SHAPE__OLEICON, GetData("shape.oleicon"));
AddProp(SHAPE__PREFERRELATIVERESIZE, GetData("shape.preferrelativeresize"));
AddProp(SHAPE__LOCKSHAPETYPE, GetData("shape.lockshapetype"));
AddProp(SHAPE__DELETEATTACHEDOBJECT, GetData("shape.deleteattachedobject"));
AddProp(SHAPE__BACKGROUNDSHAPE, GetData("shape.backgroundshape"));
AddProp(CALLOUT__CALLOUTTYPE, GetData("callout.callouttype"));
AddProp(CALLOUT__XYCALLOUTGAP, GetData("callout.xycalloutgap"));
AddProp(CALLOUT__CALLOUTANGLE, GetData("callout.calloutangle"));
AddProp(CALLOUT__CALLOUTDROPTYPE, GetData("callout.calloutdroptype"));
AddProp(CALLOUT__CALLOUTDROPSPECIFIED, GetData("callout.calloutdropspecified"));
AddProp(CALLOUT__CALLOUTLengthSPECIFIED, GetData("callout.calloutLengthspecified"));
AddProp(CALLOUT__ISCALLOUT, GetData("callout.iscallout"));
AddProp(CALLOUT__CALLOUTACCENTBAR, GetData("callout.calloutaccentbar"));
AddProp(CALLOUT__CALLOUTTEXTBORDER, GetData("callout.callouttextborder"));
AddProp(CALLOUT__CALLOUTMINUSX, GetData("callout.calloutminusx"));
AddProp(CALLOUT__CALLOUTMINUSY, GetData("callout.calloutminusy"));
AddProp(CALLOUT__DROPAUTO, GetData("callout.dropauto"));
AddProp(CALLOUT__LengthSPECIFIED, GetData("callout.Lengthspecified"));
AddProp(GROUPSHAPE__SHAPENAME, GetData("groupshape.shapename"));
AddProp(GROUPSHAPE__DESCRIPTION, GetData("groupshape.description"));
AddProp(GROUPSHAPE__HYPERLINK, GetData("groupshape.hyperlink"));
AddProp(GROUPSHAPE__WRAPPOLYGONVERTICES, GetData("groupshape.wrappolygonvertices", EscherPropertyMetaData.TYPE_ARRAY));
AddProp(GROUPSHAPE__WRAPDISTLEFT, GetData("groupshape.wrapdistleft"));
AddProp(GROUPSHAPE__WRAPDISTTOP, GetData("groupshape.wrapdisttop"));
AddProp(GROUPSHAPE__WRAPDISTRIGHT, GetData("groupshape.wrapdistright"));
AddProp(GROUPSHAPE__WRAPDISTBOTTOM, GetData("groupshape.wrapdistbottom"));
AddProp(GROUPSHAPE__REGROUPID, GetData("groupshape.regroupid"));
AddProp(GROUPSHAPE__EDITEDWRAP, GetData("groupshape.editedwrap"));
AddProp(GROUPSHAPE__BEHINDDOCUMENT, GetData("groupshape.behinddocument"));
AddProp(GROUPSHAPE__ONDBLCLICKNOTIFY, GetData("groupshape.ondblclicknotify"));
AddProp(GROUPSHAPE__ISBUTTON, GetData("groupshape.isbutton"));
AddProp(GROUPSHAPE__1DADJUSTMENT, GetData("groupshape.1dadjustment"));
AddProp(GROUPSHAPE__HIDDEN, GetData("groupshape.hidden"));
AddProp(GROUPSHAPE__PRINT, GetData("groupshape.print", EscherPropertyMetaData.TYPE_bool));
}
}
/// <summary>
/// Adds the prop.
/// </summary>
/// <param name="s">The s.</param>
/// <param name="data">The data.</param>
private static void AddProp(int s, EscherPropertyMetaData data)
{
properties[(short)s]= data;
}
/// <summary>
/// Gets the data.
/// </summary>
/// <param name="propName">Name of the prop.</param>
/// <param name="type">The type.</param>
/// <returns></returns>
private static EscherPropertyMetaData GetData(String propName, byte type)
{
return new EscherPropertyMetaData(propName, type);
}
/// <summary>
/// Gets the data.
/// </summary>
/// <param name="propName">Name of the prop.</param>
/// <returns></returns>
private static EscherPropertyMetaData GetData(String propName)
{
return new EscherPropertyMetaData(propName);
}
/// <summary>
/// Gets the name of the property.
/// </summary>
/// <param name="propertyId">The property id.</param>
/// <returns></returns>
public static String GetPropertyName(short propertyId)
{
InitProps();
EscherPropertyMetaData o = (EscherPropertyMetaData)properties[propertyId];
return o == null ? "unknown" : o.Description;
}
/// <summary>
/// Gets the type of the property.
/// </summary>
/// <param name="propertyId">The property id.</param>
/// <returns></returns>
public static byte GetPropertyType(short propertyId)
{
InitProps();
EscherPropertyMetaData escherPropertyMetaData = (EscherPropertyMetaData)properties[propertyId];
return escherPropertyMetaData == null ? (byte)0 : escherPropertyMetaData.Type;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Security;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: This is the implementation of the DataCollector
/// functionality. To enable safe access to the DataCollector from
/// untrusted code, there is one thread-local instance of this structure
/// per thread. The instance must be Enabled before any data is written to
/// it. The instance must be Finished before the data is passed to
/// EventWrite. The instance must be Disabled before the arrays referenced
/// by the pointers are freed or unpinned.
/// </summary>
internal unsafe struct DataCollector
{
[ThreadStatic]
internal static DataCollector ThreadInstance;
private byte* scratchEnd;
private EventSource.EventData* datasEnd;
private GCHandle* pinsEnd;
private EventSource.EventData* datasStart;
private byte* scratch;
private EventSource.EventData* datas;
private GCHandle* pins;
private byte[] buffer;
private int bufferPos;
private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this.
private bool writingScalars;
internal void Enable(
byte* scratch,
int scratchSize,
EventSource.EventData* datas,
int dataCount,
GCHandle* pins,
int pinCount)
{
this.datasStart = datas;
this.scratchEnd = scratch + scratchSize;
this.datasEnd = datas + dataCount;
this.pinsEnd = pins + pinCount;
this.scratch = scratch;
this.datas = datas;
this.pins = pins;
this.writingScalars = false;
}
internal void Disable()
{
this = new DataCollector();
}
/// <summary>
/// Completes the list of scalars. Finish must be called before the data
/// descriptor array is passed to EventWrite.
/// </summary>
/// <returns>
/// A pointer to the next unused data descriptor, or datasEnd if they were
/// all used. (Descriptors may be unused if a string or array was null.)
/// </returns>
internal EventSource.EventData* Finish()
{
this.ScalarsEnd();
return this.datas;
}
internal void AddScalar(void* value, int size)
{
var pb = (byte*)value;
if (this.bufferNesting == 0)
{
var scratchOld = this.scratch;
var scratchNew = scratchOld + size;
if (this.scratchEnd < scratchNew)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_AddScalarOutOfRange"));
}
this.ScalarsBegin();
this.scratch = scratchNew;
for (int i = 0; i != size; i++)
{
scratchOld[i] = pb[i];
}
}
else
{
var oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
for (int i = 0; i != size; i++, oldPos++)
{
this.buffer[oldPos] = pb[i];
}
}
}
internal void AddBinary(string value, int size)
{
if (size > ushort.MaxValue)
{
size = ushort.MaxValue - 1;
}
if (this.bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
this.AddScalar(&size, 2);
if (size != 0)
{
if (this.bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
var oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
fixed (void* p = value)
{
Marshal.Copy((IntPtr)p, buffer, oldPos, size);
}
}
}
}
internal void AddBinary(Array value, int size)
{
this.AddArray(value, size, 1);
}
internal void AddArray(Array value, int length, int itemSize)
{
if (length > ushort.MaxValue)
{
length = ushort.MaxValue;
}
var size = length * itemSize;
if (this.bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
this.AddScalar(&length, 2);
if (length != 0)
{
if (this.bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
var oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
Buffer.BlockCopy(value, 0, this.buffer, oldPos, size);
}
}
}
/// <summary>
/// Marks the start of a non-blittable array or enumerable.
/// </summary>
/// <returns>Bookmark to be passed to EndBufferedArray.</returns>
internal int BeginBufferedArray()
{
this.BeginBuffered();
this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable)
return this.bufferPos;
}
/// <summary>
/// Marks the end of a non-blittable array or enumerable.
/// </summary>
/// <param name="bookmark">The value returned by BeginBufferedArray.</param>
/// <param name="count">The number of items in the array.</param>
internal void EndBufferedArray(int bookmark, int count)
{
this.EnsureBuffer();
this.buffer[bookmark - 2] = unchecked((byte)count);
this.buffer[bookmark - 1] = unchecked((byte)(count >> 8));
this.EndBuffered();
}
/// <summary>
/// Marks the start of dynamically-buffered data.
/// </summary>
internal void BeginBuffered()
{
this.ScalarsEnd();
this.bufferNesting += 1;
}
/// <summary>
/// Marks the end of dynamically-buffered data.
/// </summary>
internal void EndBuffered()
{
this.bufferNesting -= 1;
if (this.bufferNesting == 0)
{
/*
TODO (perf): consider coalescing adjacent buffered regions into a
single buffer, similar to what we're already doing for adjacent
scalars. In addition, if a type contains a buffered region adjacent
to a blittable array, and the blittable array is small, it would be
more efficient to buffer the array instead of pinning it.
*/
this.EnsureBuffer();
this.PinArray(this.buffer, this.bufferPos);
this.buffer = null;
this.bufferPos = 0;
}
}
private void EnsureBuffer()
{
var required = this.bufferPos;
if (this.buffer == null || this.buffer.Length < required)
{
this.GrowBuffer(required);
}
}
private void EnsureBuffer(int additionalSize)
{
var required = this.bufferPos + additionalSize;
if (this.buffer == null || this.buffer.Length < required)
{
this.GrowBuffer(required);
}
}
private void GrowBuffer(int required)
{
var newSize = this.buffer == null ? 64 : this.buffer.Length;
do
{
newSize *= 2;
}
while (newSize < required);
Array.Resize(ref this.buffer, newSize);
}
private void PinArray(object value, int size)
{
var pinsTemp = this.pins;
if (this.pinsEnd <= pinsTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_PinArrayOutOfRange"));
}
var datasTemp = this.datas;
if (this.datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
}
this.pins = pinsTemp + 1;
this.datas = datasTemp + 1;
*pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned);
datasTemp->m_Ptr = (long)(ulong)(UIntPtr)(void*)pinsTemp->AddrOfPinnedObject();
datasTemp->m_Size = size;
}
private void ScalarsBegin()
{
if (!this.writingScalars)
{
var datasTemp = this.datas;
if (this.datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
}
datasTemp->m_Ptr = (long)(ulong)(UIntPtr)this.scratch;
this.writingScalars = true;
}
}
private void ScalarsEnd()
{
if (this.writingScalars)
{
var datasTemp = this.datas;
datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr));
this.datas = datasTemp + 1;
this.writingScalars = false;
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Candles.Algo
File: CandleSeries.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Candles
{
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Serialization;
using StockSharp.BusinessEntities;
using StockSharp.Localization;
using StockSharp.Messages;
/// <summary>
/// Candles series.
/// </summary>
public class CandleSeries : NotifiableObject, IPersistable
{
/// <summary>
/// Initializes a new instance of the <see cref="CandleSeries"/>.
/// </summary>
public CandleSeries()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CandleSeries"/>.
/// </summary>
/// <param name="candleType">The candle type.</param>
/// <param name="security">The instrument to be used for candles formation.</param>
/// <param name="arg">The candle formation parameter. For example, for <see cref="TimeFrameCandle"/> this value is <see cref="TimeFrameCandle.TimeFrame"/>.</param>
public CandleSeries(Type candleType, Security security, object arg)
{
if (!candleType.IsCandle())
throw new ArgumentOutOfRangeException(nameof(candleType), candleType, LocalizedStrings.WrongCandleType);
_security = security ?? throw new ArgumentNullException(nameof(security));
_candleType = candleType ?? throw new ArgumentNullException(nameof(candleType));
_arg = arg ?? throw new ArgumentNullException(nameof(arg));
WorkingTime = security.Board?.WorkingTime;
}
private Security _security;
/// <summary>
/// The instrument to be used for candles formation.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.SecurityKey,
Description = LocalizedStrings.SecurityKey + LocalizedStrings.Dot,
GroupName = LocalizedStrings.GeneralKey,
Order = 0)]
public virtual Security Security
{
get => _security;
set
{
_security = value;
NotifyChanged();
}
}
private Type _candleType;
/// <summary>
/// The candle type.
/// </summary>
[Browsable(false)]
public virtual Type CandleType
{
get => _candleType;
set
{
NotifyChanging();
_candleType = value;
NotifyChanged();
}
}
private object _arg;
/// <summary>
/// The candle formation parameter. For example, for <see cref="TimeFrameCandle"/> this value is <see cref="TimeFrameCandle.TimeFrame"/>.
/// </summary>
[Browsable(false)]
public virtual object Arg
{
get => _arg;
set
{
NotifyChanging();
_arg = value;
NotifyChanged();
}
}
/// <summary>
/// The time boundary, within which candles for give series shall be translated.
/// </summary>
[Browsable(false)]
public WorkingTime WorkingTime { get; set; }
/// <summary>
/// To perform the calculation <see cref="Candle.PriceLevels"/>. By default, it is disabled.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.VolumeProfileKey,
Description = LocalizedStrings.VolumeProfileCalcKey,
GroupName = LocalizedStrings.GeneralKey,
Order = 2)]
public bool IsCalcVolumeProfile { get; set; }
/// <summary>
/// The initial date from which you need to get data.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str343Key,
Description = LocalizedStrings.Str344Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 3)]
public DateTimeOffset? From { get; set; }
/// <summary>
/// The final date by which you need to get data.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str345Key,
Description = LocalizedStrings.Str346Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 4)]
public DateTimeOffset? To { get; set; }
/// <summary>
/// Allow build candles from smaller timeframe.
/// </summary>
/// <remarks>
/// Available only for <see cref="TimeFrameCandle"/>.
/// </remarks>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.SmallerTimeFrameKey,
Description = LocalizedStrings.SmallerTimeFrameDescKey,
GroupName = LocalizedStrings.GeneralKey,
Order = 5)]
public bool AllowBuildFromSmallerTimeFrame { get; set; } = true;
/// <summary>
/// Use only the regular trading hours for which data will be requested.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.RegularHoursKey,
Description = LocalizedStrings.RegularTradingHoursKey,
GroupName = LocalizedStrings.GeneralKey,
Order = 6)]
public bool IsRegularTradingHours { get; set; }
/// <summary>
/// Market-data count.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.CountKey,
Description = LocalizedStrings.CandlesCountKey,
GroupName = LocalizedStrings.GeneralKey,
Order = 7)]
public long? Count { get; set; }
/// <summary>
/// Build mode.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.ModeKey,
Description = LocalizedStrings.BuildModeKey,
GroupName = LocalizedStrings.BuildKey,
Order = 20)]
public MarketDataBuildModes BuildCandlesMode { get; set; }
/// <summary>
/// Which market-data type is used as a source value.
/// </summary>
//[Display(
// ResourceType = typeof(LocalizedStrings),
// Name = LocalizedStrings.Str213Key,
// Description = LocalizedStrings.CandlesBuildSourceKey,
// GroupName = LocalizedStrings.BuildKey,
// Order = 21)]
[Browsable(false)]
[Obsolete("Use BuildCandlesFrom2 property.")]
public MarketDataTypes? BuildCandlesFrom
{
get => BuildCandlesFrom2?.ToMarketDataType();
set => BuildCandlesFrom2 = value?.ToDataType(null);
}
/// <summary>
/// Which market-data type is used as a source value.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str213Key,
Description = LocalizedStrings.CandlesBuildSourceKey,
GroupName = LocalizedStrings.BuildKey,
Order = 21)]
public Messages.DataType BuildCandlesFrom2 { get; set; }
/// <summary>
/// Extra info for the <see cref="BuildCandlesFrom"/>.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str748Key,
Description = LocalizedStrings.Level1FieldKey,
GroupName = LocalizedStrings.BuildKey,
Order = 22)]
public Level1Fields? BuildCandlesField { get; set; }
/// <summary>
/// Request <see cref="CandleStates.Finished"/> only candles.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.FinishedKey,
Description = LocalizedStrings.Str1073Key,
GroupName = LocalizedStrings.BuildKey,
Order = 23)]
public bool IsFinishedOnly { get; set; }
/// <summary>
/// Try fill gaps.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.GapsKey,
Description = LocalizedStrings.FillGapsKey,
GroupName = LocalizedStrings.BuildKey,
Order = 24)]
public bool FillGaps { get; set; }
/// <inheritdoc />
public override string ToString()
{
return CandleType?.Name + "_" + Security + "_" + CandleType?.ToCandleMessageType().DataTypeArgToString(Arg);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Load(SettingsStorage storage)
{
var secProvider = ServicesRegistry.TrySecurityProvider;
if (secProvider != null)
{
var securityId = storage.GetValue<string>(nameof(SecurityId));
if (!securityId.IsEmpty())
Security = secProvider.LookupById(securityId);
}
CandleType = storage.GetValue(nameof(CandleType), CandleType);
if (CandleType != null)
Arg = CandleType.ToCandleMessageType().ToDataTypeArg(storage.GetValue<string>(nameof(Arg)));
From = storage.GetValue(nameof(From), From);
To = storage.GetValue(nameof(To), To);
WorkingTime = storage.GetValue<SettingsStorage>(nameof(WorkingTime))?.Load<WorkingTime>();
IsCalcVolumeProfile = storage.GetValue(nameof(IsCalcVolumeProfile), IsCalcVolumeProfile);
BuildCandlesMode = storage.GetValue(nameof(BuildCandlesMode), BuildCandlesMode);
if (storage.ContainsKey(nameof(BuildCandlesFrom2)))
BuildCandlesFrom2 = storage.GetValue<SettingsStorage>(nameof(BuildCandlesFrom2)).Load<Messages.DataType>();
#pragma warning disable CS0618 // Type or member is obsolete
else if (storage.ContainsKey(nameof(BuildCandlesFrom)))
BuildCandlesFrom = storage.GetValue(nameof(BuildCandlesFrom), BuildCandlesFrom);
#pragma warning restore CS0618 // Type or member is obsolete
BuildCandlesField = storage.GetValue(nameof(BuildCandlesField), BuildCandlesField);
AllowBuildFromSmallerTimeFrame = storage.GetValue(nameof(AllowBuildFromSmallerTimeFrame), AllowBuildFromSmallerTimeFrame);
IsRegularTradingHours = storage.GetValue(nameof(IsRegularTradingHours), IsRegularTradingHours);
Count = storage.GetValue(nameof(Count), Count);
IsFinishedOnly = storage.GetValue(nameof(IsFinishedOnly), IsFinishedOnly);
FillGaps = storage.GetValue(nameof(FillGaps), FillGaps);
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Save(SettingsStorage storage)
{
if (Security != null)
storage.SetValue(nameof(SecurityId), Security.Id);
if (CandleType != null)
storage.SetValue(nameof(CandleType), CandleType.GetTypeName(false));
if (Arg != null && CandleType != null)
storage.SetValue(nameof(Arg), CandleType.ToCandleMessageType().DataTypeArgToString(Arg));
storage.SetValue(nameof(From), From);
storage.SetValue(nameof(To), To);
if (WorkingTime != null)
storage.SetValue(nameof(WorkingTime), WorkingTime.Save());
storage.SetValue(nameof(IsCalcVolumeProfile), IsCalcVolumeProfile);
storage.SetValue(nameof(BuildCandlesMode), BuildCandlesMode);
if (BuildCandlesFrom2 != null)
storage.SetValue(nameof(BuildCandlesFrom2), BuildCandlesFrom2.Save());
storage.SetValue(nameof(BuildCandlesField), BuildCandlesField);
storage.SetValue(nameof(AllowBuildFromSmallerTimeFrame), AllowBuildFromSmallerTimeFrame);
storage.SetValue(nameof(IsRegularTradingHours), IsRegularTradingHours);
storage.SetValue(nameof(Count), Count);
storage.SetValue(nameof(IsFinishedOnly), IsFinishedOnly);
storage.SetValue(nameof(FillGaps), FillGaps);
}
}
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.Kinect.VisualGestureBuilder
{
//
// Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameReader
//
public sealed partial class VisualGestureBuilderFrameReader : RootSystem.IDisposable, Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal VisualGestureBuilderFrameReader(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_AddRefObject(ref _pNative);
}
~VisualGestureBuilderFrameReader()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
__EventCleanup();
Helper.NativeObjectCache.RemoveObject<VisualGestureBuilderFrameReader>(_pNative);
if (disposing)
{
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_Dispose(_pNative);
}
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern bool Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_get_IsPaused(RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused);
public bool IsPaused
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("VisualGestureBuilderFrameReader");
}
return Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_get_IsPaused(_pNative);
}
set
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("VisualGestureBuilderFrameReader");
}
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_put_IsPaused(_pNative, value);
Helper.ExceptionHelper.CheckLastError();
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_get_VisualGestureBuilderFrameSource(RootSystem.IntPtr pNative);
public Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameSource VisualGestureBuilderFrameSource
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("VisualGestureBuilderFrameReader");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_get_VisualGestureBuilderFrameSource(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameSource>(objectPointer, n => new Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameSource(n));
}
}
// Events
private static RootSystem.Runtime.InteropServices.GCHandle _Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameArrivedEventArgs>>> Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameArrivedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate))]
private static void Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameArrivedEventArgs>> callbackList = null;
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<VisualGestureBuilderFrameReader>(pNative);
var args = new Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameArrivedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrameArrivedEventArgs> FrameArrived
{
add
{
Helper.EventPump.EnsureInitialized();
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate(Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handler);
_Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_FrameArrived(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_FrameArrived(_pNative, Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handler, true);
_Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
}
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))]
private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null;
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<VisualGestureBuilderFrameReader>(pNative);
var args = new Windows.Data.PropertyChangedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged
{
add
{
Helper.EventPump.EnsureInitialized();
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_PropertyChanged(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_CalculateAndAcquireLatestFrame(RootSystem.IntPtr pNative);
public Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrame CalculateAndAcquireLatestFrame()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("VisualGestureBuilderFrameReader");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_CalculateAndAcquireLatestFrame(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrame>(objectPointer, n => new Microsoft.Kinect.VisualGestureBuilder.VisualGestureBuilderFrame(n));
}
[RootSystem.Runtime.InteropServices.DllImport("KinectVisualGestureBuilderUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_Dispose(RootSystem.IntPtr pNative);
public void Dispose()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Dispose(true);
RootSystem.GC.SuppressFinalize(this);
}
private void __EventCleanup()
{
{
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_FrameArrived(_pNative, Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handler, true);
}
_Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
{
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Microsoft_Kinect_VisualGestureBuilder_VisualGestureBuilderFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
}
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Tests.Loggers;
using Xunit;
using Xunit.Abstractions;
namespace BenchmarkDotNet.IntegrationTests
{
public class AllSetupAndCleanupTest : BenchmarkTestExecutor
{
private const string Prefix = "// ### Called: ";
private const string GlobalSetupCalled = Prefix + "GlobalSetup";
private const string GlobalCleanupCalled = Prefix + "GlobalCleanup";
private const string IterationSetupCalled = Prefix + "IterationSetup";
private const string IterationCleanupCalled = Prefix + "IterationCleanup";
private const string BenchmarkCalled = Prefix + "Benchmark";
private readonly string[] expectedLogLines = {
"// ### Called: GlobalSetup",
"// ### Called: IterationSetup (1)", // MainWarmup1
"// ### Called: Benchmark", // MainWarmup1
"// ### Called: IterationCleanup (1)", // MainWarmup1
"// ### Called: IterationSetup (2)", // MainWarmup2
"// ### Called: Benchmark", // MainWarmup2
"// ### Called: IterationCleanup (2)", // MainWarmup2
"// ### Called: IterationSetup (3)", // MainTarget1
"// ### Called: Benchmark", // MainTarget1
"// ### Called: IterationCleanup (3)", // MainTarget1
"// ### Called: IterationSetup (4)", // MainTarget2
"// ### Called: Benchmark", // MainTarget2
"// ### Called: IterationCleanup (4)", // MainTarget2
"// ### Called: IterationSetup (5)", // MainTarget3
"// ### Called: Benchmark", // MainTarget3
"// ### Called: IterationCleanup (5)", // MainTarget3
"// ### Called: GlobalCleanup"
};
public AllSetupAndCleanupTest(ITestOutputHelper output) : base(output) { }
[Fact]
public void AllSetupAndCleanupMethodRunsTest()
{
var logger = new OutputLogger(Output);
var miniJob = Job.Default.With(RunStrategy.Monitoring).WithWarmupCount(2).WithIterationCount(3).WithInvocationCount(1).WithUnrollFactor(1).WithId("MiniJob");
var config = CreateSimpleConfig(logger, miniJob);
CanExecute<AllSetupAndCleanupAttributeBenchmarks>(config);
var actualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(Prefix)).ToArray();
foreach (string line in actualLogLines)
Output.WriteLine(line);
Assert.Equal(expectedLogLines, actualLogLines);
}
public class AllSetupAndCleanupAttributeBenchmarks
{
private int setupCounter;
private int cleanupCounter;
[IterationSetup]
public void IterationSetup() => Console.WriteLine(IterationSetupCalled + " (" + ++setupCounter + ")");
[IterationCleanup]
public void IterationCleanup() => Console.WriteLine(IterationCleanupCalled + " (" + ++cleanupCounter + ")");
[GlobalSetup]
public void GlobalSetup() => Console.WriteLine(GlobalSetupCalled);
[GlobalCleanup]
public void GlobalCleanup() => Console.WriteLine(GlobalCleanupCalled);
[Benchmark]
public void Benchmark() => Console.WriteLine(BenchmarkCalled);
}
[Fact]
public void AllSetupAndCleanupMethodRunsAsyncTest()
{
var logger = new OutputLogger(Output);
var miniJob = Job.Default.With(RunStrategy.Monitoring).WithWarmupCount(2).WithIterationCount(3).WithInvocationCount(1).WithUnrollFactor(1).WithId("MiniJob");
var config = CreateSimpleConfig(logger, miniJob);
CanExecute<AllSetupAndCleanupAttributeBenchmarksAsync>(config);
var actualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(Prefix)).ToArray();
foreach (string line in actualLogLines)
Output.WriteLine(line);
Assert.Equal(expectedLogLines, actualLogLines);
}
public class AllSetupAndCleanupAttributeBenchmarksAsync
{
private int setupCounter;
private int cleanupCounter;
[IterationSetup]
public void IterationSetup() => Console.WriteLine(IterationSetupCalled + " (" + ++setupCounter + ")");
[IterationCleanup]
public void IterationCleanup() => Console.WriteLine(IterationCleanupCalled + " (" + ++cleanupCounter + ")");
[GlobalSetup]
public Task GlobalSetup() => Console.Out.WriteLineAsync(GlobalSetupCalled);
[GlobalCleanup]
public Task GlobalCleanup() => Console.Out.WriteLineAsync(GlobalCleanupCalled);
[Benchmark]
public Task Benchmark() => Console.Out.WriteLineAsync(BenchmarkCalled);
}
[Fact]
public void AllSetupAndCleanupMethodRunsAsyncTaskSetupTest()
{
var logger = new OutputLogger(Output);
var miniJob = Job.Default.With(RunStrategy.Monitoring).WithWarmupCount(2).WithIterationCount(3).WithInvocationCount(1).WithUnrollFactor(1).WithId("MiniJob");
var config = CreateSimpleConfig(logger, miniJob);
CanExecute<AllSetupAndCleanupAttributeBenchmarksAsyncTaskSetup>(config);
var actualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(Prefix)).ToArray();
foreach (string line in actualLogLines)
Output.WriteLine(line);
Assert.Equal(expectedLogLines, actualLogLines);
}
public class AllSetupAndCleanupAttributeBenchmarksAsyncTaskSetup
{
private int setupCounter;
private int cleanupCounter;
[IterationSetup]
public void IterationSetup() => Console.WriteLine(IterationSetupCalled + " (" + ++setupCounter + ")");
[IterationCleanup]
public void IterationCleanup() => Console.WriteLine(IterationCleanupCalled + " (" + ++cleanupCounter + ")");
[GlobalSetup]
public Task GlobalSetup() => Console.Out.WriteLineAsync(GlobalSetupCalled);
[GlobalCleanup]
public Task GlobalCleanup() => Console.Out.WriteLineAsync(GlobalCleanupCalled);
[Benchmark]
public void Benchmark() => Console.WriteLine(BenchmarkCalled);
}
[Fact]
public void AllSetupAndCleanupMethodRunsAsyncGenericTaskSetupTest()
{
var logger = new OutputLogger(Output);
var miniJob = Job.Default.With(RunStrategy.Monitoring).WithWarmupCount(2).WithIterationCount(3).WithInvocationCount(1).WithUnrollFactor(1).WithId("MiniJob");
var config = CreateSimpleConfig(logger, miniJob);
CanExecute<AllSetupAndCleanupAttributeBenchmarksAsyncGenericTaskSetup>(config);
var actualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(Prefix)).ToArray();
foreach (string line in actualLogLines)
Output.WriteLine(line);
Assert.Equal(expectedLogLines, actualLogLines);
}
public class AllSetupAndCleanupAttributeBenchmarksAsyncGenericTaskSetup
{
private int setupCounter;
private int cleanupCounter;
[IterationSetup]
public void IterationSetup() => Console.WriteLine(IterationSetupCalled + " (" + ++setupCounter + ")");
[IterationCleanup]
public void IterationCleanup() => Console.WriteLine(IterationCleanupCalled + " (" + ++cleanupCounter + ")");
[GlobalSetup]
public async Task<int> GlobalSetup()
{
await Console.Out.WriteLineAsync(GlobalSetupCalled);
return 42;
}
[GlobalCleanup]
public async Task<int> GlobalCleanup()
{
await Console.Out.WriteLineAsync(GlobalCleanupCalled);
return 42;
}
[Benchmark]
public void Benchmark() => Console.WriteLine(BenchmarkCalled);
}
[Fact]
public void AllSetupAndCleanupMethodRunsAsyncValueTaskSetupTest()
{
var logger = new OutputLogger(Output);
var miniJob = Job.Default.With(RunStrategy.Monitoring).WithWarmupCount(2).WithIterationCount(3).WithInvocationCount(1).WithUnrollFactor(1).WithId("MiniJob");
var config = CreateSimpleConfig(logger, miniJob);
CanExecute<AllSetupAndCleanupAttributeBenchmarksAsyncValueTaskSetup>(config);
var actualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(Prefix)).ToArray();
foreach (string line in actualLogLines)
Output.WriteLine(line);
Assert.Equal(expectedLogLines, actualLogLines);
}
public class AllSetupAndCleanupAttributeBenchmarksAsyncValueTaskSetup
{
private int setupCounter;
private int cleanupCounter;
[IterationSetup]
public void IterationSetup() => Console.WriteLine(IterationSetupCalled + " (" + ++setupCounter + ")");
[IterationCleanup]
public void IterationCleanup() => Console.WriteLine(IterationCleanupCalled + " (" + ++cleanupCounter + ")");
[GlobalSetup]
public ValueTask GlobalSetup() => new ValueTask(Console.Out.WriteLineAsync(GlobalSetupCalled));
[GlobalCleanup]
public ValueTask GlobalCleanup() => new ValueTask(Console.Out.WriteLineAsync(GlobalCleanupCalled));
[Benchmark]
public void Benchmark() => Console.WriteLine(BenchmarkCalled);
}
[Fact]
public void AllSetupAndCleanupMethodRunsAsyncGenericValueTaskSetupTest()
{
var logger = new OutputLogger(Output);
var miniJob = Job.Default.With(RunStrategy.Monitoring).WithWarmupCount(2).WithIterationCount(3).WithInvocationCount(1).WithUnrollFactor(1).WithId("MiniJob");
var config = CreateSimpleConfig(logger, miniJob);
CanExecute<AllSetupAndCleanupAttributeBenchmarksAsyncGenericValueTaskSetup>(config);
var actualLogLines = logger.GetLog().Split('\r', '\n').Where(line => line.StartsWith(Prefix)).ToArray();
foreach (string line in actualLogLines)
Output.WriteLine(line);
Assert.Equal(expectedLogLines, actualLogLines);
}
public class AllSetupAndCleanupAttributeBenchmarksAsyncGenericValueTaskSetup
{
private int setupCounter;
private int cleanupCounter;
[IterationSetup]
public void IterationSetup() => Console.WriteLine(IterationSetupCalled + " (" + ++setupCounter + ")");
[IterationCleanup]
public void IterationCleanup() => Console.WriteLine(IterationCleanupCalled + " (" + ++cleanupCounter + ")");
[GlobalSetup]
public async ValueTask<int> GlobalSetup()
{
await Console.Out.WriteLineAsync(GlobalSetupCalled);
return 42;
}
[GlobalCleanup]
public async ValueTask<int> GlobalCleanup()
{
await Console.Out.WriteLineAsync(GlobalCleanupCalled);
return 42;
}
[Benchmark]
public void Benchmark() => Console.WriteLine(BenchmarkCalled);
}
}
}
| |
// 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.ObjectModel;
using System.Threading;
using Xunit;
namespace System.IO.Tests
{
public class FileSystemWatcherFilterListTests : FileSystemWatcherTest
{
[Fact]
public void DefaultFiltersValue()
{
var watcher = new FileSystemWatcher();
Assert.Equal(0, watcher.Filters.Count);
Assert.Empty(watcher.Filters);
Assert.NotNull(watcher.Filters);
Assert.Equal(new string[] { }, watcher.Filters);
}
[Fact]
public void AddFilterToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll" }, watcher.Filters);
}
[Fact]
public void FiltersCaseSensitive()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("foo");
Assert.Equal("foo", watcher.Filters[0]);
watcher.Filters[0] = "Foo";
Assert.Equal("Foo", watcher.Filters[0]);
}
[Fact]
public void RemoveFilterFromFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Remove("*.pdb");
Assert.DoesNotContain(watcher.Filters, t => t == "*.pdb");
Assert.Equal(new string[] { "*.dll" }, watcher.Filters);
// No Exception is thrown while removing an item which is not present in the list.
watcher.Filters.Remove("*.pdb");
}
[Fact]
public void AddEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void AddNullToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void SetEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters[0] = string.Empty;
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal("*", watcher.Filters[0]);
Assert.Equal(new string[] { "*", "*.dll"}, watcher.Filters);
}
[Fact]
public void RemoveEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
watcher.Filters.Remove(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void RemoveAtFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.RemoveAt(0);
Assert.Equal(1, watcher.Filters.Count);
Assert.Equal("*.dll", watcher.Filter);
Assert.Equal(new string[] {"*.dll" }, watcher.Filters);
}
[Fact]
public void RemoveAtEmptyFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.RemoveAt(0);
Assert.Equal(0, watcher.Filters.Count);
Assert.Equal("*", watcher.Filter);
Assert.Equal(new string[] { }, watcher.Filters);
}
[Fact]
public void SetNullToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters[0] = null;
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal("*", watcher.Filters[0]);
Assert.Equal(new string[] { "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void ContainsEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.False(watcher.Filters.Contains(string.Empty));
Assert.True(watcher.Filters.Contains("*"));
}
[Fact]
public void ContainsNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.False(watcher.Filters.Contains(null));
Assert.True(watcher.Filters.Contains("*"));
}
[Fact]
public void ContainsFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.True(watcher.Filters.Contains("*.pdb"));
}
[Fact]
public void InsertEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, string.Empty);
Assert.Equal("*", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, null);
Assert.Equal("*", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, "foo");
Assert.Equal("foo", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "foo", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertAtZero()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(0, "foo");
Assert.Equal("foo", watcher.Filters[0]);
Assert.Equal("foo", watcher.Filter);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "foo", "*.pdb", "*.dll" }, watcher.Filters);
}
[Fact]
public void IndexOfEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(-1, watcher.Filters.IndexOf(string.Empty));
}
[Fact]
public void IndexOfNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.Equal(-1, watcher.Filters.IndexOf(null));
}
[Fact]
public void IndexOfFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Equal(-1, watcher.Filters.IndexOf("foo"));
Assert.Equal(0, watcher.Filters.IndexOf("*.pdb"));
}
[Fact]
public void GetTypeFilters()
{
var watcher = new FileSystemWatcher();
Assert.IsAssignableFrom<Collection<string>>(watcher.Filters);
}
[Fact]
public void ClearFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Equal(0, watcher.Filters.Count);
Assert.Equal(new string[] { }, watcher.Filters) ;
}
[Fact]
public void GetFilterAfterFiltersClear()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path);
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Equal("*", watcher.Filter);
Assert.Equal(new string[] { }, watcher.Filters);
}
}
[Fact]
public void GetFiltersAfterFiltersClear()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path);
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters[0]);
Assert.Equal(0, watcher.Filters.Count);
Assert.Empty(watcher.Filters);
Assert.NotNull(watcher.Filters);
}
}
[Fact]
public void InvalidOperationsOnFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters.Insert(4, "*"));
watcher.Filters.Clear();
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters[0]);
}
[Fact]
public void SetAndGetFilterProperty()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path, "*.pdb");
watcher.Filters.Add("foo");
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "foo" }, watcher.Filters);
watcher.Filter = "*.doc";
Assert.Equal(1, watcher.Filters.Count);
Assert.Equal("*.doc", watcher.Filter);
Assert.Equal("*.doc", watcher.Filters[0]);
Assert.Equal(new string[] { "*.doc" }, watcher.Filters);
watcher.Filters.Clear();
Assert.Equal("*", watcher.Filter);
}
}
[Fact]
public void SetAndGetFiltersProperty()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path, "*.pdb");
watcher.Filters.Add("foo");
Assert.Equal(new string[] { "*.pdb", "foo" }, watcher.Filters);
}
}
[Fact]
public void FileSystemWatcher_File_Delete_MultipleFilters()
{
// Check delete events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
fileOne.Create().Dispose();
fileTwo.Create().Dispose();
fileThree.Create().Dispose();
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => fileOne.Delete(), cleanup: null, expectedPath : fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => fileTwo.Delete(), cleanup: null, expectedPath: fileTwo.FullName );
ExpectNoEvent(watcher, WatcherChangeTypes.Deleted, () => fileThree.Delete(), cleanup: null, expectedPath: fileThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_Directory_Create_MultipleFilters()
{
// Check create events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
string directoryOne = Path.Combine(directory.FullName, GetTestFileName());
string directoryTwo = Path.Combine(directory.FullName, GetTestFileName());
string directoryThree = Path.Combine(directory.FullName, GetTestFileName());
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(Path.GetFileName(directoryOne));
watcher.Filters.Add(Path.GetFileName(directoryTwo));
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryOne), cleanup: null, expectedPath: directoryOne);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryTwo), cleanup: null, expectedPath: directoryTwo);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryThree), cleanup: null, expectedPath: directoryThree);
}
}
[Fact]
public void FileSystemWatcher_Directory_Create_Filter_Ctor()
{
// Check create events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
string directoryOne = Path.Combine(directory.FullName, GetTestFileName());
string directoryTwo = Path.Combine(directory.FullName, GetTestFileName());
string directoryThree = Path.Combine(directory.FullName, GetTestFileName());
using (var watcher = new FileSystemWatcher(directory.FullName, Path.GetFileName(directoryOne)))
{
watcher.Filters.Add(Path.GetFileName(directoryTwo));
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryOne), cleanup: null, expectedPath: directoryOne);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryTwo), cleanup: null, expectedPath: directoryTwo);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryThree), cleanup: null, expectedPath: directoryThree);
}
}
[Fact]
public void FileSystemWatcher_Directory_Delete_MultipleFilters()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
DirectoryInfo directoryOne = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
DirectoryInfo directoryTwo = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
DirectoryInfo directoryThree = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(Path.GetFileName(directoryOne.FullName));
watcher.Filters.Add(Path.GetFileName(directoryTwo.FullName));
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => directoryOne.Delete(), cleanup: null, expectedPath: directoryOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => directoryTwo.Delete(), cleanup: null, expectedPath: directoryTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Deleted, () => directoryThree.Delete(), cleanup: null, expectedPath: directoryThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_File_Create_MultipleFilters()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileOne.Create().Dispose(), cleanup: null, expectedPath: fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileTwo.Create().Dispose(), cleanup: null, expectedPath: fileTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => fileThree.Create().Dispose(), cleanup: null, expectedPath: fileThree.FullName);
}
}
}
}
| |
/*
* 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.IO;
using System.Runtime.InteropServices;
using OpenSim.Region.PhysicsModules.SharedBase;
using PrimMesher;
using OpenMetaverse;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace OpenSim.Region.PhysicsModule.ubODEMeshing
{
public class MeshBuildingData
{
private class vertexcomp : IEqualityComparer<Vertex>
{
public bool Equals(Vertex v1, Vertex v2)
{
if (v1.X == v2.X && v1.Y == v2.Y && v1.Z == v2.Z)
return true;
else
return false;
}
public int GetHashCode(Vertex v)
{
int a = v.X.GetHashCode();
int b = v.Y.GetHashCode();
int c = v.Z.GetHashCode();
return (a << 16) ^ (b << 8) ^ c;
}
}
public Dictionary<Vertex, int> m_vertices;
public List<Triangle> m_triangles;
public float m_obbXmin;
public float m_obbXmax;
public float m_obbYmin;
public float m_obbYmax;
public float m_obbZmin;
public float m_obbZmax;
public Vector3 m_centroid;
public int m_centroidDiv;
public MeshBuildingData()
{
vertexcomp vcomp = new vertexcomp();
m_vertices = new Dictionary<Vertex, int>(vcomp);
m_triangles = new List<Triangle>();
m_centroid = Vector3.Zero;
m_centroidDiv = 0;
m_obbXmin = float.MaxValue;
m_obbXmax = float.MinValue;
m_obbYmin = float.MaxValue;
m_obbYmax = float.MinValue;
m_obbZmin = float.MaxValue;
m_obbZmax = float.MinValue;
}
}
[Serializable()]
public class Mesh : IMesh
{
float[] vertices;
int[] indexes;
Vector3 m_obb;
Vector3 m_obboffset;
[NonSerialized()]
MeshBuildingData m_bdata;
[NonSerialized()]
GCHandle vhandler;
[NonSerialized()]
GCHandle ihandler;
[NonSerialized()]
IntPtr m_verticesPtr = IntPtr.Zero;
[NonSerialized()]
IntPtr m_indicesPtr = IntPtr.Zero;
[NonSerialized()]
int m_vertexCount = 0;
[NonSerialized()]
int m_indexCount = 0;
public int RefCount { get; set; }
public AMeshKey Key { get; set; }
public Mesh(bool forbuild)
{
if(forbuild)
m_bdata = new MeshBuildingData();
m_obb = new Vector3(0.5f, 0.5f, 0.5f);
m_obboffset = Vector3.Zero;
}
public Mesh Scale(Vector3 scale)
{
if (m_verticesPtr == null || m_indicesPtr == null)
return null;
Mesh result = new Mesh(false);
float x = scale.X;
float y = scale.Y;
float z = scale.Z;
float tmp;
tmp = m_obb.X * x;
if(tmp < 0.0005f)
tmp = 0.0005f;
result.m_obb.X = tmp;
tmp = m_obb.Y * y;
if(tmp < 0.0005f)
tmp = 0.0005f;
result.m_obb.Y = tmp;
tmp = m_obb.Z * z;
if(tmp < 0.0005f)
tmp = 0.0005f;
result.m_obb.Z = tmp;
result.m_obboffset.X = m_obboffset.X * x;
result.m_obboffset.Y = m_obboffset.Y * y;
result.m_obboffset.Z = m_obboffset.Z * z;
result.vertices = new float[vertices.Length];
int j = 0;
for (int i = 0; i < m_vertexCount; i++)
{
result.vertices[j] = vertices[j] * x;
j++;
result.vertices[j] = vertices[j] * y;
j++;
result.vertices[j] = vertices[j] * z;
j++;
}
result.indexes = new int[indexes.Length];
indexes.CopyTo(result.indexes,0);
result.pinMemory();
return result;
}
public Mesh Clone()
{
Mesh result = new Mesh(false);
if (m_bdata != null)
{
result.m_bdata = new MeshBuildingData();
foreach (Triangle t in m_bdata.m_triangles)
{
result.Add(new Triangle(t.v1.Clone(), t.v2.Clone(), t.v3.Clone()));
}
result.m_bdata.m_centroid = m_bdata.m_centroid;
result.m_bdata.m_centroidDiv = m_bdata.m_centroidDiv;
result.m_bdata.m_obbXmin = m_bdata.m_obbXmin;
result.m_bdata.m_obbXmax = m_bdata.m_obbXmax;
result.m_bdata.m_obbYmin = m_bdata.m_obbYmin;
result.m_bdata.m_obbYmax = m_bdata.m_obbYmax;
result.m_bdata.m_obbZmin = m_bdata.m_obbZmin;
result.m_bdata.m_obbZmax = m_bdata.m_obbZmax;
}
result.m_obb = m_obb;
result.m_obboffset = m_obboffset;
return result;
}
public void addVertexLStats(Vertex v)
{
float x = v.X;
float y = v.Y;
float z = v.Z;
m_bdata.m_centroid.X += x;
m_bdata.m_centroid.Y += y;
m_bdata.m_centroid.Z += z;
m_bdata.m_centroidDiv++;
if (x > m_bdata.m_obbXmax)
m_bdata.m_obbXmax = x;
if (x < m_bdata.m_obbXmin)
m_bdata.m_obbXmin = x;
if (y > m_bdata.m_obbYmax)
m_bdata.m_obbYmax = y;
if (y < m_bdata.m_obbYmin)
m_bdata.m_obbYmin = y;
if (z > m_bdata.m_obbZmax)
m_bdata.m_obbZmax = z;
if (z < m_bdata.m_obbZmin)
m_bdata.m_obbZmin = z;
}
public void Add(Triangle triangle)
{
if (m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero)
throw new NotSupportedException("Attempt to Add to a pinned Mesh");
triangle.v1.X = (float)Math.Round(triangle.v1.X, 6);
triangle.v1.Y = (float)Math.Round(triangle.v1.Y, 6);
triangle.v1.Z = (float)Math.Round(triangle.v1.Z, 6);
triangle.v2.X = (float)Math.Round(triangle.v2.X, 6);
triangle.v2.Y = (float)Math.Round(triangle.v2.Y, 6);
triangle.v2.Z = (float)Math.Round(triangle.v2.Z, 6);
triangle.v3.X = (float)Math.Round(triangle.v3.X, 6);
triangle.v3.Y = (float)Math.Round(triangle.v3.Y, 6);
triangle.v3.Z = (float)Math.Round(triangle.v3.Z, 6);
if ((triangle.v1.X == triangle.v2.X && triangle.v1.Y == triangle.v2.Y && triangle.v1.Z ==
triangle.v2.Z)
|| (triangle.v1.X == triangle.v3.X && triangle.v1.Y == triangle.v3.Y && triangle.v1.Z ==
triangle.v3.Z)
|| (triangle.v2.X == triangle.v3.X && triangle.v2.Y == triangle.v3.Y && triangle.v2.Z ==
triangle.v3.Z)
)
{
return;
}
if (m_bdata.m_vertices.Count == 0)
{
m_bdata.m_centroidDiv = 0;
m_bdata.m_centroid = Vector3.Zero;
}
if (!m_bdata.m_vertices.ContainsKey(triangle.v1))
{
m_bdata.m_vertices[triangle.v1] = m_bdata.m_vertices.Count;
addVertexLStats(triangle.v1);
}
if (!m_bdata.m_vertices.ContainsKey(triangle.v2))
{
m_bdata.m_vertices[triangle.v2] = m_bdata.m_vertices.Count;
addVertexLStats(triangle.v2);
}
if (!m_bdata.m_vertices.ContainsKey(triangle.v3))
{
m_bdata.m_vertices[triangle.v3] = m_bdata.m_vertices.Count;
addVertexLStats(triangle.v3);
}
m_bdata.m_triangles.Add(triangle);
}
public Vector3 GetCentroid()
{
return m_obboffset;
}
public Vector3 GetOBB()
{
return m_obb;
/*
float x, y, z;
if (m_bdata.m_centroidDiv > 0)
{
x = (m_bdata.m_obbXmax - m_bdata.m_obbXmin) * 0.5f;
y = (m_bdata.m_obbYmax - m_bdata.m_obbYmin) * 0.5f;
z = (m_bdata.m_obbZmax - m_bdata.m_obbZmin) * 0.5f;
}
else // ??
{
x = 0.5f;
y = 0.5f;
z = 0.5f;
}
return new Vector3(x, y, z);
*/
}
public int numberVertices()
{
return m_bdata.m_vertices.Count;
}
public int numberTriangles()
{
return m_bdata.m_triangles.Count;
}
public List<Vector3> getVertexList()
{
List<Vector3> result = new List<Vector3>();
foreach (Vertex v in m_bdata.m_vertices.Keys)
{
result.Add(new Vector3(v.X, v.Y, v.Z));
}
return result;
}
public float[] getVertexListAsFloat()
{
if (m_bdata.m_vertices == null)
throw new NotSupportedException();
float[] result = new float[m_bdata.m_vertices.Count * 3];
foreach (KeyValuePair<Vertex, int> kvp in m_bdata.m_vertices)
{
Vertex v = kvp.Key;
int i = kvp.Value;
result[3 * i + 0] = v.X;
result[3 * i + 1] = v.Y;
result[3 * i + 2] = v.Z;
}
return result;
}
public float[] getVertexListAsFloatLocked()
{
return null;
}
public void getVertexListAsPtrToFloatArray(out IntPtr _vertices, out int vertexStride, out int vertexCount)
{
// A vertex is 3 floats
vertexStride = 3 * sizeof(float);
// If there isn't an unmanaged array allocated yet, do it now
if (m_verticesPtr == IntPtr.Zero && m_bdata != null)
{
vertices = getVertexListAsFloat();
// Each vertex is 3 elements (floats)
m_vertexCount = vertices.Length / 3;
vhandler = GCHandle.Alloc(vertices, GCHandleType.Pinned);
m_verticesPtr = vhandler.AddrOfPinnedObject();
GC.AddMemoryPressure(Buffer.ByteLength(vertices));
}
_vertices = m_verticesPtr;
vertexCount = m_vertexCount;
}
public int[] getIndexListAsInt()
{
if (m_bdata.m_triangles == null)
throw new NotSupportedException();
int[] result = new int[m_bdata.m_triangles.Count * 3];
for (int i = 0; i < m_bdata.m_triangles.Count; i++)
{
Triangle t = m_bdata.m_triangles[i];
result[3 * i + 0] = m_bdata.m_vertices[t.v1];
result[3 * i + 1] = m_bdata.m_vertices[t.v2];
result[3 * i + 2] = m_bdata.m_vertices[t.v3];
}
return result;
}
/// <summary>
/// creates a list of index values that defines triangle faces. THIS METHOD FREES ALL NON-PINNED MESH DATA
/// </summary>
/// <returns></returns>
public int[] getIndexListAsIntLocked()
{
return null;
}
public void getIndexListAsPtrToIntArray(out IntPtr indices, out int triStride, out int indexCount)
{
// If there isn't an unmanaged array allocated yet, do it now
if (m_indicesPtr == IntPtr.Zero && m_bdata != null)
{
indexes = getIndexListAsInt();
m_indexCount = indexes.Length;
ihandler = GCHandle.Alloc(indexes, GCHandleType.Pinned);
m_indicesPtr = ihandler.AddrOfPinnedObject();
GC.AddMemoryPressure(Buffer.ByteLength(indexes));
}
// A triangle is 3 ints (indices)
triStride = 3 * sizeof(int);
indices = m_indicesPtr;
indexCount = m_indexCount;
}
public void releasePinned()
{
if (m_verticesPtr != IntPtr.Zero)
{
vhandler.Free();
GC.RemoveMemoryPressure(Buffer.ByteLength(vertices));
vertices = null;
m_verticesPtr = IntPtr.Zero;
}
if (m_indicesPtr != IntPtr.Zero)
{
ihandler.Free();
GC.RemoveMemoryPressure(Buffer.ByteLength(indexes));
indexes = null;
m_indicesPtr = IntPtr.Zero;
}
}
/// <summary>
/// frees up the source mesh data to minimize memory - call this method after calling get*Locked() functions
/// </summary>
public void releaseSourceMeshData()
{
if (m_bdata != null)
{
m_bdata.m_triangles = null;
m_bdata.m_vertices = null;
}
}
public void releaseBuildingMeshData()
{
if (m_bdata != null)
{
m_bdata.m_triangles = null;
m_bdata.m_vertices = null;
m_bdata = null;
}
}
public void Append(IMesh newMesh)
{
if (m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero)
throw new NotSupportedException("Attempt to Append to a pinned Mesh");
if (!(newMesh is Mesh))
return;
foreach (Triangle t in ((Mesh)newMesh).m_bdata.m_triangles)
Add(t);
}
// Do a linear transformation of mesh.
public void TransformLinear(float[,] matrix, float[] offset)
{
if (m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero)
throw new NotSupportedException("Attempt to TransformLinear a pinned Mesh");
foreach (Vertex v in m_bdata.m_vertices.Keys)
{
if (v == null)
continue;
float x, y, z;
x = v.X*matrix[0, 0] + v.Y*matrix[1, 0] + v.Z*matrix[2, 0];
y = v.X*matrix[0, 1] + v.Y*matrix[1, 1] + v.Z*matrix[2, 1];
z = v.X*matrix[0, 2] + v.Y*matrix[1, 2] + v.Z*matrix[2, 2];
v.X = x + offset[0];
v.Y = y + offset[1];
v.Z = z + offset[2];
}
}
public void DumpRaw(String path, String name, String title)
{
if (path == null)
return;
if (m_bdata == null)
return;
String fileName = name + "_" + title + ".raw";
String completePath = System.IO.Path.Combine(path, fileName);
StreamWriter sw = new StreamWriter(completePath);
foreach (Triangle t in m_bdata.m_triangles)
{
String s = t.ToStringRaw();
sw.WriteLine(s);
}
sw.Close();
}
public void TrimExcess()
{
m_bdata.m_triangles.TrimExcess();
}
public void pinMemory()
{
m_vertexCount = vertices.Length / 3;
vhandler = GCHandle.Alloc(vertices, GCHandleType.Pinned);
m_verticesPtr = vhandler.AddrOfPinnedObject();
GC.AddMemoryPressure(Buffer.ByteLength(vertices));
m_indexCount = indexes.Length;
ihandler = GCHandle.Alloc(indexes, GCHandleType.Pinned);
m_indicesPtr = ihandler.AddrOfPinnedObject();
GC.AddMemoryPressure(Buffer.ByteLength(indexes));
}
public void PrepForOde()
{
// If there isn't an unmanaged array allocated yet, do it now
if (m_verticesPtr == IntPtr.Zero)
vertices = getVertexListAsFloat();
// If there isn't an unmanaged array allocated yet, do it now
if (m_indicesPtr == IntPtr.Zero)
indexes = getIndexListAsInt();
float x, y, z;
if (m_bdata.m_centroidDiv > 0)
{
m_obboffset = new Vector3(m_bdata.m_centroid.X / m_bdata.m_centroidDiv, m_bdata.m_centroid.Y / m_bdata.m_centroidDiv, m_bdata.m_centroid.Z / m_bdata.m_centroidDiv);
x = (m_bdata.m_obbXmax - m_bdata.m_obbXmin) * 0.5f;
if(x < 0.0005f)
x = 0.0005f;
y = (m_bdata.m_obbYmax - m_bdata.m_obbYmin) * 0.5f;
if(y < 0.0005f)
y = 0.0005f;
z = (m_bdata.m_obbZmax - m_bdata.m_obbZmin) * 0.5f;
if(z < 0.0005f)
z = 0.0005f;
}
else
{
m_obboffset = Vector3.Zero;
x = 0.5f;
y = 0.5f;
z = 0.5f;
}
m_obb = new Vector3(x, y, z);
releaseBuildingMeshData();
pinMemory();
}
public bool ToStream(Stream st)
{
if (m_indicesPtr == IntPtr.Zero || m_verticesPtr == IntPtr.Zero)
return false;
bool ok = true;
try
{
using(BinaryWriter bw = new BinaryWriter(st))
{
bw.Write(m_vertexCount);
bw.Write(m_indexCount);
for (int i = 0; i < 3 * m_vertexCount; i++)
bw.Write(vertices[i]);
for (int i = 0; i < m_indexCount; i++)
bw.Write(indexes[i]);
bw.Write(m_obb.X);
bw.Write(m_obb.Y);
bw.Write(m_obb.Z);
bw.Write(m_obboffset.X);
bw.Write(m_obboffset.Y);
bw.Write(m_obboffset.Z);
bw.Flush();
bw.Close();
}
}
catch
{
ok = false;
}
return ok;
}
public static Mesh FromStream(Stream st, AMeshKey key)
{
Mesh mesh = new Mesh(false);
bool ok = true;
try
{
using(BinaryReader br = new BinaryReader(st))
{
mesh.m_vertexCount = br.ReadInt32();
mesh.m_indexCount = br.ReadInt32();
int n = 3 * mesh.m_vertexCount;
mesh.vertices = new float[n];
for (int i = 0; i < n; i++)
mesh.vertices[i] = br.ReadSingle();
mesh.indexes = new int[mesh.m_indexCount];
for (int i = 0; i < mesh.m_indexCount; i++)
mesh.indexes[i] = br.ReadInt32();
mesh.m_obb.X = br.ReadSingle();
mesh.m_obb.Y = br.ReadSingle();
mesh.m_obb.Z = br.ReadSingle();
mesh.m_obboffset.X = br.ReadSingle();
mesh.m_obboffset.Y = br.ReadSingle();
mesh.m_obboffset.Z = br.ReadSingle();
}
}
catch
{
ok = false;
}
if (ok)
{
mesh.pinMemory();
mesh.Key = key;
mesh.RefCount = 1;
return mesh;
}
mesh.vertices = null;
mesh.indexes = null;
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Automation.Peers;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// Displays a collection of items.
/// </summary>
[PseudoClasses(":empty", ":singleitem")]
public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener, IChildIndexProvider
{
/// <summary>
/// The default value for the <see cref="ItemsPanel"/> property.
/// </summary>
private static readonly FuncTemplate<IPanel> DefaultPanel =
new FuncTemplate<IPanel>(() => new StackPanel());
/// <summary>
/// Defines the <see cref="Items"/> property.
/// </summary>
public static readonly DirectProperty<ItemsControl, IEnumerable?> ItemsProperty =
AvaloniaProperty.RegisterDirect<ItemsControl, IEnumerable?>(nameof(Items), o => o.Items, (o, v) => o.Items = v);
/// <summary>
/// Defines the <see cref="ItemCount"/> property.
/// </summary>
public static readonly DirectProperty<ItemsControl, int> ItemCountProperty =
AvaloniaProperty.RegisterDirect<ItemsControl, int>(nameof(ItemCount), o => o.ItemCount);
/// <summary>
/// Defines the <see cref="ItemsPanel"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IPanel>> ItemsPanelProperty =
AvaloniaProperty.Register<ItemsControl, ITemplate<IPanel>>(nameof(ItemsPanel), DefaultPanel);
/// <summary>
/// Defines the <see cref="ItemTemplate"/> property.
/// </summary>
public static readonly StyledProperty<IDataTemplate?> ItemTemplateProperty =
AvaloniaProperty.Register<ItemsControl, IDataTemplate?>(nameof(ItemTemplate));
private IEnumerable? _items = new AvaloniaList<object>();
private int _itemCount;
private IItemContainerGenerator? _itemContainerGenerator;
private EventHandler<ChildIndexChangedEventArgs>? _childIndexChanged;
/// <summary>
/// Initializes static members of the <see cref="ItemsControl"/> class.
/// </summary>
static ItemsControl()
{
ItemsProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemsChanged(e));
ItemTemplateProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemTemplateChanged(e));
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemsControl"/> class.
/// </summary>
public ItemsControl()
{
UpdatePseudoClasses(0);
SubscribeToItems(_items);
}
/// <summary>
/// Gets the <see cref="IItemContainerGenerator"/> for the control.
/// </summary>
public IItemContainerGenerator ItemContainerGenerator
{
get
{
if (_itemContainerGenerator == null)
{
_itemContainerGenerator = CreateItemContainerGenerator();
_itemContainerGenerator.ItemTemplate = ItemTemplate;
_itemContainerGenerator.Materialized += (_, e) => OnContainersMaterialized(e);
_itemContainerGenerator.Dematerialized += (_, e) => OnContainersDematerialized(e);
_itemContainerGenerator.Recycled += (_, e) => OnContainersRecycled(e);
}
return _itemContainerGenerator;
}
}
/// <summary>
/// Gets or sets the items to display.
/// </summary>
[Content]
public IEnumerable? Items
{
get { return _items; }
set { SetAndRaise(ItemsProperty, ref _items, value); }
}
/// <summary>
/// Gets the number of items in <see cref="Items"/>.
/// </summary>
public int ItemCount
{
get => _itemCount;
private set => SetAndRaise(ItemCountProperty, ref _itemCount, value);
}
/// <summary>
/// Gets or sets the panel used to display the items.
/// </summary>
public ITemplate<IPanel> ItemsPanel
{
get { return GetValue(ItemsPanelProperty); }
set { SetValue(ItemsPanelProperty, value); }
}
/// <summary>
/// Gets or sets the data template used to display the items in the control.
/// </summary>
public IDataTemplate? ItemTemplate
{
get { return GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
/// <summary>
/// Gets the items presenter control.
/// </summary>
public IItemsPresenter? Presenter
{
get;
protected set;
}
private protected bool WrapFocus { get; set; }
event EventHandler<ChildIndexChangedEventArgs>? IChildIndexProvider.ChildIndexChanged
{
add => _childIndexChanged += value;
remove => _childIndexChanged -= value;
}
/// <inheritdoc/>
void IItemsPresenterHost.RegisterItemsPresenter(IItemsPresenter presenter)
{
if (Presenter is IChildIndexProvider oldInnerProvider)
{
oldInnerProvider.ChildIndexChanged -= PresenterChildIndexChanged;
}
Presenter = presenter;
ItemContainerGenerator?.Clear();
if (Presenter is IChildIndexProvider innerProvider)
{
innerProvider.ChildIndexChanged += PresenterChildIndexChanged;
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs());
}
}
void ICollectionChangedListener.PreChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
}
void ICollectionChangedListener.Changed(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
}
void ICollectionChangedListener.PostChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
ItemsCollectionChanged(sender, e);
}
/// <summary>
/// Gets the item at the specified index in a collection.
/// </summary>
/// <param name="items">The collection.</param>
/// <param name="index">The index.</param>
/// <returns>The item at the given index or null if the index is out of bounds.</returns>
protected static object? ElementAt(IEnumerable? items, int index)
{
if (index != -1 && index < items.Count())
{
return items!.ElementAt(index) ?? null;
}
else
{
return null;
}
}
/// <summary>
/// Gets the index of an item in a collection.
/// </summary>
/// <param name="items">The collection.</param>
/// <param name="item">The item.</param>
/// <returns>The index of the item or -1 if the item was not found.</returns>
protected static int IndexOf(IEnumerable? items, object item)
{
if (items != null && item != null)
{
var list = items as IList;
if (list != null)
{
return list.IndexOf(item);
}
else
{
int index = 0;
foreach (var i in items)
{
if (Equals(i, item))
{
return index;
}
++index;
}
}
}
return -1;
}
/// <summary>
/// Creates the <see cref="ItemContainerGenerator"/> for the control.
/// </summary>
/// <returns>
/// An <see cref="IItemContainerGenerator"/>.
/// </returns>
protected virtual IItemContainerGenerator CreateItemContainerGenerator()
{
return new ItemContainerGenerator(this);
}
/// <summary>
/// Called when new containers are materialized for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersMaterialized(ItemContainerEventArgs e)
{
foreach (var container in e.Containers)
{
// If the item is its own container, then it will be added to the logical tree when
// it was added to the Items collection.
if (container.ContainerControl != null && container.ContainerControl != container.Item)
{
LogicalChildren.Add(container.ContainerControl);
}
}
}
/// <summary>
/// Called when containers are dematerialized for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersDematerialized(ItemContainerEventArgs e)
{
foreach (var container in e.Containers)
{
// If the item is its own container, then it will be removed from the logical tree
// when it is removed from the Items collection.
if (container.ContainerControl != container.Item)
{
LogicalChildren.Remove(container.ContainerControl);
}
}
}
/// <summary>
/// Called when containers are recycled for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersRecycled(ItemContainerEventArgs e)
{
}
/// <summary>
/// Handles directional navigation within the <see cref="ItemsControl"/>.
/// </summary>
/// <param name="e">The key events.</param>
protected override void OnKeyDown(KeyEventArgs e)
{
if (!e.Handled)
{
var focus = FocusManager.Instance;
var direction = e.Key.ToNavigationDirection();
var container = Presenter?.Panel as INavigableContainer;
if (container == null ||
focus?.Current == null ||
direction == null ||
direction.Value.IsTab())
{
return;
}
IVisual? current = focus.Current;
while (current != null)
{
if (current.VisualParent == container && current is IInputElement inputElement)
{
var next = GetNextControl(container, direction.Value, inputElement, WrapFocus);
if (next != null)
{
focus.Focus(next, NavigationMethod.Directional, e.KeyModifiers);
e.Handled = true;
}
break;
}
current = current.VisualParent;
}
}
base.OnKeyDown(e);
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new ItemsControlAutomationPeer(this);
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == ItemCountProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<int>());
}
}
/// <summary>
/// Called when the <see cref="Items"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void ItemsChanged(AvaloniaPropertyChangedEventArgs e)
{
var oldValue = e.OldValue as IEnumerable;
var newValue = e.NewValue as IEnumerable;
if (oldValue is INotifyCollectionChanged incc)
{
CollectionChangedEventManager.Instance.RemoveListener(incc, this);
}
UpdateItemCount();
RemoveControlItemsFromLogicalChildren(oldValue);
AddControlItemsToLogicalChildren(newValue);
if (Presenter != null)
{
Presenter.Items = newValue;
}
SubscribeToItems(newValue);
}
/// <summary>
/// Called when the <see cref="INotifyCollectionChanged.CollectionChanged"/> event is
/// raised on <see cref="Items"/>.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
protected virtual void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateItemCount();
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
AddControlItemsToLogicalChildren(e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
RemoveControlItemsFromLogicalChildren(e.OldItems);
break;
}
Presenter?.ItemsChanged(e);
}
/// <summary>
/// Given a collection of items, adds those that are controls to the logical children.
/// </summary>
/// <param name="items">The items.</param>
private void AddControlItemsToLogicalChildren(IEnumerable? items)
{
var toAdd = new List<ILogical>();
if (items != null)
{
foreach (var i in items)
{
var control = i as IControl;
if (control != null && !LogicalChildren.Contains(control))
{
toAdd.Add(control);
}
}
}
LogicalChildren.AddRange(toAdd);
}
/// <summary>
/// Given a collection of items, removes those that are controls to from logical children.
/// </summary>
/// <param name="items">The items.</param>
private void RemoveControlItemsFromLogicalChildren(IEnumerable? items)
{
var toRemove = new List<ILogical>();
if (items != null)
{
foreach (var i in items)
{
var control = i as IControl;
if (control != null)
{
toRemove.Add(control);
}
}
}
LogicalChildren.RemoveAll(toRemove);
}
/// <summary>
/// Subscribes to an <see cref="Items"/> collection.
/// </summary>
/// <param name="items">The items collection.</param>
private void SubscribeToItems(IEnumerable? items)
{
if (items is INotifyCollectionChanged incc)
{
CollectionChangedEventManager.Instance.AddListener(incc, this);
}
}
/// <summary>
/// Called when the <see cref="ItemTemplate"/> changes.
/// </summary>
/// <param name="e">The event args.</param>
private void ItemTemplateChanged(AvaloniaPropertyChangedEventArgs e)
{
if (_itemContainerGenerator != null)
{
_itemContainerGenerator.ItemTemplate = (IDataTemplate?)e.NewValue;
// TODO: Rebuild the item containers.
}
}
private void UpdateItemCount()
{
if (Items == null)
{
ItemCount = 0;
}
else if (Items is IList list)
{
ItemCount = list.Count;
}
else
{
ItemCount = Items.Count();
}
}
private void UpdatePseudoClasses(int itemCount)
{
PseudoClasses.Set(":empty", itemCount == 0);
PseudoClasses.Set(":singleitem", itemCount == 1);
}
protected static IInputElement? GetNextControl(
INavigableContainer container,
NavigationDirection direction,
IInputElement? from,
bool wrap)
{
IInputElement? result;
var c = from;
do
{
result = container.GetControl(direction, c, wrap);
from = from ?? result;
if (result != null &&
result.Focusable &&
result.IsEffectivelyEnabled &&
result.IsEffectivelyVisible)
{
return result;
}
c = result;
} while (c != null && c != from);
return null;
}
private void PresenterChildIndexChanged(object? sender, ChildIndexChangedEventArgs e)
{
_childIndexChanged?.Invoke(this, e);
}
int IChildIndexProvider.GetChildIndex(ILogical child)
{
return Presenter is IChildIndexProvider innerProvider
? innerProvider.GetChildIndex(child) : -1;
}
bool IChildIndexProvider.TryGetTotalCount(out int count)
{
if (Presenter is IChildIndexProvider presenter
&& presenter.TryGetTotalCount(out count))
{
return true;
}
count = ItemCount;
return true;
}
}
}
| |
using Foundation;
using Intents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Toggl.Core.Analytics;
using Toggl.Core.Models;
using Toggl.Core.Models.Interfaces;
using Toggl.iOS.Intents;
using Toggl.iOS.Models;
using Toggl.Shared;
using UIKit;
namespace Toggl.iOS.Services
{
public class IntentDonationService
{
private IAnalyticsService analyticsService;
public IntentDonationService(IAnalyticsService analyticsService)
{
this.analyticsService = analyticsService;
}
public IObservable<IEnumerable<SiriShortcut>> GetCurrentShortcuts()
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
return Observable.Return(Enumerable.Empty<SiriShortcut>());
return Observable.Create<IEnumerable<SiriShortcut>>(observer =>
{
INVoiceShortcutCenter.SharedCenter.GetAllVoiceShortcuts((shortcuts, error) =>
{
var siriShortcuts =
shortcuts?.Select(shortcut => new SiriShortcut(shortcut))
?? Enumerable.Empty<SiriShortcut>();
observer.OnNext(siriShortcuts);
});
return new CompositeDisposable { };
});
}
public INIntent CreateIntent(SiriShortcutType shortcutType)
{
switch (shortcutType)
{
case SiriShortcutType.Start:
var startTimerIntent = new StartTimerIntent();
startTimerIntent.SuggestedInvocationPhrase = Resources.StartTimerInvocationPhrase;
return startTimerIntent;
case SiriShortcutType.StartFromClipboard:
var startTimerWithClipboardIntent = new StartTimerFromClipboardIntent();
return startTimerWithClipboardIntent;
case SiriShortcutType.Continue:
var continueTimerIntent = new ContinueTimerIntent();
continueTimerIntent.SuggestedInvocationPhrase = Resources.ContinueTimerInvocationPhrase;
return continueTimerIntent;
case SiriShortcutType.Stop:
var stopTimerIntent = new StopTimerIntent();
stopTimerIntent.SuggestedInvocationPhrase = Resources.StopTimerInvocationPhrase;
return stopTimerIntent;
case SiriShortcutType.ShowReport:
var showReportIntent = new ShowReportIntent();
showReportIntent.SuggestedInvocationPhrase = Resources.ShowReportsInvocationPhrase;
return showReportIntent;
/*
case SiriShortcutType.CustomStart:
break;
case SiriShortcutType.CustomReport:
break;
*/
default:
throw new ArgumentOutOfRangeException(nameof(shortcutType), shortcutType, null);
}
}
public void SetDefaultShortcutSuggestions()
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
return;
setupDefaultShortcuts();
}
public void DonateStartTimeEntry(IThreadSafeTimeEntry timeEntry)
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
return;
var relevantShortcuts = new List<INRelevantShortcut>();
var startTimerIntent = new StartTimerIntent();
startTimerIntent.Workspace = new INObject(timeEntry.Workspace.Id.ToString(), timeEntry.Workspace.Name);
if (!string.IsNullOrEmpty(timeEntry.Description))
{
// If any of the tags or the project id were just created and haven't sync we ignore this action until the user repeats it
if (timeEntry.ProjectId < 0 || timeEntry.TagIds.Any(tagId => tagId < 0))
return;
if (timeEntry.ProjectId is long projectId)
{
var projectINObject = new INObject(timeEntry.ProjectId.ToString(), timeEntry.Project.Name);
startTimerIntent.ProjectId = projectINObject;
if (timeEntry.TaskId is long taskId)
{
var taskINObject = new INObject(timeEntry.TaskId.ToString(), timeEntry.Task.Name);
startTimerIntent.TaskId = taskINObject;
}
}
startTimerIntent.EntryDescription = timeEntry.Description;
var tags = timeEntry.TagIds.Select(tag => new INObject(tag.ToString(), tag.ToString())).ToArray();
startTimerIntent.Tags = tags;
var billable = new INObject(timeEntry.Billable.ToString(), timeEntry.Billable.ToString());
startTimerIntent.Billable = billable;
startTimerIntent.SuggestedInvocationPhrase = string.Format(Resources.SiriTrackEntrySuggestedInvocationPhrase, timeEntry.Description);
// Relevant shortcut for the Siri Watch Face
relevantShortcuts.Add(createRelevantShortcut(startTimerIntent));
}
else
{
startTimerIntent.SuggestedInvocationPhrase = Resources.StartTimerInvocationPhrase;
}
var startTimerInteraction = new INInteraction(startTimerIntent, null);
startTimerInteraction.DonateInteraction(trackError);
// Descriptionless Relevant Shortcut. Always added even if the intent has one
var descriptionlessIntent = new StartTimerIntent();
descriptionlessIntent.Workspace = new INObject(timeEntry.Workspace.Id.ToString(), timeEntry.Workspace.Name);
var descriptionlessShortcut = createRelevantShortcut(descriptionlessIntent);
relevantShortcuts.Add(descriptionlessShortcut);
donateRelevantShortcuts(relevantShortcuts.ToArray());
}
public void DonateStopCurrentTimeEntry()
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
return;
var intent = new StopTimerIntent();
intent.SuggestedInvocationPhrase = Resources.StopTimerInvocationPhrase;
var interaction = new INInteraction(intent, null);
interaction.DonateInteraction(trackError);
var shortcut = createRelevantShortcut(intent);
donateRelevantShortcuts(shortcut);
}
public void DonateShowReport(DateRangePeriod period)
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
return;
var intent = new ShowReportPeriodIntent();
switch (period)
{
case DateRangePeriod.Today:
intent.Period = ShowReportPeriodReportPeriod.Today;
break;
case DateRangePeriod.Yesterday:
intent.Period = ShowReportPeriodReportPeriod.Yesterday;
break;
case DateRangePeriod.LastWeek:
intent.Period = ShowReportPeriodReportPeriod.LastWeek;
break;
case DateRangePeriod.LastMonth:
intent.Period = ShowReportPeriodReportPeriod.LastMonth;
break;
case DateRangePeriod.ThisMonth:
intent.Period = ShowReportPeriodReportPeriod.ThisMonth;
break;
case DateRangePeriod.ThisWeek:
intent.Period = ShowReportPeriodReportPeriod.ThisWeek;
break;
case DateRangePeriod.ThisYear:
intent.Period = ShowReportPeriodReportPeriod.ThisYear;
break;
case DateRangePeriod.Unknown:
intent.Period = ShowReportPeriodReportPeriod.Unknown;
break;
}
intent.SuggestedInvocationPhrase = string.Format(
Resources.SiriShowReportSuggestedInvocationPhrase,
period.ToHumanReadableString().ToLower());
var interaction = new INInteraction(intent, null);
interaction.DonateInteraction(trackError);
}
public void DonateShowReport()
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
return;
var intent = new ShowReportIntent();
intent.SuggestedInvocationPhrase = Resources.ShowReportsInvocationPhrase;
var interaction = new INInteraction(intent, null);
interaction.DonateInteraction(trackError);
}
public void ClearAll()
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
return;
INInteraction.DeleteAllInteractions(_ => { });
INVoiceShortcutCenter.SharedCenter.SetShortcutSuggestions(new INShortcut[0]);
INRelevantShortcutStore.DefaultStore.SetRelevantShortcuts(new INRelevantShortcut[0], trackError);
}
private void setupDefaultShortcuts()
{
INRelevanceProvider[] startTimerRelevanceProviders = {
new INDailyRoutineRelevanceProvider(INDailyRoutineSituation.Work),
new INDailyRoutineRelevanceProvider(INDailyRoutineSituation.Gym),
new INDailyRoutineRelevanceProvider(INDailyRoutineSituation.School)
};
INRelevanceProvider[] stopTimerRelevanceProviders = {
new INDailyRoutineRelevanceProvider(INDailyRoutineSituation.Home)
};
var startShortcut = new INShortcut(CreateIntent(SiriShortcutType.Start));
var startRelevantShorcut = new INRelevantShortcut(startShortcut);
startRelevantShorcut.RelevanceProviders = startTimerRelevanceProviders;
var startTimerWithClipboardShortcut = new INShortcut(CreateIntent(SiriShortcutType.StartFromClipboard));
var startTimerWithClipboardRelevantShorcut = new INRelevantShortcut(startTimerWithClipboardShortcut);
startTimerWithClipboardRelevantShorcut.RelevanceProviders = startTimerRelevanceProviders;
var stopShortcut = new INShortcut(CreateIntent(SiriShortcutType.Stop));
var stopRelevantShortcut = new INRelevantShortcut(stopShortcut);
stopRelevantShortcut.RelevanceProviders = stopTimerRelevanceProviders;
var reportShortcut = new INShortcut(CreateIntent(SiriShortcutType.ShowReport));
var continueTimerShortcut = new INShortcut(CreateIntent(SiriShortcutType.Continue));
var continueTimerRelevantShortcut = new INRelevantShortcut(continueTimerShortcut);
continueTimerRelevantShortcut.RelevanceProviders = startTimerRelevanceProviders;
var shortcuts = new[] { startShortcut, stopShortcut, reportShortcut, continueTimerShortcut, startTimerWithClipboardShortcut };
INVoiceShortcutCenter.SharedCenter.SetShortcutSuggestions(shortcuts);
var relevantShortcuts = new[] { startRelevantShorcut, stopRelevantShortcut, continueTimerRelevantShortcut, startTimerWithClipboardRelevantShorcut };
INRelevantShortcutStore.DefaultStore.SetRelevantShortcuts(relevantShortcuts, trackError);
}
private INRelevantShortcut createRelevantShortcut(INIntent intent)
{
var shortcut = new INShortcut(intent);
var relevantShortcut = new INRelevantShortcut(shortcut);
relevantShortcut.RelevanceProviders = new List<INRelevanceProvider>().ToArray();
return relevantShortcut;
}
private void donateRelevantShortcuts(params INRelevantShortcut[] relevantShortcuts)
{
INRelevantShortcutStore.DefaultStore.SetRelevantShortcuts(relevantShortcuts, trackError);
}
private void trackError(NSError error)
{
if (error == null)
return;
analyticsService.TrackAnonymized(new Exception(error.LocalizedDescription));
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_MATRIX_PALETTE_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int MATRIX_PALETTE_ARB = 0x8840;
/// <summary>
/// [GL] Value of GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
public const int MAX_MATRIX_PALETTE_STACK_DEPTH_ARB = 0x8841;
/// <summary>
/// [GL] Value of GL_MAX_PALETTE_MATRICES_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int MAX_PALETTE_MATRICES_ARB = 0x8842;
/// <summary>
/// [GL] Value of GL_CURRENT_PALETTE_MATRIX_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int CURRENT_PALETTE_MATRIX_ARB = 0x8843;
/// <summary>
/// [GL] Value of GL_MATRIX_INDEX_ARRAY_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int MATRIX_INDEX_ARRAY_ARB = 0x8844;
/// <summary>
/// [GL] Value of GL_CURRENT_MATRIX_INDEX_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
public const int CURRENT_MATRIX_INDEX_ARB = 0x8845;
/// <summary>
/// [GL] Value of GL_MATRIX_INDEX_ARRAY_SIZE_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int MATRIX_INDEX_ARRAY_SIZE_ARB = 0x8846;
/// <summary>
/// [GL] Value of GL_MATRIX_INDEX_ARRAY_TYPE_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int MATRIX_INDEX_ARRAY_TYPE_ARB = 0x8847;
/// <summary>
/// [GL] Value of GL_MATRIX_INDEX_ARRAY_STRIDE_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int MATRIX_INDEX_ARRAY_STRIDE_ARB = 0x8848;
/// <summary>
/// [GL] Value of GL_MATRIX_INDEX_ARRAY_POINTER_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_matrix_palette")]
[RequiredByFeature("GL_OES_matrix_palette", Api = "gles1")]
public const int MATRIX_INDEX_ARRAY_POINTER_ARB = 0x8849;
/// <summary>
/// [GL] glCurrentPaletteMatrixARB: Binding for glCurrentPaletteMatrixARB.
/// </summary>
/// <param name="index">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GL_ARB_matrix_palette")]
public static void CurrentPaletteMatrixARB(int index)
{
Debug.Assert(Delegates.pglCurrentPaletteMatrixARB != null, "pglCurrentPaletteMatrixARB not implemented");
Delegates.pglCurrentPaletteMatrixARB(index);
LogCommand("glCurrentPaletteMatrixARB", null, index );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMatrixIndexubvARB: Binding for glMatrixIndexubvARB.
/// </summary>
/// <param name="indices">
/// A <see cref="T:byte[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_matrix_palette")]
public static void MatrixIndexARB(byte[] indices)
{
unsafe {
fixed (byte* p_indices = indices)
{
Debug.Assert(Delegates.pglMatrixIndexubvARB != null, "pglMatrixIndexubvARB not implemented");
Delegates.pglMatrixIndexubvARB(indices.Length, p_indices);
LogCommand("glMatrixIndexubvARB", null, indices.Length, indices );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMatrixIndexusvARB: Binding for glMatrixIndexusvARB.
/// </summary>
/// <param name="indices">
/// A <see cref="T:ushort[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_matrix_palette")]
public static void MatrixIndexARB(ushort[] indices)
{
unsafe {
fixed (ushort* p_indices = indices)
{
Debug.Assert(Delegates.pglMatrixIndexusvARB != null, "pglMatrixIndexusvARB not implemented");
Delegates.pglMatrixIndexusvARB(indices.Length, p_indices);
LogCommand("glMatrixIndexusvARB", null, indices.Length, indices );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMatrixIndexuivARB: Binding for glMatrixIndexuivARB.
/// </summary>
/// <param name="indices">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_matrix_palette")]
public static void MatrixIndexARB(uint[] indices)
{
unsafe {
fixed (uint* p_indices = indices)
{
Debug.Assert(Delegates.pglMatrixIndexuivARB != null, "pglMatrixIndexuivARB not implemented");
Delegates.pglMatrixIndexuivARB(indices.Length, p_indices);
LogCommand("glMatrixIndexuivARB", null, indices.Length, indices );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMatrixIndexPointerARB: Binding for glMatrixIndexPointerARB.
/// </summary>
/// <param name="size">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="type">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="stride">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="pointer">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_ARB_matrix_palette")]
public static void MatrixIndexPointerARB(int size, int type, int stride, IntPtr pointer)
{
Debug.Assert(Delegates.pglMatrixIndexPointerARB != null, "pglMatrixIndexPointerARB not implemented");
Delegates.pglMatrixIndexPointerARB(size, type, stride, pointer);
LogCommand("glMatrixIndexPointerARB", null, size, type, stride, pointer );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glMatrixIndexPointerARB: Binding for glMatrixIndexPointerARB.
/// </summary>
/// <param name="size">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="type">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="stride">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="pointer">
/// A <see cref="T:object"/>.
/// </param>
[RequiredByFeature("GL_ARB_matrix_palette")]
public static void MatrixIndexPointerARB(int size, int type, int stride, object pointer)
{
GCHandle pin_pointer = GCHandle.Alloc(pointer, GCHandleType.Pinned);
try {
MatrixIndexPointerARB(size, type, stride, pin_pointer.AddrOfPinnedObject());
} finally {
pin_pointer.Free();
}
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_ARB_matrix_palette")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glCurrentPaletteMatrixARB(int index);
[RequiredByFeature("GL_ARB_matrix_palette")]
[ThreadStatic]
internal static glCurrentPaletteMatrixARB pglCurrentPaletteMatrixARB;
[RequiredByFeature("GL_ARB_matrix_palette")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMatrixIndexubvARB(int size, byte* indices);
[RequiredByFeature("GL_ARB_matrix_palette")]
[ThreadStatic]
internal static glMatrixIndexubvARB pglMatrixIndexubvARB;
[RequiredByFeature("GL_ARB_matrix_palette")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMatrixIndexusvARB(int size, ushort* indices);
[RequiredByFeature("GL_ARB_matrix_palette")]
[ThreadStatic]
internal static glMatrixIndexusvARB pglMatrixIndexusvARB;
[RequiredByFeature("GL_ARB_matrix_palette")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMatrixIndexuivARB(int size, uint* indices);
[RequiredByFeature("GL_ARB_matrix_palette")]
[ThreadStatic]
internal static glMatrixIndexuivARB pglMatrixIndexuivARB;
[RequiredByFeature("GL_ARB_matrix_palette")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glMatrixIndexPointerARB(int size, int type, int stride, IntPtr pointer);
[RequiredByFeature("GL_ARB_matrix_palette")]
[ThreadStatic]
internal static glMatrixIndexPointerARB pglMatrixIndexPointerARB;
}
}
}
| |
using Newtonsoft.Json;
using NHibernate;
using NHibernate.Engine;
using NHibernate.Id;
using NHibernate.Metadata;
using NHibernate.Persister.Collection;
using NHibernate.Persister.Entity;
using NHibernate.Type;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Breeze.Persistence.NH {
/// <summary>
/// Builds a data structure containing the metadata required by Breeze.
/// <see cref="http://breeze.github.io/doc-js/metadata-schema.html"/>
/// </summary>
public class NHMetadataBuilder {
private readonly ISessionFactory _sessionFactory;
private NHBreezeMetadata _map;
private List<MetaType> _typeList;
private Dictionary<string, object> _resourceMap;
private HashSet<string> _typeNames;
private List<MetaEnumType> _enumList;
public NHMetadataBuilder(ISessionFactory sessionFactory) {
_sessionFactory = sessionFactory;
}
/// <summary>
/// Build the Breeze metadata.
/// The result can be converted to JSON and sent to the Breeze client.
/// </summary>
/// <returns></returns>
public NHBreezeMetadata BuildMetadata() {
return BuildMetadata((Func<Type, bool>)null);
}
/// <summary>
/// Build the Breeze metadata.
/// The result can be converted to JSON and sent to the Breeze client.
/// </summary>
/// <param name="includeFilter">Function that returns true if a Type should be included in metadata, false otherwise</param>
/// <returns></returns>
public NHBreezeMetadata BuildMetadata(Func<Type, bool> includeFilter) {
// retrieves all mappings with the name property set on the class (mapping with existing type, no duck typing)
IDictionary<string, IClassMetadata> classMeta = _sessionFactory.GetAllClassMetadata().Where(p => ((IEntityPersister)p.Value).EntityMetamodel.Type != null).ToDictionary(p => p.Key, p => p.Value);
if (includeFilter != null) {
classMeta = classMeta.Where(p => includeFilter(((IEntityPersister)p.Value).EntityMetamodel.Type)).ToDictionary(p => p.Key, p => p.Value);
}
return BuildMetadata(classMeta.Values);
}
/// <summary>
/// Build the Breeze metadata.
/// The result can be converted to JSON and sent to the Breeze client.
/// </summary>
/// <param name="classMeta">Entity metadata types to include in the metadata</param>
/// <returns></returns>
public NHBreezeMetadata BuildMetadata(IEnumerable<IClassMetadata> classMeta) {
InitMap();
foreach (var meta in classMeta) {
AddClass(meta);
}
return _map;
}
/// <summary>
/// Create the top-level data structure. Populate the metadata header.
/// </summary>
void InitMap() {
_map = new NHBreezeMetadata();
_typeList = new List<MetaType>();
_typeNames = new HashSet<string>();
_resourceMap = new Dictionary<string, object>();
_enumList = new List<MetaEnumType>();
_map.ForeignKeyMap = new Dictionary<string, string>();
_map.EnumTypes = _enumList;
_map.StructuralTypes = _typeList;
//_map.Add("localQueryComparisonOptions", "caseInsensitiveSQL");
//_map.Add("resourceEntityTypeMap", _resourceMap);
}
/// <summary>
/// Add the metadata for an entity.
/// </summary>
/// <param name="meta"></param>
void AddClass(IClassMetadata meta) {
var type = meta.MappedClass;
// "Customer:#Breeze.Nhibernate.NorthwindIBModel": {
var classKey = type.Name + ":#" + type.Namespace;
var cmap = new MetaType();
_typeList.Add(cmap);
cmap.ShortName = type.Name;
cmap.Namespace = type.Namespace;
if (type.IsAbstract) {
cmap.IsAbstract = true;
}
var entityPersister = meta as IEntityPersister;
var metaModel = entityPersister.EntityMetamodel;
var superType = metaModel.SuperclassType;
if (superType != null) {
cmap.BaseTypeName = superType.Name + ":#" + superType.Namespace;
}
var generator = entityPersister != null ? entityPersister.IdentifierGenerator : null;
if (generator != null) {
if (generator is IdentityGenerator) cmap.AutoGeneratedKeyType = AutoGeneratedKeyType.Identity;
else if (generator is Assigned || generator is ForeignGenerator) cmap.AutoGeneratedKeyType = AutoGeneratedKeyType.None;
else cmap.AutoGeneratedKeyType = AutoGeneratedKeyType.KeyGenerator;
}
var resourceName = Pluralize(type.Name); // TODO find the real name
cmap.DefaultResourceName = resourceName;
_resourceMap.Add(resourceName, classKey);
cmap.DataProperties = new List<MetaDataProperty>();
cmap.NavigationProperties = new List<MetaNavProperty>();
AddClassProperties(meta, cmap.DataProperties, cmap.NavigationProperties);
}
/// <summary>
/// Add the properties for an entity.
/// </summary>
/// <param name="meta"></param>
/// <param name="dataList">will be populated with the data properties of the entity</param>
/// <param name="navList">will be populated with the navigation properties of the entity</param>
void AddClassProperties(IClassMetadata meta, List<MetaDataProperty> dataList, List<MetaNavProperty> navList) {
var persister = meta as AbstractEntityPersister;
var metaModel = persister.EntityMetamodel;
var type = metaModel.Type;
HashSet<String> inheritedProperties = GetSuperProperties(persister);
var propNames = meta.PropertyNames;
var propTypes = meta.PropertyTypes;
var propNull = meta.PropertyNullability;
var properties = metaModel.Properties;
for (int i = 0; i < propNames.Length; i++) {
var propName = propNames[i];
if (inheritedProperties.Contains(propName)) continue; // skip property defined on superclass
var propType = propTypes[i];
if (!propType.IsAssociationType) // skip association types until we handle all the data types, so they can be looked up
{
if (propType.IsComponentType) {
// complex type
var columnNames = persister.GetPropertyColumnNames(i);
var compType = (ComponentType)propType;
var complexTypeName = AddComponent(compType, columnNames);
var comp = new MetaDataProperty {
NameOnServer = propName,
ComplexTypeName = complexTypeName,
IsNullable = propNull[i]
};
dataList.Add(comp);
} else {
// data property
var isKey = meta.HasNaturalIdentifier && meta.NaturalIdentifierProperties.Contains(i);
var isVersion = meta.IsVersioned && i == meta.VersionProperty;
var dmap = MakeDataProperty(propName, propType, propNull[i], isKey, isVersion);
dataList.Add(dmap);
}
}
// Expose enum types
if (propType is AbstractEnumType) {
var types = propType.GetType().GetGenericArguments();
if (types.Length > 0) {
var realType = types[0];
string[] enumNames = Enum.GetNames(realType);
var et = new MetaEnumType {
ShortName = realType.Name,
Namespace = realType.Namespace,
Values = enumNames
};
if (!_enumList.Exists(x => x.ShortName == realType.Name)) {
_enumList.Add(et);
}
}
}
}
// Hibernate identifiers are excluded from the list of data properties, so we have to add them separately
if (meta.HasIdentifierProperty && !inheritedProperties.Contains(meta.IdentifierPropertyName)) {
var dmap = MakeDataProperty(meta.IdentifierPropertyName, meta.IdentifierType, false, true, false);
dmap.IsIdentityColumn = (meta.IdentifierType.ReturnedClass == typeof(NHibernate.Id.IdentityGenerator));
dataList.Insert(0, dmap);
} else if (meta.IdentifierType != null && meta.IdentifierType.IsComponentType) {
// composite key is a ComponentType
var compType = (ComponentType)meta.IdentifierType;
// check that the component belongs to this class, not a superclass
if (compType.ReturnedClass == type || meta.IdentifierPropertyName == null || !inheritedProperties.Contains(meta.IdentifierPropertyName)) {
var compNames = compType.PropertyNames;
for (int i = 0; i < compNames.Length; i++) {
var compName = compNames[i];
var propType = compType.Subtypes[i];
if (!propType.IsAssociationType) {
var dmap = MakeDataProperty(compName, propType, compType.PropertyNullability[i], true, false);
dataList.Insert(0, dmap);
} else {
var assProp = MakeAssociationProperty(persister, (IAssociationType)propType, compName, dataList, true);
navList.Add(assProp);
}
}
}
}
// We do the association properties after the data properties, so we can do the foreign key lookups
for (int i = 0; i < propNames.Length; i++) {
var propName = propNames[i];
if (inheritedProperties.Contains(propName)) continue; // skip property defined on superclass
var propType = propTypes[i];
if (propType.IsAssociationType) {
// navigation property
var assProp = MakeAssociationProperty(persister, (IAssociationType)propType, propName, dataList, false);
navList.Add(assProp);
}
}
}
/// <summary>
/// Return names of all properties that are defined in the mapped ancestors of the
/// given persister. Note that unmapped superclasses are deliberately ignored, because
/// they shouldn't affect the metadata.
/// </summary>
/// <param name="persister"></param>
/// <returns>set of property names. Empty if the persister doesn't have a superclass.</returns>
HashSet<string> GetSuperProperties(AbstractEntityPersister persister) {
HashSet<string> set = new HashSet<String>();
if (!persister.IsInherited) return set;
string superClassName = persister.MappedSuperclass;
if (superClassName == null) return set;
IClassMetadata superMeta = _sessionFactory.GetClassMetadata(superClassName);
if (superMeta == null) return set;
string[] superProps = superMeta.PropertyNames;
set = new HashSet<string>(superProps);
set.Add(superMeta.IdentifierPropertyName);
return set;
}
/// <summary>
/// Adds a complex type definition
/// </summary>
/// <param name="compType">The complex type</param>
/// <param name="columnNames">The names of the columns which the complex type spans.</param>
/// <returns>The class name and namespace of the complex type, in the form "Location:#Breeze.Nhibernate.NorthwindIBModel"</returns>
string AddComponent(ComponentType compType, string[] columnNames) {
var type = compType.ReturnedClass;
// "Location:#Breeze.Nhibernate.NorthwindIBModel"
var classKey = type.Name + ":#" + type.Namespace;
if (_typeNames.Contains(classKey)) {
// Only add a complex type definition once.
return classKey;
}
var cmap = new MetaType();
_typeList.Insert(0, cmap);
_typeNames.Add(classKey);
cmap.ShortName = type.Name;
cmap.Namespace = type.Namespace;
cmap.IsComplexType = true;
cmap.DataProperties = new List<MetaDataProperty>();
var propNames = compType.PropertyNames;
var propTypes = compType.Subtypes;
var propNull = compType.PropertyNullability;
var colIndex = 0;
for (int i = 0; i < propNames.Length; i++) {
var propType = propTypes[i];
var propName = propNames[i];
if (propType.IsComponentType) {
// nested complex type
var compType2 = (ComponentType)propType;
var span = compType2.GetColumnSpan((IMapping)_sessionFactory);
var subColumns = columnNames.Skip(colIndex).Take(span).ToArray();
var complexTypeName = AddComponent(compType2, subColumns);
var compMap = new MetaDataProperty();
compMap.NameOnServer = propName;
compMap.ComplexTypeName = complexTypeName;
compMap.IsNullable = propNull[i];
cmap.DataProperties.Add(compMap);
colIndex += span;
} else {
// data property
var dmap = MakeDataProperty(propName, propType, propNull[i], false, false);
cmap.DataProperties.Add(dmap);
colIndex++;
}
}
return classKey;
}
/// <summary>
/// Make data property metadata for the entity
/// </summary>
/// <param name="propName">name of the property on the server</param>
/// <param name="type">data type of the property, e.g. Int32</param>
/// <param name="isNullable">whether the property is nullable in the database</param>
/// <param name="isKey">true if this property is part of the key for the entity</param>
/// <param name="isVersion">true if this property contains the version of the entity (for a concurrency strategy)</param>
/// <returns></returns>
private MetaDataProperty MakeDataProperty(string propName, IType type, bool isNullable, bool isKey, bool isVersion) {
string newType;
var typeName = (BreezeTypeMap.TryGetValue(type.Name, out newType)) ? newType : type.Name;
var dmap = new MetaDataProperty {
NameOnServer = propName,
DataType = typeName,
IsNullable = isNullable
};
var sqlTypes = type.SqlTypes((ISessionFactoryImplementor)this._sessionFactory);
var sqlType = sqlTypes[0];
// This doesn't work; NH does not pick up the default values from the property/column definition
//if (type is PrimitiveType && !(type is DateTimeOffsetType))
//{
// var def = ((PrimitiveType)type).DefaultValue;
// if (def != null && def.ToString() != "0")
// dmap.Add("defaultValue", def);
//}
if (isKey) {
dmap.IsPartOfKey = true;
}
if (isVersion) {
dmap.ConcurrencyMode = "Fixed";
}
if (!isNullable) {
dmap.Validators.Add(MetaValidator.Required);
}
if (sqlType.LengthDefined) {
dmap.MaxLength = sqlType.Length;
dmap.Validators.Add(new MaxLengthMetaValidator(sqlType.Length));
}
var validator = MetaValidator.FindValidator(type.ReturnedClass);
if (validator != null) {
dmap.Validators.Add(validator);
}
return dmap;
}
/// <summary>
/// Make association property metadata for the entity.
/// Also populates the ForeignKeyMap which is used for related-entity fixup in NHContext.FixupRelationships
/// </summary>
/// <param name="containingPersister">Entity Persister containing the property</param>
/// <param name="propType">Association property</param>
/// <param name="propName">Name of the property</param>
/// <param name="dataProperties">Data properties already collected for the containingType. "isPartOfKey" may be added to a property.</param>
/// <param name="isKey">Whether the property is part of the key</param>
/// <returns></returns>
private MetaNavProperty MakeAssociationProperty(AbstractEntityPersister containingPersister, IAssociationType propType, string propName, List<MetaDataProperty> dataProperties, bool isKey) {
var nmap = new MetaNavProperty();
nmap.NameOnServer = propName;
var relatedEntityType = GetEntityType(propType.ReturnedClass, propType.IsCollectionType);
nmap.EntityTypeName = relatedEntityType.Name + ":#" + relatedEntityType.Namespace;
nmap.IsScalar = !propType.IsCollectionType;
// the associationName must be the same at both ends of the association.
Type containingType = containingPersister.EntityMetamodel.Type;
var columnNames = GetPropertyColumnNames(containingPersister, propName, propType);
nmap.AssociationName = GetAssociationName(containingType.Name, relatedEntityType.Name, columnNames);
List<string> fkNames = null;
var joinable = propType.GetAssociatedJoinable((ISessionFactoryImplementor)this._sessionFactory);
if (propType.IsCollectionType) {
// inverse foreign key
var collectionPersister = joinable as AbstractCollectionPersister;
if (collectionPersister != null && collectionPersister.IsOneToMany) {
// many-to-many relationships do not have a direct connection on the client or in metadata
var elementPersister = collectionPersister.ElementPersister as AbstractEntityPersister;
if (elementPersister != null) {
fkNames = GetPropertyNamesForColumns(elementPersister, columnNames);
if (fkNames != null)
nmap.InvForeignKeyNamesOnServer = fkNames;
}
}
} else {
// Not a collection type - a many-to-one or one-to-one association
var entityRelationship = containingType.FullName + '.' + propName;
// Look up the related foreign key name using the column name
fkNames = GetPropertyNamesForColumns(containingPersister, columnNames);
if (fkNames != null) {
if (propType.ForeignKeyDirection == ForeignKeyDirection.ForeignKeyFromParent) {
nmap.ForeignKeyNamesOnServer = fkNames;
if (propType.RHSUniqueKeyPropertyName != null) {
nmap.InvForeignKeyNamesOnServer = new List<string> { propType.RHSUniqueKeyPropertyName };
}
} else {
nmap.InvForeignKeyNamesOnServer = fkNames;
}
// For many-to-one and one-to-one associations, save the relationship in ForeignKeyMap for re-establishing relationships during save
_map.ForeignKeyMap.Add(entityRelationship, string.Join(",", fkNames));
if (isKey) {
foreach (var fkName in fkNames) {
var relatedDataProperty = FindPropertyByName(dataProperties, fkName) as MetaDataProperty;
relatedDataProperty.IsPartOfKey = true;
}
}
} else if (fkNames == null) {
nmap.ForeignKeyNamesOnServer = columnNames;
//nmap.Add("ERROR", "Could not find matching fk for property " + entityRelationship);
_map.ForeignKeyMap.Add(entityRelationship, string.Join(",", columnNames));
throw new ArgumentException("Could not find matching fk for property " + entityRelationship);
}
}
return nmap;
}
/// <summary>
/// Get the column names for a given property as a comma-delimited string of unbracketed names.
/// For a collection property, the column name is the inverse foreign key (i.e. the column on
/// the other table that points back to the persister's table)
/// </summary>
/// <param name="persister"></param>
/// <param name="propertyName"></param>
/// <param name="propType"></param>
/// <returns></returns>
List<string> GetPropertyColumnNames(AbstractEntityPersister persister, string propertyName, IType propType) {
string[] propColumnNames = null;
if (propType.IsCollectionType) {
propColumnNames = ((CollectionType)propType).GetReferencedColumns((ISessionFactoryImplementor)this._sessionFactory);
} else {
propColumnNames = persister.GetPropertyColumnNames(propertyName);
}
if (propColumnNames == null || propColumnNames.Length == 0) {
// this happens when the property is part of the key
propColumnNames = persister.KeyColumnNames;
}
// HACK for NHibernate formula: when using formula propColumnNames[0] equals null
if (propColumnNames[0] == null) {
propColumnNames = new string[] { propertyName };
}
return UnBracket(propColumnNames);
}
/// <summary>
/// Gets the properties matching the given columns. May be a component, but will not be an association.
/// </summary>
/// <param name="persister"></param>
/// <param name="columnNames">Array of column names</param>
/// <returns></returns>
static List<string> GetPropertyNamesForColumns(AbstractEntityPersister persister, IList<string> columnNames) {
var propNames = persister.PropertyNames;
var propTypes = persister.PropertyTypes;
for (int i = 0; i < propNames.Length; i++) {
var propName = propNames[i];
var propType = propTypes[i];
if (propType.IsAssociationType) continue;
var columnArray = persister.GetPropertyColumnNames(i);
// HACK for NHibernate formula: when using formula GetPropertyColumnNames(i) returns an array with the first element null
if (columnArray[0] == null) {
continue;
}
if (NamesEqual(columnArray, columnNames)) return new List<string> { propName };
}
// If we got here, maybe the property is the identifier
var keyColumnArray = persister.KeyColumnNames;
if (NamesEqual(keyColumnArray, columnNames)) {
if (persister.IdentifierPropertyName != null) {
return new List<string> { persister.IdentifierPropertyName };
}
if (persister.IdentifierType.IsComponentType) {
var compType = (ComponentType)persister.IdentifierType;
return compType.PropertyNames.ToList(); ;
}
}
if (columnNames.Count > 1) {
// go one-by-one through columnNames, trying to find a matching property.
// TODO: maybe this should split columnNames into all possible combinations of ordered subsets, and try those
var propList = new List<string>();
var prop = new string[1];
for (int i = 0; i < columnNames.Count; i++) {
prop[0] = columnNames[i];
var names = GetPropertyNamesForColumns(persister, prop); // recursive call
if (names != null) propList.AddRange(names);
}
if (propList.Count > 0) return propList;
}
return null;
}
/// <summary>
/// Unbrackets the column names and concatenates them into a comma-delimited string
/// </summary>
static string CatColumnNames(IEnumerable<string> columnNames, char delim = ',') {
var sb = new StringBuilder();
foreach (var s in columnNames) {
if (sb.Length > 0) sb.Append(delim);
sb.Append(UnBracket(s));
}
return sb.ToString();
}
/// <summary>
/// return true if the two arrays contain the same names, false otherwise.
/// Names are compared after UnBracket(), and are case-insensitive.
/// </summary>
static bool NamesEqual(IList<string> a, IList<string> b) {
if (a.Count != b.Count) return false;
for (int i = 0; i < a.Count; i++) {
if (UnBracket(a[i]).ToLower() != UnBracket(b[i]).ToLower()) return false;
}
return true;
}
/// <summary>
/// Get the column name without square brackets or quotes around it. E.g. "[OrderID]" -> OrderID
/// Because sometimes Hibernate gives us brackets, and sometimes it doesn't.
/// Double-quotes happen with SQL CE. Backticks happen with MySQL.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
static string UnBracket(string name) {
name = (name[0] == '[') ? name.Substring(1, name.Length - 2) : name;
name = (name[0] == '"') ? name.Substring(1, name.Length - 2) : name;
name = (name[0] == '`') ? name.Substring(1, name.Length - 2) : name;
return name;
}
/// <summary>
/// Return a new array containing the UnBracketed names
/// </summary>
static List<string> UnBracket(IList<string> names) {
var u = new List<string>();
for (int i = 0; i < names.Count; i++) {
u.Add(UnBracket(names[i]));
}
return u;
}
/// <summary>
/// Find the property in the list that has the given name.
/// </summary>
/// <param name="properties">list of DataProperty or NavigationProperty maps</param>
/// <param name="name">matched against the nameOnServer value of entries in the list</param>
/// <returns></returns>
static MetaProperty FindPropertyByName(IEnumerable<MetaProperty> properties, string name) {
//object nameOnServer;
foreach (var prop in properties) {
if (prop.NameOnServer == name) {
return prop;
}
}
return null;
}
/// <summary>
/// Get the Breeze name of the entity type.
/// For collections, Breeze expects the name of the element type.
/// </summary>
/// <param name="type"></param>
/// <param name="isCollectionType"></param>
/// <returns></returns>
static Type GetEntityType(Type type, bool isCollectionType) {
if (!isCollectionType) {
return type;
} else if (type.HasElementType) {
return type.GetElementType();
} else if (type.IsGenericType) {
return type.GetGenericArguments()[0];
}
throw new ArgumentException("Don't know how to handle " + type);
}
/// <summary>
/// lame pluralizer. Assumes we just need to add a suffix.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static string Pluralize(string s) {
if (string.IsNullOrEmpty(s)) return s;
var last = s.Length - 1;
var c = s[last];
switch (c) {
case 'y':
return s.Substring(0, last) + "ies";
default:
return s + 's';
}
}
/// <summary>
/// Creates an association name from two entity names.
/// For consistency, puts the entity names in alphabetical order.
/// </summary>
/// <param name="name1"></param>
/// <param name="name2"></param>
/// <param name="propType">Used to ensure the association name is unique for a type</param>
/// <returns></returns>
static string GetAssociationName(string name1, string name2, IEnumerable<string> columnNames) {
var cols = CatColumnNames(columnNames, '_');
if (name1.CompareTo(name2) < 0)
return ASSN + name1 + '_' + name2 + '_' + cols;
else
return ASSN + name2 + '_' + name1 + '_' + cols;
}
const string ASSN = "AN_";
// Map of NH datatype to Breeze datatype.
static readonly Dictionary<string, string> BreezeTypeMap = new Dictionary<string, string>() {
{"Byte[]", "Binary" },
{"BinaryBlob", "Binary" },
{"Timestamp", "DateTime" },
{"TimeAsTimeSpan", "Time" }
};
}
/// <summary>
/// Metadata describing the entity model. Converted to JSON to send to Breeze client.
/// </summary>
public class NHBreezeMetadata : BreezeMetadata {
/// <summary>
/// Map of relationship name -> foreign key name, e.g. "Customer" -> "CustomerID".
/// Used for re-establishing the entity relationships from the foreign key values during save.
/// This part is not sent to the client because it is for server-side save implementation.
/// </summary>
[JsonIgnore]
public IDictionary<string, string> ForeignKeyMap;
/// <summary> List of Enum types in NHibernate properties. Not sure if this is useful on the client. </summary>
public List<MetaEnumType> EnumTypes;
}
public class MetaEnumType {
public string ShortName { get; set; }
public string Namespace { get; set; }
public string[] Values { get; set; }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Utilities;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.GenerateType
{
[ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared]
internal class CSharpGenerateTypeService :
AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax>
{
private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
protected override string DefaultFileExtension => ".cs";
protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName)
{
return simpleName.GetLeftSideOfDot();
}
protected override bool IsInCatchDeclaration(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.CatchDeclaration);
}
protected override bool IsArrayElementType(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.ArrayType) &&
expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression);
}
protected override bool IsInValueTypeConstraintContext(
SemanticModel semanticModel,
ExpressionSyntax expression,
CancellationToken cancellationToken)
{
if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList))
{
var typeArgumentList = (TypeArgumentListSyntax)expression.Parent;
var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken);
var symbol = symbolInfo.GetAnySymbol();
if (symbol.IsConstructor())
{
symbol = symbol.ContainingType;
}
var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression);
var type = symbol as INamedTypeSymbol;
if (type != null)
{
type = type.OriginalDefinition;
var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
var method = symbol as IMethodSymbol;
if (method != null)
{
method = method.OriginalDefinition;
var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
}
return false;
}
protected override bool IsInInterfaceList(ExpressionSyntax expression)
{
if (expression is TypeSyntax &&
expression.Parent is BaseTypeSyntax &&
expression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)expression.Parent).Type == expression)
{
var baseList = (BaseListSyntax)expression.Parent.Parent;
// If it's after the first item, then it's definitely an interface.
if (baseList.Types[0] != expression.Parent)
{
return true;
}
// If it's in the base list of an interface or struct, then it's definitely an
// interface.
return
baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) ||
baseList.IsParentKind(SyntaxKind.StructDeclaration);
}
if (expression is TypeSyntax &&
expression.IsParentKind(SyntaxKind.TypeConstraint) &&
expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
{
var typeConstraint = (TypeConstraintSyntax)expression.Parent;
var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent;
var index = constraintClause.Constraints.IndexOf(typeConstraint);
// If it's after the first item, then it's definitely an interface.
return index > 0;
}
return false;
}
protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts)
{
nameParts = new List<string>();
return expression.TryGetNameParts(out nameParts);
}
protected override bool TryInitializeState(
SemanticDocument document,
SimpleNameSyntax simpleName,
CancellationToken cancellationToken,
out GenerateTypeServiceStateOptions generateTypeServiceStateOptions)
{
generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions();
if (simpleName.IsVar)
{
return false;
}
if (SyntaxFacts.IsAliasQualifier(simpleName))
{
return false;
}
// Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly
// unlikely that this would be a location where a user would be wanting to generate
// something. They're really just trying to reference something that exists but
// isn't available for some reason (i.e. a missing reference).
var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword)
{
return false;
}
ExpressionSyntax nameOrMemberAccessExpression = null;
if (simpleName.IsRightSideOfDot())
{
// This simplename comes from the cref
if (simpleName.IsParentKind(SyntaxKind.NameMemberCref))
{
return false;
}
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent;
// If we're on the right side of a dot, then the left side better be a name (and
// not an arbitrary expression).
var leftSideExpression = simpleName.GetLeftSideOfDot();
if (!leftSideExpression.IsKind(
SyntaxKind.QualifiedName,
SyntaxKind.IdentifierName,
SyntaxKind.AliasQualifiedName,
SyntaxKind.GenericName,
SyntaxKind.SimpleMemberAccessExpression))
{
return false;
}
}
else
{
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName;
}
// BUG(5712): Don't offer generate type in an enum's base list.
if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax &&
nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression &&
nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration))
{
return false;
}
// If we can guarantee it's a type only context, great. Otherwise, we may not want to
// provide this here.
var semanticModel = document.SemanticModel;
if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
// Don't offer Generate Type in an expression context *unless* we're on the left
// side of a dot. In that case the user might be making a type that they're
// accessing a static off of.
var syntaxTree = semanticModel.SyntaxTree;
var start = nameOrMemberAccessExpression.SpanStart;
var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken);
var isExpressionOrStatementContext = isExpressionContext || isStatementContext;
// Delegate Type Creation is not allowed in Non Type Namespace Context
generateTypeServiceStateOptions.IsDelegateAllowed = false;
if (!isExpressionOrStatementContext)
{
return false;
}
if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf())
{
if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot())
{
return false;
}
var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol;
var token = simpleName.GetLastToken().GetNextToken();
// We let only the Namespace to be left of the Dot
if (leftSymbol == null ||
!leftSymbol.IsKind(SymbolKind.Namespace) ||
!token.IsKind(SyntaxKind.DotToken))
{
return false;
}
else
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
// Global Namespace
if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess &&
!SyntaxFacts.IsInNamespaceOrTypeContext(simpleName))
{
var token = simpleName.GetLastToken().GetNextToken();
if (token.IsKind(SyntaxKind.DotToken) &&
simpleName.Parent == token.Parent)
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
}
var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>();
if (fieldDeclaration != null &&
fieldDeclaration.Parent is CompilationUnitSyntax &&
document.Document.SourceCodeKind == SourceCodeKind.Regular)
{
return false;
}
// Check to see if Module could be an option in the Type Generation in Cross Language Generation
var nextToken = simpleName.GetLastToken().GetNextToken();
if (simpleName.IsLeftSideOfDot() ||
nextToken.IsKind(SyntaxKind.DotToken))
{
if (simpleName.IsRightSideOfDot())
{
var parent = simpleName.Parent as QualifiedNameSyntax;
if (parent != null)
{
var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol;
if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace))
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
}
}
}
if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
if (nextToken.IsKind(SyntaxKind.DotToken))
{
// In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName
generateTypeServiceStateOptions.IsDelegateAllowed = false;
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
// case: class Foo<T> where T: MyType
if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any())
{
generateTypeServiceStateOptions.IsClassInterfaceTypes = true;
return true;
}
// Events
if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() ||
nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any())
{
// Case : event foo name11
// Only Delegate
if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax))
{
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
// Case : event SomeSymbol.foo name11
if (nameOrMemberAccessExpression is QualifiedNameSyntax)
{
// Only Namespace, Class, Struct and Module are allowed to contain Delegate
// Case : event Something.Mytype.<Delegate> Identifier
if (nextToken.IsKind(SyntaxKind.DotToken))
{
if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax)
{
return true;
}
else
{
Contract.Fail("Cannot reach this point");
}
}
else
{
// Case : event Something.<Delegate> Identifier
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
}
}
}
else
{
// MemberAccessExpression
if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)))
&& nameOrMemberAccessExpression.IsLeftSideOfDot())
{
// Check to see if the expression is part of Invocation Expression
ExpressionSyntax outerMostMemberAccessExpression = null;
if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
outerMostMemberAccessExpression = nameOrMemberAccessExpression;
}
else
{
Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression));
outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent;
}
outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault();
if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax)
{
generateTypeServiceStateOptions.IsEnumNotAllowed = true;
}
}
}
// Cases:
// // 1 - Function Address
// var s2 = new MyD2(foo);
// // 2 - Delegate
// MyD1 d = null;
// var s1 = new MyD2(d);
// // 3 - Action
// Action action1 = null;
// var s3 = new MyD2(action1);
// // 4 - Func
// Func<int> lambda = () => { return 0; };
// var s4 = new MyD3(lambda);
if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax)
{
var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent;
// Enum and Interface not Allowed in Object Creation Expression
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
if (objectCreationExpressionOpt.ArgumentList != null)
{
if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing)
{
return false;
}
// Get the Method symbol for the Delegate to be created
if (generateTypeServiceStateOptions.IsDelegateAllowed &&
objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 &&
objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken);
}
else
{
generateTypeServiceStateOptions.IsDelegateAllowed = false;
}
}
if (objectCreationExpressionOpt.Initializer != null)
{
foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
{
var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
if (simpleAssignmentExpression == null)
{
continue;
}
var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
if (name == null)
{
continue;
}
generateTypeServiceStateOptions.PropertiesToGenerate.Add(name);
}
}
}
if (generateTypeServiceStateOptions.IsDelegateAllowed)
{
// MyD1 z1 = foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration))
{
var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent;
if (variableDeclaration.Variables.Count != 0)
{
var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null);
if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken);
}
}
}
// var w1 = (MyD1)foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression))
{
var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent;
if (castExpression.Expression != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken);
}
}
}
return true;
}
private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
{
if (expression == null)
{
return null;
}
var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken);
if (memberGroup.Length != 0)
{
return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null;
}
var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType.IsDelegateType())
{
return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod;
}
var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol;
if (expressionSymbol.IsKind(SymbolKind.Method))
{
return (IMethodSymbol)expressionSymbol;
}
return null;
}
private Accessibility DetermineAccessibilityConstraint(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return semanticModel.DetermineAccessibilityConstraint(
state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken);
}
protected override ImmutableArray<ITypeParameterSymbol> GetTypeParameters(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (state.SimpleName is GenericNameSyntax)
{
var genericName = (GenericNameSyntax)state.SimpleName;
var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count
? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList()
: Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity);
return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken);
}
return ImmutableArray<ITypeParameterSymbol>.Empty;
}
protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList)
{
if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null)
{
argumentList = objectCreationExpression.ArgumentList.Arguments.ToList();
return true;
}
argumentList = null;
return false;
}
protected override IList<ParameterName> GenerateParameterNames(
SemanticModel semanticModel, IList<ArgumentSyntax> arguments, CancellationToken cancellationToken)
{
return semanticModel.GenerateParameterNames(arguments, reservedNames: null, cancellationToken: cancellationToken);
}
public override string GetRootNamespace(CompilationOptions options)
{
return string.Empty;
}
protected override bool IsInVariableTypeContext(ExpressionSyntax expression)
{
return false;
}
protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken);
}
protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken)
{
var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken);
if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess)
{
var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken);
if (accessibilityConstraint == Accessibility.Public ||
accessibilityConstraint == Accessibility.Internal)
{
accessibility = accessibilityConstraint;
}
}
return accessibility;
}
protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
{
return argument.DetermineParameterType(semanticModel, cancellationToken);
}
protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
{
return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
}
public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync(
INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken)
{
var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot;
var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (containers.Length != 0)
{
// Search the NS declaration in the root
var containerList = new List<string>(containers);
var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit);
if (enclosingNamespace != null)
{
var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken);
if (enclosingNamespaceSymbol.Symbol != null)
{
return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol,
(INamespaceOrTypeSymbol)namedTypeSymbol,
enclosingNamespace.CloseBraceToken.GetLocation());
}
}
}
var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken);
var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers);
var lastMember = compilationUnit.Members.LastOrDefault();
Location afterThisLocation = null;
if (lastMember != null)
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0));
}
else
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan());
}
return Tuple.Create(globalNamespace,
rootNamespaceOrType,
afterThisLocation);
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
{
foreach (var member in compilationUnit.Members)
{
var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
if (namespaceDeclaration != null)
{
return namespaceDeclaration;
}
}
return null;
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
{
var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
{
return null;
}
List<string> namespaceContainers = new List<string>();
GetNamespaceContainers(namespaceDecl.Name, namespaceContainers);
if (namespaceContainers.Count + indexDone > containers.Count ||
!IdentifierMatches(indexDone, namespaceContainers, containers))
{
return null;
}
indexDone = indexDone + namespaceContainers.Count;
if (indexDone == containers.Count)
{
return namespaceDecl;
}
foreach (var member in namespaceDecl.Members)
{
var resultant = GetDeclaringNamespace(containers, indexDone, member);
if (resultant != null)
{
return resultant;
}
}
return null;
}
private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers)
{
for (int i = 0; i < namespaceContainers.Count; ++i)
{
if (namespaceContainers[i] != containers[indexDone + i])
{
return false;
}
}
return true;
}
private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers)
{
if (name is QualifiedNameSyntax qualifiedName)
{
GetNamespaceContainers(qualifiedName.Left, namespaceContainers);
namespaceContainers.Add(qualifiedName.Right.Identifier.ValueText);
}
else
{
Debug.Assert(name is SimpleNameSyntax);
namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText);
}
}
internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue)
{
typeKindValue = TypeKindOptions.AllOptions;
if (expression == null)
{
return false;
}
var node = expression as SyntaxNode;
while (node != null)
{
if (node is BaseListSyntax)
{
if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax))
{
typeKindValue = TypeKindOptions.Interface;
return true;
}
typeKindValue = TypeKindOptions.BaseList;
return true;
}
node = node.Parent;
}
return false;
}
internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project)
{
if (expression == null)
{
return false;
}
if (GeneratedTypesMustBePublic(project))
{
return true;
}
var node = expression as SyntaxNode;
SyntaxNode previousNode = null;
while (node != null)
{
// Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type
if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
var typeDecl = node.Parent as TypeDeclarationSyntax;
if (typeDecl != null)
{
if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return IsAllContainingTypeDeclsPublic(typeDecl);
}
else
{
// The Type Decl which contains the BaseList does not contain Public
return false;
}
}
Contract.Fail("Cannot reach this point");
}
if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
// Make sure the GFU is not inside the Accessors
if (previousNode != null && previousNode is AccessorListSyntax)
{
return false;
}
// Make sure that Event Declaration themselves are Public in the first place
if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return false;
}
return IsAllContainingTypeDeclsPublic(node);
}
previousNode = node;
node = node.Parent;
}
return false;
}
private bool IsAllContainingTypeDeclsPublic(SyntaxNode node)
{
// Make sure that all the containing Type Declarations are also Public
var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>();
if (containingTypeDeclarations.Count() == 0)
{
return true;
}
else
{
return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword));
}
}
internal override bool IsGenericName(SimpleNameSyntax simpleName)
{
if (simpleName == null)
{
return false;
}
var genericName = simpleName as GenericNameSyntax;
return genericName != null;
}
internal override bool IsSimpleName(ExpressionSyntax expression)
{
return expression is SimpleNameSyntax;
}
internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
{
// Nothing to include
if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
{
return updatedSolution;
}
SyntaxNode root = null;
if (modifiedRoot == null)
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
root = modifiedRoot;
}
if (root is CompilationUnitSyntax compilationRoot)
{
var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports));
// Check if the usings is already present
if (compilationRoot.Usings.Where(n => n != null && n.Alias == null)
.Select(n => n.Name.ToString())
.Any(n => n.Equals(includeUsingsOrImports)))
{
return updatedSolution;
}
// Check if the GFU is triggered from the namespace same as the usings namespace
if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false))
{
return updatedSolution;
}
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst);
var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
}
return updatedSolution;
}
private ITypeSymbol GetPropertyType(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken)
{
var parentAssignment = propertyName.Parent as AssignmentExpressionSyntax;
if (parentAssignment != null)
{
return typeInference.InferType(
semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken);
}
var isPatternExpression = propertyName.Parent as IsPatternExpressionSyntax;
if (isPatternExpression != null)
{
return typeInference.InferType(
semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken);
}
return null;
}
private IPropertySymbol CreatePropertySymbol(
SimpleNameSyntax propertyName, ITypeSymbol propertyType)
{
return CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
explicitInterfaceImplementations: default,
name: propertyName.Identifier.ValueText,
type: propertyType,
returnsByRef: false,
parameters: default(ImmutableArray<IParameterSymbol>),
getMethod: s_accessor,
setMethod: s_accessor,
isIndexer: false);
}
private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: Accessibility.Public,
statements: default(ImmutableArray<SyntaxNode>));
internal override bool TryGenerateProperty(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken,
out IPropertySymbol property)
{
property = null;
var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken);
if (propertyType == null || propertyType is IErrorTypeSymbol)
{
property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType);
return property != null;
}
property = CreatePropertySymbol(propertyName, propertyType);
return property != null;
}
internal override IMethodSymbol GetDelegatingConstructor(
SemanticDocument document,
ObjectCreationExpressionSyntax objectCreation,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken)
{
var model = document.SemanticModel;
var oldNode = objectCreation
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
.LastOrDefault();
var typeNameToReplace = objectCreation.Type;
var newTypeName = namedType.GenerateTypeSyntax();
var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation);
var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation);
var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model);
if (speculativeModel != null)
{
newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken);
var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select(
a => a.DetermineParameterType(speculativeModel, cancellationToken)).ToList();
return GenerateConstructorHelpers.GetDelegatingConstructor(
document, symbolInfo, candidates, namedType, parameterTypes);
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraPivotGrid;
using EIDSS.RAM.Layout;
using EIDSS.RAM.Presenters.Base;
using EIDSS.RAM_DB.Common.CommandProcessing.Commands;
using EIDSS.RAM_DB.Common.CommandProcessing.Commands.Layout;
using EIDSS.RAM_DB.Common.EventHandlers;
using EIDSS.RAM_DB.Components;
using EIDSS.RAM_DB.DBService;
using EIDSS.RAM_DB.DBService.Access;
using EIDSS.RAM_DB.DBService.DataSource;
using EIDSS.RAM_DB.DBService.Enumerations;
using EIDSS.RAM_DB.DBService.Models;
using EIDSS.RAM_DB.Views;
using bv.common.Configuration;
using bv.common.Core;
using bv.common.Enums;
using bv.common.Objects;
using bv.common.Resources;
using bv.common.db;
using bv.common.db.Core;
using bv.model.Model.Core;
using bv.winclient.Core;
using eidss.model.Resources;
using ErrorForm = bv.common.win.ErrorForm;
using Localizer = bv.common.Core.Localizer;
using ReflectionHelper = EIDSS.RAM_DB.Common.ReflectionHelper;
namespace EIDSS.RAM.Presenters
{
public sealed class PivotPresenter : RelatedObjectPresenter
{
public const string ColumnIdName = "id";
public const string ColumnLongitudeName = "x";
public const string ColumnLatitudeName = "y";
public const string ColumnTypeName = "type";
public const string ColumnValueName = "value";
public const string ColumnInfoName = "info";
private readonly IPivotView m_PivotView;
private readonly BaseRamDbService m_PivotFormService;
private readonly LayoutMediator m_LayoutMediator;
static PivotPresenter()
{
InitGisTypes();
}
public PivotPresenter(SharedPresenter sharedPresenter, IPivotView view)
: base(sharedPresenter, view)
{
m_PivotFormService = new BaseRamDbService();
m_PivotView = view;
m_PivotView.DBService = PivotFormService;
m_LayoutMediator = new LayoutMediator(this);
m_PivotView.PivotSelected += PivotView_PivotSelected;
m_PivotView.PivotDataLoaded += PivotView_PivotDataLoaded;
m_PivotView.InitAdmUnit += PivotView_InitAdmUnit;
m_PivotView.InitDenominator += PivotView_InitDenominator;
m_PivotView.InitStatDate += PivotView_InitStatDate;
m_SharedPresenter.SharedModel.PropertyChanged += SharedModel_PropertyChanged;
m_SharedPresenter.SharedModel.GetMapDataTableCallback = GetWinMapDataTable;
m_SharedPresenter.SharedModel.GetAvailableMapFieldViewCallback = GetAvailableMapFieldView;
m_SharedPresenter.SharedModel.GetDenominatorDataViewCallback = GetDenominatorDataView;
m_SharedPresenter.SharedModel.GetStatDateDataViewCallback = GetStatDateDataView;
}
public static Dictionary<string, GisCaseType> GisTypeDictionary
{ get; private set; }
public BaseRamDbService PivotFormService
{
get { return m_PivotFormService; }
}
public string CorrectedLayoutName
{
get
{
return (Utils.IsEmpty(LayoutName))
? EidssMessages.Get("msgNoReportHeader", "[Untitled]")
: LayoutName;
}
}
public string LayoutName
{
get
{
return (ModelUserContext.CurrentLanguage == Localizer.lngEn)
? m_LayoutMediator.LayoutRow.strDefaultLayoutName
: m_LayoutMediator.LayoutRow.strLayoutName;
}
}
public string PivotName
{
get { return m_LayoutMediator.LayoutRow.strPivotName; }
set
{
SharedPresenter.SharedModel.PivotName = value;
m_LayoutMediator.LayoutRow.strPivotName = value;
}
}
public string ChartName
{
get { return m_LayoutMediator.LayoutRow.strChartName; }
set
{
SharedPresenter.SharedModel.ChartName = value;
m_LayoutMediator.LayoutRow.strChartName = value;
}
}
public string MapName
{
get { return m_LayoutMediator.LayoutRow.strMapName; }
set
{
SharedPresenter.SharedModel.MapName = value;
m_LayoutMediator.LayoutRow.strMapName = value;
}
}
public long LayoutId
{
get { return m_LayoutMediator.LayoutRow.idflLayout; }
}
public long QueryId
{
get { return m_LayoutMediator.LayoutRow.idflQuery; }
}
public bool ApplyFilter
{
get
{
if (m_LayoutMediator.LayoutRow.IsblnApplyFilterNull())
{
return false;
}
return m_LayoutMediator.LayoutRow.blnApplyFilter;
}
}
public LayoutDetailDataSet.AggregateDataTable AggregateTable
{
get { return m_LayoutMediator.LayoutDataSet.Aggregate; }
}
public string LayoutXml
{
get
{
string basicXml = m_LayoutMediator.LayoutRow.IsstrBasicXmlNull()
? String.Empty
: m_LayoutMediator.LayoutRow.strBasicXml;
return basicXml;
}
set { m_LayoutMediator.LayoutRow.strBasicXml = value; }
}
public bool ReadOnly
{
get { return m_LayoutMediator.LayoutRow.blnReadOnly; }
}
public bool CopyPivotName { get; set; }
public bool CopyMapName { get; set; }
public bool CopyChartName { get; set; }
#region Binding
public void BindShareLayout(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnShareLayoutColumn.ColumnName);
}
public void BindApplyFilter(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnApplyFilterColumn.ColumnName);
}
public void BindDefaultLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDefaultLayoutNameColumn.ColumnName);
}
public void BindLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strLayoutNameColumn.ColumnName);
}
public void BindDescription(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDescriptionColumn.ColumnName);
}
internal void BindGroupInterval(LookUpEdit comboBox)
{
BindingHelper.BindCombobox(comboBox,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.idfsGroupIntervalColumn.ColumnName,
BaseReferenceType.rftGroupInterval,
(long) DBGroupInterval.gitDate);
}
public void BindShowTotalCols(CheckedComboBoxEdit edit)
{
edit.Properties.Items[0].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowColsTotals);
edit.Properties.Items[1].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowRowsTotals);
edit.Properties.Items[2].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowColGrandTotals);
edit.Properties.Items[3].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowRowGrandTotals);
edit.Properties.Items[4].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowForSingleTotals);
edit.RefreshEditValue();
edit.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
if (Utils.IsEmpty(edit.EditValue))
{
edit.EditValue = DBNull.Value;
}
}
public void BindBackShowTotalCols(CheckedComboBoxEdit edit, PivotGridOptionsView optionsView, bool isCompact)
{
if (isCompact)
{
optionsView.ShowRowTotals = true;
optionsView.ShowTotalsForSingleValues = true;
// optionsView.ShowColumnTotals = true;
// optionsView.ShowColumnGrandTotals = true;
// optionsView.ShowRowGrandTotals = true;
// optionsView.ShowGrandTotalsForSingleValues = true;
optionsView.RowTotalsLocation = PivotRowTotalsLocation.Tree;
}
else
{
optionsView.RowTotalsLocation = PivotRowTotalsLocation.Far;
m_LayoutMediator.LayoutRow.blnShowColsTotals = IsChecked(edit, 0);
m_LayoutMediator.LayoutRow.blnShowRowsTotals = IsChecked(edit, 1);
m_LayoutMediator.LayoutRow.blnShowColGrandTotals = IsChecked(edit, 2);
m_LayoutMediator.LayoutRow.blnShowRowGrandTotals = IsChecked(edit, 3);
m_LayoutMediator.LayoutRow.blnShowForSingleTotals = IsChecked(edit, 4);
optionsView.ShowColumnTotals = m_LayoutMediator.LayoutRow.blnShowColsTotals;
optionsView.ShowRowTotals = m_LayoutMediator.LayoutRow.blnShowRowsTotals;
optionsView.ShowColumnGrandTotals = m_LayoutMediator.LayoutRow.blnShowColGrandTotals;
optionsView.ShowRowGrandTotals = m_LayoutMediator.LayoutRow.blnShowRowGrandTotals;
optionsView.ShowTotalsForSingleValues = m_LayoutMediator.LayoutRow.blnShowForSingleTotals;
optionsView.ShowGrandTotalsForSingleValues = m_LayoutMediator.LayoutRow.blnShowForSingleTotals;
}
}
private static CheckState GetCheckState(bool flag)
{
return flag
? CheckState.Checked
: CheckState.Unchecked;
}
private static bool IsChecked(CheckedComboBoxEdit edit, int index)
{
if (index >= edit.Properties.Items.Count || index < 0)
{
throw new ArgumentException("Index out of range");
}
return edit.Properties.Items[index].CheckState == CheckState.Checked;
}
#endregion
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strLayoutName = layoutName;
}
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetDefaultLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strDefaultLayoutName = layoutName;
}
public void SetFilterText(string text)
{
SharedPresenter.SharedModel.FilterText = ApplyFilter ? text : String.Empty;
}
public void CopyLayoutNameIfNeeded()
{
if (!IsNewObject)
{
return;
}
if (CopyPivotName)
{
PivotName = LayoutName;
}
if (CopyChartName)
{
ChartName = LayoutName;
}
if (CopyMapName)
{
MapName = LayoutName;
}
}
private void PivotView_InitAdmUnit(object sender, ComboBoxEventArgs e)
{
m_SharedPresenter.BindAdmUnitComboBox(e);
}
private void PivotView_InitDenominator(object sender, ComboBoxEventArgs e)
{
m_SharedPresenter.BindDenominatorComboBox(e);
}
private void PivotView_InitStatDate(object sender, ComboBoxEventArgs e)
{
m_SharedPresenter.BindStatDateComboBox(e);
}
/// <summary>
/// Returns layout name with prefix "Copy of" on corresponding language
/// </summary>
/// <param name="layoutName"> </param>
/// <param name="columnName"> </param>
/// <param name="lngName"> </param>
/// <returns> </returns>
public string GetValueWithPrefix(string layoutName, string columnName, string lngName)
{
Utils.CheckNotNullOrEmpty(columnName, "columnName");
Utils.CheckNotNullOrEmpty(lngName, "lngName");
string result = layoutName;
for (int index = 0; index < Int32.MaxValue; index++)
{
string strIndex = index > 0 ? String.Format(" ({0})", index) : String.Empty;
string prefix = EidssMessages.Get("msgCopyPrefix", "Copy{0} of", lngName);
prefix = String.Format(Utils.Str(prefix).Trim(), strIndex);
string format = EidssMessages.Get("msgCopyFormat", "{0} {1}", lngName);
result = String.Format(format, prefix, Utils.Str(layoutName));
if (!IsLayoutExists(result, columnName))
{
break;
}
}
return result;
}
/// <summary>
/// Defines is layout with name stored in column "columnName" equals value "layoutName" exists
/// </summary>
/// <param name="layoutName"> </param>
/// <param name="columnName"> </param>
/// <returns> </returns>
private bool IsLayoutExists(string layoutName, string columnName)
{
Utils.CheckNotNull(layoutName, "layoutName");
Utils.CheckNotNullOrEmpty(columnName, "columnName");
LookupTableInfo info = LookupCache.LookupTables[LookupTables.Layout.ToString()];
DataTable dtLayout = LookupCache.Fill(info);
string filter = String.Format("idflQuery={0} and {1} = '{2}'", PivotFormService.QueryID, columnName,
layoutName.Replace("'", "''"));
DataRow[] dr = dtLayout.Select(filter);
bool isExists = (dr.Length > 1) ||
(IsNewObject && dr.Length > 0) ||
((dr.Length == 1) && (Utils.Str(dr[0]["idflLayout"]) != Utils.Str(m_LayoutMediator.LayoutRow.idflLayout)));
return isExists;
}
private void SharedModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var property = (SharedProperty) (Enum.Parse(typeof (SharedProperty), e.PropertyName));
switch (property)
{
case SharedProperty.SelectedQueryId:
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
PivotFormService.QueryID = queryId;
break;
case SharedProperty.ChartDataVertical:
bool vertical = m_SharedPresenter.SharedModel.ChartDataVertical;
m_PivotView.OnChangeOrientation(new ChartChangeOrientationEventArgs(vertical));
break;
}
}
public Dictionary<string, CustomSummaryType> GetNameSummaryTypeDictionary()
{
return GetNameSummaryTypeDictionary(AggregateTable);
}
public static Dictionary<string, CustomSummaryType> GetNameSummaryTypeDictionary
(LayoutDetailDataSet.AggregateDataTable aggregateTable)
{
var dictionary = new Dictionary<string, CustomSummaryType>();
foreach (LayoutDetailDataSet.AggregateRow row in aggregateTable.Rows)
{
string key = RamPivotGridHelper.CreateFieldName(row.SearchFieldAlias, row.idfLayoutSearchField);
if (!dictionary.ContainsKey(key))
{
CustomSummaryType value = ParseSummaryType(row.idfsAggregateFunction);
dictionary.Add(key, value);
}
}
return dictionary;
}
public Dictionary<string, int> GetIndexesDictionary()
{
return GetIndexesDictionary(AggregateTable, m_PivotView.BaseFields);
}
public static Dictionary<string, int> GetIndexesDictionary
(LayoutDetailDataSet.AggregateDataTable aggregateTable, PivotGridFieldCollectionBase fields)
{
var dictionary = new Dictionary<string, int>();
foreach (LayoutDetailDataSet.AggregateRow row in aggregateTable.Rows)
{
if (row.IsidfDenominatorQuerySearchFieldNull() || row.IsDenominatorSearchFieldAliasNull())
{
continue;
}
string fieldName = RamPivotGridHelper.CreateFieldName(row.SearchFieldAlias, row.idfLayoutSearchField);
string denominatorFieldName = RamPivotGridHelper.CreateFieldName(row.DenominatorSearchFieldAlias,
row.idfDenominatorQuerySearchField);
PivotGridFieldBase denominatorField = fields[denominatorFieldName];
if ((denominatorField != null) && denominatorField.Visible &&
(denominatorField.Area == PivotArea.DataArea))
{
dictionary.Add(fieldName, denominatorField.AreaIndex);
}
}
return dictionary;
}
public override void Process(Command cmd)
{
try
{
if (cmd is LayoutCommand)
{
ProcessLayout((LayoutCommand) cmd);
}
else if (cmd is ExportCommand)
{
ProcessExport(cmd as ExportCommand);
}
else if (cmd is ChangeFieldCaptionCommand)
{
ProcessChangeFieldCaption(cmd as ChangeFieldCaptionCommand);
}
}
catch (Exception ex)
{
if (BaseSettings.ThrowExceptionOnError)
{
throw;
}
ErrorForm.ShowError(ex);
}
}
private void ProcessExport(ExportCommand exportCommand)
{
if (exportCommand.ExportObject != ExportObject.Access)
{
return;
}
exportCommand.State = CommandState.Pending;
var dialog = new OpenFileDialog
{
DefaultExt = "mdb",
Filter = EidssMessages.Get("msgFilterAccess", "MS Access database|*.mdb"),
CheckFileExists = false
};
if (dialog.ShowDialog(m_PivotView.ParentForm) == DialogResult.OK)
{
DataTable dataTable = m_PivotView.FilteredDataSource;
var adapter = new AccessDataAdapter(dialog.FileName);
bool needExport = true;
if (adapter.IsTableExistInAccess(dataTable.TableName))
{
string caption = EidssMessages.Get("msgMessage");
string formatMsg = EidssMessages.Get("msgOverwriteAccessTable");
string msg = String.Format(formatMsg, adapter.DbFileName, dataTable.TableName);
needExport = AskQuestion(msg, caption);
}
if (needExport)
{
adapter.ExportTableToAccess(dataTable);
}
}
exportCommand.State = CommandState.Processed;
}
private void ProcessLayout(LayoutCommand layoutCommand)
{
if (layoutCommand.Operation == LayoutOperation.Filter)
{
layoutCommand.State = CommandState.Pending;
m_PivotView.ShowFilterForm();
layoutCommand.State = CommandState.Processed;
m_PivotView.RaiseDataLoadedEvent();
}
}
private void ProcessChangeFieldCaption(ChangeFieldCaptionCommand command)
{
if (command == null || String.IsNullOrEmpty(command.FieldName))
{
return;
}
command.State = CommandState.Pending;
WinPivotGridField field = m_PivotView.GetField(command.FieldName);
if (field == null)
{
throw new RamException(String.Format("Could not find field {0} in the PivotGrid", command.FieldName));
}
LayoutDetailDataSet.AggregateRow row = GetAggregateRowByField(field);
using (var form = new FieldCaptionForm(row.strOriginalFieldENCaption, row.strOriginalFieldCaption,
row.strNewFieldENCaption, row.strNewFieldCaption))
{
if (form.ShowDialog(m_PivotView.ParentForm) == DialogResult.OK)
{
row.strNewFieldENCaption = form.NewEnglishCaption;
row.strNewFieldCaption = ModelUserContext.CurrentLanguage == Localizer.lngEn
? form.NewEnglishCaption
: form.NewNationalCaption;
field.Caption = row.strNewFieldCaption;
m_PivotView.InitFilterControlHelperAndRefreshFilter();
}
}
command.State = CommandState.Processed;
}
private void PivotView_PivotSelected(object sender, PivotSelectionEventArgs e)
{
m_SharedPresenter.SharedModel.ControlsView = e;
}
private void PivotView_PivotDataLoaded(object sender, PivotDataEventArgs e)
{
m_SharedPresenter.SharedModel.PivotData = e;
}
internal bool ValidateLayoutName()
{
if (IsLayoutExists(m_LayoutMediator.LayoutRow.strDefaultLayoutName, "strDefaultLayoutName"))
{
MessageForm.Show(EidssMessages.Get("msgNoUniqueLayoutName",
"Layout with that name already exists. Please modify it."));
return false;
}
if ((ModelUserContext.CurrentLanguage != Localizer.lngEn) &&
(IsLayoutExists(m_LayoutMediator.LayoutRow.strLayoutName, "strLayoutName")))
{
MessageForm.Show(EidssMessages.Get("msgNoUniqueNatLayoutName",
"Layout with that national name already exists. Please modify it."));
return false;
}
return true;
}
internal PivotSelectionEventArgs DefineMapChartPageEnabled(Rectangle selection)
{
bool mapPageEnabled = false;
bool chartPageEnabled = (selection.Width > 0) || (selection.Height > 0);
bool isColumnSelected = (selection.Width == 1) && (selection.Height > 0);
bool isCellSelected = (selection.Width == 0) && (selection.Height == 0);
if (isColumnSelected || isCellSelected)
{
DataView dvMapFieldList = GetMapFiledView(PivotFormService.QueryID, true);
foreach (DataRowView r in dvMapFieldList)
{
if (GetFieldsInRow(Utils.Str(r["FieldAlias"])).Count > 0)
{
mapPageEnabled = true;
break;
}
}
}
return new PivotSelectionEventArgs(chartPageEnabled, mapPageEnabled);
}
public static DataTable GetMapDataTable()
{
//string tableName = m_PivotView.CorrectedLayoutName;
var dataTable = new DataTable();
dataTable.Columns.AddRange(new[]
{
new DataColumn(ColumnIdName, typeof (long)),
new DataColumn(ColumnLongitudeName, typeof (double)),
new DataColumn(ColumnLatitudeName, typeof (double)),
new DataColumn(ColumnTypeName, typeof (int)),
new DataColumn(ColumnValueName, typeof (double)),
new DataColumn(ColumnInfoName, typeof (string))
});
return dataTable;
}
public DataTable GetWinMapDataTable(string fieldName, out bool isSingle)
{
var idField = (PivotGridField) GetMapIdField(m_PivotView.BaseFields, fieldName);
var typeField = (PivotGridField) RamPivotGridHelper.GetEventTypeField(m_PivotView.BaseFields.Cast<PivotGridFieldBase>());
isSingle = (typeField == null);
IList<CustomMapDataItem> mapData = m_PivotView.GetSelectedCells(idField, typeField);
DataTable mapDataTable = ConvertMapDataForGis(mapData);
mapDataTable.TableName = m_PivotView.CorrectedLayoutName;
return mapDataTable;
}
public static DataTable GetWebMapDataTable(IRamPivotGridView pivotGrid, string fieldName, out bool isSingle)
{
PivotGridFieldBase idField = GetMapIdField(pivotGrid.BaseFields, fieldName);
PivotGridFieldBase typeField = RamPivotGridHelper.GetEventTypeField(pivotGrid.BaseFields.Cast<PivotGridFieldBase>());
isSingle = (typeField == null);
IList<CustomMapDataItem> mapData = pivotGrid.GetSelectedCells(idField, typeField);
DataTable mapDataTable = ConvertMapDataForGis(mapData);
return mapDataTable;
}
private static PivotGridFieldBase GetMapIdField(PivotGridFieldCollectionBase fields, string fieldName)
{
Utils.CheckNotNullOrEmpty(fieldName, "fieldName");
Utils.CheckNotNull(fields, "fields");
List<PivotGridFieldBase> list = fields.Cast<PivotGridFieldBase>().ToList();
PivotGridFieldBase idField = list.Find(field => (field.Visible) &&
(field.AreaIndex >= 0) &&
(field.Area == PivotArea.RowArea) &&
(field.FieldName == fieldName));
if (idField == null)
{
throw new RamException(
String.Format("Invalid map field name {0}", fieldName));
}
return idField;
}
public static DataTable ConvertMapDataForGis(IList<CustomMapDataItem> mapData)
{
DataView gisView = LookupCache.Get(LookupTables.AVRGIS);
gisView.Sort = "ExtendedName";
// creating table for map
DataTable dataTable = GetMapDataTable();
// filling table for map
dataTable.BeginLoadData();
foreach (CustomMapDataItem item in mapData)
{
DataRowView[] foundRows = gisView.FindRows(item.GisReferenceName);
if (foundRows.Length > 0)
{
DataRow row = dataTable.NewRow();
row[ColumnIdName] = foundRows[0]["idfsReference"];
row[ColumnLongitudeName] = foundRows[0]["dblLongitude"];
row[ColumnLatitudeName] = foundRows[0]["dblLatitude"];
row[ColumnTypeName] = item.GisCaseType;
row[ColumnValueName] = item.Value;
row[ColumnInfoName] = item.TotalCaption;
dataTable.Rows.Add(row);
}
else
{
Match match = Regex.Match(item.GisReferenceName, @"\((?<Latitude>-?\d+.\d+)\D+(?<Longitude>-?\d+.\d+)\)");
Group latitudeGroup = match.Groups["Latitude"];
Group longitudeGroup = match.Groups["Longitude"];
if ((latitudeGroup.Captures.Count > 0) && (longitudeGroup.Captures.Count > 0))
{
float latitude;
float longitude;
if (
Single.TryParse(latitudeGroup.Captures[0].Value, NumberStyles.Float,
CultureInfo.InvariantCulture, out latitude) &&
Single.TryParse(longitudeGroup.Captures[0].Value, NumberStyles.Float,
CultureInfo.InvariantCulture, out longitude))
{
DataRow row = dataTable.NewRow();
row[ColumnLongitudeName] = longitude;
row[ColumnLatitudeName] = latitude;
row[ColumnValueName] = item.Value;
row[ColumnTypeName] = item.GisCaseType;
row[ColumnInfoName] = item.TotalCaption;
dataTable.Rows.Add(row);
}
}
}
}
dataTable.EndLoadData();
dataTable.AcceptChanges();
return dataTable;
}
internal DataView GetStatDateDataView()
{
DataTable dataTable = GetListDataTable("DateFieldList");
dataTable.BeginLoadData();
foreach (WinPivotGridField field in m_PivotView.WinFields)
{
if (field.Visible &&
field.Area == PivotArea.ColumnArea &&
field.FieldDataType == typeof (DateTime))
{
DataRow dr = dataTable.NewRow();
dr["Alias"] = field.FieldName;
dr["Caption"] = field.Caption;
dataTable.Rows.Add(dr);
}
}
dataTable.EndLoadData();
dataTable.AcceptChanges();
return new DataView(dataTable, "", "Caption, Alias", DataViewRowState.CurrentRows);
}
internal DataView GetDenominatorDataView()
{
DataTable dataTable = GetListDataTable("DenominatorList");
dataTable.BeginLoadData();
foreach (WinPivotGridField field in m_PivotView.WinFields)
{
if (field.Visible &&
field.Area == PivotArea.DataArea &&
field.OriginalName != m_PivotView.SelectedRow.SearchFieldAlias)
{
DataRow dr = dataTable.NewRow();
dr["Alias"] = field.FieldName;
dr["Caption"] = field.Caption;
dataTable.Rows.Add(dr);
}
}
dataTable.EndLoadData();
dataTable.AcceptChanges();
return new DataView(dataTable, "", "Caption, Alias", DataViewRowState.CurrentRows);
}
private static DataTable GetListDataTable(string tableName)
{
var dataTable = new DataTable(tableName);
var colAlias = new DataColumn("Alias", typeof (string));
dataTable.Columns.Add(colAlias);
var colCaption = new DataColumn("Caption", typeof (string));
dataTable.Columns.Add(colCaption);
dataTable.PrimaryKey = new[] {colAlias};
return dataTable;
}
internal DataView GetAvailableMapFieldView(bool isMap)
{
DataView dvMapFieldList = GetMapFiledView(PivotFormService.QueryID, isMap);
DataTable dataTable = GetListDataTable("AdmUnitList");
var colOrder = new DataColumn("Order", typeof (int));
dataTable.Columns.Add(colOrder);
dataTable.BeginLoadData();
foreach (DataRowView r in dvMapFieldList)
{
List<WinPivotGridField> fields = GetFieldsInRow(Utils.Str(r["FieldAlias"]));
foreach (WinPivotGridField field in fields)
{
DataRow dr = dataTable.NewRow();
dr["Alias"] = field.FieldName;
dr["Caption"] = field.Caption;
dr["Order"] = isMap ? r["intMapDisplayOrder"] : r["intIncidenceDisplayOrder"];
dataTable.Rows.Add(dr);
}
}
if (!isMap)
{
DataRow countryRow = dataTable.NewRow();
countryRow["Alias"] = SharedPresenter.VirtualCountryFieldName;
countryRow["Caption"] = EidssMessages.Get("strCountry", "Country");
countryRow["Order"] = -1;
dataTable.Rows.Add(countryRow);
}
dataTable.EndLoadData();
dataTable.AcceptChanges();
return new DataView(dataTable, "", "Order, Caption, Alias", DataViewRowState.CurrentRows);
}
public static DataView GetMapFiledView(long queryId, bool isMap)
{
string key = LookupTables.QuerySearchField.ToString();
DataTable dtMapFieldList = LookupCache.Fill(LookupCache.LookupTables[key]);
string field = isMap ? "intMapDisplayOrder" : "intIncidenceDisplayOrder";
string filter = String.Format("idflQuery = {0} and {1} is not null", queryId, field);
string sort = String.Format("{0}, FieldCaption", field);
var dvMapFieldList = new DataView(dtMapFieldList, filter, sort, DataViewRowState.CurrentRows);
return dvMapFieldList;
}
#region Prepare Data Source For Pivot Grid
public DataTable GetPreparedDataSource()
{
if (m_SharedPresenter.IsQueryResultNull)
{
return null;
}
if (!m_SharedPresenter.SharedModel.PivotAccessible)
{
return m_SharedPresenter.GetQueryResultClone();
}
DataTable newDataSource = m_SharedPresenter.GetQueryResultCopy();
FillAggregateForNewFields(newDataSource, IsNewObject);
DeleteColumnsMissingInAggregateTable(AggregateTable, newDataSource, IsNewObject);
CreateCopiedColumnsAndAjustColumnNames(AggregateTable, newDataSource);
return newDataSource;
}
public static DataTable GetWebPreparedDataSource
(LayoutDetailDataSet.AggregateDataTable aggregateTable, DataTable queryResult)
{
if (queryResult == null)
{
return null;
}
DataTable newDataSource = queryResult.Copy();
DeleteColumnsMissingInAggregateTable(aggregateTable, newDataSource, false);
CreateCopiedColumnsAndAjustColumnNames(aggregateTable, newDataSource);
return newDataSource;
}
/// <summary>
/// method generates AggregateRow for each column in the Data Source that hasn't aggregate information
/// </summary>
/// <param name="newDataSource"> </param>
/// <param name="isNewObject"> </param>
private void FillAggregateForNewFields(DataTable newDataSource, bool isNewObject)
{
List<LayoutDetailDataSet.AggregateRow> aggregateRows =
AggregateTable.Rows.Cast<LayoutDetailDataSet.AggregateRow>().OrderBy(row=>row.idfLayoutSearchField).ToList();
// If AggregateTable doesn't contain row with Search Field that corresponds to one of QueryResult column,
// we should create corresponding aggregate row
List<long> idList = null;
if (isNewObject)
{
idList = BaseDbService.NewListIntID(newDataSource.Columns.Count);
}
int count = 0;
foreach (DataColumn column in newDataSource.Columns)
{
string columnName = column.ColumnName;
// process original fields, not copied fields in filter
// we think than each column has a copy
if (RamPivotGridHelper.GetIsCopyForFilter(columnName))
continue;
var foundRows = aggregateRows.FindAll(row => (row.SearchFieldAlias == columnName));
if (foundRows.Count < 2)
{
CustomSummaryType summaryType = (foundRows.Count == 0)
? Configuration.GetSummaryTypeFor(columnName, column.DataType)
: (CustomSummaryType) foundRows[0].idfsAggregateFunction;
var copyColumnName = columnName + RamPivotGridHelper.CopySuffix;
if (isNewObject && idList != null)
{
if (foundRows.Count == 0)
{
AddNewAggregateRow(columnName, (long)summaryType, idList[count]);
count++;
}
AddNewAggregateRow(copyColumnName, (long)summaryType, idList[count]);
count++;
}
else
{
if (foundRows.Count == 0)
{
AddNewAggregateRow(columnName, (long)summaryType);
}
AddNewAggregateRow(copyColumnName, (long)summaryType);
}
}
else
{
// second row corresponding to the copied column, so we should change SearchFieldAlias according to copied column name
foundRows[1].SearchFieldAlias = columnName + RamPivotGridHelper.CopySuffix;
}
}
}
/// <summary>
/// If Current object is NOT new, Method deletes all columns in the Data Source that hasn't corresponding rows in AggregateTable
/// </summary>
/// <param name="aggregateTable"> </param>
/// <param name="newDataSource"> </param>
/// <param name="isNewObject"> </param>
private static void DeleteColumnsMissingInAggregateTable
(LayoutDetailDataSet.AggregateDataTable aggregateTable,
DataTable newDataSource, bool isNewObject)
{
if (!isNewObject)
{
List<LayoutDetailDataSet.AggregateRow> aggregateRows =
aggregateTable.Rows.Cast<LayoutDetailDataSet.AggregateRow>().ToList();
List<DataColumn> dataColumns = newDataSource.Columns.Cast<DataColumn>().ToList();
foreach (DataColumn column in dataColumns)
{
string columnName = column.ExtendedProperties.ContainsKey(RamPivotGridHelper.CopySuffix)
? RamPivotGridHelper.GetOriginalNameFromCopyForFilterName(column.ColumnName)
: column.ColumnName;
LayoutDetailDataSet.AggregateRow foundRow =
aggregateRows.Find(row => (row.SearchFieldAlias == columnName));
if (foundRow == null)
{
newDataSource.Columns.Remove(column);
}
}
}
}
/// <summary>
/// If AggregateTable contains multiple rows with the same SearchFieldAlias, method creates corresponding columns. Also method appends Column Name with corresponding idfLayoutSearchField for each column
/// </summary>
/// <param name="aggregateTable"> </param>
/// <param name="newDataSource"> </param>
private static void CreateCopiedColumnsAndAjustColumnNames
(LayoutDetailDataSet.AggregateDataTable aggregateTable,
DataTable newDataSource)
{
List<DataColumn> dataColumns = newDataSource.Columns.Cast<DataColumn>().ToList();
List<LayoutDetailDataSet.AggregateRow> aggregateRows =
aggregateTable.Rows.Cast<LayoutDetailDataSet.AggregateRow>().ToList();
foreach (DataColumn column in dataColumns)
{
string originalName = column.ColumnName;
List<LayoutDetailDataSet.AggregateRow> foundRows =
aggregateRows.FindAll(row => (row.SearchFieldAlias == originalName));
int rowCounter = 0;
foreach (LayoutDetailDataSet.AggregateRow row in foundRows)
{
CheckAggregateRowTranslations(row);
if (column.ExtendedProperties.ContainsKey(RamPivotGridHelper.CopySuffix))
{
row.SearchFieldAlias = RamPivotGridHelper.GetOriginalNameFromCopyForFilterName(originalName);
}
string caption = row.IsstrNewFieldCaptionNull() || Utils.IsEmpty(row.strNewFieldCaption)
? row.strOriginalFieldCaption
: row.strNewFieldCaption;
if (rowCounter == 0)
{
// change name so it shall contain idfLayoutSearchField
column.ColumnName = RamPivotGridHelper.CreateFieldName(row.SearchFieldAlias, row.idfLayoutSearchField);
column.Caption = caption;
}
else
{
// create copy of column with new idfLayoutSearchField
// name of new column shall contain new id
CreateDataSourceColumnCopy(newDataSource,
column.ColumnName,
row.SearchFieldAlias,
caption,
row.idfLayoutSearchField);
}
rowCounter++;
}
}
}
private static void CheckAggregateRowTranslations(LayoutDetailDataSet.AggregateRow row)
{
string msg = EidssMessages.Get("msgEmptyRow", "One of rows has empty translation {0}");
if (row.IsstrOriginalFieldENCaptionNull() || row.IsstrOriginalFieldCaptionNull())
{
throw new RamDbException(String.Format(msg, row.SearchFieldAlias));
}
}
#endregion
#region Create and delete Field Copy
public void CreateFieldCopy(WinPivotGridField sourceField)
{
Utils.CheckNotNull(sourceField, "sourceField");
LayoutDetailDataSet.AggregateRow destRow = CreateAggregateInformationCopy(sourceField);
DataColumn destColumn = CreateDataSourceColumnCopy(sourceField, destRow.idfLayoutSearchField);
CreatePivotGridFieldCopy(sourceField, destColumn.ColumnName);
}
private LayoutDetailDataSet.AggregateRow CreateAggregateInformationCopy(WinPivotGridField sourceField)
{
LayoutDetailDataSet.AggregateRow sourceRow = GetAggregateRowByField(sourceField);
LayoutDetailDataSet.AggregateRow destRow = AddNewAggregateRow(sourceRow.SearchFieldAlias,
(long) sourceField.GetSummaryType);
destRow.strNewFieldCaption = sourceRow.strNewFieldCaption;
destRow.strNewFieldENCaption = sourceRow.strNewFieldENCaption;
if (!sourceRow.IsidfUnitQuerySearchFieldNull() && !sourceRow.IsUnitSearchFieldAliasNull())
{
destRow.UnitSearchFieldAlias = sourceRow.UnitSearchFieldAlias;
destRow.idfUnitQuerySearchField = sourceRow.idfUnitQuerySearchField;
}
if (!sourceRow.IsidfDenominatorQuerySearchFieldNull() && !sourceRow.IsDenominatorSearchFieldAliasNull())
{
destRow.DenominatorSearchFieldAlias = sourceRow.DenominatorSearchFieldAlias;
destRow.idfDenominatorQuerySearchField = sourceRow.idfDenominatorQuerySearchField;
}
if (!sourceRow.IsidfDateQuerySearchFieldNull() && !sourceRow.IsDateSearchFieldAliasNull())
{
destRow.DateSearchFieldAlias = sourceRow.DateSearchFieldAlias;
destRow.idfDateQuerySearchField = sourceRow.idfDateQuerySearchField;
}
return destRow;
}
private LayoutDetailDataSet.AggregateRow GetAggregateRowByField(WinPivotGridField sourceField)
{
Utils.CheckNotNull(sourceField, "sourceField");
if (sourceField.Id < 0)
{
throw new RamException(String.Format("Field {0} doesn't has Id", sourceField.FieldName));
}
LayoutDetailDataSet.AggregateRow sourceRow = AggregateTable.FindByidfLayoutSearchField(sourceField.Id);
if (sourceRow == null)
{
throw new RamException(String.Format("Aggregate information not found for field {0} with ID {1}",
sourceField.FieldName, sourceField.Id));
}
return sourceRow;
}
private DataColumn CreateDataSourceColumnCopy
(WinPivotGridField sourceField, long idfLayoutSearchField)
{
return CreateDataSourceColumnCopy(m_PivotView.DataSource,
sourceField.FieldName,
sourceField.OriginalName,
sourceField.Caption,
idfLayoutSearchField);
}
private static DataColumn CreateDataSourceColumnCopy
(DataTable dataSource, string fullFieldName, string originalFieldName, string fieldCaption, long idfLayoutSearchField)
{
DataColumn sourceColumn = dataSource.Columns[fullFieldName];
DataColumn destColumn = ReflectionHelper.CreateAndCopyProperties(sourceColumn);
destColumn.ColumnName = RamPivotGridHelper.CreateFieldName(originalFieldName, idfLayoutSearchField);
dataSource.Columns.Add(destColumn);
foreach (DataRow row in dataSource.Rows)
{
bool isAddedRow = row.RowState == DataRowState.Added;
row[destColumn] = row[sourceColumn];
if (!isAddedRow)
{
row.AcceptChanges();
}
}
destColumn.Caption = fieldCaption;
return destColumn;
}
public void DeleteFieldCopy(WinPivotGridField sourceField)
{
string message =
String.Format(
BvMessages.Get("msgDeleteAVRFieldPrompt", "{0} field will be deleted. Delete field?"),
sourceField.Caption);
DialogResult dialogResult = MessageForm.Show(message, BvMessages.Get("Confirmation"),
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult != DialogResult.Yes)
{
return;
}
DataColumn sourceColumn = m_PivotView.DataSource.Columns[sourceField.FieldName];
m_PivotView.DataSource.Columns.Remove(sourceColumn);
m_PivotView.RemoveField(sourceField);
m_PivotView.RefreshData();
// clear Unit, Denoninator, Date and other fields here
string originalName = sourceField.OriginalName;
List<LayoutDetailDataSet.AggregateRow> aggregateRows =
AggregateTable.Rows.Cast<LayoutDetailDataSet.AggregateRow>().ToList();
List<LayoutDetailDataSet.AggregateRow> denominatorRows =
aggregateRows.FindAll(
denRow =>
(!denRow.IsDenominatorSearchFieldAliasNull() && denRow.DenominatorSearchFieldAlias == originalName));
foreach (LayoutDetailDataSet.AggregateRow denRow in denominatorRows)
{
denRow.SetDenominatorSearchFieldAliasNull();
denRow.SetidfDenominatorQuerySearchFieldNull();
}
List<LayoutDetailDataSet.AggregateRow> unitRows =
aggregateRows.FindAll(uRow => (!uRow.IsUnitSearchFieldAliasNull() && uRow.UnitSearchFieldAlias == originalName));
foreach (LayoutDetailDataSet.AggregateRow uRow in unitRows)
{
uRow.SetUnitSearchFieldAliasNull();
uRow.SetidfUnitQuerySearchFieldNull();
}
List<LayoutDetailDataSet.AggregateRow> dateRows =
aggregateRows.FindAll(dateRow => (!dateRow.IsDateSearchFieldAliasNull() && dateRow.DateSearchFieldAlias == originalName));
foreach (LayoutDetailDataSet.AggregateRow dateRow in dateRows)
{
dateRow.SetDateSearchFieldAliasNull();
dateRow.SetidfDateQuerySearchFieldNull();
}
// remove corresponding aggregate row
LayoutDetailDataSet.AggregateRow row = AggregateTable.FindByidfLayoutSearchField(sourceField.Id);
AggregateTable.RemoveAggregateRow(row);
}
private void CreatePivotGridFieldCopy(WinPivotGridField sourceField, string fieldName)
{
WinPivotGridField field = ReflectionHelper.CreateAndCopyProperties(sourceField);
field.Name = "field" + fieldName;
field.FieldName = fieldName;
m_PivotView.AddField(field);
m_PivotView.RefreshData();
}
#endregion
#region Helper Methods
private static void InitGisTypes()
{
GisTypeDictionary = new Dictionary<string, GisCaseType>();
DataView lookupGisTypes = LookupCache.Get(LookupTables.CaseType.ToString());
if (lookupGisTypes == null)
{
return;
}
foreach (DataRowView row in lookupGisTypes)
{
string key = row["name"].ToString();
if (!GisTypeDictionary.ContainsKey(key))
{
var id = (long) row["idfsReference"];
switch (id)
{
case 10012001:
GisTypeDictionary.Add(key, GisCaseType.Human);
break;
case 10012003:
GisTypeDictionary.Add(key, GisCaseType.Livestock);
break;
case 10012004:
GisTypeDictionary.Add(key, GisCaseType.Avian);
break;
case 10012005:
GisTypeDictionary.Add(key, GisCaseType.Vet);
break;
case 10012006:
GisTypeDictionary.Add(key, GisCaseType.Vector);
break;
default:
GisTypeDictionary.Add(key, GisCaseType.Unkown);
break;
}
}
}
}
public LayoutDetailDataSet.AggregateRow AddNewAggregateRow(string originalFieldName, long aggregateFunctionId)
{
return AddNewAggregateRow(AggregateTable, QueryId, LayoutId, originalFieldName, aggregateFunctionId, BaseDbService.NewIntID());
}
public LayoutDetailDataSet.AggregateRow AddNewAggregateRow
(string originalFieldName, long aggregateFunctionId, long idfLayoutSearchField)
{
return AddNewAggregateRow(AggregateTable, QueryId, LayoutId, originalFieldName, aggregateFunctionId, idfLayoutSearchField);
}
internal static string GetReferenceID(string prefix, Enum reference)
{
return String.Format("{0}{1}", prefix, reference);
}
internal static PivotGroupInterval GetGroupInterval(object interval)
{
try
{
string strInterval = ((DBGroupInterval) interval).ToString().Substring(3);
return (PivotGroupInterval) Enum.Parse(typeof (PivotGroupInterval), strInterval);
}
catch (Exception)
{
return PivotGroupInterval.Date;
}
}
internal static CustomSummaryType ParseSummaryType(long value)
{
IEnumerable<CustomSummaryType> allEnumValues =
Enum.GetValues(typeof (CustomSummaryType)).Cast<CustomSummaryType>();
CustomSummaryType result = allEnumValues.Any(current => current == (CustomSummaryType) value)
? (CustomSummaryType) value
: CustomSummaryType.Max;
return result;
}
internal static int ConvertValueToInt(object oValue)
{
return (int) ConvertValueToLong(oValue);
}
internal static long ConvertValueToLong(object oValue)
{
long value = 0;
if (!Utils.IsEmpty(oValue))
{
double dValue;
if (Double.TryParse(oValue.ToString(), out dValue))
{
value = (long) Math.Round(dValue);
}
}
return value;
}
public static double ConvertValueToDouble(object oValue)
{
if (!Utils.IsEmpty(oValue))
{
double dValue;
if (Double.TryParse(oValue.ToString(), out dValue))
{
return dValue;
}
}
return 0;
}
private List<WinPivotGridField> GetFieldsInRow(string originalFieldName)
{
Utils.CheckNotNullOrEmpty(originalFieldName, "originalFieldName");
List<WinPivotGridField> fields = m_PivotView.WinFields.ToList();
List<WinPivotGridField> found = fields.FindAll(field => (field.Visible) &&
(field.AreaIndex >= 0) &&
(field.Area == PivotArea.RowArea) &&
(field.OriginalName == originalFieldName));
return found;
}
public static bool AskQuestion(string text, string caption)
{
return MessageForm.Show(text, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes;
}
public static string AppendLanguageNameTo(string text)
{
if (!Utils.IsEmpty(text))
{
int bracketInd = text.IndexOf("(", StringComparison.Ordinal);
if (bracketInd >= 0)
{
text = text.Substring(0, bracketInd).Trim();
}
string languageName = Localizer.GetLanguageName(ModelUserContext.CurrentLanguage);
text = String.Format("{0} ({1})", text, languageName);
}
return text;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Diagnostics.Tracing
{
/// <summary>
/// A TelemetryListener is something that forwards on events written with TelemetrySource.
/// It is an IObservable (has Subscribe method), and it also has a Subscribe overload that
/// lets you specify a 'IsEnabled' predicate that users of TelemetrySource will use for
/// 'quick checks'.
///
/// The item in the stream is a KeyValuePair[string, object] where the string is the name
/// of the telemetry item and the object is the payload (typically an anonymous type).
///
/// There may be many TelemetryListeners in the system, but we encourage the use of
/// The TelemetrySource.DefaultSource which goes to the TelemetryListener.DefaultListener.
///
/// If you need to see 'everything' you can subscribe to the 'AllListeners' event that
/// will fire for every live TelemetryListener in the appdomain (past or present).
/// </summary>
public class TelemetryListener : TelemetrySource, IObservable<KeyValuePair<string, object>>, IDisposable
{
/// <summary>
/// This is the TelemetryListener that is used by default by the class library.
/// Generally you don't want to make your own but rather have everyone use this one, which
/// ensures that everyone who wished to subscribe gets the callbacks.
/// The main reason not to us this one is that you WANT isolation from other
/// events in the system (e.g. multi-tenancy).
/// </summary>
public static TelemetryListener DefaultListener { get { return s_default; } }
/// <summary>
/// When you subscribe to this you get callbacks for all NotificationListeners in the appdomain
/// as well as those that occurred in the past, and all future Listeners created in the future.
/// </summary>
public static IObservable<TelemetryListener> AllListeners
{
get
{
if (s_allListenerObservable == null)
{
s_allListenerObservable = new AllListenerObservable();
}
return s_allListenerObservable;
}
}
// Subscription implementation
/// <summary>
/// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled
/// will always return true.
/// </summary>
virtual public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
// If we have been disposed, we silently ignore any subscriptions.
if (_disposed)
{
return new TelemetrySubscription() { Owner = this };
}
TelemetrySubscription newSubscription = new TelemetrySubscription() { Observer = observer, IsEnabled = isEnabled, Owner = this, Next = _subscriptions };
while (Interlocked.CompareExchange(ref _subscriptions, newSubscription, newSubscription.Next) != newSubscription.Next)
newSubscription.Next = _subscriptions;
return newSubscription;
}
/// <summary>
/// Same as other Subscribe overload where the predicate is assumed to always return true.
/// </summary>
public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
return Subscribe(observer, null);
}
/// <summary>
/// Make a new TelemetryListener, it is a NotificationSource, which means the returned result can be used to
/// log notifications, but it also has a Subscribe method so notifications can be forwarded
/// arbitrarily. Thus its job is to forward things from the producer to all the listeners
/// (multi-casting). Generally you should not be making your own TelemetryListener but use the
/// TelemetryListener.Default, so that notifications are as 'public' as possible.
/// </summary>
public TelemetryListener(string name)
{
Name = name;
// To avoid allocating an explicit lock object I lock the Default TelemetryListener. However there is a
// chicken and egg problem because I need to call this code to initialize TelemetryListener.DefaultListener.
var lockObj = DefaultListener;
if (lockObj == null)
{
lockObj = this;
Debug.Assert(this.Name == "TelemetryListener.DefaultListener");
}
// Insert myself into the list of all Listeners.
lock (lockObj)
{
// Issue the callback for this new telemetry listener.
var allListenerObservable = s_allListenerObservable;
if (allListenerObservable != null)
allListenerObservable.OnNewTelemetryListener(this);
// And add it to the list of all past listeners.
_next = s_allListeners;
s_allListeners = this;
}
}
/// <summary>
/// Clean up the NotificationListeners. Notification listeners do NOT DIE ON THEIR OWN
/// because they are in a global list (for discoverability). You must dispose them explicitly.
/// Note that we do not do the Dispose(bool) pattern because we frankly don't want to support
/// subclasses that have non-managed state.
/// </summary>
virtual public void Dispose()
{
// Remove myself from the list of all listeners.
lock (DefaultListener)
{
if (_disposed)
{
return;
}
_disposed = true;
if (s_allListeners == this)
s_allListeners = s_allListeners._next;
else
{
var cur = s_allListeners;
while (cur != null)
{
if (cur._next == this)
{
cur._next = _next;
break;
}
cur = cur._next;
}
}
_next = null;
}
// Indicate completion to all subscribers.
TelemetrySubscription subscriber = null;
Interlocked.Exchange(ref subscriber, _subscriptions);
while (subscriber != null)
{
subscriber.Observer.OnCompleted();
subscriber = subscriber.Next;
}
// The code above also nulled out all subscriptions.
}
/// <summary>
/// When a TelemetryListener is created it is given a name. Return this.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Return the name for the ToString() to aid in debugging.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#region private
// NotificationSource implementation
/// <summary>
/// Override abstract method
/// </summary>
public override bool IsEnabled(string telemetryName)
{
for (TelemetrySubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
{
if (curSubscription.IsEnabled == null || curSubscription.IsEnabled(telemetryName))
return true;
}
return false;
}
/// <summary>
/// Override abstract method
/// </summary>
public override void WriteTelemetry(string telemetryName, object arguments)
{
for (TelemetrySubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
curSubscription.Observer.OnNext(new KeyValuePair<string, object>(telemetryName, arguments));
}
// Note that Subscriptions are READ ONLY. This means you never update any fields (even on removal!)
private class TelemetrySubscription : IDisposable
{
internal IObserver<KeyValuePair<string, object>> Observer;
internal Predicate<string> IsEnabled;
internal TelemetryListener Owner; // The TelemetryListener this is a subscription for.
internal TelemetrySubscription Next; // Linked list of subscribers
public void Dispose()
{
// TO keep this lock free and easy to analyze, the linked list is READ ONLY. Thus we copy
for (;;)
{
TelemetrySubscription subscriptions = Owner._subscriptions;
TelemetrySubscription newSubscriptions = Remove(subscriptions, this); // Make a new list, with myself removed.
// try to update, but if someone beat us to it, then retry.
if (Interlocked.CompareExchange(ref Owner._subscriptions, newSubscriptions, subscriptions) == subscriptions)
{
#if DEBUG
var cur = newSubscriptions;
while (cur != null)
{
Debug.Assert(!(cur.Observer == Observer && cur.IsEnabled == IsEnabled), "Did not remove subscription!");
cur = cur.Next;
}
#endif
break;
}
}
}
// Create a new linked list where 'subscription has been removed from the linked list of 'subscriptions'.
private static TelemetrySubscription Remove(TelemetrySubscription subscriptions, TelemetrySubscription subscription)
{
if (subscriptions == null)
{
// May happen if the IDisposable returned from Subscribe is Dispose'd again
return null;
}
if (subscriptions.Observer == subscription.Observer && subscriptions.IsEnabled == subscription.IsEnabled)
return subscriptions.Next;
#if DEBUG
// Delay a bit. This makes it more likely that races will happen.
for (int i = 0; i < 100; i++)
GC.KeepAlive("");
#endif
return new TelemetrySubscription() { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled = subscriptions.IsEnabled, Next = Remove(subscriptions.Next, subscription) };
}
}
#region AllListenerObservable
/// <summary>
/// Logically AllListenerObservable has a very simple task. It has a linked list of subscribers that want
/// a callback when a new listener gets created. When a new TelemetryListener gets created it should call
/// OnNewTelemetryListener so that AllListenerObservable can forward it on to all the subscribers.
/// </summary>
private class AllListenerObservable : IObservable<TelemetryListener>
{
public IDisposable Subscribe(IObserver<TelemetryListener> observer)
{
lock (DefaultListener)
{
// Call back for each existing listener on the new callback (catch-up).
for (TelemetryListener cur = s_allListeners; cur != null; cur = cur._next)
observer.OnNext(cur);
// Add the observer to the list of subscribers.
_subscriptions = new AllListenerSubscription(this, observer, _subscriptions);
return _subscriptions;
}
}
/// <summary>
/// Called when a new TelemetryListener gets created to tell anyone who subscribed that this happened.
/// </summary>
/// <param name="telemetryListener"></param>
internal void OnNewTelemetryListener(TelemetryListener telemetryListener)
{
// Simply send a callback to every subscriber that we have a new listener
lock (DefaultListener)
{
for (var cur = _subscriptions; cur != null; cur = cur.Next)
cur.Subscriber.OnNext(telemetryListener);
}
}
#region private
/// <summary>
/// Remove 'subscription from the list of subscriptions that the observable has. Called when
/// subscriptions are disposed.
/// </summary>
private bool Remove(AllListenerSubscription subscription)
{
lock (DefaultListener)
{
if (_subscriptions == subscription)
{
_subscriptions = subscription.Next;
return true;
}
else if (_subscriptions != null)
{
for (var cur = _subscriptions; cur.Next != null; cur = cur.Next)
{
if (cur.Next == subscription)
{
cur.Next = cur.Next.Next;
return true;
}
}
}
// Subscriber likely disposed multiple times
return false;
}
}
/// <summary>
/// One node in the linked list of subscriptions that AllListenerObservable keeps. It is
/// IDisposable, and when that is called it removes itself from the list.
/// </summary>
internal class AllListenerSubscription : IDisposable
{
internal AllListenerSubscription(AllListenerObservable owner, IObserver<TelemetryListener> subscriber, AllListenerSubscription next)
{
this._owner = owner;
this.Subscriber = subscriber;
this.Next = next;
}
public void Dispose()
{
if (_owner.Remove(this))
{
Subscriber.OnCompleted();
}
}
private readonly AllListenerObservable _owner; // the list this is a member of.
internal readonly IObserver<TelemetryListener> Subscriber;
internal AllListenerSubscription Next;
}
private AllListenerSubscription _subscriptions;
#endregion
}
#endregion
// TODO _subscriptions should be volatile but we get a warning (which gets treated as an error) that
// when it gets passed as ref to Interlock.* functions that its volatileness disappears. We really should
// just be suppressing the warning. We can get away without the volatile because we only read it once
private /* volatile */ TelemetrySubscription _subscriptions;
private TelemetryListener _next; // We keep a linked list of all NotificationListeners (s_allListeners)
private bool _disposed; // Has Dispose been called?
private static TelemetryListener s_allListeners; // linked list of all instances of TelemetryListeners.
private static AllListenerObservable s_allListenerObservable; // to make callbacks to this object when listeners come into existence.
private static readonly TelemetryListener s_default = new TelemetryListener("TelemetryListener.DefaultListener");
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// InstanceDescriptorTest.cs - Unit tests for
// System.ComponentModel.Design.Serialization.InstanceDescriptor
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Xunit;
using System.Reflection;
using System.Linq;
namespace System.ComponentModel.Design.Serialization.Tests
{
public class InstanceDescriptorTest
{
private const string Url = "http://www.mono-project.com/";
[Fact]
public void Ctor_ConstructorInfo_ICollection()
{
ConstructorInfo ci = typeof(Uri).GetConstructor(new Type[] { typeof(string) });
InstanceDescriptor id = new InstanceDescriptor(ci, new object[] { Url });
Assert.Equal(1, id.Arguments.Count);
Assert.True(id.IsComplete);
Assert.Same(ci, id.MemberInfo);
Uri uri = (Uri)id.Invoke();
Assert.Equal(Url, uri.AbsoluteUri);
}
[Fact]
public void Constructor_ConstructorInfo_ICollection_Boolean()
{
ConstructorInfo ci = typeof(Uri).GetConstructor(new Type[] { typeof(string) });
InstanceDescriptor id = new InstanceDescriptor(ci, new object[] { Url }, false);
Assert.Equal(1, id.Arguments.Count);
Assert.False(id.IsComplete);
Assert.Same(ci, id.MemberInfo);
Uri uri = (Uri)id.Invoke();
Assert.Equal(Url, uri.AbsoluteUri);
}
[Theory]
[InlineData(null)]
[InlineData(new object[] { new object[] { } })]
public void Ctor_ConstructorInfoArgumentMismatch_ThrowsArgumentException(object[] arguments)
{
ConstructorInfo ci = typeof(Uri).GetConstructor(new Type[] { typeof(string) });
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(ci, arguments));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(ci, arguments, false));
}
[Fact]
public void Ctor_StaticConstructor_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(StaticConstructor).GetConstructors(BindingFlags.Static | BindingFlags.NonPublic).Single();
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(constructor, null));
}
[Theory]
[InlineData(null)]
[InlineData(new object[] { new object[] { } })]
public void Ctor_FieldInfo_ICollection(object[] arguments)
{
FieldInfo fi = typeof(StaticField).GetField(nameof(StaticField.Field));
InstanceDescriptor id = new InstanceDescriptor(fi, arguments);
Assert.Equal(0, id.Arguments.Count);
Assert.True(id.IsComplete);
Assert.Same(fi, id.MemberInfo);
Assert.NotNull(id.Invoke());
}
[Fact]
public void Ctor_FieldInfoArgumentMismatch_ThrowsArgumentException()
{
FieldInfo fi = typeof(StaticField).GetField(nameof(StaticField.Field));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(fi, new object[] { Url }));
}
[Fact]
public void Ctor_NonStaticFieldInfo_ThrowsArgumentException()
{
FieldInfo fi = typeof(InstanceField).GetField(nameof(InstanceField.Name));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(fi, null));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(fi, null, false));
}
[Theory]
[InlineData(null)]
[InlineData(new object[] { new object[] { } })]
public void Ctor_PropertyInfo_ICollection(object[] arguments)
{
PropertyInfo pi = typeof(StaticProperty).GetProperty(nameof(StaticProperty.Property));
InstanceDescriptor id = new InstanceDescriptor(pi, arguments);
Assert.Equal(0, id.Arguments.Count);
Assert.True(id.IsComplete);
Assert.Same(pi, id.MemberInfo);
Assert.NotNull(id.Invoke());
}
[Fact]
public void Invoke_PropertyInfoArgumentMismatch_ThrowsTargetParameterCountException()
{
PropertyInfo pi = typeof(StaticProperty).GetProperty(nameof(StaticProperty.Property));
InstanceDescriptor id = new InstanceDescriptor(pi, new object[] { Url });
Assert.Equal(1, id.Arguments.Count);
object[] arguments = new object[id.Arguments.Count];
id.Arguments.CopyTo(arguments, 0);
Assert.Same(Url, arguments[0]);
Assert.True(id.IsComplete);
Assert.Same(pi, id.MemberInfo);
Assert.Throws<TargetParameterCountException>(() => id.Invoke());
}
[Fact]
public void Ctor_NonStaticPropertyInfo_ThrowsArgumentException()
{
PropertyInfo pi = typeof(InstanceProperty).GetProperty(nameof(InstanceProperty.Property));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(pi, null));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(pi, null, false));
}
[Fact]
public void Ctor_WriteOnlyPropertyInfo_ThrowsArgumentException()
{
PropertyInfo pi = typeof(WriteOnlyProperty).GetProperty(nameof(WriteOnlyProperty.Name));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(pi, null));
}
[Fact]
public void Ctor_MethodInfo_ICollection()
{
MethodInfo method = typeof(MethodClass).GetMethod(nameof(MethodClass.StaticMethod));
var arguments = new object[] { 1 };
var instanceDescriptor = new InstanceDescriptor(method, arguments);
Assert.Same(method, instanceDescriptor.MemberInfo);
Assert.Equal(arguments, instanceDescriptor.Arguments);
Assert.NotSame(arguments, instanceDescriptor.Arguments);
Assert.True(instanceDescriptor.IsComplete);
Assert.Equal("1", instanceDescriptor.Invoke());
}
[Fact]
public void Ctor_NonStaticMethod_ThrowsArgumentException()
{
MethodInfo method = typeof(MethodClass).GetMethod(nameof(MethodClass.Method));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(method, new object[] { 1 }));
}
[Theory]
[InlineData(0)]
[InlineData(2)]
public void Ctor_IncorrectMethodArgumentCount_ThrowsArgumentException(int count)
{
MethodInfo method = typeof(MethodClass).GetMethod(nameof(MethodClass.StaticMethod));
AssertExtensions.Throws<ArgumentException>(null, () => new InstanceDescriptor(method, new object[count]));
}
[Fact]
public void Ctor_EventInfo_ICollection()
{
EventInfo eventInfo = typeof(EventClass).GetEvent(nameof(EventClass.Event));
var arguments = new object[] { 1 };
var instanceDescriptor = new InstanceDescriptor(eventInfo, arguments);
Assert.Same(eventInfo, instanceDescriptor.MemberInfo);
Assert.Equal(arguments, instanceDescriptor.Arguments);
Assert.NotSame(arguments, instanceDescriptor.Arguments);
Assert.True(instanceDescriptor.IsComplete);
Assert.Null(instanceDescriptor.Invoke());
}
[Fact]
public void Invoke_ArgumentInstanceDescriptor_InvokesArgument()
{
MethodInfo argumentMethod = typeof(MethodClass).GetMethod(nameof(MethodClass.IntMethod));
var argumentInstanceDescriptor = new InstanceDescriptor(argumentMethod, null);
MethodInfo method = typeof(MethodClass).GetMethod(nameof(MethodClass.StaticMethod));
var instanceDescriptor = new InstanceDescriptor(method, new object[] { argumentInstanceDescriptor });
Assert.Equal("1", instanceDescriptor.Invoke());
}
[Fact]
public void Invoke_NullMember_ReturnsNull()
{
var instanceDescriptor = new InstanceDescriptor(null, new object[0]);
Assert.Null(instanceDescriptor.Invoke());
}
private class EventClass
{
public event EventHandler Event { add { } remove { } }
}
private class StaticConstructor
{
static StaticConstructor() { }
}
private class MethodClass
{
public void Method(int i) { }
public static int IntMethod() => 1;
public static string StaticMethod(int i) => i.ToString();
}
private class WriteOnlyProperty
{
public static string Name
{
set { }
}
}
public class InstanceField
{
public string Name = "FieldValue";
}
public class InstanceProperty
{
public string Property => "PropertyValue";
}
public class StaticField
{
public static readonly string Field = "FieldValue";
}
public class StaticProperty
{
public static string Property => "PropertyValue";
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.DataFeeds.Enumerators
{
/// <summary>
/// The FillForwardEnumerator wraps an existing base data enumerator and inserts extra 'base data' instances
/// on a specified fill forward resolution
/// </summary>
public class FillForwardEnumerator : IEnumerator<BaseData>
{
private DateTime? _delistedTime;
private BaseData _previous;
private bool _isFillingForward;
private bool _emittedAuxilliaryData;
private readonly TimeSpan _dataResolution;
private readonly bool _isExtendedMarketHours;
private readonly DateTime _subscriptionEndTime;
private readonly IEnumerator<BaseData> _enumerator;
private readonly IReadOnlyRef<TimeSpan> _fillForwardResolution;
/// <summary>
/// The exchange used to determine when to insert fill forward data
/// </summary>
protected readonly SecurityExchange Exchange;
/// <summary>
/// Initializes a new instance of the <see cref="FillForwardEnumerator"/> class that accepts
/// a reference to the fill forward resolution, useful if the fill forward resolution is dynamic
/// and changing as the enumeration progresses
/// </summary>
/// <param name="enumerator">The source enumerator to be filled forward</param>
/// <param name="exchange">The exchange used to determine when to insert fill forward data</param>
/// <param name="fillForwardResolution">The resolution we'd like to receive data on</param>
/// <param name="isExtendedMarketHours">True to use the exchange's extended market hours, false to use the regular market hours</param>
/// <param name="subscriptionEndTime">The end time of the subscrition, once passing this date the enumerator will stop</param>
/// <param name="dataResolution">The source enumerator's data resolution</param>
public FillForwardEnumerator(IEnumerator<BaseData> enumerator,
SecurityExchange exchange,
IReadOnlyRef<TimeSpan> fillForwardResolution,
bool isExtendedMarketHours,
DateTime subscriptionEndTime,
TimeSpan dataResolution
)
{
_subscriptionEndTime = subscriptionEndTime;
Exchange = exchange;
_enumerator = enumerator;
_dataResolution = dataResolution;
_fillForwardResolution = fillForwardResolution;
_isExtendedMarketHours = isExtendedMarketHours;
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
public BaseData Current
{
get;
private set;
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>
/// The current element in the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
object IEnumerator.Current
{
get { return Current; }
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public bool MoveNext()
{
if (_delistedTime.HasValue)
{
// don't fill forward after data after the delisted date
if (_previous == null || _previous.EndTime >= _delistedTime.Value)
{
return false;
}
}
if (!_emittedAuxilliaryData && Current != null)
{
// only set the _previous if the last item we emitted was NOT auxilliary data,
// since _previous is used for fill forward behavior
_previous = Current;
}
BaseData fillForward;
if (!_isFillingForward)
{
// if we're filling forward we don't need to move next since we haven't emitted _enumerator.Current yet
if (!_enumerator.MoveNext())
{
if (_delistedTime.HasValue)
{
// don't fill forward delisted data
return false;
}
// check to see if we ran out of data before the end of the subscription
if (_previous == null || _previous.EndTime >= _subscriptionEndTime)
{
// we passed the end of subscription, we're finished
return false;
}
// we can fill forward the rest of this subscription if required
var endOfSubscription = (Current ?? _previous).Clone(true);
endOfSubscription.Time = _subscriptionEndTime.RoundDown(_dataResolution);
if (RequiresFillForwardData(_fillForwardResolution.Value, _previous, endOfSubscription, out fillForward))
{
// don't mark as filling forward so we come back into this block, subscription is done
//_isFillingForward = true;
Current = fillForward;
_emittedAuxilliaryData = false;
return true;
}
// don't emit the last bar if the market isn't considered open!
if (!Exchange.IsOpenDuringBar(endOfSubscription.Time, endOfSubscription.EndTime, _isExtendedMarketHours))
{
return false;
}
Current = endOfSubscription;
_emittedAuxilliaryData = false;
return true;
}
}
var underlyingCurrent = _enumerator.Current;
if (_previous == null)
{
// first data point we dutifully emit without modification
Current = underlyingCurrent;
return true;
}
if (underlyingCurrent != null && underlyingCurrent.DataType == MarketDataType.Auxiliary)
{
_emittedAuxilliaryData = true;
Current = underlyingCurrent;
var delisting = Current as Delisting;
if (delisting != null && delisting.Type == DelistingType.Delisted)
{
_delistedTime = delisting.EndTime;
}
return true;
}
_emittedAuxilliaryData = false;
if (RequiresFillForwardData(_fillForwardResolution.Value, _previous, underlyingCurrent, out fillForward))
{
// we require fill forward data because the _enumerator.Current is too far in future
_isFillingForward = true;
Current = fillForward;
return true;
}
_isFillingForward = false;
Current = underlyingCurrent;
return true;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
_enumerator.Dispose();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public void Reset()
{
_enumerator.Reset();
}
/// <summary>
/// Determines whether or not fill forward is required, and if true, will produce the new fill forward data
/// </summary>
/// <param name="fillForwardResolution"></param>
/// <param name="previous">The last piece of data emitted by this enumerator</param>
/// <param name="next">The next piece of data on the source enumerator</param>
/// <param name="fillForward">When this function returns true, this will have a non-null value, null when the function returns false</param>
/// <returns>True when a new fill forward piece of data was produced and should be emitted by this enumerator</returns>
protected virtual bool RequiresFillForwardData(TimeSpan fillForwardResolution, BaseData previous, BaseData next, out BaseData fillForward)
{
if (next.EndTime < previous.Time)
{
throw new ArgumentException("FillForwardEnumerator received data out of order.");
}
// check to see if the gap between previous and next warrants fill forward behavior
if (next.Time - previous.Time <= fillForwardResolution)
{
fillForward = null;
return false;
}
// is the bar after previous in market hours?
var barAfterPreviousEndTime = previous.EndTime + fillForwardResolution;
if (Exchange.IsOpenDuringBar(previous.EndTime, barAfterPreviousEndTime, _isExtendedMarketHours))
{
// this is the normal case where we had a hole in the middle of the day
fillForward = previous.Clone(true);
fillForward.Time = (previous.Time + fillForwardResolution).RoundDown(fillForwardResolution);
return true;
}
// find the next fill forward time after the next market open
var nextFillForwardTime = Exchange.Hours.GetNextMarketOpen(previous.EndTime, _isExtendedMarketHours) + fillForwardResolution;
if (_dataResolution == Time.OneDay)
{
// special case for daily, we need to emit a midnight bar even though markets are closed
var dailyBarEnd = GetNextOpenDateAfter(previous.Time.Date) + Time.OneDay;
if (dailyBarEnd < nextFillForwardTime)
{
// only emit the midnight bar if it's the next bar to be emitted
nextFillForwardTime = dailyBarEnd;
}
}
if (nextFillForwardTime < next.EndTime)
{
// if next is still in the future then we need to emit a fill forward for market open
fillForward = previous.Clone(true);
fillForward.Time = (nextFillForwardTime - _dataResolution).RoundDown(fillForwardResolution);
return true;
}
// the next is before the next fill forward time, so do nothing
fillForward = null;
return false;
}
/// <summary>
/// Finds the next open date that follows the specified date, this functions expects a date, not a date time
/// </summary>
private DateTime GetNextOpenDateAfter(DateTime date)
{
do
{
date = date + Time.OneDay;
}
while (!Exchange.DateIsOpen(date));
return date;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.UnitTests;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using System.Xml;
using Xunit;
namespace Microsoft.Build.UnitTests
{
sealed public class XmlPeek_Tests
{
private string _xmlFileWithNs = @"<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE plist PUBLIC ""-//Apple//DTD PLIST 1.0//EN"" ""http://www.apple.com/DTDs/PropertyList-1.0.dtd"">
<class AccessModifier='public' Name='test' xmlns:s='http://nsurl'>
<s:variable Type='String' Name='a'></s:variable>
<s:variable Type='String' Name='b'></s:variable>
<s:variable Type='String' Name='c'></s:variable>
<method AccessModifier='public static' Name='GetVal' />
</class>
";
private string _xmlFileWithNsWithText = @"<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE plist PUBLIC ""-//Apple//DTD PLIST 1.0//EN"" ""http://www.apple.com/DTDs/PropertyList-1.0.dtd"">
<class AccessModifier='public' Name='test' xmlns:s='http://nsurl'>
<s:variable Type='String' Name='a'>This</s:variable>
<s:variable Type='String' Name='b'>is</s:variable>
<s:variable Type='String' Name='c'>Sparta!</s:variable>
<method AccessModifier='public static' Name='GetVal' />
</class>
";
private string _xmlFileNoNsNoDtd = @"<?xml version='1.0' encoding='utf-8'?>
<class AccessModifier='public' Name='test'>
<variable Type='String' Name='a'></variable>
<variable Type='String' Name='b'></variable>
<variable Type='String' Name='c'></variable>
<method AccessModifier='public static' Name='GetVal' />
</class>
";
[Fact]
public void PeekWithNamespaceAttribute()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileWithNs, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//s:variable/@Name";
p.Namespaces = "<Namespace Prefix=\"s\" Uri=\"http://nsurl\" />";
Assert.True(p.Execute()); // "Test should've passed"
Assert.Equal(3, p.Result.Length); // "result Length should be 3"
string[] results = new string[] { "a", "b", "c" };
for (int i = 0; i < p.Result.Length; i++)
{
Assert.Equal(p.Result[i].ItemSpec, results[i]);
}
}
[Fact]
public void PeekWithNamespaceNode()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileWithNs, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//s:variable/.";
p.Namespaces = "<Namespace Prefix=\"s\" Uri=\"http://nsurl\" />";
Assert.True(p.Execute()); // "Test should've passed"
Assert.Equal(3, p.Result.Length); // "result Length should be 3"
string[] results = new string[] {
"<s:variable Type=\"String\" Name=\"a\" xmlns:s=\"http://nsurl\"></s:variable>",
"<s:variable Type=\"String\" Name=\"b\" xmlns:s=\"http://nsurl\"></s:variable>",
"<s:variable Type=\"String\" Name=\"c\" xmlns:s=\"http://nsurl\"></s:variable>"
};
for (int i = 0; i < p.Result.Length; i++)
{
Assert.Equal(p.Result[i].ItemSpec, results[i]);
}
}
[Fact]
public void PeekWithNamespaceText()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileWithNsWithText, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//s:variable/text()";
p.Namespaces = "<Namespace Prefix=\"s\" Uri=\"http://nsurl\" />";
Assert.Equal("<Namespace Prefix=\"s\" Uri=\"http://nsurl\" />", p.Namespaces);
Assert.True(p.Execute()); // "Test should've passed"
Assert.Equal(3, p.Result.Length); // "result Length should be 3"
string[] results = new string[] {
"This",
"is",
"Sparta!"
};
for (int i = 0; i < p.Result.Length; i++)
{
Assert.Equal(p.Result[i].ItemSpec, results[i]);
}
}
[Fact]
public void PeekNoNamespace()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileNoNsNoDtd, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//variable/@Name";
Assert.True(p.Execute()); // "Test should've passed"
Assert.Equal(3, p.Result.Length); // "result Length should be 3"
string[] results = new string[] { "a", "b", "c" };
for (int i = 0; i < p.Result.Length; i++)
{
Assert.Equal(p.Result[i].ItemSpec, results[i]);
}
}
[Fact]
public void PeekNoNSXmlContent()
{
MockEngine engine = new MockEngine(true);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlContent = _xmlFileNoNsNoDtd;
p.Query = "//variable/@Name";
Assert.True(p.Execute()); // "Test should've passed"
Assert.Equal(3, p.Result.Length); // "result Length should be 3"
string[] results = new string[] { "a", "b", "c" };
for (int i = 0; i < p.Result.Length; i++)
{
Assert.Equal(p.Result[i].ItemSpec, results[i]);
}
}
[Fact]
public void PeekNoNSXmlContentAndXmlInputError1()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileNoNsNoDtd, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.XmlContent = _xmlFileNoNsNoDtd;
Assert.Equal(xmlInputPath, p.XmlInputPath.ItemSpec);
Assert.Equal(_xmlFileNoNsNoDtd, p.XmlContent);
p.Query = "//variable/@Name";
Assert.Equal("//variable/@Name", p.Query);
Assert.False(p.Execute()); // "Test should've failed"
Assert.Contains("MSB3741", engine.Log); // "Error message MSB3741 should fire"
}
[Fact]
public void PeekNoNSXmlContentAndXmlInputError2()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileNoNsNoDtd, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.Query = "//variable/@Name";
Assert.False(p.Execute()); // "Test should've failed"
Assert.Contains("MSB3741", engine.Log); // "Error message MSB3741 should fire"
}
[Fact]
public void PeekNoNSWPrefixedQueryError()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileNoNsNoDtd, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//s:variable/@Name";
Assert.False(p.Execute()); // "Test should've failed"
Assert.Contains("MSB3743", engine.Log); // "Engine log should contain error code MSB3743"
}
[Fact]
public void PeekDtdWhenDtdProhibitedError()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileWithNs, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.ProhibitDtd = true;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//s:variable/@Name";
Assert.False(p.Execute()); // "Test should've failed"
Assert.Contains("MSB3733", engine.Log); // "Engine log should contain error code MSB3733"
}
[Fact]
public void ErrorInNamespaceDecl()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileWithNs, out xmlInputPath);
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//s:variable/@Name";
p.Namespaces = "<!THIS IS ERROR Namespace Prefix=\"s\" Uri=\"http://nsurl\" />";
bool executeResult = p.Execute();
Assert.True(engine.Log.Contains("MSB3742"), "Engine Log: " + engine.Log);
Assert.False(executeResult); // "Execution should've failed"
}
[Fact]
public void MissingNamespaceParameters()
{
MockEngine engine = new MockEngine(true);
string xmlInputPath;
Prepare(_xmlFileWithNs, out xmlInputPath);
string[] attrs = new string[] { "Prefix=\"s\"", "Uri=\"http://nsurl\"" };
for (int i = 0; i < Math.Pow(2, attrs.Length); i++)
{
string res = "";
for (int k = 0; k < attrs.Length; k++)
{
if ((i & (int)Math.Pow(2, k)) != 0)
{
res += attrs[k] + " ";
}
}
XmlPeek p = new XmlPeek();
p.BuildEngine = engine;
p.XmlInputPath = new TaskItem(xmlInputPath);
p.Query = "//s:variable/@Name";
p.Namespaces = "<Namespace " + res + " />";
bool result = p.Execute();
Console.WriteLine(engine.Log);
if (i == 3)
{
Assert.True(result); // "Only 3rd value should pass."
}
else
{
Assert.False(result); // "Only 3rd value should pass."
}
}
}
[Fact]
public void PeekWithoutUsingTask()
{
string projectContents = @"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='x'>
<XmlPeek Query='abc' ContinueOnError='true' />
</Target>
</Project>";
// The task won't complete properly, but ContinueOnError converts the errors to warnings, so the build should succeed
MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents);
// Verify that the task was indeed found.
logger.AssertLogDoesntContain("MSB4036");
}
private void Prepare(string xmlFile, out string xmlInputPath)
{
string dir = Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString());
Directory.CreateDirectory(dir);
xmlInputPath = dir + Path.DirectorySeparatorChar + "doc.xml";
File.WriteAllText(xmlInputPath, xmlFile);
}
}
}
| |
/*
* 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 Apache.Ignite.Core;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
namespace dotnet_helloworld
{
public class UsingSqlApi
{
// tag::sqlQueryFields[]
class Person
{
// Indexed field. Will be visible to the SQL engine.
[QuerySqlField(IsIndexed = true)] public long Id;
//Queryable field. Will be visible to the SQL engine
[QuerySqlField] public string Name;
//Will NOT be visible to the SQL engine.
public int Age;
/**
* Indexed field sorted in descending order.
* Will be visible to the SQL engine.
*/
[QuerySqlField(IsIndexed = true, IsDescending = true)]
public float Salary;
}
public static void SqlQueryFieldDemo()
{
var cacheCfg = new CacheConfiguration
{
Name = "cacheName",
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(Person))
}
};
var ignite = Ignition.Start();
var cache = ignite.CreateCache<int, Person>(cacheCfg);
}
// end::sqlQueryFields[]
public class Inner
{
// tag::queryEntities[]
private class Person
{
public long Id;
public string Name;
public int Age;
public float Salary;
}
public static void QueryEntitiesDemo()
{
var personCacheCfg = new CacheConfiguration
{
Name = "Person",
QueryEntities = new[]
{
new QueryEntity
{
KeyType = typeof(long),
ValueType = typeof(Person),
Fields = new[]
{
new QueryField("Id", typeof(long)),
new QueryField("Name", typeof(string)),
new QueryField("Age", typeof(int)),
new QueryField("Salary", typeof(float))
},
Indexes = new[]
{
new QueryIndex("Id"),
new QueryIndex(true, "Salary"),
}
}
}
};
var ignite = Ignition.Start();
var personCache = ignite.CreateCache<int, Person>(personCacheCfg);
}
// end::queryEntities[]
public static void QueryingDemo()
{
var ignite = Ignition.Start();
// tag::querying[]
var cache = ignite.GetCache<long, Person>("Person");
var sql = new SqlFieldsQuery("select concat(FirstName, ' ', LastName) from Person");
using (var cursor = cache.Query(sql))
{
foreach (var row in cursor)
{
Console.WriteLine("personName=" + row[0]);
}
}
// end::querying[]
// tag::schema[]
var sqlFieldsQuery = new SqlFieldsQuery("select name from City") {Schema = "PERSON"};
// end::schema[]
}
public static void CreateTableDdlDemo()
{
var ignite = Ignition.Start(new IgniteConfiguration
{
DiscoverySpi = new TcpDiscoverySpi
{
LocalPort = 48500,
LocalPortRange = 20,
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[]
{
"127.0.0.1:48500..48520"
}
}
}
});
// tag::creatingTables[]
var cache = ignite.GetOrCreateCache<long, Person>(
new CacheConfiguration
{
Name = "Person"
}
);
//Creating City table
cache.Query(new SqlFieldsQuery("CREATE TABLE City (id int primary key, name varchar, region varchar)"));
// end::creatingTables[]
var qry = new SqlFieldsQuery("select name from City") {Schema = "PERSON"};
cache.Query(qry).GetAll();
}
public static void CancellingQueries()
{
var ignite = Ignition.Start(
new IgniteConfiguration
{
DiscoverySpi = new TcpDiscoverySpi
{
LocalPort = 48500,
LocalPortRange = 20,
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[]
{
"127.0.0.1:48500..48520"
}
}
},
CacheConfiguration = new[]
{
new CacheConfiguration
{
Name = "personCache",
QueryEntities = new[] {new QueryEntity(typeof(long), typeof(Person)),}
},
}
}
);
var cache = ignite.GetOrCreateCache<long, Person>("personCache");
// tag::qryTimeout[]
var query = new SqlFieldsQuery("select * from Person") {Timeout = TimeSpan.FromSeconds(10)};
// end::qryTimeout[]
// tag::cursorDispose[]
var qry = new SqlFieldsQuery("select * from Person");
var cursor = cache.Query(qry);
//Executing query
//Halting the query that might be still in progress
cursor.Dispose();
// end::cursorDispose[]
}
}
}
}
| |
//
// Copyright (c) 2012-2021 Antmicro
//
// This file is licensed under the MIT License.
// Full license text is available in the LICENSE file.
using System;
using NUnit.Framework;
using System.Linq;
using Antmicro.Migrant.Customization;
using Antmicro.Migrant.VersionTolerance;
namespace Antmicro.Migrant.Tests
{
[TestFixture]
public class TypeDescriptorComparisonTests
{
[SetUp]
public void SetUp()
{
DynamicType.prefix = null;
}
[Test]
public void ShouldFindNoDifferences()
{
var obj = DynamicType.CreateClass("C", DynamicType.CreateClass("B", DynamicType.CreateClass("A"))).Instantiate();
var typeDescriptor = ((TypeFullDescriptor)obj.GetType());
var compareResult = typeDescriptor.CompareWith(typeDescriptor);
Assert.IsTrue(compareResult.Empty);
}
[Test]
public void ShouldDetectFieldInsertionSimple()
{
var objPrev = DynamicType.CreateClass("A").Instantiate();
var objCurr = DynamicType.CreateClass("A").WithField("a", typeof(int)).Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsEmpty(compareResult.FieldsRemoved);
Assert.IsEmpty(compareResult.FieldsChanged);
Assert.AreEqual(1, compareResult.FieldsAdded.Count);
Assert.AreEqual("A:a", compareResult.FieldsAdded[0].FullName);
}
[Test]
public void ShouldNotDetectInsertionOfTransientField()
{
var objPrev = DynamicType.CreateClass("A").Instantiate();
var objCurr = DynamicType.CreateClass("A").WithTransientField("a", typeof(int)).Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsTrue(compareResult.Empty);
}
[Test]
public void ShouldDetectInsertionOfOverridingField()
{
var objPrev = DynamicType.CreateClass("A", DynamicType.CreateClass("Base").WithField("a", typeof(int))).Instantiate();
var objCurr = DynamicType.CreateClass("A", DynamicType.CreateClass("Base").WithField("a", typeof(int))).WithField("a", typeof(int)).Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsEmpty(compareResult.FieldsRemoved);
Assert.IsEmpty(compareResult.FieldsChanged);
Assert.AreEqual(1, compareResult.FieldsAdded.Count);
Assert.AreEqual("A:a", compareResult.FieldsAdded[0].FullName);
}
[Test]
public void ShouldDetectFieldRemovalSimple()
{
var objPrev = DynamicType.CreateClass("A").WithField("a", typeof(int)).Instantiate();
var objCurr = DynamicType.CreateClass("A").Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsEmpty(compareResult.FieldsAdded);
Assert.IsEmpty(compareResult.FieldsChanged);
Assert.AreEqual(1, compareResult.FieldsRemoved.Count);
Assert.AreEqual("A:a", compareResult.FieldsRemoved[0].FullName);
}
[Test]
public void ShouldNotDetectRemovalOfTransientField()
{
var objPrev = DynamicType.CreateClass("A").WithTransientField("a", typeof(int)).Instantiate();
var objCurr = DynamicType.CreateClass("A").Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsTrue(compareResult.Empty);
}
[Test]
public void ShouldDetectRemovalOfOverridingField()
{
var objPrev = DynamicType.CreateClass("A", DynamicType.CreateClass("Base").WithField("a", typeof(int))).WithField("a", typeof(int)).Instantiate();
var objCurr = DynamicType.CreateClass("A", DynamicType.CreateClass("Base").WithField("a", typeof(int))).Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsEmpty(compareResult.FieldsAdded);
Assert.IsEmpty(compareResult.FieldsChanged);
Assert.AreEqual(1, compareResult.FieldsRemoved.Count);
Assert.AreEqual("A:a", compareResult.FieldsRemoved[0].FullName);
}
[Test]
public void ShouldHandleFieldMoveDownSimple()
{
var objPrev = DynamicType.CreateClass("A", DynamicType.CreateClass("Base")).WithField("a", typeof(int)).Instantiate();
var objCurr = DynamicType.CreateClass("A", DynamicType.CreateClass("Base").WithField("a", typeof(int))).Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsEmpty(compareResult.FieldsChanged);
Assert.AreEqual(1, compareResult.FieldsAdded.Count);
Assert.AreEqual(1, compareResult.FieldsRemoved.Count);
Assert.AreEqual("Base:a", compareResult.FieldsAdded.ElementAt(0).FullName);
Assert.AreEqual("A:a", compareResult.FieldsRemoved.ElementAt(0).FullName);
}
[Test]
public void ShouldHandleFieldMoveUpSimple()
{
var objPrev = DynamicType.CreateClass("A", DynamicType.CreateClass("Base")).WithField("a", typeof(int)).Instantiate();
var objCurr = DynamicType.CreateClass("A", DynamicType.CreateClass("Base").WithField("a", typeof(int))).Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsEmpty(compareResult.FieldsChanged);
Assert.AreEqual(1, compareResult.FieldsAdded.Count);
Assert.AreEqual(1, compareResult.FieldsRemoved.Count);
Assert.AreEqual("A:a", compareResult.FieldsRemoved.ElementAt(0).FullName);
Assert.AreEqual("Base:a", compareResult.FieldsAdded.ElementAt(0).FullName);
}
[Test]
public void ShouldDetectFieldTypeChange()
{
var objPrev = DynamicType.CreateClass("A").WithField("a", typeof(int)).Instantiate();
var objCurr = DynamicType.CreateClass("A").WithField("a", typeof(long)).Instantiate();
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev);
Assert.IsEmpty(compareResult.FieldsAdded);
Assert.IsEmpty(compareResult.FieldsRemoved);
Assert.AreEqual(1, compareResult.FieldsChanged.Count);
Assert.AreEqual("A:a", compareResult.FieldsChanged.ElementAt(0).FullName);
}
[Test]
public void ShouldHandleAssemblyVersionChange()
{
var objPrev = DynamicType.CreateClass("A").WithField("a", DynamicType.CreateClass("C").WithField<int>("c")).Instantiate(new Version(1, 0));
var objCurr = DynamicType.CreateClass("A").WithField("a", DynamicType.CreateClass("C").WithField<int>("c")).Instantiate(new Version(1, 1));
var descPrev = ((TypeFullDescriptor)objPrev.GetType());
var descCurr = ((TypeFullDescriptor)objCurr.GetType());
var compareResult = descCurr.CompareWith(descPrev, VersionToleranceLevel.AllowAssemblyVersionChange);
Assert.IsEmpty(compareResult.FieldsAdded);
Assert.IsEmpty(compareResult.FieldsChanged);
Assert.IsEmpty(compareResult.FieldsRemoved);
}
}
}
| |
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// 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 ComponentAce 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.
/*
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, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
namespace Cocos2D.Compression.Zlib
{
internal sealed class Inflate
{
private const int MAX_WBITS = 15; // 32K LZ77 window
// preset dictionary flag in zlib header
private const int PRESET_DICT = 0x20;
internal const int Z_NO_FLUSH = 0;
internal const int Z_PARTIAL_FLUSH = 1;
internal const int Z_SYNC_FLUSH = 2;
internal const int Z_FULL_FLUSH = 3;
internal const int Z_FINISH = 4;
private const int Z_DEFLATED = 8;
private const int Z_OK = 0;
private const int Z_STREAM_END = 1;
private const int Z_NEED_DICT = 2;
private const int Z_ERRNO = - 1;
private const int Z_STREAM_ERROR = - 2;
private const int Z_DATA_ERROR = - 3;
private const int Z_MEM_ERROR = - 4;
private const int Z_BUF_ERROR = - 5;
private const int Z_VERSION_ERROR = - 6;
private const int METHOD = 0; // waiting for method byte
private const int FLAG = 1; // waiting for flag byte
private const int DICT4 = 2; // four dictionary check bytes to go
private const int DICT3 = 3; // three dictionary check bytes to go
private const int DICT2 = 4; // two dictionary check bytes to go
private const int DICT1 = 5; // one dictionary check byte to go
private const int DICT0 = 6; // waiting for inflateSetDictionary
private const int BLOCKS = 7; // decompressing blocks
private const int CHECK4 = 8; // four check bytes to go
private const int CHECK3 = 9; // three check bytes to go
private const int CHECK2 = 10; // two check bytes to go
private const int CHECK1 = 11; // one check byte to go
private const int DONE = 12; // finished check, done
private const int BAD = 13; // got an error--stay here
private static readonly byte[] mark = new[]
{(byte) 0, (byte) 0, (byte) SupportClass.Identity(0xff), (byte) SupportClass.Identity(0xff)};
internal InfBlocks blocks; // current inflate_blocks state
internal int marker;
// mode dependent information
internal int method; // if FLAGS, method byte
internal int mode; // current inflate mode
// if CHECK, check values to compare
internal long need; // stream check value
// if BAD, inflateSync's marker bytes count
// mode independent information
internal int nowrap; // flag for no wrapper
internal long[] was = new long[1]; // computed check value
internal int wbits; // log2(window size) (8..15, defaults to 15)
internal int inflateReset(ZStream z)
{
if (z == null || z.istate == null)
return Z_STREAM_ERROR;
z.total_in = z.total_out = 0;
z.msg = null;
z.istate.mode = z.istate.nowrap != 0 ? BLOCKS : METHOD;
z.istate.blocks.reset(z, null);
return Z_OK;
}
internal int inflateEnd(ZStream z)
{
if (blocks != null)
blocks.free(z);
blocks = null;
// ZFREE(z, z->state);
return Z_OK;
}
internal int inflateInit(ZStream z, int w)
{
z.msg = null;
blocks = null;
// handle undocumented nowrap option (no zlib header or check)
nowrap = 0;
if (w < 0)
{
w = - w;
nowrap = 1;
}
// set window size
if (w < 8 || w > 15)
{
inflateEnd(z);
return Z_STREAM_ERROR;
}
wbits = w;
z.istate.blocks = new InfBlocks(z, z.istate.nowrap != 0 ? null : this, 1 << w);
// reset state
inflateReset(z);
return Z_OK;
}
internal int inflate(ZStream z, int f)
{
int r;
int b;
if (z == null || z.istate == null || z.next_in == null)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (true)
{
//System.out.println("mode: "+z.istate.mode);
switch (z.istate.mode)
{
case METHOD:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
if (((z.istate.method = z.next_in[z.next_in_index++]) & 0xf) != Z_DEFLATED)
{
z.istate.mode = BAD;
z.msg = "unknown compression method";
z.istate.marker = 5; // can't try inflateSync
break;
}
if ((z.istate.method >> 4) + 8 > z.istate.wbits)
{
z.istate.mode = BAD;
z.msg = "invalid window size";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = FLAG;
goto case FLAG;
case FLAG:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
b = (z.next_in[z.next_in_index++]) & 0xff;
if ((((z.istate.method << 8) + b) % 31) != 0)
{
z.istate.mode = BAD;
z.msg = "incorrect header check";
z.istate.marker = 5; // can't try inflateSync
break;
}
if ((b & PRESET_DICT) == 0)
{
z.istate.mode = BLOCKS;
break;
}
z.istate.mode = DICT4;
goto case DICT4;
case DICT4:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int) 0xff000000L);
z.istate.mode = DICT3;
goto case DICT3;
case DICT3:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L);
z.istate.mode = DICT2;
goto case DICT2;
case DICT2:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L);
z.istate.mode = DICT1;
goto case DICT1;
case DICT1:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
z.adler = z.istate.need;
z.istate.mode = DICT0;
return Z_NEED_DICT;
case DICT0:
z.istate.mode = BAD;
z.msg = "need dictionary";
z.istate.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case BLOCKS:
r = z.istate.blocks.proc(z, r);
if (r == Z_DATA_ERROR)
{
z.istate.mode = BAD;
z.istate.marker = 0; // can try inflateSync
break;
}
if (r == Z_OK)
{
r = f;
}
if (r != Z_STREAM_END)
{
return r;
}
r = f;
z.istate.blocks.reset(z, z.istate.was);
if (z.istate.nowrap != 0)
{
z.istate.mode = DONE;
break;
}
z.istate.mode = CHECK4;
goto case CHECK4;
case CHECK4:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int) 0xff000000L);
z.istate.mode = CHECK3;
goto case CHECK3;
case CHECK3:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L);
z.istate.mode = CHECK2;
goto case CHECK2;
case CHECK2:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L);
z.istate.mode = CHECK1;
goto case CHECK1;
case CHECK1:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
if (((int) (z.istate.was[0])) != ((int) (z.istate.need)))
{
z.istate.mode = BAD;
z.msg = "incorrect data check";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = DONE;
goto case DONE;
case DONE:
return Z_STREAM_END;
case BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
}
}
internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength)
{
int index = 0;
int length = dictLength;
if (z == null || z.istate == null || z.istate.mode != DICT0)
return Z_STREAM_ERROR;
if (z._adler.adler32(1L, dictionary, 0, dictLength) != z.adler)
{
return Z_DATA_ERROR;
}
z.adler = z._adler.adler32(0, null, 0, 0);
if (length >= (1 << z.istate.wbits))
{
length = (1 << z.istate.wbits) - 1;
index = dictLength - length;
}
z.istate.blocks.set_dictionary(dictionary, index, length);
z.istate.mode = BLOCKS;
return Z_OK;
}
internal int inflateSync(ZStream z)
{
int n; // number of bytes to look at
int p; // pointer to bytes
int m; // number of marker bytes found in a row
long r, w; // temporaries to save total_in and total_out
// set up
if (z == null || z.istate == null)
return Z_STREAM_ERROR;
if (z.istate.mode != BAD)
{
z.istate.mode = BAD;
z.istate.marker = 0;
}
if ((n = z.avail_in) == 0)
return Z_BUF_ERROR;
p = z.next_in_index;
m = z.istate.marker;
// search
while (n != 0 && m < 4)
{
if (z.next_in[p] == mark[m])
{
m++;
}
else if (z.next_in[p] != 0)
{
m = 0;
}
else
{
m = 4 - m;
}
p++;
n--;
}
// restore
z.total_in += p - z.next_in_index;
z.next_in_index = p;
z.avail_in = n;
z.istate.marker = m;
// return no joy or set up to restart on a new block
if (m != 4)
{
return Z_DATA_ERROR;
}
r = z.total_in;
w = z.total_out;
inflateReset(z);
z.total_in = r;
z.total_out = w;
z.istate.mode = BLOCKS;
return Z_OK;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
// implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
// but removes the length bytes of the resulting empty stored block. When
// decompressing, PPP checks that at the end of input packet, inflate is
// waiting for these length bytes.
internal int inflateSyncPoint(ZStream z)
{
if (z == null || z.istate == null || z.istate.blocks == null)
return Z_STREAM_ERROR;
return z.istate.blocks.sync_point();
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
namespace MsgPack
{
partial class MessagePackObjectDictionary
{
/// <summary>
/// Represents the set of <see cref="MessagePackObjectDictionary"/> keys.
/// </summary>
#if !SILVERLIGHT && !NETFX_CORE
[Serializable]
#endif
[DebuggerDisplay( "Count={Count}" )]
[DebuggerTypeProxy( typeof( CollectionDebuggerProxy<> ) )]
[SuppressMessage( "Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "ICollection implementing dictionary should return ICollection implementing values." )]
#if !UNITY
public sealed partial class KeySet :
#if !NETFX_35
ISet<MessagePackObject>,
#endif // !NETFX_35
#else
public sealed partial class KeyCollection :
#endif // !UNITY
// ReSharper disable once RedundantExtendsListEntry
ICollection<MessagePackObject>, ICollection
{
private readonly MessagePackObjectDictionary _dictionary;
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get { return this._dictionary.Count; }
}
bool ICollection<MessagePackObject>.IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return this; }
}
#if !UNITY
internal KeySet( MessagePackObjectDictionary dictionary )
#else
internal KeyCollection( MessagePackObjectDictionary dictionary )
#endif // !UNITY
{
#if !UNITY
Contract.Assert( dictionary != null, "dictionary != null" );
#endif // !UNITY
this._dictionary = dictionary;
}
/// <summary>
/// Copies the entire collection to a compatible one-dimensional array, starting at the beginning of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this dictionary.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
public void CopyTo( MessagePackObject[] array )
{
if ( array == null )
{
throw new ArgumentNullException( "array" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
CollectionOperation.CopyTo( this, this.Count, 0, array, 0, this.Count );
}
/// <summary>
/// Copies the entire collection to a compatible one-dimensional array,
/// starting at the specified index of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this dictionary.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
public void CopyTo( MessagePackObject[] array, int arrayIndex )
{
CollectionOperation.CopyTo( this, this.Count, 0, array, arrayIndex, this.Count );
}
/// <summary>
/// Copies a range of elements from this collection to a compatible one-dimensional array,
/// starting at the specified index of the target array.
/// </summary>
/// <param name="index">
/// The zero-based index in the source dictionary at which copying begins.
/// </param>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this dictionary.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
/// <param name="count">
/// The number of elements to copy.
/// </param>
public void CopyTo( int index, MessagePackObject[] array, int arrayIndex, int count )
{
if ( array == null )
{
throw new ArgumentNullException( "array" );
}
if ( index < 0 )
{
throw new ArgumentOutOfRangeException( "index" );
}
if ( 0 < this.Count && this.Count <= index )
{
throw new ArgumentException( "Specified array is too small to complete copy operation.", "array" );
}
if ( arrayIndex < 0 )
{
throw new ArgumentOutOfRangeException( "arrayIndex" );
}
if ( count < 0 )
{
throw new ArgumentOutOfRangeException( "count" );
}
if ( array.Length - count <= arrayIndex )
{
throw new ArgumentException( "Specified array is too small to complete copy operation.", "array" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
CollectionOperation.CopyTo( this, this.Count, index, array, arrayIndex, count );
}
void ICollection.CopyTo( Array array, int arrayIndex )
{
CollectionOperation.CopyTo( this, this.Count, array, arrayIndex );
}
/// <summary>
/// Determines whether this collection contains a specific value.
/// </summary>
/// <param name="item">
/// The object to locate in this collection.</param>
/// <returns>
/// <c>true</c> if <paramref name="item"/> is found in this collection; otherwise, <c>false</c>.
/// </returns>
bool ICollection<MessagePackObject>.Contains( MessagePackObject item )
{
return this._dictionary.ContainsKey( item );
}
void ICollection<MessagePackObject>.Add( MessagePackObject item )
{
throw new NotSupportedException();
}
void ICollection<MessagePackObject>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<MessagePackObject>.Remove( MessagePackObject item )
{
throw new NotSupportedException();
}
#if !UNITY
#if !NETFX_35
bool ISet<MessagePackObject>.Add( MessagePackObject item )
{
throw new NotSupportedException();
}
void ISet<MessagePackObject>.ExceptWith( IEnumerable<MessagePackObject> other )
{
throw new NotSupportedException();
}
void ISet<MessagePackObject>.IntersectWith( IEnumerable<MessagePackObject> other )
{
throw new NotSupportedException();
}
#endif // !NETFX_35
/// <summary>
/// Determines whether this set is proper subset of the specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if this set is proper subset of the specified collection; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="other"/> is Nothing.
/// </exception>
public bool IsProperSubsetOf( IEnumerable<MessagePackObject> other )
{
return SetOperation.IsProperSubsetOf( this, other );
}
/// <summary>
/// Determines whether this set is proper superset of the specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if this set is proper superset of the specified collection; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="other"/> is Nothing.
/// </exception>
public bool IsProperSupersetOf( IEnumerable<MessagePackObject> other )
{
return SetOperation.IsProperSupersetOf( this, other );
}
/// <summary>
/// Determines whether this set is subset of the specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if this set is subset of the specified collection; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="other"/> is Nothing.
/// </exception>
public bool IsSubsetOf( IEnumerable<MessagePackObject> other )
{
return SetOperation.IsSubsetOf( this, other );
}
/// <summary>
/// Determines whether this set is superset of the specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if this set is superset of the specified collection; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="other"/> is Nothing.
/// </exception>
public bool IsSupersetOf( IEnumerable<MessagePackObject> other )
{
return SetOperation.IsSupersetOf( this, other );
}
/// <summary>
/// Determines whether the current set and a specified collection share common elements.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if this set and <paramref name="other"/> share at least one common element; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="other"/> is Nothing.
/// </exception>
public bool Overlaps( IEnumerable<MessagePackObject> other )
{
return SetOperation.Overlaps( this, other );
}
/// <summary>
/// Determines whether this set and the specified collection contain the same elements.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if this set is equal to <paramref name="other"/>; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="other"/> is Nothing.
/// </exception>
public bool SetEquals( IEnumerable<MessagePackObject> other )
{
return SetOperation.SetEquals( this, other );
}
#if !NETFX_35
void ISet<MessagePackObject>.SymmetricExceptWith( IEnumerable<MessagePackObject> other )
{
throw new NotSupportedException();
}
void ISet<MessagePackObject>.UnionWith( IEnumerable<MessagePackObject> other )
{
throw new NotSupportedException();
}
#endif // !NETFX_35
#endif // !UNITY
/// <summary>
/// Returns an enumerator that iterates through this collction.
/// </summary>
/// <returns>
/// Returns an enumerator that iterates through this collction.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator( this._dictionary );
}
IEnumerator<MessagePackObject> IEnumerable<MessagePackObject>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// base class for TweenChains and TweenFlows
/// </summary>
public class AbstractGoTweenCollection : AbstractGoTween
{
protected List<TweenFlowItem> _tweenFlows = new List<TweenFlowItem>();
/// <summary>
/// data class that wraps an AbstractTween and its start time for the timeline
/// </summary>
protected class TweenFlowItem
{
public float startTime;
public float duration;
public AbstractGoTween tween;
public TweenFlowItem( float startTime, AbstractGoTween tween )
{
this.tween = tween;
this.startTime = startTime;
this.duration = tween.totalDuration;
}
public TweenFlowItem( float startTime, float duration )
{
this.duration = duration;
this.startTime = startTime;
}
}
public AbstractGoTweenCollection( GoTweenCollectionConfig config )
{
// copy the TweenConfig info over
id = config.id;
loopType = config.loopType;
iterations = config.iterations;
updateType = config.propertyUpdateType;
_onComplete = config.onCompleteHandler;
_onStart = config.onStartHandler;
timeScale = 1;
state = GoTweenState.Paused;
Go.addTween( this );
}
#region AbstractTween overrides
/// <summary>
/// returns a list of all Tweens with the given target in the collection
/// technically, this should be marked as internal
/// </summary>
public List<GoTween> tweensWithTarget( object target )
{
List<GoTween> list = new List<GoTween>();
foreach( var item in _tweenFlows )
{
// skip TweenFlowItems with no target
if( item.tween == null )
continue;
// check Tweens first
var tween = item.tween as GoTween;
if( tween != null && tween.target == target )
list.Add( tween );
// check for TweenCollections
if( tween == null )
{
var tweenCollection = item.tween as AbstractGoTweenCollection;
if( tweenCollection != null )
{
var tweensInCollection = tweenCollection.tweensWithTarget( target );
if( tweensInCollection.Count > 0 )
list.AddRange( tweensInCollection );
}
}
}
return list;
}
public override bool removeTweenProperty( AbstractTweenProperty property )
{
foreach( var tweenFlowItem in _tweenFlows )
{
// skip delay items which have no tween
if( tweenFlowItem.tween == null )
continue;
if( tweenFlowItem.tween.removeTweenProperty( property ) )
return true;
}
return false;
}
public override bool containsTweenProperty( AbstractTweenProperty property )
{
foreach( var tweenFlowItem in _tweenFlows )
{
// skip delay items which have no tween
if( tweenFlowItem.tween == null )
continue;
if( tweenFlowItem.tween.containsTweenProperty( property ) )
return true;
}
return false;
}
public override List<AbstractTweenProperty> allTweenProperties()
{
var propList = new List<AbstractTweenProperty>();
foreach( var tweenFlowItem in _tweenFlows )
{
// skip delay items which have no tween
if( tweenFlowItem.tween == null )
continue;
propList.AddRange( tweenFlowItem.tween.allTweenProperties() );
}
return propList;
}
/// <summary>
/// we are always considered valid because our constructor adds us to Go and we start paused
/// </summary>
public override bool isValid()
{
return true;
}
/// <summary>
/// tick method. if it returns true it indicates the tween is complete
/// </summary>
public override bool update( float deltaTime )
{
base.update( deltaTime );
// if we are looping back on a PingPong loop
var convertedElapsedTime = _isLoopingBackOnPingPong ? duration - _elapsedTime : _elapsedTime;
if( state == GoTweenState.Complete )
{
//Make sure all tweens get completed
//Sometimes, it happens the last tween has not yet completed when the tweenchain is completed (maybe for a 0.0000000001 difference in the way convertedElapsedTime calculated)
foreach( var flow in _tweenFlows )
{
// only update flows that have a Tween and whose startTime has passed
if( flow.tween != null && flow.tween.state!=GoTweenState.Complete )
{
//Finish the tween and update it to call onComplete if needed
flow.tween.complete();
flow.tween.update(0);
}
}
if( !_didComplete )
onComplete();
return true; //true if complete
} else {
// update all properties
foreach( var flow in _tweenFlows )
{
// only update flows that have a Tween and whose startTime has passed
if( flow.tween != null && flow.startTime < convertedElapsedTime )
{
// TODO: further narrow down who gets an update for efficiency
var tweenConvertedElapsed = convertedElapsedTime - flow.startTime;
flow.tween.goTo( tweenConvertedElapsed );
}
}
return false; //false if not complete
}
}
public override void rewind()
{
state = GoTweenState.Paused;
// reset all state here
_elapsedTime = _totalElapsedTime = 0;
_isLoopingBackOnPingPong = false;
_completedIterations = 0;
}
/// <summary>
/// completes the tween. sets the object to it's final position as if the tween completed normally
/// </summary>
public override void complete()
{
if( iterations < 0 )
return;
base.complete();
foreach( var flow in _tweenFlows )
{
// only update flows that have a Tween and whose startTime has passed
if( flow.tween != null )
flow.tween.goTo( flow.tween.totalDuration );
}
}
#endregion
}
| |
//-----------------------------------------------------------------------
// <copyright file="DepthListener.cs" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace Tango
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
/// <summary>
/// Delegate for Tango point cloud events.
/// </summary>
/// <param name="pointCloud">The point cloud data from Tango.</param>
internal delegate void OnPointCloudAvailableEventHandler(TangoPointCloudData pointCloud);
/// <summary>
/// Delegate for Tango point cloud events that can be called on any thread.
/// </summary>
/// <param name="pointCloud">The point cloud data from Tango.</param>
internal delegate void OnPointCloudMultithreadedAvailableEventHandler(ref TangoPointCloudIntPtr pointCloud);
/// <summary>
/// DEPRECATED: Delegate for Tango depth events.
/// </summary>
/// <param name="tangoDepth">TangoUnityDepth object for the available depth frame.</param>
internal delegate void OnTangoDepthAvailableEventHandler(TangoUnityDepth tangoDepth);
/// <summary>
/// DEPRECATED: Delegate for Tango depth event that can be called on any thread.
/// </summary>
/// <param name="tangoDepth"><c>TangoXYZij</c> object for the available depth frame.</param>
internal delegate void OnTangoDepthMulithreadedAvailableEventHandler(TangoXYZij tangoDepth);
/// <summary>
/// Marshals Tango depth data between the C callbacks in one thread and
/// the main Unity thread.
/// </summary>
internal static class DepthListener
{
/// <summary>
/// The lock object used as a mutex.
/// </summary>
private static System.Object m_lockObject = new System.Object();
private static Tango.DepthProvider.APIOnPointCloudAvailable m_onPointCloudAvailableCallback;
private static bool m_isDirty;
private static TangoPointCloudData m_pointCloud;
private static float[] m_xyzPoints;
/// <summary>
/// Maximum number of depth points DepthListener will pass on from the tango service.
/// If value is 0, no limit is imposed.
/// </summary>
private static int m_maxNumReducedDepthPoints;
/// <summary>
/// Called when a new Tango depth is available.
/// </summary>
private static OnTangoDepthAvailableEventHandler m_onTangoDepthAvailable;
/// <summary>
/// Called when a new Tango depth is available on the thread the depth came from.
/// </summary>
private static OnTangoDepthMulithreadedAvailableEventHandler m_onTangoDepthMultithreadedAvailable;
/// <summary>
/// Called when a new PointCloud is available.
/// </summary>
private static OnPointCloudAvailableEventHandler m_onPointCloudAvailable;
/// <summary>
/// Called when a new PointCloud is available on the thread the point cloud came from.
/// </summary>
private static OnPointCloudMultithreadedAvailableEventHandler m_onPointCloudMultithreadedAvailable;
/// <summary>
/// Initializes the <see cref="Tango.DepthListener"/> class.
/// </summary>
static DepthListener()
{
Reset();
}
/// <summary>
/// Stop getting Tango depth callbacks, clear all listeners.
/// </summary>
internal static void Reset()
{
// Avoid calling into tango_client_api before the correct library is loaded.
if (m_onPointCloudAvailableCallback != null)
{
Tango.DepthProvider.ClearCallback();
}
m_onPointCloudAvailableCallback = null;
m_isDirty = false;
m_pointCloud = new TangoPointCloudData();
m_pointCloud.m_points = new float[Common.MAX_NUM_POINTS * 4];
m_xyzPoints = new float[Common.MAX_NUM_POINTS * 3];
m_maxNumReducedDepthPoints = 0;
m_onTangoDepthAvailable = null;
m_onTangoDepthMultithreadedAvailable = null;
m_onPointCloudAvailable = null;
m_onPointCloudMultithreadedAvailable = null;
}
/// <summary>
/// Register to get Tango depth callbacks.
///
/// NOTE: Tango depth callbacks happen on a different thread than the main
/// Unity thread.
/// </summary>
internal static void SetCallback()
{
if (m_onPointCloudAvailableCallback != null)
{
Debug.Log("DepthListener.SetCallback() called when callback is already set.");
return;
}
Debug.Log("DepthListener.SetCallback()");
m_onPointCloudAvailableCallback = new DepthProvider.APIOnPointCloudAvailable(_OnPointCloudAvailable);
Tango.DepthProvider.SetCallback(m_onPointCloudAvailableCallback);
}
/// <summary>
/// Raise a Tango depth event if there is new data.
/// </summary>
internal static void SendIfAvailable()
{
if (m_onPointCloudAvailableCallback == null)
{
return;
}
#if UNITY_EDITOR
lock (m_lockObject)
{
if (DepthProvider.m_emulationIsDirty)
{
DepthProvider.m_emulationIsDirty = false;
if (m_onTangoDepthAvailable != null || m_onTangoDepthMultithreadedAvailable != null
|| m_onPointCloudAvailable != null | m_onPointCloudMultithreadedAvailable != null)
{
_FillEmulatedPointCloud(ref m_pointCloud);
}
if (m_onTangoDepthMultithreadedAvailable != null)
{
// Pretend to be making a call from unmanaged code.
TangoUnityDepth depth = new TangoUnityDepth(m_pointCloud);
GCHandle pinnedPoints = GCHandle.Alloc(depth.m_points, GCHandleType.Pinned);
TangoXYZij emulatedXyzij = _GetEmulatedRawXyzijData(depth, pinnedPoints);
m_onTangoDepthMultithreadedAvailable(emulatedXyzij);
pinnedPoints.Free();
}
if (m_onPointCloudMultithreadedAvailable != null)
{
// Pretend to be making a call from unmanaged code.
GCHandle pinnedPoints = GCHandle.Alloc(m_pointCloud.m_points, GCHandleType.Pinned);
TangoPointCloudIntPtr rawData = _GetEmulatedRawData(m_pointCloud, pinnedPoints);
m_onPointCloudMultithreadedAvailable(ref rawData);
pinnedPoints.Free();
}
if (m_onTangoDepthAvailable != null || m_onPointCloudAvailable != null)
{
m_isDirty = true;
}
}
}
#endif
if (m_isDirty && (m_onTangoDepthAvailable != null || m_onPointCloudAvailable != null))
{
lock (m_lockObject)
{
_ReducePointCloudPoints(m_pointCloud, m_maxNumReducedDepthPoints);
if (m_onTangoDepthAvailable != null)
{
m_onTangoDepthAvailable(new TangoUnityDepth(m_pointCloud));
}
if (m_onPointCloudAvailable != null)
{
m_onPointCloudAvailable(m_pointCloud);
}
}
m_isDirty = false;
}
}
/// <summary>
/// Register a Unity main thread handler for the Tango depth event.
/// </summary>
/// <param name="handler">Event handler to register.</param>
internal static void RegisterOnTangoDepthAvailable(OnTangoDepthAvailableEventHandler handler)
{
if (handler != null)
{
m_onTangoDepthAvailable += handler;
}
}
/// <summary>
/// Unregisters a Unity main thread handler for the Tango depth event.
/// </summary>
/// <param name="handler">Event handler to unregister.</param>
internal static void UnregisterOnTangoDepthAvailable(OnTangoDepthAvailableEventHandler handler)
{
if (handler != null)
{
m_onTangoDepthAvailable -= handler;
}
}
/// <summary>
/// Register a multithread handler for the Tango depth event.
/// </summary>
/// <param name="handler">Event handler to register.</param>
internal static void RegisterOnTangoDepthMultithreadedAvailable(OnTangoDepthMulithreadedAvailableEventHandler handler)
{
if (handler != null)
{
m_onTangoDepthMultithreadedAvailable += handler;
}
}
/// <summary>
/// Unregisters a multithread handler for the Tango depth event.
/// </summary>
/// <param name="handler">Event handler to unregister.</param>
internal static void UnregisterOnTangoDepthMultithreadedAvailable(OnTangoDepthMulithreadedAvailableEventHandler handler)
{
if (handler != null)
{
m_onTangoDepthMultithreadedAvailable -= handler;
}
}
/// <summary>
/// Registers a Unity main thread handler for the Tango point cloud event.
/// </summary>
/// <param name="handler">Event handler to register.</param>
internal static void RegisterOnPointCloudAvailable(OnPointCloudAvailableEventHandler handler)
{
if (handler != null)
{
m_onPointCloudAvailable += handler;
}
}
/// <summary>
/// Unregisters a Unity main thread handler for the Tango point cloud event.
/// </summary>
/// <param name="handler">Event handler to unregister.</param>
internal static void UnregisterOnPointCloudAvailable(OnPointCloudAvailableEventHandler handler)
{
if (handler != null)
{
m_onPointCloudAvailable -= handler;
}
}
/// <summary>
/// Registers a Unity multithread handler for the Tango point cloud event.
/// </summary>
/// <param name="handler">Event handler to register.</param>
internal static void RegisterOnPointCloudMultithreadedAvailable(
OnPointCloudMultithreadedAvailableEventHandler handler)
{
if (handler != null)
{
m_onPointCloudMultithreadedAvailable += handler;
}
}
/// <summary>
/// Unregisters a Unity multithread handler for the Tango point cloud event.
/// </summary>
/// <param name="handler">Event handler to register.</param>
internal static void UnregisterOnPointCloudMultithreadedAvailable(
OnPointCloudMultithreadedAvailableEventHandler handler)
{
if (handler != null)
{
m_onPointCloudMultithreadedAvailable -= handler;
}
}
/// <summary>
/// Set an upper limit on the number of points in the point cloud.
/// Hopefully a temporary workaround 'till this is implemented as an option C-side.
/// </summary>
/// <param name="maxPoints">Max points.</param>
internal static void SetPointCloudLimit(int maxPoints)
{
m_maxNumReducedDepthPoints = maxPoints;
}
/// <summary>
/// Callback that gets called when depth is available from the Tango Service.
/// </summary>
/// <param name="callbackContext">Callback context.</param>
/// <param name="rawPointCloud">The depth data returned from Tango.</param>
[AOT.MonoPInvokeCallback(typeof(DepthProvider.APIOnPointCloudAvailable))]
private static void _OnPointCloudAvailable(IntPtr callbackContext, ref TangoPointCloudIntPtr rawPointCloud)
{
// Fill in the data to draw the point cloud.
if (m_onPointCloudMultithreadedAvailable != null)
{
m_onPointCloudMultithreadedAvailable(ref rawPointCloud);
}
lock (m_lockObject)
{
// copy single members
m_pointCloud.m_timestamp = rawPointCloud.m_timestamp;
m_pointCloud.m_numPoints = rawPointCloud.m_numPoints;
if (rawPointCloud.m_numPoints > 0)
{
Marshal.Copy(rawPointCloud.m_points, m_pointCloud.m_points, 0,
rawPointCloud.m_numPoints * 4);
}
m_isDirty = true;
}
// This must be done after the above Marshal.Copy so that it can efficiently reduce the array to just XYZ.
if (m_onTangoDepthMultithreadedAvailable != null)
{
TangoXYZij xyzij = new TangoXYZij();
xyzij.version = rawPointCloud.m_version;
xyzij.timestamp = rawPointCloud.m_timestamp;
xyzij.xyz_count = rawPointCloud.m_numPoints;
xyzij.ij_rows = 0;
xyzij.ij_cols = 0;
xyzij.ij = IntPtr.Zero;
xyzij.color_image = IntPtr.Zero;
for (int it = 0; it < m_pointCloud.m_numPoints; ++it)
{
m_xyzPoints[(it * 3) + 0] = m_pointCloud.m_points[(it * 4) + 0];
m_xyzPoints[(it * 3) + 1] = m_pointCloud.m_points[(it * 4) + 1];
m_xyzPoints[(it * 3) + 2] = m_pointCloud.m_points[(it * 4) + 2];
}
GCHandle pinnedXyzPoints = GCHandle.Alloc(m_xyzPoints, GCHandleType.Pinned);
xyzij.xyz = pinnedXyzPoints.AddrOfPinnedObject();
m_onTangoDepthMultithreadedAvailable(xyzij);
pinnedXyzPoints.Free();
}
}
/// <summary>
/// Reduces depth points down to below a fixed number of points.
///
/// TODO: Do this sort of thing in C code before before passing to Unity instead.
/// </summary>
/// <param name="pointCloud">Tango depth data to reduce.</param>
/// <param name="maxNumPoints">Max points to reduce down to.</param>
private static void _ReducePointCloudPoints(TangoPointCloudData pointCloud, int maxNumPoints)
{
if (maxNumPoints > 0 && pointCloud.m_numPoints > maxNumPoints)
{
// Here (maxNumPoints - 1) rather than maxPoints is just a quick and
// dirty way to avoid any possibile edge-case accumulated FP error
// in the sketchy code below.
float keepFraction = (maxNumPoints - 1) / (float)pointCloud.m_numPoints;
int keptPoints = 0;
float keepCounter = 0;
for (int i = 0; i < pointCloud.m_numPoints; i++)
{
keepCounter += keepFraction;
if (keepCounter > 1)
{
pointCloud.m_points[keptPoints] = pointCloud.m_points[i];
keepCounter--;
keptPoints++;
}
}
pointCloud.m_numPoints = keptPoints;
}
}
#if UNITY_EDITOR
/// <summary>
/// Fill out <c>pointCloudData</c> with emulated values from Tango.
/// </summary>
/// <param name="pointCloudData">The point cloud data to fill out.</param>
private static void _FillEmulatedPointCloud(ref TangoPointCloudData pointCloud)
{
List<Vector3> emulated = DepthProvider.GetTangoEmulation(out pointCloud.m_timestamp);
pointCloud.m_numPoints = emulated.Count;
for (int it = 0; it < emulated.Count; ++it)
{
pointCloud.m_points[(it * 4) + 0] = emulated[it].x;
pointCloud.m_points[(it * 4) + 1] = emulated[it].y;
pointCloud.m_points[(it * 4) + 2] = emulated[it].z;
pointCloud.m_points[(it * 4) + 3] = 1;
}
}
/// <summary>
/// It's backwards, but fill an emulated TangoXYZij instance from an emulated TangoPointCloudData
/// instance. It is the responsibility of the caller to GC pin/free the pointCloudData's m_points.
/// </summary>
/// <returns>Emulated raw xyzij data.</returns>
/// <param name="depth">Emulated point cloud data.</param>>
/// <param name="pinnedPoints">Pinned array of pointCloudData.m_points.</param>
private static TangoXYZij _GetEmulatedRawXyzijData(TangoUnityDepth depth, GCHandle pinnedPoints)
{
TangoXYZij data = new TangoXYZij();
data.xyz = pinnedPoints.AddrOfPinnedObject();
data.xyz_count = depth.m_pointCount;
data.ij_cols = 0;
data.ij_rows = 0;
data.ij = IntPtr.Zero;
data.timestamp = depth.m_timestamp;
return data;
}
/// <summary>
/// It's backwards, but fill an emulated TangoPointCloudIntPtr instance from an emulated TangoPointCloudData
/// instance. It is the responsibility of the caller to GC pin/free the pointCloudData's m_points.
/// </summary>
/// <returns>Emulated TangoPointCloudIntPtr instance.</returns>
/// <param name="pointCloud">Emulated point cloud data.</param>>
/// <param name="pinnedPoints">Pinned array of pointCloudData.m_points.</param>
private static TangoPointCloudIntPtr _GetEmulatedRawData(TangoPointCloudData pointCloud, GCHandle pinnedPoints)
{
TangoPointCloudIntPtr raw;
raw.m_version = 0;
raw.m_timestamp = pointCloud.m_timestamp;
raw.m_numPoints = pointCloud.m_numPoints;
raw.m_points = pinnedPoints.AddrOfPinnedObject();
return raw;
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
using Xunit;
using SortedList_SortedListUtils;
namespace SortedListCtorIntIKeyComp
{
public class Driver<KeyType, ValueType>
{
private Test m_test;
public Driver(Test test)
{
m_test = test;
}
private CultureInfo _english = new CultureInfo("en");
private CultureInfo _german = new CultureInfo("de");
private CultureInfo _danish = new CultureInfo("da");
private CultureInfo _turkish = new CultureInfo("tr");
//CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING
//CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING
//CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING
//CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING
//CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING
private const String strAE = "AE";
private const String strUC4 = "\u00C4";
private const String straA = "aA";
private const String strAa = "Aa";
private const String strI = "I";
private const String strTurkishUpperI = "\u0131";
private const String strBB = "BB";
private const String strbb = "bb";
private const String value = "Default_Value";
public void TestVanilla(int capacity)
{
SortedList<String, String> _dic;
IComparer<String> comparer;
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.OrdinalIgnoreCase,
StringComparer.Ordinal};
foreach (IComparer<String> predefinedComparer in predefinedComparers)
{
_dic = new SortedList<String, String>(capacity, predefinedComparer);
m_test.Eval(_dic.Comparer == predefinedComparer, String.Format("Err_4568aijueud! Comparer differ expected: {0} actual: {1}", predefinedComparer, _dic.Comparer));
m_test.Eval(_dic.Count == 0, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly == false, String.Format("Err_435wsdg! Count different: {0}", ((IDictionary<KeyType, ValueType>)_dic).IsReadOnly));
m_test.Eval(_dic.Keys.Count == 0, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == 0, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_848652ahued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strAE, value);
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//bug #11263 in NDPWhidbey
CultureInfo.DefaultThreadCurrentCulture = _german;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_54848ahuede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strAE, value);
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_788989ajeude! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(straA, value);
m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_54878aheuid! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
//OrdinalIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.OrdinalIgnoreCase;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5588ahied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
CultureInfo.DefaultThreadCurrentCulture = _turkish;
comparer = StringComparer.OrdinalIgnoreCase;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_8488ahiued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
//Ordinal - not that many meaningful test
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.Ordinal;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_488ahede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.Ordinal;
_dic = new SortedList<String, String>(capacity, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_05848ahied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
}
public void TestParm()
{
//passing null will revert to the default comparison mechanism
SortedList<String, String> _dic;
IComparer<String> comparer = null;
try
{
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(0, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_9237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<String, String>(comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_90723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
int[] negativeValues = { -1, -2, -5, Int32.MinValue };
comparer = StringComparer.CurrentCulture;
for (int i = 0; i < negativeValues.Length; i++)
{
try
{
_dic = new SortedList<String, String>(negativeValues[i], comparer);
m_test.Eval(false, String.Format("Err_387tsg! No exception thrown"));
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
}
public void IkeyComparerOwnImplementation(int capacity)
{
//This just ensure that we can call our own implementation
SortedList<String, String> _dic;
IComparer<String> comparer = new MyOwnIKeyImplementation<String>();
try
{
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(capacity, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<String, String>(comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_00723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
}
public class Constructor_int_IKeyComparer
{
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void RunTests()
{
//This mostly follows the format established by the original author of these tests
//These tests mostly uses the scenarios that were used in the individual constructors
Test test = new Test();
Driver<String, String> driver1 = new Driver<String, String>(test);
//Scenario 1: Pass all the enum values and ensure that the behavior is correct
int[] validCapacityValues = { 0, 1, 2, 5, 10, 16, 32, 50, 500, 5000, 10000 };
for (int i = 0; i < validCapacityValues.Length; i++)
driver1.TestVanilla(validCapacityValues[i]);
//Scenario 2: Parm validation: null for IKeyComparer and negative for capacity
driver1.TestParm();
//Scenario 3: Implement our own IKeyComparer and check
for (int i = 0; i < validCapacityValues.Length; i++)
driver1.IkeyComparerOwnImplementation(validCapacityValues[i]);
Assert.True(test.result);
}
}
//[Serializable]
internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType>
{
public int GetHashCode(KeyType key)
{
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key.GetHashCode();
}
public int Compare(KeyType key1, KeyType key2)
{
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key1.GetHashCode();
}
public bool Equals(KeyType key1, KeyType key2)
{
return key1.Equals(key2);
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.12.4: Stop freeze simulation, relaible. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(ClockTime))]
public partial class StopFreezeReliablePdu : SimulationManagementWithReliabilityFamilyPdu, IEquatable<StopFreezeReliablePdu>
{
/// <summary>
/// time in real world for this operation to happen
/// </summary>
private ClockTime _realWorldTime = new ClockTime();
/// <summary>
/// Reason for stopping/freezing simulation
/// </summary>
private byte _reason;
/// <summary>
/// internal behvior of the simulation while frozen
/// </summary>
private byte _frozenBehavior;
/// <summary>
/// reliablity level
/// </summary>
private byte _requiredReliablityService;
/// <summary>
/// padding
/// </summary>
private byte _pad1;
/// <summary>
/// Request ID
/// </summary>
private uint _requestID;
/// <summary>
/// Initializes a new instance of the <see cref="StopFreezeReliablePdu"/> class.
/// </summary>
public StopFreezeReliablePdu()
{
PduType = (byte)54;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(StopFreezeReliablePdu left, StopFreezeReliablePdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(StopFreezeReliablePdu left, StopFreezeReliablePdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._realWorldTime.GetMarshalledSize(); // this._realWorldTime
marshalSize += 1; // this._reason
marshalSize += 1; // this._frozenBehavior
marshalSize += 1; // this._requiredReliablityService
marshalSize += 1; // this._pad1
marshalSize += 4; // this._requestID
return marshalSize;
}
/// <summary>
/// Gets or sets the time in real world for this operation to happen
/// </summary>
[XmlElement(Type = typeof(ClockTime), ElementName = "realWorldTime")]
public ClockTime RealWorldTime
{
get
{
return this._realWorldTime;
}
set
{
this._realWorldTime = value;
}
}
/// <summary>
/// Gets or sets the Reason for stopping/freezing simulation
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "reason")]
public byte Reason
{
get
{
return this._reason;
}
set
{
this._reason = value;
}
}
/// <summary>
/// Gets or sets the internal behvior of the simulation while frozen
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "frozenBehavior")]
public byte FrozenBehavior
{
get
{
return this._frozenBehavior;
}
set
{
this._frozenBehavior = value;
}
}
/// <summary>
/// Gets or sets the reliablity level
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "requiredReliablityService")]
public byte RequiredReliablityService
{
get
{
return this._requiredReliablityService;
}
set
{
this._requiredReliablityService = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "pad1")]
public byte Pad1
{
get
{
return this._pad1;
}
set
{
this._pad1 = value;
}
}
/// <summary>
/// Gets or sets the Request ID
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._realWorldTime.Marshal(dos);
dos.WriteUnsignedByte((byte)this._reason);
dos.WriteUnsignedByte((byte)this._frozenBehavior);
dos.WriteUnsignedByte((byte)this._requiredReliablityService);
dos.WriteUnsignedByte((byte)this._pad1);
dos.WriteUnsignedInt((uint)this._requestID);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._realWorldTime.Unmarshal(dis);
this._reason = dis.ReadUnsignedByte();
this._frozenBehavior = dis.ReadUnsignedByte();
this._requiredReliablityService = dis.ReadUnsignedByte();
this._pad1 = dis.ReadUnsignedByte();
this._requestID = dis.ReadUnsignedInt();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<StopFreezeReliablePdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<realWorldTime>");
this._realWorldTime.Reflection(sb);
sb.AppendLine("</realWorldTime>");
sb.AppendLine("<reason type=\"byte\">" + this._reason.ToString(CultureInfo.InvariantCulture) + "</reason>");
sb.AppendLine("<frozenBehavior type=\"byte\">" + this._frozenBehavior.ToString(CultureInfo.InvariantCulture) + "</frozenBehavior>");
sb.AppendLine("<requiredReliablityService type=\"byte\">" + this._requiredReliablityService.ToString(CultureInfo.InvariantCulture) + "</requiredReliablityService>");
sb.AppendLine("<pad1 type=\"byte\">" + this._pad1.ToString(CultureInfo.InvariantCulture) + "</pad1>");
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("</StopFreezeReliablePdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as StopFreezeReliablePdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(StopFreezeReliablePdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._realWorldTime.Equals(obj._realWorldTime))
{
ivarsEqual = false;
}
if (this._reason != obj._reason)
{
ivarsEqual = false;
}
if (this._frozenBehavior != obj._frozenBehavior)
{
ivarsEqual = false;
}
if (this._requiredReliablityService != obj._requiredReliablityService)
{
ivarsEqual = false;
}
if (this._pad1 != obj._pad1)
{
ivarsEqual = false;
}
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._realWorldTime.GetHashCode();
result = GenerateHash(result) ^ this._reason.GetHashCode();
result = GenerateHash(result) ^ this._frozenBehavior.GetHashCode();
result = GenerateHash(result) ^ this._requiredReliablityService.GetHashCode();
result = GenerateHash(result) ^ this._pad1.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
return result;
}
}
}
| |
#region License
// Copyright 2009 The Sixth Form College Farnborough (http://www.farnborough.ac.uk)
//
// 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.
//
// The latest version of this file can be found at http://github.com/JeremySkinner/SagePayMvc
#endregion
namespace SagePayMvc.Internal {
/// <summary>
/// Represents a transaction registration that is sent to SagePay.
/// This should be serialized using the HttpPostSerializer.
/// </summary>
public class TransactionRegistration {
readonly ShoppingBasket basket;
readonly Address billingAddress;
readonly Address deliveryAddress;
readonly string customerEMail;
readonly string vendorName;
readonly string profile;
readonly string accountType;
readonly string currency;
const string NormalFormMode = "NORMAL";
const string LowProfileFormMode = "LOW";
const string AccountTypeEcommerce = "E";
const string AccountTypeMailOrder = "M";
public TransactionRegistration(string vendorTxCode, ShoppingBasket basket, string notificationUrl,
Address billingAddress, Address deliveryAddress, string customerEmail,
string vendorName, PaymentFormProfile paymentFormProfile, string currencyCode,
MerchantAccountType accountType) {
VendorTxCode = vendorTxCode;
NotificationURL = notificationUrl;
this.basket = basket;
this.billingAddress = billingAddress;
this.deliveryAddress = deliveryAddress;
customerEMail = customerEmail;
this.vendorName = vendorName;
switch (paymentFormProfile) {
case PaymentFormProfile.Low:
profile = LowProfileFormMode;
break;
default:
profile = NormalFormMode;
break;
}
switch (accountType)
{
case MerchantAccountType.MailOrder:
this.accountType=AccountTypeMailOrder;
break;
default:
this.accountType = AccountTypeEcommerce;
break;
}
this.currency = currencyCode;
}
public string VPSProtocol {
get { return Configuration.ProtocolVersion; }
}
public string TxType {
get { return "PAYMENT"; }
}
public string Vendor {
get { return vendorName; }
}
public string VendorTxCode { get; private set; }
[Format("f2")]
public decimal Amount {
get { return basket.Total; }
}
public string Currency {
get { return currency; }
}
public string Description {
get { return basket.Name; }
}
[Unencoded]
public string NotificationURL { get; private set; }
public string BillingSurname {
get { return billingAddress.Surname; }
}
public string BillingFirstnames {
get { return billingAddress.Firstnames; }
}
public string BillingAddress1 {
get { return billingAddress.Address1; }
}
[Optional]
public string BillingAddress2 {
get { return billingAddress.Address2; }
}
public string BillingCity {
get { return billingAddress.City; }
}
public string BillingPostCode {
get { return billingAddress.PostCode; }
}
public string BillingCountry {
get { return billingAddress.Country; }
}
[Optional]
public string BillingState {
get { return billingAddress.State; }
}
[Optional]
public string BillingPhone {
get { return billingAddress.Phone; }
}
public string DeliverySurname {
get { return deliveryAddress.Surname; }
}
public string DeliveryFirstnames {
get { return deliveryAddress.Firstnames; }
}
public string DeliveryAddress1 {
get { return deliveryAddress.Address1; }
}
[Optional]
public string DeliveryAddress2 {
get { return deliveryAddress.Address2; }
}
public string DeliveryCity {
get { return deliveryAddress.City; }
}
public string DeliveryPostCode {
get { return deliveryAddress.PostCode; }
}
public string DeliveryCountry {
get { return deliveryAddress.Country; }
}
[Optional]
public string DeliveryState {
get { return deliveryAddress.State; }
}
[Optional]
public string DeliveryPhone {
get { return deliveryAddress.Phone; }
}
public string CustomerEMail {
get { return customerEMail; }
}
public string Basket {
get { return basket.ToString(); }
}
//NOTE: Not currently supported
public int AllowGiftAid {
get { return 0; }
}
public int Apply3DSecure {
get { return 0; }
}
public string Profile {
get { return profile; }
}
public string AccountType
{
get { return accountType; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Xml;
using System.Xml.Serialization;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.TestClient;
namespace OpenMetaverse.TestClient
{
public class QueuedDownloadInfo
{
public UUID TransferID;
public UUID AssetID;
public UUID ItemID;
public UUID TaskID;
public UUID OwnerID;
public AssetType Type;
public string FileName;
public DateTime WhenRequested;
public bool IsRequested;
public QueuedDownloadInfo(string file, UUID asset, UUID item, UUID task, UUID owner, AssetType type)
{
FileName = file;
AssetID = asset;
ItemID = item;
TaskID = task;
OwnerID = owner;
Type = type;
TransferID = UUID.Zero;
WhenRequested = DateTime.Now;
IsRequested = false;
}
}
public class BackupCommand : Command
{
/// <summary>Maximum number of transfer requests to send to the server</summary>
private const int MAX_TRANSFERS = 10;
// all items here, fed by the inventory walking thread
private Queue<QueuedDownloadInfo> PendingDownloads = new Queue<QueuedDownloadInfo>();
// items sent to the server here
private List<QueuedDownloadInfo> CurrentDownloads = new List<QueuedDownloadInfo>(MAX_TRANSFERS);
// background workers
private BackgroundWorker BackupWorker;
private BackgroundWorker QueueWorker;
// some stats
private int TextItemsFound;
private int TextItemsTransferred;
private int TextItemErrors;
#region Properties
/// <summary>
/// true if either of the background threads is running
/// </summary>
private bool BackgroundBackupRunning
{
get { return InventoryWalkerRunning || QueueRunnerRunning; }
}
/// <summary>
/// true if the thread walking inventory is running
/// </summary>
private bool InventoryWalkerRunning
{
get { return BackupWorker != null; }
}
/// <summary>
/// true if the thread feeding the queue to the server is running
/// </summary>
private bool QueueRunnerRunning
{
get { return QueueWorker != null; }
}
/// <summary>
/// returns a string summarizing activity
/// </summary>
/// <returns></returns>
private string BackgroundBackupStatus
{
get
{
StringBuilder sbResult = new StringBuilder();
sbResult.AppendFormat("{0} is {1} running.", Name, BoolToNot(BackgroundBackupRunning));
if (TextItemErrors != 0 || TextItemsFound != 0 || TextItemsTransferred != 0)
{
sbResult.AppendFormat("\r\n{0} : Inventory walker ( {1} running ) has found {2} items.",
Name, BoolToNot(InventoryWalkerRunning), TextItemsFound);
sbResult.AppendFormat("\r\n{0} : Server Transfers ( {1} running ) has transferred {2} items with {3} errors.",
Name, BoolToNot(QueueRunnerRunning), TextItemsTransferred, TextItemErrors);
sbResult.AppendFormat("\r\n{0} : {1} items in Queue, {2} items requested from server.",
Name, PendingDownloads.Count, CurrentDownloads.Count);
}
return sbResult.ToString();
}
}
#endregion Properties
public BackupCommand(TestClient testClient)
{
Name = "backuptext";
Description = "Backup inventory to a folder on your hard drive. Usage: " + Name + " [to <directory>] | [abort] | [status]";
testClient.Assets.OnAssetReceived += new AssetManager.AssetReceivedCallback(Assets_OnAssetReceived);
}
public override string Execute(string[] args, UUID fromAgentID)
{
StringBuilder sbResult = new StringBuilder();
if (args.Length == 1 && args[0] == "status")
{
return BackgroundBackupStatus;
}
else if (args.Length == 1 && args[0] == "abort")
{
if (!BackgroundBackupRunning)
return BackgroundBackupStatus;
BackupWorker.CancelAsync();
QueueWorker.CancelAsync();
Thread.Sleep(500);
// check status
return BackgroundBackupStatus;
}
else if (args.Length != 2)
{
return "Usage: " + Name + " [to <directory>] | [abort] | [status]";
}
else if (BackgroundBackupRunning)
{
return BackgroundBackupStatus;
}
QueueWorker = new BackgroundWorker();
QueueWorker.WorkerSupportsCancellation = true;
QueueWorker.DoWork += new DoWorkEventHandler(bwQueueRunner_DoWork);
QueueWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwQueueRunner_RunWorkerCompleted);
QueueWorker.RunWorkerAsync();
BackupWorker = new BackgroundWorker();
BackupWorker.WorkerSupportsCancellation = true;
BackupWorker.DoWork += new DoWorkEventHandler(bwBackup_DoWork);
BackupWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwBackup_RunWorkerCompleted);
BackupWorker.RunWorkerAsync(args);
return "Started background operations.";
}
void bwQueueRunner_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
QueueWorker = null;
Console.WriteLine(BackgroundBackupStatus);
}
void bwQueueRunner_DoWork(object sender, DoWorkEventArgs e)
{
TextItemErrors = TextItemsTransferred = 0;
while (QueueWorker.CancellationPending == false)
{
// have any timed out?
if (CurrentDownloads.Count > 0)
{
foreach (QueuedDownloadInfo qdi in CurrentDownloads)
{
if ((qdi.WhenRequested + TimeSpan.FromSeconds(60)) < DateTime.Now)
{
Logger.DebugLog(Name + ": timeout on asset " + qdi.AssetID.ToString(), Client);
// submit request again
qdi.TransferID = Client.Assets.RequestInventoryAsset(
qdi.AssetID, qdi.ItemID, qdi.TaskID, qdi.OwnerID, qdi.Type, true);
qdi.WhenRequested = DateTime.Now;
qdi.IsRequested = true;
}
}
}
if (PendingDownloads.Count != 0)
{
// room in the server queue?
if (CurrentDownloads.Count < MAX_TRANSFERS)
{
// yes
QueuedDownloadInfo qdi = PendingDownloads.Dequeue();
qdi.WhenRequested = DateTime.Now;
qdi.IsRequested = true;
qdi.TransferID = Client.Assets.RequestInventoryAsset(
qdi.AssetID, qdi.ItemID, qdi.TaskID, qdi.OwnerID, qdi.Type, true);
lock (CurrentDownloads) CurrentDownloads.Add(qdi);
}
}
if (CurrentDownloads.Count == 0 && PendingDownloads.Count == 0 && BackupWorker == null)
{
Logger.DebugLog(Name + ": both transfer queues empty AND inventory walking thread is done", Client);
return;
}
Thread.Sleep(100);
}
}
void bwBackup_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine(Name + ": Inventory walking thread done.");
BackupWorker = null;
}
private void bwBackup_DoWork(object sender, DoWorkEventArgs e)
{
string[] args;
TextItemsFound = 0;
args = (string[])e.Argument;
lock (CurrentDownloads) CurrentDownloads.Clear();
// FIXME:
//Client.Inventory.RequestFolderContents(Client.Inventory.Store.RootFolder.UUID, Client.Self.AgentID,
// true, true, false, InventorySortOrder.ByName);
DirectoryInfo di = new DirectoryInfo(args[1]);
// recurse on the root folder into the entire inventory
BackupFolder(Client.Inventory.Store.RootNode, di.FullName);
}
/// <summary>
/// BackupFolder - recurse through the inventory nodes sending scripts and notecards to the transfer queue
/// </summary>
/// <param name="folder">The current leaf in the inventory tree</param>
/// <param name="sPathSoFar">path so far, in the form @"c:\here" -- this needs to be "clean" for the current filesystem</param>
private void BackupFolder(InventoryNode folder, string sPathSoFar)
{
StringBuilder sbRequests = new StringBuilder();
// FIXME:
//Client.Inventory.RequestFolderContents(folder.Data.UUID, Client.Self.AgentID, true, true, false,
// InventorySortOrder.ByName);
// first scan this folder for text
foreach (InventoryNode iNode in folder.Nodes.Values)
{
if (BackupWorker.CancellationPending)
return;
if (iNode.Data is OpenMetaverse.InventoryItem)
{
InventoryItem ii = iNode.Data as InventoryItem;
if (ii.AssetType == AssetType.LSLText || ii.AssetType == AssetType.Notecard)
{
// check permissions on scripts
if (ii.AssetType == AssetType.LSLText)
{
if ((ii.Permissions.OwnerMask & PermissionMask.Modify) == PermissionMask.None)
{
// skip this one
continue;
}
}
string sExtension = (ii.AssetType == AssetType.LSLText) ? ".lsl" : ".txt";
// make the output file
string sPath = sPathSoFar + @"\" + MakeValid(ii.Name.Trim()) + sExtension;
// create the new qdi
QueuedDownloadInfo qdi = new QueuedDownloadInfo(sPath, ii.AssetUUID, iNode.Data.UUID, UUID.Zero,
Client.Self.AgentID, ii.AssetType);
// add it to the queue
lock (PendingDownloads)
{
TextItemsFound++;
PendingDownloads.Enqueue(qdi);
}
}
}
}
// now run any subfolders
foreach (InventoryNode i in folder.Nodes.Values)
{
if (BackupWorker.CancellationPending)
return;
else if (i.Data is OpenMetaverse.InventoryFolder)
BackupFolder(i, sPathSoFar + @"\" + MakeValid(i.Data.Name.Trim()));
}
}
private string MakeValid(string path)
{
// FIXME: We need to strip illegal characters out
return path.Trim().Replace('"', '\'');
}
private void Assets_OnAssetReceived(AssetDownload asset, Asset blah)
{
lock (CurrentDownloads)
{
// see if we have this in our transfer list
QueuedDownloadInfo r = CurrentDownloads.Find(delegate(QueuedDownloadInfo q)
{
return q.TransferID == asset.ID;
});
if (r != null && r.TransferID == asset.ID)
{
if (asset.Success)
{
// create the directory to put this in
Directory.CreateDirectory(Path.GetDirectoryName(r.FileName));
// write out the file
File.WriteAllBytes(r.FileName, asset.AssetData);
Logger.DebugLog(Name + " Wrote: " + r.FileName, Client);
TextItemsTransferred++;
}
else
{
TextItemErrors++;
Console.WriteLine("{0}: Download of asset {1} ({2}) failed with status {3}", Name, r.FileName,
r.AssetID.ToString(), asset.Status.ToString());
}
// remove the entry
CurrentDownloads.Remove(r);
}
}
}
/// <summary>
/// returns blank or "not" if false
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
private static string BoolToNot(bool b)
{
return b ? String.Empty : "not";
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="UnsafeNativeMethods.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Messaging.Interop
{
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.ComponentModel;
using Microsoft.Win32;
using System.Security;
using System.Security.Permissions;
[System.Runtime.InteropServices.ComVisible(false),
System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods
{
[DllImport(ExternDll.Mqrt, EntryPoint = "MQOpenQueue", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQOpenQueue(string formatName, int access, int shareMode, out MessageQueueHandle handle);
public static int MQOpenQueue(string formatName, int access, int shareMode, out MessageQueueHandle handle)
{
try
{
return IntMQOpenQueue(formatName, access, shareMode, out handle);
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
[DllImport(ExternDll.Mqrt, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern int MQSendMessage(MessageQueueHandle handle, MessagePropertyVariants.MQPROPS properties, IntPtr transaction);
[DllImport(ExternDll.Mqrt, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern int MQSendMessage(MessageQueueHandle handle, MessagePropertyVariants.MQPROPS properties, ITransaction transaction);
[DllImport(ExternDll.Mqrt, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public unsafe static extern int MQReceiveMessage(MessageQueueHandle handle, uint timeout, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
SafeNativeMethods.ReceiveCallback receiveCallback, CursorHandle cursorHandle, IntPtr transaction);
[DllImport(ExternDll.Mqrt, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public unsafe static extern int MQReceiveMessage(MessageQueueHandle handle, uint timeout, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
SafeNativeMethods.ReceiveCallback receiveCallback, CursorHandle cursorHandle, ITransaction transaction);
[DllImport(ExternDll.Mqrt, EntryPoint = "MQReceiveMessageByLookupId", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private unsafe static extern int IntMQReceiveMessageByLookupId(MessageQueueHandle handle, long lookupId, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
SafeNativeMethods.ReceiveCallback receiveCallback, IntPtr transaction);
public unsafe static int MQReceiveMessageByLookupId(MessageQueueHandle handle, long lookupId, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
SafeNativeMethods.ReceiveCallback receiveCallback, IntPtr transaction)
{
try
{
return IntMQReceiveMessageByLookupId(handle, lookupId, action, properties, overlapped, receiveCallback, transaction);
}
catch (EntryPointNotFoundException)
{
throw new PlatformNotSupportedException(Res.GetString(Res.PlatformNotSupported));
}
}
[DllImport(ExternDll.Mqrt, EntryPoint = "MQReceiveMessageByLookupId", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private unsafe static extern int IntMQReceiveMessageByLookupId(MessageQueueHandle handle, long lookupId, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
SafeNativeMethods.ReceiveCallback receiveCallback, ITransaction transaction);
public unsafe static int MQReceiveMessageByLookupId(MessageQueueHandle handle, long lookupId, int action, MessagePropertyVariants.MQPROPS properties, NativeOverlapped* overlapped,
SafeNativeMethods.ReceiveCallback receiveCallback, ITransaction transaction)
{
try
{
return IntMQReceiveMessageByLookupId(handle, lookupId, action, properties, overlapped, receiveCallback, transaction);
}
catch (EntryPointNotFoundException)
{
throw new PlatformNotSupportedException(Res.GetString(Res.PlatformNotSupported));
}
}
[DllImport(ExternDll.Mqrt, EntryPoint = "MQCreateQueue", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQCreateQueue(IntPtr securityDescriptor, MessagePropertyVariants.MQPROPS queueProperties, StringBuilder formatName, ref int formatNameLength);
public static int MQCreateQueue(IntPtr securityDescriptor, MessagePropertyVariants.MQPROPS queueProperties, StringBuilder formatName, ref int formatNameLength)
{
try
{
return IntMQCreateQueue(securityDescriptor, queueProperties, formatName, ref formatNameLength);
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
[DllImport(ExternDll.Mqrt, EntryPoint = "MQDeleteQueue", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQDeleteQueue(string formatName);
public static int MQDeleteQueue(string formatName)
{
try
{
return IntMQDeleteQueue(formatName);
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
[DllImport(ExternDll.Mqrt, EntryPoint = "MQLocateBegin", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQLocateBegin(string context, Restrictions.MQRESTRICTION Restriction, Columns.MQCOLUMNSET columnSet, IntPtr sortSet, out LocatorHandle enumHandle);
public static int MQLocateBegin(string context, Restrictions.MQRESTRICTION Restriction, Columns.MQCOLUMNSET columnSet, out LocatorHandle enumHandle)
{
try
{
return IntMQLocateBegin(context, Restriction, columnSet, IntPtr.Zero, out enumHandle);
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
[DllImport(ExternDll.Mqrt, EntryPoint = "MQGetMachineProperties", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQGetMachineProperties(string machineName, IntPtr machineIdPointer, MessagePropertyVariants.MQPROPS machineProperties);
public static int MQGetMachineProperties(string machineName, IntPtr machineIdPointer, MessagePropertyVariants.MQPROPS machineProperties)
{
try
{
return IntMQGetMachineProperties(machineName, machineIdPointer, machineProperties);
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
[DllImport(ExternDll.Mqrt, EntryPoint = "MQGetQueueProperties", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQGetQueueProperties(string formatName, MessagePropertyVariants.MQPROPS queueProperties);
public static int MQGetQueueProperties(string formatName, MessagePropertyVariants.MQPROPS queueProperties)
{
try
{
return IntMQGetQueueProperties(formatName, queueProperties);
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
[DllImport(ExternDll.Mqrt, EntryPoint = "MQMgmtGetInfo", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQMgmtGetInfo(string machineName, string objectName, MessagePropertyVariants.MQPROPS queueProperties);
public static int MQMgmtGetInfo(string machineName, string objectName, MessagePropertyVariants.MQPROPS queueProperties)
{
try
{
return IntMQMgmtGetInfo(machineName, objectName, queueProperties);
}
catch (EntryPointNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQInfoNotSupported));
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
[DllImport(ExternDll.Mqrt, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern int MQPurgeQueue(MessageQueueHandle handle);
[DllImport(ExternDll.Mqrt, EntryPoint = "MQSetQueueProperties", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntMQSetQueueProperties(string formatName, MessagePropertyVariants.MQPROPS queueProperties);
public static int MQSetQueueProperties(string formatName, MessagePropertyVariants.MQPROPS queueProperties)
{
try
{
return IntMQSetQueueProperties(formatName, queueProperties);
}
catch (DllNotFoundException)
{
throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled));
}
}
// This method gets us the current security descriptor In "self-relative" format - so it contains offsets instead of pointers,
// and we don't know how big the return buffer is, so we just use an IntPtr parameter
[DllImport(ExternDll.Mqrt, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
public static extern int MQGetQueueSecurity(string formatName, int SecurityInformation, IntPtr SecurityDescriptor, int length, out int lengthNeeded);
// This method takes a security descriptor In "absolute" formate - so it will always be the same size and
// we can just use the SECURITY_DESCRIPTOR class.
[DllImport(ExternDll.Mqrt, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
public static extern int MQSetQueueSecurity(string formatName, int SecurityInformation, NativeMethods.SECURITY_DESCRIPTOR SecurityDescriptor);
[DllImport(ExternDll.Advapi32, SetLastError = true)]
public static extern bool GetSecurityDescriptorDacl(IntPtr pSD, out bool daclPresent, out IntPtr pDacl, out bool daclDefaulted);
[DllImport(ExternDll.Advapi32, SetLastError = true)]
public static extern bool SetSecurityDescriptorDacl(NativeMethods.SECURITY_DESCRIPTOR pSD, bool daclPresent, IntPtr pDacl, bool daclDefaulted);
[DllImport(ExternDll.Advapi32, SetLastError = true)]
public static extern bool InitializeSecurityDescriptor(NativeMethods.SECURITY_DESCRIPTOR SD, int revision);
[DllImport(ExternDll.Advapi32, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public static extern bool LookupAccountName(string lpSystemName,
string lpAccountName,
IntPtr sid,
ref int sidSize,
StringBuilder DomainName,
ref int DomainSize,
out int pUse);
}
}
| |
using System;
namespace WellFired.Shared
{
public static class DoubleEasing
{
public delegate double EasingFunction(double currentTime, double startingValue, double finalValue, double duration);
public static DoubleEasing.EasingFunction GetEasingFunctionFor(Easing.EasingType easingType)
{
switch (easingType)
{
case Easing.EasingType.Linear:
return new DoubleEasing.EasingFunction(DoubleEasing.Linear);
case Easing.EasingType.QuadraticEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.QuadraticEaseOut);
case Easing.EasingType.QuadraticEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.QuadraticEaseIn);
case Easing.EasingType.QuadraticEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.QuadraticEaseInOut);
case Easing.EasingType.QuadraticEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.QuadraticEaseOutIn);
case Easing.EasingType.SineEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.SineEaseOut);
case Easing.EasingType.SineEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.SineEaseIn);
case Easing.EasingType.SineEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.SineEaseInOut);
case Easing.EasingType.SineEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.SineEaseOutIn);
case Easing.EasingType.ExponentialEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.ExponentialEaseOut);
case Easing.EasingType.ExponentialEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.ExponentialEaseIn);
case Easing.EasingType.ExponentialEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.ExponentialEaseInOut);
case Easing.EasingType.ExponentialEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.ExponentialEaseOutIn);
case Easing.EasingType.CirclicEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.CirclicEaseOut);
case Easing.EasingType.CirclicEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.CirclicEaseIn);
case Easing.EasingType.CirclicEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.CirclicEaseInOut);
case Easing.EasingType.CirclicEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.CirclicEaseOutIn);
case Easing.EasingType.CubicEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.CubicEaseOut);
case Easing.EasingType.CubicEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.CubicEaseIn);
case Easing.EasingType.CubicEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.CubicEaseInOut);
case Easing.EasingType.CubicEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.CubicEaseOutIn);
case Easing.EasingType.QuarticEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.QuarticEaseOut);
case Easing.EasingType.QuarticEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.QuarticEaseIn);
case Easing.EasingType.QuarticEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.QuarticEaseInOut);
case Easing.EasingType.QuarticEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.QuarticEaseOutIn);
case Easing.EasingType.QuinticEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.QuinticEaseOut);
case Easing.EasingType.QuinticEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.QuinticEaseIn);
case Easing.EasingType.QuinticEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.QuinticEaseInOut);
case Easing.EasingType.QuinticEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.QuinticEaseOutIn);
case Easing.EasingType.ElasticEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.ElasticEaseOut);
case Easing.EasingType.ElasticEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.ElasticEaseIn);
case Easing.EasingType.ElasticEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.ElasticEaseInOut);
case Easing.EasingType.ElasticEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.ElasticEaseOutIn);
case Easing.EasingType.BounceEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.BounceEaseOut);
case Easing.EasingType.BounceEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.BounceEaseIn);
case Easing.EasingType.BounceEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.BounceEaseInOut);
case Easing.EasingType.BounceEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.BounceEaseOutIn);
case Easing.EasingType.BackEaseOut:
return new DoubleEasing.EasingFunction(DoubleEasing.BackEaseOut);
case Easing.EasingType.BackEaseIn:
return new DoubleEasing.EasingFunction(DoubleEasing.BackEaseIn);
case Easing.EasingType.BackEaseInOut:
return new DoubleEasing.EasingFunction(DoubleEasing.BackEaseInOut);
case Easing.EasingType.BackEaseOutIn:
return new DoubleEasing.EasingFunction(DoubleEasing.BackEaseOutIn);
default:
throw new Exception("Easing type not implemented");
}
}
public static double Linear(double t, double b, double c, double d)
{
return c * t / d + b;
}
public static double ExponentialEaseOut(double t, double b, double c, double d)
{
return (t != d) ? (c * (-Math.Pow(2.0, -10.0 * t / d) + 1.0) + b) : (b + c);
}
public static double ExponentialEaseIn(double t, double b, double c, double d)
{
return (t != 0.0) ? (c * Math.Pow(2.0, 10.0 * (t / d - 1.0)) + b) : b;
}
public static double ExponentialEaseInOut(double t, double b, double c, double d)
{
if (t == 0.0)
{
return b;
}
if (t == d)
{
return b + c;
}
if ((t /= d / 2.0) < 1.0)
{
return c / 2.0 * Math.Pow(2.0, 10.0 * (t - 1.0)) + b;
}
return c / 2.0 * (-Math.Pow(2.0, -10.0 * (t -= 1.0)) + 2.0) + b;
}
public static double ExponentialEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.ExponentialEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.ExponentialEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double CirclicEaseOut(double t, double b, double c, double d)
{
return c * Math.Sqrt(1.0 - (t = t / d - 1.0) * t) + b;
}
public static double CirclicEaseIn(double t, double b, double c, double d)
{
return -c * (Math.Sqrt(1.0 - (t /= d) * t) - 1.0) + b;
}
public static double CirclicEaseInOut(double t, double b, double c, double d)
{
if ((t /= d / 2.0) < 1.0)
{
return -c / 2.0 * (Math.Sqrt(1.0 - t * t) - 1.0) + b;
}
return c / 2.0 * (Math.Sqrt(1.0 - (t -= 2.0) * t) + 1.0) + b;
}
public static double CirclicEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.CirclicEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.CirclicEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double QuadraticEaseOut(double t, double b, double c, double d)
{
return -c * (t /= d) * (t - 2.0) + b;
}
public static double QuadraticEaseIn(double t, double b, double c, double d)
{
return c * (t /= d) * t + b;
}
public static double QuadraticEaseInOut(double t, double b, double c, double d)
{
if ((t /= d / 2.0) < 1.0)
{
return c / 2.0 * t * t + b;
}
return -c / 2.0 * ((t -= 1.0) * (t - 2.0) - 1.0) + b;
}
public static double QuadraticEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.QuadraticEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.QuadraticEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double SineEaseOut(double t, double b, double c, double d)
{
return c * Math.Sin(t / d * 1.5707963267948966) + b;
}
public static double SineEaseIn(double t, double b, double c, double d)
{
return -c * Math.Cos(t / d * 1.5707963267948966) + c + b;
}
public static double SineEaseInOut(double t, double b, double c, double d)
{
if ((t /= d / 2.0) < 1.0)
{
return c / 2.0 * Math.Sin(3.1415926535897931 * t / 2.0) + b;
}
return -c / 2.0 * (Math.Cos(3.1415926535897931 * (t -= 1.0) / 2.0) - 2.0) + b;
}
public static double SineEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.SineEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.SineEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double CubicEaseOut(double t, double b, double c, double d)
{
return c * ((t = t / d - 1.0) * t * t + 1.0) + b;
}
public static double CubicEaseIn(double t, double b, double c, double d)
{
return c * (t /= d) * t * t + b;
}
public static double CubicEaseInOut(double t, double b, double c, double d)
{
if ((t /= d / 2.0) < 1.0)
{
return c / 2.0 * t * t * t + b;
}
return c / 2.0 * ((t -= 2.0) * t * t + 2.0) + b;
}
public static double CubicEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.CubicEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.CubicEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double QuarticEaseOut(double t, double b, double c, double d)
{
return -c * ((t = t / d - 1.0) * t * t * t - 1.0) + b;
}
public static double QuarticEaseIn(double t, double b, double c, double d)
{
return c * (t /= d) * t * t * t + b;
}
public static double QuarticEaseInOut(double t, double b, double c, double d)
{
if ((t /= d / 2.0) < 1.0)
{
return c / 2.0 * t * t * t * t + b;
}
return -c / 2.0 * ((t -= 2.0) * t * t * t - 2.0) + b;
}
public static double QuarticEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.QuarticEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.QuarticEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double QuinticEaseOut(double t, double b, double c, double d)
{
return c * ((t = t / d - 1.0) * t * t * t * t + 1.0) + b;
}
public static double QuinticEaseIn(double t, double b, double c, double d)
{
return c * (t /= d) * t * t * t * t + b;
}
public static double QuinticEaseInOut(double t, double b, double c, double d)
{
if ((t /= d / 2.0) < 1.0)
{
return c / 2.0 * t * t * t * t * t + b;
}
return c / 2.0 * ((t -= 2.0) * t * t * t * t + 2.0) + b;
}
public static double QuinticEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.QuinticEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.QuinticEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double ElasticEaseOut(double t, double b, double c, double d)
{
if ((t /= d) == 1.0)
{
return b + c;
}
double num = d * 0.3;
double num2 = num / 4.0;
return c * Math.Pow(2.0, -10.0 * t) * Math.Sin((t * d - num2) * 6.2831853071795862 / num) + c + b;
}
public static double ElasticEaseIn(double t, double b, double c, double d)
{
if ((t /= d) == 1.0)
{
return b + c;
}
double num = d * 0.3;
double num2 = num / 4.0;
return -(c * Math.Pow(2.0, 10.0 * (t -= 1.0)) * Math.Sin((t * d - num2) * 6.2831853071795862 / num)) + b;
}
public static double ElasticEaseInOut(double t, double b, double c, double d)
{
if ((t /= d / 2.0) == 2.0)
{
return b + c;
}
double num = d * 0.44999999999999996;
double num2 = num / 4.0;
if (t < 1.0)
{
return -0.5 * (c * Math.Pow(2.0, 10.0 * (t -= 1.0)) * Math.Sin((t * d - num2) * 6.2831853071795862 / num)) + b;
}
return c * Math.Pow(2.0, -10.0 * (t -= 1.0)) * Math.Sin((t * d - num2) * 6.2831853071795862 / num) * 0.5 + c + b;
}
public static double ElasticEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.ElasticEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.ElasticEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double BounceEaseOut(double t, double b, double c, double d)
{
if ((t /= d) < 0.36363636363636365)
{
return c * (7.5625 * t * t) + b;
}
if (t < 0.72727272727272729)
{
return c * (7.5625 * (t -= 0.54545454545454541) * t + 0.75) + b;
}
if (t < 0.90909090909090906)
{
return c * (7.5625 * (t -= 0.81818181818181823) * t + 0.9375) + b;
}
return c * (7.5625 * (t -= 0.95454545454545459) * t + 0.984375) + b;
}
public static double BounceEaseIn(double t, double b, double c, double d)
{
return c - DoubleEasing.BounceEaseOut(d - t, 0.0, c, d) + b;
}
public static double BounceEaseInOut(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.BounceEaseIn(t * 2.0, 0.0, c, d) * 0.5 + b;
}
return DoubleEasing.BounceEaseOut(t * 2.0 - d, 0.0, c, d) * 0.5 + c * 0.5 + b;
}
public static double BounceEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.BounceEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.BounceEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
public static double BackEaseOut(double t, double b, double c, double d)
{
return c * ((t = t / d - 1.0) * t * (2.70158 * t + 1.70158) + 1.0) + b;
}
public static double BackEaseIn(double t, double b, double c, double d)
{
return c * (t /= d) * t * (2.70158 * t - 1.70158) + b;
}
public static double BackEaseInOut(double t, double b, double c, double d)
{
double num = 1.70158;
if ((t /= d / 2.0) < 1.0)
{
return c / 2.0 * (t * t * (((num *= 1.525) + 1.0) * t - num)) + b;
}
return c / 2.0 * ((t -= 2.0) * t * (((num *= 1.525) + 1.0) * t + num) + 2.0) + b;
}
public static double BackEaseOutIn(double t, double b, double c, double d)
{
if (t < d / 2.0)
{
return DoubleEasing.BackEaseOut(t * 2.0, b, c / 2.0, d);
}
return DoubleEasing.BackEaseIn(t * 2.0 - d, b + c / 2.0, c / 2.0, d);
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.MathUtil.Matrices;
using Encog.MathUtil.Randomize;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Util.Simple;
namespace Encog.Neural.CPN
{
/// <summary>
/// Counterpropagation Neural Networks (CPN) were developed by Professor
/// Robert Hecht-Nielsen in 1987. CPN neural networks are a hybrid neural
/// network, employing characteristics of both a feedforward neural
/// network and a self-organzing map (SOM). The CPN is composed of
/// three layers, the input, the instar and the outstar. The connection
/// from the input to the instar layer is competitive, with only one
/// neuron being allowed to win. The connection between the instar and
/// outstar is feedforward. The layers are trained separately,
/// using instar training and outstar training. The CPN network is
/// good at regression.
/// </summary>
///
[Serializable]
public class CPNNetwork : BasicML, IMLRegression, IMLResettable, IMLError
{
/// <summary>
/// The number of neurons in the input layer.
/// </summary>
///
private readonly int _inputCount;
/// <summary>
/// The number of neurons in the instar, or hidden, layer.
/// </summary>
///
private readonly int _instarCount;
/// <summary>
/// The number of neurons in the outstar, or output, layer.
/// </summary>
///
private readonly int _outstarCount;
/// <summary>
/// The weights from the input to the instar layer.
/// </summary>
///
private readonly Matrix _weightsInputToInstar;
/// <summary>
/// The weights from the instar to the outstar layer.
/// </summary>
///
private readonly Matrix _weightsInstarToOutstar;
/// <summary>
/// The number of winning neurons.
/// </summary>
///
private readonly int _winnerCount;
/// <summary>
/// Construct the counterpropagation neural network.
/// </summary>
///
/// <param name="theInputCount">The number of input neurons.</param>
/// <param name="theInstarCount">The number of instar neurons.</param>
/// <param name="theOutstarCount">The number of outstar neurons.</param>
/// <param name="theWinnerCount">The winner count.</param>
public CPNNetwork(int theInputCount, int theInstarCount,
int theOutstarCount, int theWinnerCount)
{
_inputCount = theInputCount;
_instarCount = theInstarCount;
_outstarCount = theOutstarCount;
_weightsInputToInstar = new Matrix(_inputCount, _instarCount);
_weightsInstarToOutstar = new Matrix(_instarCount, _outstarCount);
_winnerCount = theWinnerCount;
}
/// <value>The instar count, same as the input count.</value>
public int InstarCount
{
get { return _instarCount; }
}
/// <value>The outstar count, same as the output count.</value>
public int OutstarCount
{
get { return _outstarCount; }
}
/// <value>The weights between the input and instar.</value>
public Matrix WeightsInputToInstar
{
get { return _weightsInputToInstar; }
}
/// <value>The weights between the instar and outstar.</value>
public Matrix WeightsInstarToOutstar
{
get { return _weightsInstarToOutstar; }
}
/// <value>The winner count.</value>
public int WinnerCount
{
get { return _winnerCount; }
}
#region MLError Members
/// <summary>
/// Calculate the error for this neural network.
/// </summary>
///
/// <param name="data">The training set.</param>
/// <returns>The error percentage.</returns>
public double CalculateError(IMLDataSet data)
{
return EncogUtility.CalculateRegressionError(this, data);
}
#endregion
#region MLRegression Members
/// <inheritdoc/>
public IMLData Compute(IMLData input)
{
IMLData temp = ComputeInstar(input);
return ComputeOutstar(temp);
}
/// <inheritdoc/>
public int InputCount
{
get { return _inputCount; }
}
/// <inheritdoc/>
public int OutputCount
{
get { return _outstarCount; }
}
#endregion
#region MLResettable Members
/// <summary>
///
/// </summary>
///
public void Reset()
{
Reset(0);
}
/// <summary>
///
/// </summary>
///
public void Reset(int seed)
{
var randomize = new ConsistentRandomizer(-1, 1,
seed);
randomize.Randomize(_weightsInputToInstar);
randomize.Randomize(_weightsInstarToOutstar);
}
#endregion
/// <summary>
/// Compute the instar layer.
/// </summary>
///
/// <param name="input">The input.</param>
/// <returns>The output.</returns>
public IMLData ComputeInstar(IMLData input)
{
var result = new BasicMLData(_instarCount);
int w, i;
int winner = 0;
var winners = new bool[_instarCount];
for (i = 0; i < _instarCount; i++)
{
double sum = 0;
int j;
for (j = 0; j < _inputCount; j++)
{
sum += _weightsInputToInstar[j, i]*input[j];
}
result[i] = sum;
winners[i] = false;
}
double sumWinners = 0;
for (w = 0; w < _winnerCount; w++)
{
double maxOut = Double.MinValue;
for (i = 0; i < _instarCount; i++)
{
if (!winners[i] && (result[i] > maxOut))
{
winner = i;
maxOut = result[winner];
}
}
winners[winner] = true;
sumWinners += result[winner];
}
for (i = 0; i < _instarCount; i++)
{
if (winners[i]
&& (Math.Abs(sumWinners) > EncogFramework.DefaultDoubleEqual))
{
result[i] /= sumWinners;
}
else
{
result[i] = 0;
}
}
return result;
}
/// <summary>
/// Compute the outstar layer.
/// </summary>
///
/// <param name="input">The input.</param>
/// <returns>The output.</returns>
public IMLData ComputeOutstar(IMLData input)
{
var result = new BasicMLData(_outstarCount);
for (int i = 0; i < _outstarCount; i++)
{
double sum = 0;
for (int j = 0; j < _instarCount; j++)
{
sum += _weightsInstarToOutstar[j, i]*input[j];
}
result[i] = sum;
}
return result;
}
/// <summary>
///
/// </summary>
///
public override void UpdateProperties()
{
// unneeded
}
}
}
| |
// 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 XorUInt64()
{
var test = new SimpleBinaryOpTest__XorUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorUInt64
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[ElementCount];
private static UInt64[] _data2 = new UInt64[ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64> _dataTable;
static SimpleBinaryOpTest__XorUInt64()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__XorUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64>(_data1, _data2, new UInt64[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Xor(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Xor(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Xor(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorUInt64();
var result = Sse2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[ElementCount];
UInt64[] inArray2 = new UInt64[ElementCount];
UInt64[] outArray = new UInt64[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[ElementCount];
UInt64[] inArray2 = new UInt64[ElementCount];
UInt64[] outArray = new UInt64[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
if ((ulong)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((ulong)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<UInt64>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2010-2016 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.Globalization;
using System.Linq;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Results
{
public class TestResultGeneralTests : TestResultTests
{
protected const double EXPECTED_DURATION = 0.125;
protected static readonly DateTime EXPECTED_START = new DateTime(1968, 4, 8, 15, 05, 30, 250, DateTimeKind.Utc);
protected static readonly DateTime EXPECTED_END = EXPECTED_START.AddSeconds(EXPECTED_DURATION);
private const string TEST_DESCRIPTION = "Test description";
private const string TEST_CATEGORY = "Dubious";
private const string TEST_PRIORITY = "low";
private const string SUITE_DESCRIPTION = "Suite description";
private const string SUITE_CATEGORY = "Fast";
private const int SUITE_LEVEL = 3;
[SetUp]
public void SimulateTestRun()
{
_test.Properties.Set(PropertyNames.Description, TEST_DESCRIPTION);
_test.Properties.Set(PropertyNames.Category, TEST_CATEGORY);
_test.Properties.Set("Priority", TEST_PRIORITY);
_suite.Properties.Set(PropertyNames.Description, SUITE_DESCRIPTION);
_suite.Properties.Set(PropertyNames.Category, SUITE_CATEGORY);
_suite.Properties.Set("Level", SUITE_LEVEL);
_testResult.StartTime = EXPECTED_START;
_testResult.Duration = EXPECTED_DURATION;
_testResult.EndTime = EXPECTED_END;
_suiteResult.StartTime = EXPECTED_START;
_suiteResult.Duration = EXPECTED_DURATION;
_suiteResult.EndTime = EXPECTED_END;
}
[Test]
public void TestResult_Identification()
{
Assert.AreEqual(_test.Name, _testResult.Name);
Assert.AreEqual(_test.FullName, _testResult.FullName);
}
[Test]
public void TestResult_Properties()
{
Assert.That(_testResult.Test.Properties.Get(PropertyNames.Description), Is.EqualTo(TEST_DESCRIPTION));
Assert.That(_testResult.Test.Properties.Get(PropertyNames.Category), Is.EqualTo(TEST_CATEGORY));
Assert.That(_testResult.Test.Properties.Get("Priority"), Is.EqualTo(TEST_PRIORITY));
}
[Test]
public void TestResult_Duration()
{
Assert.AreEqual(EXPECTED_START, _testResult.StartTime);
Assert.AreEqual(EXPECTED_END, _testResult.EndTime);
Assert.AreEqual(EXPECTED_DURATION, _testResult.Duration);
}
[Test]
public void TestResult_MinimumDuration()
{
// Change duration to value less than minimum
_testResult.Duration = TestResult.MIN_DURATION - 0.000001d;
Assert.That(_testResult.Duration, Is.EqualTo(TestResult.MIN_DURATION));
}
[Test]
public void SuiteResult_Identification()
{
Assert.AreEqual(_suite.Name, _suiteResult.Name);
Assert.AreEqual(_suite.FullName, _suiteResult.FullName);
}
[Test]
public void SuiteResult_Properties()
{
Assert.That(_suiteResult.Test.Properties.Get(PropertyNames.Description), Is.EqualTo(SUITE_DESCRIPTION));
Assert.That(_suiteResult.Test.Properties.Get(PropertyNames.Category), Is.EqualTo(SUITE_CATEGORY));
Assert.That(_suiteResult.Test.Properties.Get("Level"), Is.EqualTo(SUITE_LEVEL));
}
[Test]
public void SuiteResult_Duration()
{
Assert.AreEqual(EXPECTED_START, _suiteResult.StartTime);
Assert.AreEqual(EXPECTED_END, _suiteResult.EndTime);
Assert.AreEqual(EXPECTED_DURATION, _suiteResult.Duration);
}
[Test]
public void SuiteResult_MinimumDuration()
{
// Change duration to value less than minimum
_suiteResult.Duration = TestResult.MIN_DURATION - 0.000001d;
Assert.That(_suiteResult.Duration, Is.EqualTo(TestResult.MIN_DURATION));
}
[Test]
public void TestResultXml_Identification()
{
TNode testNode = _testResult.ToXml(true);
Assert.NotNull(testNode.Attributes["id"]);
Assert.AreEqual("test-case", testNode.Name);
Assert.AreEqual(_testResult.Name, testNode.Attributes["name"]);
Assert.AreEqual(_testResult.FullName, testNode.Attributes["fullname"]);
}
[Test]
public void TestResultXml_Properties()
{
TNode testNode = _testResult.ToXml(true);
Assert.AreEqual(TEST_DESCRIPTION, testNode.SelectSingleNode("properties/property[@name='Description']").Attributes["value"]);
Assert.AreEqual(TEST_CATEGORY, testNode.SelectSingleNode("properties/property[@name='Category']").Attributes["value"]);
Assert.AreEqual(TEST_PRIORITY, testNode.SelectSingleNode("properties/property[@name='Priority']").Attributes["value"]);
}
[Test]
public void TestResultXml_NoChildren()
{
TNode testNode = _testResult.ToXml(true);
Assert.AreEqual(0, testNode.SelectNodes("test-case").Count);
}
[Test]
public void TestResultXml_Duration()
{
TNode testNode = _testResult.ToXml(true);
Assert.AreEqual(EXPECTED_START.ToString("u"), testNode.Attributes["start-time"]);
Assert.AreEqual(EXPECTED_END.ToString("u"), testNode.Attributes["end-time"]);
Assert.AreEqual(EXPECTED_DURATION.ToString("0.000000", CultureInfo.InvariantCulture), testNode.Attributes["duration"]);
}
[Test]
public void SuiteResultXml_Identification()
{
TNode suiteNode = _suiteResult.ToXml(true);
Assert.NotNull(suiteNode.Attributes["id"]);
Assert.AreEqual("test-suite", suiteNode.Name);
Assert.AreEqual(_suiteResult.Name, suiteNode.Attributes["name"]);
Assert.AreEqual(_suiteResult.FullName, suiteNode.Attributes["fullname"]);
}
[Test]
public void SuiteResultXml_Properties()
{
TNode suiteNode = _suiteResult.ToXml(true);
Assert.AreEqual(SUITE_DESCRIPTION, suiteNode.SelectSingleNode("properties/property[@name='Description']").Attributes["value"]);
Assert.AreEqual(SUITE_CATEGORY, suiteNode.SelectSingleNode("properties/property[@name='Category']").Attributes["value"]);
Assert.AreEqual(SUITE_LEVEL.ToString(), suiteNode.SelectSingleNode("properties/property[@name='Level']").Attributes["value"]);
}
[Test]
public void SuiteResultXml_Children()
{
TNode suiteNode = _suiteResult.ToXml(true);
Assert.AreEqual(_suiteResult.Children.Count(), suiteNode.SelectNodes("test-case").Count);
}
[Test]
public void SuiteResultXml_Duration()
{
TNode suiteNode = _suiteResult.ToXml(true);
Assert.AreEqual(EXPECTED_START.ToString("u"), suiteNode.Attributes["start-time"]);
Assert.AreEqual(EXPECTED_END.ToString("u"), suiteNode.Attributes["end-time"]);
Assert.AreEqual(EXPECTED_DURATION.ToString("0.000000", CultureInfo.InvariantCulture), suiteNode.Attributes["duration"]);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Rimss.Common.Collections.Synchronized
{
/// <summary>
/// Base class to provide syncronized (thread-safe) collections.
/// </summary>
/// <typeparam name="T">The type of elements in the collection.</typeparam>
public abstract class SynchronizedEnumerableBase<T> : IEnumerable<T>, IList
{
private List<T> _innerList;
/// <summary>
/// Initializes a new instance of the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> class that is empty and has the
/// default initial capacity.
/// </summary>
/// <exception cref="System.InvalidOperationException"><see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>.CreateSynchronizedList()"/>
/// was overridden and did not return a syncrhonzized list.</exception>
protected SynchronizedEnumerableBase() : this(new List<T>()) { }
/// <summary>
/// Initializes a new instance of the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> class that contains elements copied from the
/// specified list and has sufficient capacity to accommodate the number of elements copied.
/// </summary>
/// <param name="list">The list whose elements are copied to the new list.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="list"/> is null.</exception>
/// <exception cref="System.InvalidOperationException"><see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>.CreateSynchronizedList()"/>
/// was overridden and did not return a syncrhonzized list.</exception>
protected SynchronizedEnumerableBase(IList<T> list)
{
if (list == null)
throw new ArgumentNullException("list");
this.Initialize(list);
}
/// <summary>
/// Initializes a new instance of the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> class that contains elements copied from the
/// specified collection and has sufficient capacity to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="collection"/> is null.</exception>
/// <exception cref="System.InvalidOperationException"><see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>.CreateSynchronizedList()"/>
/// was overridden and did not return a syncrhonzized list.</exception>
protected SynchronizedEnumerableBase(ICollection<T> collection)
{
this.Initialize(collection);
}
/// <summary>
/// Called from within the base constructor to initialize the inner synchronized list.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <exception cref="System.InvalidOperationException"><see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>.CreateSynchronizedList()"/>
/// was overridden and did not return a syncrhonzized list.</exception>
protected virtual void Initialize(ICollection<T> collection)
{
this._innerList = new List<T>(collection);
}
#region IList<T> Support Members
/// <summary>
/// Determines the index of a specific item in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <returns>The zero-based index of <paramref name="item"/> if found in the list; otherwise, -1.</returns>
public int IndexOf(T item) { return this.InnerIndexOf(item); }
/// <summary>
/// Gets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get.</param>
/// <returns>The element at the specified index.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
public T this[int index] { get { return (T)(this.InnerGet(index)); } }
/// <summary>
/// Inserts an item to the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is read-only
/// <para>-or-</para>
/// <para>The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> has a fixed size.</para></exception>
/// <exception cref="System.NullReferenceException"><paramref name="item"/> is null reference in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
protected void BaseInsert(int index, T item) { this.InnerInsert(index, item); }
/// <summary>
/// Removes the S<see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is read-only.</exception>
protected virtual void BaseRemoveAt(int index) { this._innerList.RemoveAt(index); }
/// <summary>
/// Sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to set.</param>
/// <param name="item">The object to set at the specified index in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
/// <exception cref="System.NotSupportedException">The property is set and the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>
/// is read-only.</exception>
protected void BaseSet(int index, T item) { this.InnerSet(index, item); }
#endregion
#region ICollection<T> Support Members
/// <summary>
/// Determines whether the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <returns>true if <paramref name="item"/> is found in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>; otherwise, false.</returns>
public bool Contains(T item) { return this.InnerContains(item); }
/// <summary>
/// Copies the elements of the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> to an <see cref="System.Array"/>,
/// starting at a particular <see cref="System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="System.Array"/> that is the destination of the elements copied
/// from <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>. The <see cref="System.Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="array"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception>
/// <exception cref="System.ArgumentException">The number of elements in the source <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>
/// is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination array.</exception>
public void CopyTo(T[] array, int arrayIndex) { this.InnerCopyTo(array, arrayIndex); }
/// <summary>
/// Gets the number of elements contained in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
public int Count { get { return this._innerList.Count; } }
/// <summary>
/// Adds an item to the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is read-only.
/// <para>-or-</para>
/// <para>The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> has a fixed size.</para></exception>
protected void BaseAdd(T item) { this.InnerAdd(item); }
/// <summary>
/// Removes all items from the <see cref="SynchronizedCollections.SyncrhonizedEnumerableBase<T>"/>.
/// </summary>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SyncrhonizedEnumerableBase<T>"/> is read-only.
/// <para>-or-</para>
/// <para>The <see cref="SynchronizedCollections.SyncrhonizedEnumerableBase<T>"/> has a fixed size.</exception>
protected virtual void BaseClear() { this._innerList.Clear(); }
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <returns>true if item was successfully removed from the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>;
/// otherwise, false. This method also returns false if item is not found in the
/// original <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</returns>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is read-only
/// <para>-or-</para>
/// <para>The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> has a fixed size.</para></exception>
protected virtual bool BaseRemove(T item) { return this.InnerRemove(item); }
#endregion
#region IList Members
bool IList.IsFixedSize { get { return false; } }
bool IList.IsReadOnly { get { return false; } }
/// <summary>
/// Determines whether the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> contains a specific value.
/// </summary>
/// <param name="value">The object to locate in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <returns>true if the <see cref="System.Object"/> is found in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>;
/// otherwise, false.</returns>
protected bool InnerContains(object value) { return (this._innerList as IList).Contains(value); }
/// <summary>
/// Determines the index of a specific item in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
/// <param name="value">The object to locate in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <returns>The index of value if found in the list; otherwise, -1.</returns>
protected int InnerIndexOf(object value) { return (this._innerList as IList).IndexOf(value); }
/// <summary>
/// Gets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get.</param>
/// <returns>The element at the specified index.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
protected object InnerGet(int index) { return this._innerList[index]; }
/// <summary>
/// Adds an item to the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
/// <param name="value">The object to add to the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <returns>The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection.</returns>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is read-only
/// <para>-or-</para>
/// <para>The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> has a fixed size.</para></exception>
/// <exception cref="InvalidCastException"><paramref name="value"/> could not be cast to <typeparamref name="T"/>.</exception>
protected virtual int InnerAdd(object value) { return (this._innerList as IList).Add((T)value); }
/// <summary>
/// Inserts an item to the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The object to insert into the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is read-only
/// <para>-or-</para>
/// <para>The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> has a fixed size.</para></exception>
/// <exception cref="System.NullReferenceException"><paramref name="value"/> is null reference in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
/// <exception cref="InvalidCastException"><paramref name="value"/> could not be cast to <typeparamref name="T"/>.</exception>
protected virtual void InnerInsert(int index, object value) { this._innerList.Insert(index, (T)value); }
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
/// <param name="value">The object to remove from the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <returns>true if item is successfully removed; otherwise, false. This method also returns false if item was not found in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</returns>
/// <exception cref="System.NotSupportedException">The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is read-only
/// <para>-or-</para>
/// <para>The <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> has a fixed size.</para></exception>
protected virtual bool InnerRemove(object value)
{
if (!(this._innerList as IList).Contains(value))
return false;
(this._innerList as IList).Remove(value);
return true;
}
/// <summary>
/// Sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to set.</param>
/// <param name="value">The object to set at the specified index in the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</exception>
/// <exception cref="System.NotSupportedException">The property is set and the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>
/// is read-only.</exception>
/// <exception cref="InvalidCastException"><paramref name="value"/> could not be cast to <typeparamref name="T"/>.</exception>
protected virtual void InnerSet(int index, object value) { this._innerList[index] = (T)value; }
#region Explicit Members
bool IList.Contains(object value) { return this.InnerContains(value); }
int IList.IndexOf(object value) { return this.InnerIndexOf(value); }
object IList.this[int index]
{
get { return this.InnerGet(index); }
set { this.InnerSet(index, value); }
}
int IList.Add(object value) { return this.InnerAdd(value); }
void IList.Clear() { this.BaseClear(); }
void IList.Insert(int index, object value) { this.InnerInsert(index, value); }
void IList.Remove(object value) { this.InnerRemove(value); }
void IList.RemoveAt(int index) { this.BaseRemoveAt(index); }
#endregion
#endregion
#region ICollection Members
bool ICollection.IsSynchronized { get { return true; } }
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
object ICollection.SyncRoot { get { return this._innerList; } }
/// <summary>
/// Copies the elements of the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> to an <see cref="System.Array"/>,
/// starting at a particular <see cref="System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="System.Array"/> that is the destination of the elements copied
/// from <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>. The <see cref="System.Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="array"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.</exception>
/// <exception cref="System.ArgumentException"><paramref name="array"/> is multidimensional.
/// <para>-or-</para>
/// <para>The number of elements in the source <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> is greater than the available space
/// from <paramref name="index"/> to the end of the destination array.</para>
/// <para>-or-</para>
/// <para>The type of the source <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/> cannot be cast automatically to the type of the
/// destination array.</para></exception>
protected void InnerCopyTo(Array array, int index) { (this._innerList as IList).CopyTo(array, index); }
void ICollection.CopyTo(Array array, int index) { this.InnerCopyTo(array, index); }
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.
/// </summary>
/// <returns>A <see cref="System.Collections.Generic.IEnumerator<T>"/> that can be used to iterate through
/// the <see cref="SynchronizedCollections.SynchronizedEnumerableBase<T>"/>.</returns>
public IEnumerator<T> GetEnumerator() { return new TypedEnumeratorWrapper<T>(this._innerList); }
IEnumerator IEnumerable.GetEnumerator() { return this.InnerGetEnumerator(); }
/// <summary>
/// Returns an enumerator that iterates through the inner collection.
/// </summary>
/// <returns>An <see cref="System.Collections.IEnumerator"/> object that can be used to iterate through the collection.</returns>
protected IEnumerator InnerGetEnumerator() { return this._innerList.GetEnumerator(); }
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using NUnit.Framework;
using System.Linq;
namespace QuantConnect.Tests
{
[TestFixture, Category("TravisExclude")]
public class RegressionTests
{
[Test, TestCaseSource("GetRegressionTestParameters")]
public void AlgorithmStatisticsRegression(AlgorithmStatisticsTestParameters parameters)
{
AlgorithmRunner.RunLocalBacktest(parameters.Algorithm, parameters.Statistics, parameters.Language);
}
private static TestCaseData[] GetRegressionTestParameters()
{
var basicTemplateStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "264.956%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "4.411"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.752"},
{"Beta", "0.186"},
{"Annual Standard Deviation", "0.193"},
{"Annual Variance", "0.037"},
{"Information Ratio", "1.316"},
{"Tracking Error", "0.246"},
{"Treynor Ratio", "4.572"},
{"Total Fees", "$3.09"}
};
var limitFillRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "34"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "8.350%"},
{"Drawdown", "0.400%"},
{"Expectancy", "0.447"},
{"Net Profit", "0.103%"},
{"Sharpe Ratio", "1.747"},
{"Loss Rate", "31%"},
{"Win Rate", "69%"},
{"Profit-Loss Ratio", "1.10"},
{"Alpha", "0.051"},
{"Beta", "0.002"},
{"Annual Standard Deviation", "0.03"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-2.451"},
{"Tracking Error", "0.194"},
{"Treynor Ratio", "29.506"},
{"Total Fees", "$34.00"}
};
var updateOrderRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "21"},
{"Average Win", "0%"},
{"Average Loss", "-1.71%"},
{"Compounding Annual Return", "-8.289%"},
{"Drawdown", "16.700%"},
{"Expectancy", "-1"},
{"Net Profit", "-15.892%"},
{"Sharpe Ratio", "-1.225"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.076"},
{"Beta", "0.039"},
{"Annual Standard Deviation", "0.056"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-2.167"},
{"Tracking Error", "0.112"},
{"Treynor Ratio", "-1.755"},
{"Total Fees", "$21.00"}
};
var regressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5433"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-3.886%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-0.991"},
{"Net Profit", "-0.054%"},
{"Sharpe Ratio", "-30.336"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "2.40"},
{"Alpha", "-0.023"},
{"Beta", "0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-4.203"},
{"Tracking Error", "0.174"},
{"Treynor Ratio", "-33.666"},
{"Total Fees", "$5433.00"}
};
var universeSelectionRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0.70%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-56.034%"},
{"Drawdown", "3.800%"},
{"Expectancy", "0"},
{"Net Profit", "-3.755%"},
{"Sharpe Ratio", "-3.629"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.643"},
{"Beta", "0.684"},
{"Annual Standard Deviation", "0.173"},
{"Annual Variance", "0.03"},
{"Information Ratio", "-3.927"},
{"Tracking Error", "0.166"},
{"Treynor Ratio", "-0.918"},
{"Total Fees", "$2.00"}
};
var customDataRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "155.210%"},
{"Drawdown", "99.900%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0.453"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "48.714"},
{"Beta", "50.259"},
{"Annual Standard Deviation", "118.922"},
{"Annual Variance", "14142.47"},
{"Information Ratio", "0.452"},
{"Tracking Error", "118.917"},
{"Treynor Ratio", "1.072"},
{"Total Fees", "$0.00"}
};
var addRemoveSecurityRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0.49%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "307.853%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Net Profit", "1.814%"},
{"Sharpe Ratio", "6.474"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.906"},
{"Beta", "0.018"},
{"Annual Standard Deviation", "0.141"},
{"Annual Variance", "0.02"},
{"Information Ratio", "1.648"},
{"Tracking Error", "0.236"},
{"Treynor Ratio", "50.372"},
{"Total Fees", "$25.20"}
};
var dropboxBaseDataUniverseSelectionStatistics = new Dictionary<string, string>
{
{"Total Trades", "67"},
{"Average Win", "1.13%"},
{"Average Loss", "-0.69%"},
{"Compounding Annual Return", "17.718%"},
{"Drawdown", "5.100%"},
{"Expectancy", "0.813"},
{"Net Profit", "17.718%"},
{"Sharpe Ratio", "1.38"},
{"Loss Rate", "31%"},
{"Win Rate", "69%"},
{"Profit-Loss Ratio", "1.64"},
{"Alpha", "0.151"},
{"Beta", "-0.073"},
{"Annual Standard Deviation", "0.099"},
{"Annual Variance", "0.01"},
{"Information Ratio", "-0.506"},
{"Tracking Error", "0.146"},
{"Treynor Ratio", "-1.873"},
{"Total Fees", "$300.15"}
};
var dropboxUniverseSelectionStatistics = new Dictionary<string, string>
{
{"Total Trades", "49"},
{"Average Win", "1.58%"},
{"Average Loss", "-1.03%"},
{"Compounding Annual Return", "21.281%"},
{"Drawdown", "8.200%"},
{"Expectancy", "0.646"},
{"Net Profit", "21.281%"},
{"Sharpe Ratio", "1.362"},
{"Loss Rate", "35%"},
{"Win Rate", "65%"},
{"Profit-Loss Ratio", "1.52"},
{"Alpha", "0.178"},
{"Beta", "-0.071"},
{"Annual Standard Deviation", "0.12"},
{"Annual Variance", "0.014"},
{"Information Ratio", "-0.296"},
{"Tracking Error", "0.161"},
{"Treynor Ratio", "-2.319"},
{"Total Fees", "$232.92"}
};
var parameterizedStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "278.616%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "11.017"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.764"},
{"Beta", "0.186"},
{"Annual Standard Deviation", "0.078"},
{"Annual Variance", "0.006"},
{"Information Ratio", "1.957"},
{"Tracking Error", "0.171"},
{"Treynor Ratio", "4.634"},
{"Total Fees", "$3.09"},
};
return new List<AlgorithmStatisticsTestParameters>
{
// CSharp
new AlgorithmStatisticsTestParameters("AddRemoveSecurityRegressionAlgorithm", addRemoveSecurityRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CustomDataRegressionAlgorithm", customDataRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("DropboxBaseDataUniverseSelectionAlgorithm", dropboxBaseDataUniverseSelectionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("DropboxUniverseSelectionAlgorithm", dropboxUniverseSelectionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("LimitFillRegressionAlgorithm", limitFillRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("ParameterizedAlgorithm", parameterizedStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("RegressionAlgorithm", regressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("UniverseSelectionRegressionAlgorithm", universeSelectionRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("UpdateOrderRegressionAlgorithm", updateOrderRegressionStatistics, Language.CSharp),
// FSharp
new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.FSharp),
// VisualBasic
new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.VisualBasic),
}.Select(x => new TestCaseData(x).SetName(x.Language + "/" + x.Algorithm)).ToArray();
}
public class AlgorithmStatisticsTestParameters
{
public readonly string Algorithm;
public readonly Dictionary<string, string> Statistics;
public readonly Language Language;
public AlgorithmStatisticsTestParameters(string algorithm, Dictionary<string, string> statistics, Language language)
{
Algorithm = algorithm;
Statistics = statistics;
Language = language;
}
}
}
}
| |
// 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.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using WebsitePanel.Providers.FTP.IIs70;
using WebsitePanel.Providers.FTP.IIs70.Authorization;
using WebsitePanel.Providers.FTP.IIs70.Config;
using WebsitePanel.Providers.OS;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Providers.Utils.LogParser;
using WebsitePanel.Server.Utils;
using Microsoft.Web.Management.Server;
using Microsoft.Win32;
using IisFtpSite = WebsitePanel.Providers.FTP.IIs70.Config.FtpSite;
using IisSite = Microsoft.Web.Administration.Site;
namespace WebsitePanel.Providers.FTP
{
public class MsFTP : HostingServiceProviderBase, IFtpServer
{
private SitesModuleService ftpSitesService;
private static readonly string DefaultFtpSiteFolder = @"%SystemDrive%\inetpub\ftproot";
private static readonly string DefaultFtpSiteLogsFolder = @"%SystemDrive%\inetpub\logs\LogFiles";
public const string DEFAULT_LOG_EXT_FILE_FIELDS = @"Date,Time,ClientIP,UserName,SiteName,ComputerName,
ServerIP,Method,UriStem,FtpStatus,Win32Status,BytesSent,BytesRecv,TimeTaken,ServerPort,Host,FtpSubStatus,
Session,FullPath,Info,ClientPort";
private static string[] FTP70_SERVICE_CMD_LIST = new string[] {
"DataChannelClosed",
"DataChannelOpened",
"ControlChannelOpened"
};
public const string EMPTY_LOG_FIELD = "-";
/// <summary>
/// Initializes a new instance of the <see cref="MsFTP"/> class.
/// </summary>
public MsFTP()
{
if (IsMsFTPInstalled())
{
this.ftpSitesService = new SitesModuleService();
}
}
#region Properties
protected string SiteId
{
get { return ProviderSettings["SiteId"]; }
}
protected string SharedIP
{
get { return ProviderSettings["SharedIP"]; }
}
protected string FtpGroupName
{
get { return ProviderSettings["FtpGroupName"]; }
}
protected string UsersOU
{
get { return ProviderSettings["ADUsersOU"]; }
}
protected string GroupsOU
{
get { return ProviderSettings["ADGroupsOU"]; }
}
protected string AdFtpRoot
{
get { return ProviderSettings["AdFtpRoot"]; }
}
protected Mode UserIsolationMode
{
get
{
var site = GetSite(ProviderSettings["SiteId"]);
return (Mode)Enum.Parse(typeof(Mode), site["UserIsolationMode"]);
}
}
#endregion
#region IFtpServer Members
/// <summary>
/// Changes site's state.
/// </summary>
/// <param name="siteId">Site's id to change state for.</param>
/// <param name="state">State to be set.</param>
/// <exception cref="ArgumentException">Is thrown in case site name is null or empty.</exception>
public void ChangeSiteState(string siteId, ServerState state)
{
if (String.IsNullOrEmpty(siteId))
{
throw new ArgumentException("Site name is null or empty.");
}
switch (state)
{
case ServerState.Continuing:
case ServerState.Started:
this.ftpSitesService.StartSite(siteId);
break;
case ServerState.Stopped:
case ServerState.Paused:
this.ftpSitesService.StopSite(siteId);
break;
}
}
/// <summary>
/// Gets state for ftp site with supplied id.
/// </summary>
/// <param name="siteId">Site's id to get state for.</param>
/// <returns>Ftp site's state.</returns>
/// <exception cref="ArgumentException">Is thrown in case site name is null or empty.</exception>
public ServerState GetSiteState(string siteId)
{
if (String.IsNullOrEmpty(siteId))
{
throw new ArgumentException("Site name is null or empty.");
}
return this.ftpSitesService.GetSiteState(siteId);
}
/// <summary>
/// Checks whether site with given name exists.
/// </summary>
/// <param name="siteId">Site's name to check.</param>
/// <returns>true - if it exists; false - otherwise.</returns>
/// <exception cref="ArgumentException">Is thrown in case site name is null or empty.</exception>
public bool SiteExists(string siteId)
{
if (String.IsNullOrEmpty(siteId))
{
throw new ArgumentException("Site name is null or empty.");
}
// In case site id doesn't contain default ftp site name we consider it as not existent.
return this.ftpSitesService.SiteExists(siteId);
}
/// <summary>
/// Gets list of available ftp sites.
/// </summary>
/// <returns>List of available ftp sites.</returns>
public FtpSite[] GetSites()
{
List<FtpSite> ftpSites = new List<FtpSite>();
foreach (string ftpSiteName in this.ftpSitesService.GetSitesNames())
{
ftpSites.Add(this.GetSite(ftpSiteName));
}
return ftpSites.ToArray();
}
/// <summary>
/// Gets ftp site with given name.
/// </summary>
/// <param name="siteId">Ftp site's name to get.</param>
/// <returns>Ftp site.</returns>
/// <exception cref="ArgumentException"> Is thrown in case site name is null or empty. </exception>
public FtpSite GetSite(string siteId)
{
if (String.IsNullOrEmpty(siteId))
{
throw new ArgumentException("Site name is null or empty.");
}
FtpSite ftpSite = new FtpSite();
ftpSite.SiteId = siteId;
ftpSite.Name = siteId;
this.FillFtpSiteFromIis(ftpSite);
return ftpSite;
}
/// <summary>
/// Creates ftp site.
/// </summary>
/// <param name="site">Ftp site to be created.</param>
/// <returns>Created site id.</returns>
/// <exception cref="ArgumentNullException">Is thrown in case supplied argument is null.</exception>
/// <exception cref="ArgumentException">
/// Is thrown in case site id or its name is null or empty or if site id is not equal to default ftp site name.
/// </exception>
public string CreateSite(FtpSite site)
{
if (site == null)
{
throw new ArgumentNullException("site");
}
if (String.IsNullOrEmpty(site.SiteId) || String.IsNullOrEmpty(site.Name))
{
throw new ArgumentException("Site id or name is null or empty.");
}
this.CheckFtpServerBindings(site);
PropertyBag siteBag = this.ftpSitesService.GetSiteDefaults();
// Set site name
siteBag[FtpSiteGlobals.Site_Name] = site.Name;
// Set site physical path
siteBag[FtpSiteGlobals.VirtualDirectory_PhysicalPath] = site.ContentPath;
PropertyBag ftpBinding = new PropertyBag();
// Set site binding protocol
ftpBinding[FtpSiteGlobals.BindingProtocol] = "ftp";
// fill binding summary info
ftpBinding[FtpSiteGlobals.BindingInformation] = site.Bindings[0].ToString();
// Set site binding
siteBag[FtpSiteGlobals.Site_SingleBinding] = ftpBinding;
// Auto-start
siteBag[FtpSiteGlobals.FtpSite_AutoStart] = true;
// Set anonumous authentication
siteBag[FtpSiteGlobals.Authentication_AnonymousEnabled] = true;
siteBag[FtpSiteGlobals.Authentication_BasicEnabled] = true;
this.ftpSitesService.AddSite(siteBag);
AuthorizationRuleCollection rules = this.ftpSitesService.GetAuthorizationRuleCollection(site.Name);
rules.Add(AuthorizationRuleAccessType.Allow, "*", String.Empty, PermissionsFlags.Read);
IisFtpSite iisFtpSite = this.ftpSitesService.GetIisFtpSite(site.Name);
iisFtpSite.UserIsolation.Mode = Mode.StartInUsersDirectory;
iisFtpSite.Security.Ssl.ControlChannelPolicy = ControlChannelPolicy.SslAllow;
iisFtpSite.Security.Ssl.DataChannelPolicy = DataChannelPolicy.SslAllow;
this.FillIisFromFtpSite(site);
this.ftpSitesService.CommitChanges();
// Do not start the site because it is started during creation.
try
{
this.ChangeSiteState(site.Name, ServerState.Started);
}
catch
{
// Ignore the error if happened.
}
return site.Name;
}
/// <summary>
/// Updates site with given information.
/// </summary>
/// <param name="site">Ftp site.</param>
public void UpdateSite(FtpSite site)
{
// Check server bindings.
CheckFtpServerBindings(site);
this.FillIisFromFtpSite(site);
this.ftpSitesService.CommitChanges();
}
/// <summary>
/// Deletes site with specified name.
/// </summary>
/// <param name="siteId">Site's name to be deleted.</param>
public void DeleteSite(string siteId)
{
this.ftpSitesService.DeleteSite(siteId);
}
/// <summary>
/// Checks whether account with given name exists.
/// </summary>
/// <param name="accountName">Account name to check.</param>
/// <returns>true - if it exists; false - otherwise.</returns>
public bool AccountExists(string accountName)
{
if (String.IsNullOrEmpty(accountName))
{
return false;
}
switch (UserIsolationMode)
{
case Mode.ActiveDirectory:
return SecurityUtils.UserExists(accountName, ServerSettings, UsersOU);
default:
// check acocunt on FTP server
bool ftpExists = this.ftpSitesService.VirtualDirectoryExists(this.SiteId, accountName);
// check account in the system
bool systemExists = SecurityUtils.UserExists(accountName, ServerSettings, UsersOU);
return (ftpExists || systemExists);
}
}
/// <summary>
/// Gets available ftp accounts.
/// </summary>
/// <returns>List of avaialble accounts.</returns>
public FtpAccount[] GetAccounts()
{
switch (UserIsolationMode)
{
case Mode.ActiveDirectory:
return SecurityUtils.GetUsers(ServerSettings, UsersOU).Select(GetAccount).ToArray();
default:
List<FtpAccount> accounts = new List<FtpAccount>();
foreach (string directory in this.ftpSitesService.GetVirtualDirectoriesNames(this.SiteId))
{
// Skip root virtual directory
if (String.Equals(directory, "/"))
continue;
//
accounts.Add(this.GetAccount(directory.Substring(1)));
}
return accounts.ToArray();
}
}
/// <summary>
/// Gets account with given name.
/// </summary>
/// <param name="accountName">Account's name to get.</param>
/// <returns>Ftp account.</returns>
public FtpAccount GetAccount(string accountName)
{
switch (UserIsolationMode)
{
case Mode.ActiveDirectory:
var user = SecurityUtils.GetUser(accountName, ServerSettings, UsersOU);
var path = Path.Combine(user.MsIIS_FTPRoot, user.MsIIS_FTPDir);
var permission = GetUserPermission(accountName, path);
var account = new FtpAccount()
{
CanRead = permission.Read,
CanWrite = permission.Write,
Enabled = !user.AccountDisabled,
Folder = path,
Name = accountName
};
return account;
default:
FtpAccount acc = new FtpAccount();
acc.Name = accountName;
this.FillFtpAccountFromIis(acc);
return acc;
}
}
protected UserPermission GetUserPermission(string accountName, string folder)
{
var userPermission = new UserPermission {AccountName = accountName};
return SecurityUtils.GetGroupNtfsPermissions(folder, new[] {userPermission}, ServerSettings, UsersOU, GroupsOU)[0];
}
/// <summary>
/// Creates ftp account under root ftp site.
/// </summary>
/// <param name="account">Ftp account to create.</param>
public void CreateAccount(FtpAccount account)
{
switch (UserIsolationMode)
{
case Mode.ActiveDirectory:
SecurityUtils.EnsureOrganizationalUnitsExist(ServerSettings, UsersOU, GroupsOU);
var systemUser = SecurityUtils.GetUser(account.Name, ServerSettings, UsersOU);
if (systemUser == null)
{
systemUser = new SystemUser
{
Name = account.Name,
FullName = account.Name,
Password = account.Password,
PasswordCantChange = true,
PasswordNeverExpires = true,
System = true
};
SecurityUtils.CreateUser(systemUser, ServerSettings, UsersOU, GroupsOU);
}
UpdateAccount(account);
break;
default:
// Create user account.
SystemUser user = new SystemUser();
user.Name = account.Name;
user.FullName = account.Name;
user.Description = "WebsitePanel System Account";
user.MemberOf = new string[] {FtpGroupName};
user.Password = account.Password;
user.PasswordCantChange = true;
user.PasswordNeverExpires = true;
user.AccountDisabled = !account.Enabled;
user.System = true;
// Create in the operating system.
if (SecurityUtils.UserExists(user.Name, ServerSettings, UsersOU))
{
SecurityUtils.DeleteUser(user.Name, ServerSettings, UsersOU);
}
SecurityUtils.CreateUser(user, ServerSettings, UsersOU, GroupsOU);
// Prepare account's home folder.
this.EnsureUserHomeFolderExists(account.Folder, account.Name, account.CanRead, account.CanWrite);
// Future account will be given virtual directory under default ftp web site.
this.ftpSitesService.CreateFtpAccount(this.SiteId, account);
//
this.ftpSitesService.ConfigureConnectAs(account.Folder, this.SiteId, account.VirtualPath,
this.GetQualifiedAccountName(account.Name), account.Password, true);
break;
}
}
/// <summary>
/// Updates ftp account.
/// </summary>
/// <param name="account">Accoun to update.</param>
public void UpdateAccount(FtpAccount account)
{
var user = SecurityUtils.GetUser(account.Name, ServerSettings, UsersOU);
switch (UserIsolationMode)
{
case Mode.ActiveDirectory:
var ftpRoot = AdFtpRoot.ToLower();
var ftpDir = account.Folder.ToLower().Replace(ftpRoot, "");
var oldDir = user.MsIIS_FTPDir;
user.Password = account.Password;
user.PasswordCantChange = true;
user.PasswordNeverExpires = true;
user.Description = "WebsitePanel FTP Account with AD User Isolation";
user.MemberOf = new[] {FtpGroupName};
user.AccountDisabled = !account.Enabled;
user.MsIIS_FTPRoot = ftpRoot;
user.MsIIS_FTPDir = ftpDir;
user.System = true;
SecurityUtils.UpdateUser(user, ServerSettings, UsersOU, GroupsOU);
// Set NTFS permissions
var userPermission = GetUserPermission(account.Name, account.Folder);
// Do we need to change the NTFS permissions? i.e. is users home dir changed or are permissions changed?
if (oldDir != ftpDir || account.CanRead != userPermission.Read || account.CanWrite != userPermission.Write)
{
// First get sid of user account
var sid = SecurityUtils.GetAccountSid(account.Name, ServerSettings, UsersOU, GroupsOU);
// Remove the permissions set for this account on previous folder
SecurityUtils.RemoveNtfsPermissionsBySid(Path.Combine(ftpRoot, oldDir), sid);
// If no permissions is to be set, exit
if (!account.CanRead && !account.CanWrite)
{
return;
}
// Add the new permissions
var ntfsPermissions = account.CanRead ? NTFSPermission.Read : NTFSPermission.Write;
if (account.CanRead && account.CanWrite)
{
ntfsPermissions = NTFSPermission.Modify;
}
SecurityUtils.GrantNtfsPermissionsBySid(account.Folder, sid, ntfsPermissions, true, true);
}
break;
default:
// Change user account state and password (if required).
user.Password = account.Password;
user.AccountDisabled = !account.Enabled;
SecurityUtils.UpdateUser(user, ServerSettings, UsersOU, GroupsOU);
// Update iis configuration.
this.FillIisFromFtpAccount(account);
break;
}
}
/// <summary>
/// Deletes account with given name.
/// </summary>
/// <param name="accountName">Account's name to be deleted.</param>
public void DeleteAccount(string accountName)
{
switch (UserIsolationMode)
{
case Mode.ActiveDirectory:
var account = GetAccount(accountName);
// Remove the NTFS permissions first
SecurityUtils.RemoveNtfsPermissions(account.Folder, account.Name, ServerSettings, UsersOU, GroupsOU);
if (SecurityUtils.UserExists(accountName, ServerSettings, UsersOU))
{
SecurityUtils.DeleteUser(accountName, ServerSettings, UsersOU);
}
break;
default:
string virtualDirectory = String.Format("/{0}", accountName);
string currentPhysicalPath = this.ftpSitesService.GetSitePhysicalPath(this.SiteId, virtualDirectory);
// Delete virtual directory
this.ftpSitesService.DeleteFtpAccount(this.SiteId, virtualDirectory);
this.ftpSitesService.CommitChanges();
// Remove permissions
RemoveFtpFolderPermissions(currentPhysicalPath, accountName);
// Delete system user account
if (SecurityUtils.UserExists(accountName, ServerSettings, UsersOU))
{
SecurityUtils.DeleteUser(accountName, ServerSettings, UsersOU);
}
break;
}
}
/// <summary>
/// Fills iis configuration from ftp account.
/// </summary>
/// <param name="ftpAccount">Ftp account to fill from.</param>
private void FillIisFromFtpAccount(FtpAccount ftpAccount)
{
// Remove permissions if required.
string currentPhysicalPath = this.ftpSitesService.GetSitePhysicalPath(this.SiteId, String.Format("/{0}", ftpAccount.Name));
if (String.Compare(currentPhysicalPath, ftpAccount.Folder, true) != 0)
{
RemoveFtpFolderPermissions(currentPhysicalPath, ftpAccount.Name);
}
// Set new permissions
EnsureUserHomeFolderExists(ftpAccount.Folder, ftpAccount.Name, ftpAccount.CanRead, ftpAccount.CanWrite);
// Update physical path.
this.ftpSitesService.SetSitePhysicalPath(this.SiteId, ftpAccount.VirtualPath, ftpAccount.Folder);
// Configure connect as feature.
this.ftpSitesService.ConfigureConnectAs(ftpAccount.Folder, this.SiteId, ftpAccount.VirtualPath,
this.GetQualifiedAccountName(ftpAccount.Name), ftpAccount.Password, false);
// Update authorization rules.
AuthorizationRuleCollection authRulesCollection = this.ftpSitesService.GetAuthorizationRuleCollection(String.Format("{0}/{1}", this.SiteId, ftpAccount.Name));
AuthorizationRule realtedRule = null;
foreach(AuthorizationRule rule in authRulesCollection)
{
IList<string> users = rule.Users.Split(',');
if (users.Contains(ftpAccount.Name))
{
realtedRule = rule;
}
}
if (realtedRule != null)
{
PermissionsFlags permissions = 0;
if (ftpAccount.CanRead)
{
permissions |= PermissionsFlags.Read;
}
if (ftpAccount.CanWrite)
{
permissions |= PermissionsFlags.Write;
}
if (ftpAccount.CanRead || ftpAccount.CanWrite)
{
realtedRule.Permissions = permissions;
}
}
this.ftpSitesService.CommitChanges();
}
/// <summary>
/// Fills ftp account from iis configuration.
/// </summary>
/// <param name="ftpAccount">Ftp account to fill.</param>
private void FillFtpAccountFromIis(FtpAccount ftpAccount)
{
//
ftpAccount.Folder = this.ftpSitesService.GetSitePhysicalPath(this.SiteId, String.Format("/{0}", ftpAccount.Name));
AuthorizationRuleCollection authRulesCollection = this.ftpSitesService.GetAuthorizationRuleCollection(String.Format("{0}/{1}", this.SiteId, ftpAccount.Name));
ftpAccount.CanRead = false;
ftpAccount.CanWrite = false;
foreach(AuthorizationRule rule in authRulesCollection)
{
if (rule.AccessType == AuthorizationRuleAccessType.Allow)
{
foreach(string userName in rule.Users.Split(','))
{
if (String.Compare(userName, ftpAccount.Name, true) == 0)
{
ftpAccount.CanWrite = (rule.Permissions & PermissionsFlags.Write) == PermissionsFlags.Write;
ftpAccount.CanRead = (rule.Permissions & PermissionsFlags.Read) == PermissionsFlags.Read;
}
}
}
}
// Load user account.
SystemUser user = SecurityUtils.GetUser(ftpAccount.Name, ServerSettings, UsersOU);
if (user != null)
{
ftpAccount.Enabled = !user.AccountDisabled;
}
}
/// <summary>
/// Fills ftp site with data from iis ftp site.
/// </summary>
/// <param name="ftpSite">Ftp site to fill.</param>
private void FillFtpSiteFromIis(FtpSite ftpSite)
{
IisFtpSite iisFtpSite = this.ftpSitesService.GetIisFtpSite(ftpSite.SiteId);
if (iisFtpSite != null)
{
// Security settings.
ftpSite.AllowAnonymous = iisFtpSite.Security.Authentication.AnonymousAuthentication.Enabled;
ftpSite.AnonymousUsername = iisFtpSite.Security.Authentication.AnonymousAuthentication.UserName;
ftpSite.AnonymousUserPassword = iisFtpSite.Security.Authentication.AnonymousAuthentication.Password;
ftpSite["UserIsolationMode"] = iisFtpSite.UserIsolation.Mode.ToString();
// Logging settings.
ftpSite[FtpSite.MSFTP7_SITE_ID] = iisFtpSite.SiteServiceId;
if (iisFtpSite.LogFile.Enabled)
{
ftpSite.LogFileDirectory = iisFtpSite.LogFile.Directory;
ftpSite[FtpSite.MSFTP7_LOG_EXT_FILE_FIELDS] = iisFtpSite.LogFile.LogExtFileFlags.ToString();
}
}
// Bindings
ftpSite.Bindings = this.ftpSitesService.GetSiteBindings(ftpSite.SiteId);
// Physical path
ftpSite.ContentPath = this.ftpSitesService.GetSitePhysicalPath(ftpSite.SiteId, "/");
}
/// <summary>
/// Fills iis configuration with information from ftp site.
/// </summary>
/// <param name="ftpSite">Ftp site that holds information.</param>
private void FillIisFromFtpSite(FtpSite ftpSite)
{
IisFtpSite iisFtpSite = this.ftpSitesService.GetIisFtpSite(ftpSite.SiteId);
string logExtFileFields = ftpSite[FtpSite.MSFTP7_LOG_EXT_FILE_FIELDS];
if (iisFtpSite != null)
{
// Security settings.
iisFtpSite.Security.Authentication.AnonymousAuthentication.Enabled = ftpSite.AllowAnonymous;
iisFtpSite.Security.Authentication.AnonymousAuthentication.UserName = ftpSite.AnonymousUsername;
iisFtpSite.Security.Authentication.AnonymousAuthentication.Password = ftpSite.AnonymousUserPassword;
// enable logging
iisFtpSite.LogFile.Enabled = true;
// set logging fields
if (!String.IsNullOrEmpty(logExtFileFields))
iisFtpSite.LogFile.LogExtFileFlags = (FtpLogExtFileFlags)Enum.Parse(typeof(FtpLogExtFileFlags), logExtFileFields);
// set log files directory
if (!String.IsNullOrEmpty(ftpSite.LogFileDirectory))
iisFtpSite.LogFile.Directory = ftpSite.LogFileDirectory;
}
// Set new bindings.
this.CheckFtpServerBindings(ftpSite);
this.ftpSitesService.SetSiteBindings(ftpSite.Name, ftpSite.Bindings);
// Physical path
this.ftpSitesService.SetSitePhysicalPath(ftpSite.SiteId, "/", ftpSite.ContentPath);
}
/// <summary>
/// Ensures that home folder for ftp account exists.
/// </summary>
/// <param name="folder">Path to home folder.</param>
/// <param name="accountName">Account name.</param>
/// <param name="allowRead">A value which specifies whether read operation is allowed or not.</param>
/// <param name="allowWrite">A value which specifies whether write operation is allowed or not.</param>
private void EnsureUserHomeFolderExists(string folder, string accountName, bool allowRead, bool allowWrite)
{
// create folder
if (!FileUtils.DirectoryExists(folder))
{
FileUtils.CreateDirectory(folder);
}
if (!allowRead && !allowWrite)
{
return;
}
NTFSPermission permissions = allowRead ? NTFSPermission.Read : NTFSPermission.Write;
if (allowRead && allowWrite)
{
permissions = NTFSPermission.Modify;
}
// Set ntfs permissions
SecurityUtils.GrantNtfsPermissions(folder, accountName, permissions, true, true,
ServerSettings, UsersOU, GroupsOU);
}
/// <summary>
/// Removes user specific permissions from folder.
/// </summary>
/// <param name="path">Folder to operate on.</param>
/// <param name="accountName">User's name.</param>
private void RemoveFtpFolderPermissions(string path, string accountName)
{
if (!FileUtils.DirectoryExists(path))
{
return;
}
// Anonymous account
SecurityUtils.RemoveNtfsPermissions(path, accountName, ServerSettings, UsersOU, GroupsOU);
}
/// <summary>
/// Checks if bindings listed in given site already in use.
/// </summary>
/// <param name="site">Site to check.</param>
/// <exception cref="InvalidOperationException">Is thrown in case supplied site contains bindings that are already in use.</exception>
private void CheckFtpServerBindings(FtpSite site)
{
if (this.IsFtpServerBindingsInUse(site))
{
throw new InvalidOperationException("Some of ftp site's bindings are already in use.");
}
}
/// <summary>
/// Gets a value which shows whether supplied site contains bindings that are already in use.
/// </summary>
/// <param name="site">Site to check.</param>
/// <returns>true - if any of supplied bindinds is in use; false -otherwise.</returns>
private bool IsFtpServerBindingsInUse(FtpSite site)
{
if (site == null)
{
throw new ArgumentNullException("site");
}
// check for server bindings
foreach (FtpSite existentSite in this.GetSites())
{
if (existentSite.Name != site.Name)
{
foreach (ServerBinding usedBinding in existentSite.Bindings)
{
foreach (ServerBinding requestedBinding in site.Bindings)
{
if (usedBinding.IP == requestedBinding.IP && usedBinding.Port == usedBinding.Port)
{
return true;
}
}
}
}
}
return false;
}
/// <summary>
/// Gets fully qualified name with respect to enabled active directory.
/// </summary>
/// <param name="accountName">Account name.</param>
/// <returns>Fully qualified acount/domain name.</returns>
private string GetQualifiedAccountName(string accountName)
{
if (!ServerSettings.ADEnabled)
{
return accountName;
}
if (accountName.IndexOf("\\") != -1)
{
return accountName; // already has domain information
}
// DO IT FOR ACTIVE DIRECTORY MODE ONLY
string domainName = null;
try
{
DirectoryContext objContext = new DirectoryContext(DirectoryContextType.Domain, ServerSettings.ADRootDomain);
Domain objDomain = Domain.GetDomain(objContext);
domainName = objDomain.Name;
}
catch (Exception ex)
{
Log.WriteError("Get domain name error", ex);
}
return domainName != null ? domainName + "\\" + accountName : accountName;
}
#endregion
#region IHostingServiceProvier methods
/// <summary>
/// Installs Ftp7 provider.
/// </summary>
/// <returns>Error messages.</returns>
public override string[] Install()
{
List<string> messages = new List<string>();
FtpSite site = null;
string folder = FileUtils.EvaluateSystemVariables(DefaultFtpSiteFolder);
string logsDirectory = FileUtils.EvaluateSystemVariables(DefaultFtpSiteLogsFolder);
// Create site folder.
if (!FileUtils.DirectoryExists(folder))
{
FileUtils.CreateDirectory(folder);
}
// Create logs folder.
if (!FileUtils.DirectoryExists(logsDirectory))
{
FileUtils.CreateDirectory(logsDirectory);
}
site = new FtpSite();
site.Name = this.SiteId;
site.SiteId = this.SiteId;
site.ContentPath = DefaultFtpSiteFolder;
site.Bindings = new ServerBinding[1];
// set default log directory
site.LogFileDirectory = DefaultFtpSiteLogsFolder;
// set default logging fields
site[FtpSite.MSFTP7_LOG_EXT_FILE_FIELDS] = DEFAULT_LOG_EXT_FILE_FIELDS;
if (!String.IsNullOrEmpty(this.SharedIP))
{
site.Bindings[0] = new ServerBinding(this.SharedIP, "21", String.Empty);
}
else
{
site.Bindings[0] = new ServerBinding("*", "21", "*");
//// Get information on local server.
//IPHostEntry localServerHostEntry = Dns.GetHostEntry(Dns.GetHostName());
//foreach (IPAddress address in localServerHostEntry.AddressList)
//{
// if (address.AddressFamily == AddressFamily.InterNetwork)
// {
// site.Bindings[0] = new ServerBinding(address.ToString(), "21", String.Empty);
// }
//}
}
if (this.IsFtpServerBindingsInUse(site))
{
messages.Add("Cannot create ftp site because requested bindings are already in use.");
return messages.ToArray();
}
try
{
SecurityUtils.EnsureOrganizationalUnitsExist(ServerSettings, UsersOU, GroupsOU);
}
catch (Exception ex)
{
messages.Add(String.Format("Could not check/create Organizational Units: {0}", ex.Message));
return messages.ToArray();
}
// create folder if it not exists
if (String.IsNullOrEmpty(SiteId))
{
messages.Add("Please, select FTP site to create accounts on");
}
else
{
// create FTP group name
if (String.IsNullOrEmpty(FtpGroupName))
{
messages.Add("FTP Group can not be blank");
}
else
{
try
{
// create group
if (!SecurityUtils.GroupExists(FtpGroupName, ServerSettings, GroupsOU))
{
SystemGroup group = new SystemGroup();
group.Name = FtpGroupName;
group.Members = new string[] { };
group.Description = "WebsitePanel System Group";
SecurityUtils.CreateGroup(group, ServerSettings, UsersOU, GroupsOU);
}
}
catch (Exception ex)
{
messages.Add(String.Format("There was an error while adding '{0}' group: {1}",
FtpGroupName, ex.Message));
return messages.ToArray();
}
}
if (!this.ftpSitesService.SiteExists(this.SiteId))
{
this.CreateSite(site);
}
else
{
this.UpdateSite(site);
}
try
{
// set permissions on the site root
SecurityUtils.GrantNtfsPermissions(site.ContentPath, FtpGroupName,
NTFSPermission.Read, true, true, ServerSettings,
UsersOU, GroupsOU);
}
catch (Exception ex)
{
messages.Add(String.Format("Can not set permissions on '{0}' folder: {1}",
site.ContentPath, ex.Message));
return messages.ToArray();
}
}
return messages.ToArray();
}
public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
{
foreach (ServiceProviderItem item in items)
{
if (item is FtpAccount)
{
try
{
// make FTP account read-only
FtpAccount account = GetAccount(item.Name);
account.Enabled = enabled;
UpdateAccount(account);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
}
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
if (item is FtpAccount)
{
try
{
// delete FTP account from default FTP site
DeleteAccount(item.Name);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
}
public override ServiceProviderItemBandwidth[] GetServiceItemsBandwidth(ServiceProviderItem[] items, DateTime since)
{
ServiceProviderItemBandwidth[] itemsBandwidth = new ServiceProviderItemBandwidth[items.Length];
// calculate bandwidth for Default FTP Site
FtpSite ftpSite = GetSite(SiteId);
string siteId = String.Concat("FTPSVC", ftpSite[FtpSite.MSFTP7_SITE_ID]);
string logsPath = Path.Combine(ftpSite.LogFileDirectory, siteId);
// create parser object
// and update statistics
LogParser parser = new LogParser("Ftp", siteId, logsPath, "s-sitename", "cs-username");
// Subscribe to the events because FTP 7.0 has several differences that should be taken into account
// and processed in a specific way
parser.ProcessKeyFields += new ProcessKeyFieldsEventHandler(LogParser_ProcessKeyFields);
parser.CalculateStatisticsLine += new CalculateStatsLineEventHandler(LogParser_CalculateStatisticsLine);
//
parser.ParseLogs();
// update items with diskspace
for (int i = 0; i < items.Length; i++)
{
ServiceProviderItem item = items[i];
// create new bandwidth object
itemsBandwidth[i] = new ServiceProviderItemBandwidth();
itemsBandwidth[i].ItemId = item.Id;
itemsBandwidth[i].Days = new DailyStatistics[0];
if (item is FtpAccount)
{
try
{
// get daily statistics
itemsBandwidth[i].Days = parser.GetDailyStatistics(since, new string[] { siteId, item.Name });
}
catch (Exception ex)
{
Log.WriteError(ex);
}
}
}
return itemsBandwidth;
}
#endregion
#region LogParser event handlers and helper routines
private bool IsFtpServiceCommand(string command)
{
return (Array.IndexOf(FTP70_SERVICE_CMD_LIST, command) > -1);
}
private void LogParser_ProcessKeyFields(string[] key_fields, string[] key_values, string[] log_fields,
string[] log_values)
{
int cs_method = Array.IndexOf(log_fields, "cs-method");
int cs_uri_stem = Array.IndexOf(log_fields, "cs-uri-stem");
int cs_username = Array.IndexOf(key_fields, "cs-username");
//
if (cs_username > -1)
{
string valueStr = EMPTY_LOG_FIELD;
// this trick allows to calculate USER command bytes as well
// in spite that "cs-username" field is empty for the command
if (key_values[cs_username] != EMPTY_LOG_FIELD)
valueStr = key_values[cs_username];
else if (cs_method > -1 && cs_uri_stem > -1 && log_values[cs_method] == "USER")
valueStr = log_values[cs_uri_stem];
//
key_values[cs_username] = valueStr.Substring(valueStr.IndexOf(@"\") + 1);
}
}
private void LogParser_CalculateStatisticsLine(StatsLine line, string[] fields, string[] values)
{
int cs_method = Array.IndexOf(fields, "cs-method");
// bandwidth calculation ignores FTP 7.0 serviced commands
if (cs_method > -1 && !IsFtpServiceCommand(values[cs_method]))
{
int cs_bytes = Array.IndexOf(fields, "cs-bytes");
int sc_bytes = Array.IndexOf(fields, "sc-bytes");
// skip empty cs-bytes value processing
if (cs_bytes > -1 && values[cs_bytes] != "0")
line.BytesReceived += Int64.Parse(values[cs_bytes]);
// skip empty sc-bytes value processing
if (sc_bytes > -1 && values[sc_bytes] != "0")
line.BytesSent += Int64.Parse(values[sc_bytes]);
}
}
#endregion
protected virtual bool IsMsFTPInstalled()
{
int value = 0;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\InetStp");
if (rk != null)
{
value = (int)rk.GetValue("MajorVersion", null);
rk.Close();
}
RegistryKey ftp = root.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\ftpsvc");
bool res = (value == 7) && ftp != null;
if (ftp != null)
ftp.Close();
return res;
}
public override bool IsInstalled()
{
return IsMsFTPInstalled();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/16/2009 12:11:19 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections.Generic;
using System.Data;
using DotSpatial.NTSExtension;
using DotSpatial.Serialization;
using GeoAPI.Geometries;
using GeoAPI.Operation.Buffer;
using NetTopologySuite.Operation.Buffer;
namespace DotSpatial.Data
{
/// <summary>
/// Extension Methods for the Features
/// </summary>
public static class FeatureExt
{
///// <summary>
///// Calculates the area of the geometric portion of this feature. This is 0 unless the feature
///// is a polygon, or multi-polygon.
///// </summary>
///// <param name="self">The feature to test</param>
///// <returns>The double valued area</returns>
//public static double Area(this IFeature self)
//{
// return Geometry.FromBasicGeometry(self.Geometry).Area;
//}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance)
{
IGeometry g = self.Geometry.Buffer(distance);
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance, EndCapStyle endCapStyle)
{
IGeometry g = self.Geometry.Buffer(distance, new BufferParameters { EndCapStyle = endCapStyle });
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments)
{
IGeometry g = self.Geometry.Buffer(distance, quadrantSegments);
return new Feature(g);
}
/// <summary>
/// Generates a new feature from the buffer of this feature. The DataRow of
/// the new feature will be null.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="distance">The double distance</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <returns>An IFeature representing the output from the buffer operation</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, EndCapStyle endCapStyle)
{
IGeometry g = self.Geometry.Buffer(distance, quadrantSegments, endCapStyle);
return new Feature(g);
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, EndCapStyle endCapStyle, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, endCapStyle);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, quadrantSegments);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
/// <summary>
/// Generates a buffer, but also adds the newly created feature to the specified output featureset.
/// This will also compare the field names of the input featureset with the destination featureset.
/// If a column name exists in both places, it will copy those values to the destination featureset.
/// </summary>
/// <param name="self">The feature to calcualate the buffer for.</param>
/// <param name="distance">The double distance to use for calculating the buffer</param>
/// <param name="quadrantSegments">The number of segments to use to approximate a quadrant of a circle</param>
/// <param name="endCapStyle">The end cap style to use</param>
/// <param name="destinationFeatureset">The output featureset to add this feature to and use
/// as a reference for determining which data columns to copy.</param>
/// <returns>The IFeature that represents the buffer feature.</returns>
public static IFeature Buffer(this IFeature self, double distance, int quadrantSegments, EndCapStyle endCapStyle, IFeatureSet destinationFeatureset)
{
IFeature f = Buffer(self, distance, quadrantSegments, endCapStyle);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
///// <summary>
///// Returns a feature constructed from the centroid of this feature
///// </summary>
///// <param name="self">This feature</param>
///// <returns>An IFeature that is also a point geometry</returns>
//public static IFeature Centroid(this IFeature self)
//{
// return new Feature(Geometry.FromBasicGeometry(self.Geometry).Centroid);
//}
///// <summary>
///// Gets a boolean that is true if this feature contains the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The other feature to test</param>
///// <returns>Boolean, true if this feature contains the other feature</returns>
//public static bool Contains(this IFeature self, IFeature other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).Contains(Geometry.FromBasicGeometry(other.Geometry));
//}
///// <summary>
///// Gets a boolean that is true if this feature contains the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The other feature to test</param>
///// <returns>Boolean, true if this feature contains the other feature</returns>
//public static bool Contains(this IFeature self, IGeometry other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).Contains(other);
//}
/// <summary>
/// Calculates a new feature that has a geometry that is the convex hull of this feature.
/// </summary>
/// <param name="self">This feature</param>
/// <returns>A new feature that is the convex hull of this feature.</returns>
public static IFeature ConvexHull(this IFeature self)
{
return new Feature(self.Geometry.ConvexHull());
}
/// <summary>
/// Calculates a new feature that has a geometry that is the convex hull of this feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="destinationFeatureset">The destination featureset to add this feature to</param>
/// <returns>The newly created IFeature</returns>
public static IFeature ConvexHull(this IFeature self, IFeatureSet destinationFeatureset)
{
IFeature f = ConvexHull(self);
destinationFeatureset.Features.Add(f);
foreach (DataColumn dc in destinationFeatureset.DataTable.Columns)
{
if (self.DataRow[dc.ColumnName] != null)
{
f.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
return f;
}
///// <summary>
///// Gets a boolean that is true if the geometry of this feature is covered by the geometry
///// of the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The feature to compare this feature to</param>
///// <returns>Boolean, true if this feature is covered by the specified feature</returns>
//public static bool CoveredBy(this IFeature self, IFeature other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).CoveredBy(Geometry.FromBasicGeometry(other));
//}
///// <summary>
///// Gets a boolean that is true if the geometry of this feature is covered by the geometry
///// of the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The feature to compare this feature to</param>
///// <returns>Boolean, true if this feature is covered by the specified feature</returns>
//public static bool CoveredBy(this IFeature self, IGeometry other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).CoveredBy((other));
//}
///// <summary>
///// Gets a boolean that is true if the geometry of this feature covers the geometry
///// of the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The feature to compare this feature to</param>
///// <returns>Boolean, true if this feature covers the specified feature</returns>
//public static bool Covers(this IFeature self, IFeature other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).Covers(Geometry.FromBasicGeometry(other));
//}
///// <summary>
///// Gets a boolean that is true if the geometry of this feature covers the geometry
///// of the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The feature to compare this feature to</param>
///// <returns>Boolean, true if this feature covers the specified feature</returns>
//public static bool Covers(this IFeature self, IGeometry other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).Covers(other);
//}
///// <summary>
///// Gets a boolean that is true if the geometry of this feature crosses the geometry
///// of the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The feature to compare this feature to</param>
///// <returns>Boolean, true if this feature crosses the specified feature</returns>
//public static bool Crosses(this IFeature self, IFeature other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).Crosses(Geometry.FromBasicGeometry(other));
//}
///// <summary>
///// Gets a boolean that is true if the geometry of this feature crosses the geometry
///// of the specified feature
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The feature to compare this feature to</param>
///// <returns>Boolean, true if this feature crosses the specified feature</returns>
//public static bool Crosses(this IFeature self, IGeometry other)
//{
// return Geometry.FromBasicGeometry(self.Geometry).Crosses(other);
//}
///// <summary>
///// Creates a new Feature that has a geometry that is the difference between this feature and the specified feature.
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The other feature to compare to.</param>
///// <returns>A new feature that is the geometric difference between this feature and the specified feature.</returns>
//public static IFeature Difference(this IFeature self, IFeature other)
//{
// if (other == null) return self.Copy();
// IGeometry g = Geometry.FromBasicGeometry(self.Geometry).Difference(Geometry.FromBasicGeometry(other.Geometry));
// if (g == null) return null;
// if (g.IsEmpty) return null;
// return new Feature(g);
//}
/// <summary>
/// Creates a new Feature that has a geometry that is the difference between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric difference between this feature and the specified feature.</returns>
public static IFeature Difference(this IFeature self, IGeometry other)
{
if (other == null) return self.Copy();
IGeometry g = self.Geometry.Difference(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the difference between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric difference between this feature and the specified feature.</returns>
public static IFeature Difference(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Difference(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
// This handles the slightly complex business of attribute outputs.
private static void UpdateFields(IFeature self, IFeature other, IFeature result, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
if (destinationFeatureSet.FeatureType != result.FeatureType) return;
destinationFeatureSet.Features.Add(result);
if (joinType == FieldJoinType.None) return;
if (joinType == FieldJoinType.All)
{
// This overly complex mess is concerned with preventing duplicate field names.
// This assumes that numbers were appended when duplicates occured, and will
// repeat the process here to establish one set of string names and values.
Dictionary<string, object> mappings = new Dictionary<string, object>();
foreach (DataColumn dc in self.ParentFeatureSet.DataTable.Columns)
{
string name = dc.ColumnName;
int i = 1;
while (mappings.ContainsKey(name))
{
name = dc.ColumnName + i;
i++;
}
mappings.Add(name, self.DataRow[dc.ColumnName]);
}
foreach (DataColumn dc in other.ParentFeatureSet.DataTable.Columns)
{
string name = dc.ColumnName;
int i = 1;
while (mappings.ContainsKey(name))
{
name = dc.ColumnName + i;
i++;
}
mappings.Add(name, other.DataRow[dc.ColumnName]);
}
foreach (KeyValuePair<string, object> pair in mappings)
{
if (!result.DataRow.Table.Columns.Contains(pair.Key))
{
result.DataRow.Table.Columns.Add(pair.Key);
}
result.DataRow[pair.Key] = pair.Value;
}
}
if (joinType == FieldJoinType.LocalOnly)
{
foreach (DataColumn dc in destinationFeatureSet.DataTable.Columns)
{
if (self.DataRow.Table.Columns.Contains(dc.ColumnName))
{
result.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
}
if (joinType == FieldJoinType.ForeignOnly)
{
foreach (DataColumn dc in destinationFeatureSet.DataTable.Columns)
{
if (other.DataRow[dc.ColumnName] != null)
{
result.DataRow[dc.ColumnName] = self.DataRow[dc.ColumnName];
}
}
}
}
// /// <summary>
// /// Gets a boolean that is true if the geometry of this feature is disjoint with the geometry
// /// of the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns>Boolean, true if this feature is disjoint with the specified feature</returns>
// public static bool Disjoint(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Disjoint(Geometry.FromBasicGeometry(other));
// }
// /// <summary>
// /// Gets a boolean that is true if the geometry of this feature is disjoint with the geometry
// /// of the specified feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns>Boolean, true if this feature is disjoint with the specified feature</returns>
// public static bool Disjoint(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Disjoint(other);
// }
// /// <summary>
// /// Distance between features.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns></returns>
// public static double Distance(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Distance(Geometry.FromBasicGeometry(other));
// }
// /// <summary>
// /// Gets a boolean that is true if the geometry of this feature is disjoint with the geometry
// /// of the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The feature to compare this feature to</param>
// /// <returns>Boolean, true if this feature is disjoint with the specified feature</returns>
// public static double Distance(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Distance(other);
// }
// /// <summary>
// /// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to compare to.</param>
// /// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
// public static IFeature Intersection(this IFeature self, IFeature other)
// {
// IGeometry g = Geometry.FromBasicGeometry(self.Geometry).Intersection(Geometry.FromBasicGeometry(other.Geometry));
// if (g == null) return null;
// if (g.IsEmpty) return null;
// return new Feature(g);
// }
/// <summary>
/// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
public static IFeature Intersection(this IFeature self, IGeometry other)
{
IGeometry g = self.Geometry.Intersection(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the intersection between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric intersection between this feature and the specified feature.</returns>
public static IFeature Intersection(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Intersection(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
// /// <summary>
// /// Gets a boolean that is true if this feature intersects the other feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if the two IFeatures intersect</returns>
// public static bool Intersects(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Intersects(Geometry.FromBasicGeometry(other.Geometry));
// }
// /// <summary>
// /// Gets a boolean that is true if this feature intersects the other feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if the two IFeatures intersect</returns>
// public static bool Intersects(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Intersects(other);
// }
// /// <summary>
// /// This tests the current feature to see if the geometry intersects with the specified
// /// coordinate.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="coordinate">The coordinate</param>
// /// <returns>Boolean if the coordinate intersects with this feature</returns>
// public static bool Intersects(this IFeature self, Coordinate coordinate)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Intersects(new Point(coordinate));
// }
// /// <summary>
// /// Gets a boolean that is true if this feature is within the specified distance of the other feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <param name="distance">The double distance criteria</param>
// /// <returns>Boolean, true if the other feature is within the specified distance of this feature</returns>
// public static bool IsWithinDistance(this IFeature self, IFeature other, double distance)
// {
// return Geometry.FromBasicGeometry(self.Geometry).IsWithinDistance(Geometry.FromBasicGeometry(other.Geometry), distance);
// }
// /// <summary>
// /// Gets a boolean that is true if this feature is within the specified distance of the other feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <param name="distance">The double distance criteria</param>
// /// <returns>Boolean, true if the other feature is within the specified distance of this feature</returns>
// public static bool IsWithinDistance(this IFeature self, IGeometry other, double distance)
// {
// return Geometry.FromBasicGeometry(self.Geometry).IsWithinDistance(other, distance);
// }
// /// <summary>
// /// Gets a boolean that is true if this feature overlaps the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if the two IFeatures overlap</returns>
// public static bool Overlaps(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Overlaps(Geometry.FromBasicGeometry(other.Geometry));
// }
// /// <summary>
// /// Gets a boolean that is true if this feature overlaps the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if the two IFeatures overlap</returns>
// public static bool Overlaps(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Overlaps(other);
// }
// /// <summary>
// /// Gets a boolean that is true if the relationship between this feature and the other feature
// /// matches the relationship matrix specified by other
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <param name="intersectionPattern">The string relationship pattern to test</param>
// /// <returns>Boolean, true if the other feature's relationship to this feature matches the relate expression.</returns>
// public static bool Relates(this IFeature self, IFeature other, string intersectionPattern)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Relate(Geometry.FromBasicGeometry(other.Geometry), intersectionPattern);
// }
// /// <summary>
// /// Gets a boolean that is true if the relationship between this feature and the other feature
// /// matches the relationship matrix specified by other
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <param name="intersectionPattern">The string relationship pattern to test</param>
// /// <returns>Boolean, true if the other feature's relationship to this feature matches the relate expression.</returns>
// public static bool Relates(this IFeature self, IGeometry other, string intersectionPattern)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Relate(other, intersectionPattern);
// }
/// <summary>
/// Rotates the BasicGeometry of the feature by the given radian angle around the given Origin.
/// </summary>
/// <param name="self">This feature.</param>
/// <param name="origin">The coordinate the feature gets rotated around.</param>
/// <param name="radAngle">The rotation angle in radian.</param>
public static void Rotate(this IFeature self, Coordinate origin, double radAngle)
{
IGeometry geo = self.Geometry.Copy();
geo.Rotate(origin, radAngle);
self.Geometry = geo;
self.UpdateEnvelope();
}
// /// <summary>
// /// Creates a new Feature that has a geometry that is the symmetric difference between this feature and the specified feature.
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to compare to.</param>
// /// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
// public static IFeature SymmetricDifference(this IFeature self, IFeature other)
// {
// IGeometry g = Geometry.FromBasicGeometry(self.Geometry).SymmetricDifference(Geometry.FromBasicGeometry(other.Geometry));
// if (g == null) return null;
// if (g.IsEmpty) return null;
// return new Feature(g);
// }
/// <summary>
/// Creates a new Feature that has a geometry that is the symmetric difference between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature SymmetricDifference(this IFeature self, IGeometry other)
{
IGeometry g = self.Geometry.SymmetricDifference(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the symmetric difference between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">This clarifies the overall join strategy being used with regards to attribute fields.</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature SymmetricDifference(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = SymmetricDifference(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
// /// <summary>
// /// Gets a boolean that is true if this feature touches the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if the two IFeatures touch</returns>
// public static bool Touches(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Touches(Geometry.FromBasicGeometry(other.Geometry));
// }
// /// <summary>
// /// Gets a boolean that is true if this feature touches the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if the two IFeatures touch</returns>
// public static bool Touches(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Touches(other);
// }
///// <summary>
///// Creates a new Feature that has a geometry that is the union between this feature and the specified feature.
///// </summary>
///// <param name="self">This feature</param>
///// <param name="other">The other feature to compare to.</param>
///// <returns>A new feature that is the geometric union between this feature and the specified feature.</returns>
//public static IFeature Union(this IFeature self, IFeature other)
//{
// IGeometry g = self.Geometry.Union(other.Geometry);
// if (g == null || g.IsEmpty) return null;
// return new Feature(g);
//}
/// <summary>
/// Creates a new Feature that has a geometry that is the union between this feature and the specified feature.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <returns>A new feature that is the geometric union between this feature and the specified feature.</returns>
public static IFeature Union(this IFeature self, IGeometry other)
{
IGeometry g = self.Geometry.Union(other);
if (g == null || g.IsEmpty) return null;
return new Feature(g);
}
/// <summary>
/// Creates a new Feature that has a geometry that is the union between this feature and the specified feature.
/// This also copies the attributes that are shared between this featureset and the
/// specified destination featureset, and adds this feature to the destination featureset.
/// </summary>
/// <param name="self">This feature</param>
/// <param name="other">The other feature to compare to.</param>
/// <param name="destinationFeatureSet">The featureset to add the new feature to.</param>
/// <param name="joinType">Clarifies how the attributes should be handled during the union</param>
/// <returns>A new feature that is the geometric symmetric difference between this feature and the specified feature.</returns>
public static IFeature Union(this IFeature self, IFeature other, IFeatureSet destinationFeatureSet, FieldJoinType joinType)
{
IFeature f = Union(self, other.Geometry);
if (f != null)
{
UpdateFields(self, other, f, destinationFeatureSet, joinType);
}
return f;
}
// /// <summary>
// /// Gets a boolean that is true if this feature is within the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if this feature is within the specified feature</returns>
// public static bool Within(this IFeature self, IFeature other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Within(Geometry.FromBasicGeometry(other.Geometry));
// }
// /// <summary>
// /// Gets a boolean that is true if this feature is within the specified feature
// /// </summary>
// /// <param name="self">This feature</param>
// /// <param name="other">The other feature to test</param>
// /// <returns>Boolean, true if this feature is within the specified feature</returns>
// public static bool Within(this IFeature self, IGeometry other)
// {
// return Geometry.FromBasicGeometry(self.Geometry).Within(other);
// }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace StacksOfWax.WebApiTemplate.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
#pragma warning disable SA1633 // File should have header - This is an imported file,
// original header with license shall remain the same
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet
* The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangTurkishModel.cpp
* and adjusted to language specific support.
*/
namespace UtfUnknown.Core.Models.SingleByte.Turkish;
internal class Iso_8859_9_TurkishModel : TurkishModel
{
// Generated by BuildLangModel.py
// On: 2015-12-04 02:24:44.730727
// Character Mapping Table:
// ILL: illegal character.
// CTR: control character specific to the charset.
// RET: carriage/return.
// SYM: symbol (punctuation) that does not belong to word.
// NUM: 0 - 9.
// Other characters are ordered by probabilities
// (0 is the most common character in the language).
// Orders are generic to a language. So the codepoint with order X in
// CHARSET1 maps to the same character as the codepoint with the same
// order X in CHARSET2 for the same language.
// As such, it is possible to get missing order. For instance the
// ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1
// even though they are both used for French. Same for the euro sign.
private static byte[] CHAR_TO_ORDER_MAP =
{
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
RET,
CTR,
CTR,
RET,
CTR,
CTR, /* 0X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 1X */
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 2X */
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 3X */
SYM,
0,
15,
21,
7,
1,
26,
22,
19,
6,
28,
9,
5,
11,
3,
14, /* 4X */
23,
34,
4,
10,
8,
12,
20,
29,
32,
13,
18,
SYM,
SYM,
SYM,
SYM,
SYM, /* 5X */
SYM,
0,
15,
21,
7,
1,
26,
22,
19,
2,
28,
9,
5,
11,
3,
14, /* 6X */
23,
34,
4,
10,
8,
12,
20,
29,
32,
13,
18,
SYM,
SYM,
SYM,
SYM,
CTR, /* 7X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 8X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 9X */
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* AX */
SYM,
SYM,
SYM,
SYM,
SYM,
81,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* BX */
41,
36,
30,
44,
39,
82,
46,
24,
42,
33,
83,
45,
84,
37,
31,
85, /* CX */
25,
47,
86,
38,
87,
88,
27,
SYM,
43,
89,
40,
35,
16,
2,
17,
90, /* DX */
41,
36,
30,
44,
39,
91,
46,
24,
42,
33,
92,
45,
93,
37,
31,
94, /* EX */
25,
47,
95,
38,
96,
97,
27,
SYM,
43,
98,
40,
35,
16,
6,
17,
99 /* FX */
};
/*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */
public Iso_8859_9_TurkishModel()
: base(
CHAR_TO_ORDER_MAP,
CodepageName.ISO_8859_9) { }
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.POIFS.Macros
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using NPOI.POIFS.FileSystem;
using NPOI.Util;
/**
* Finds all VBA Macros in an office file (OLE2/POIFS and OOXML/OPC),
* and returns them.
*
* @since 3.15-beta2
*/
public class VBAMacroReader : ICloseable
{
protected static String VBA_PROJECT_OOXML = "vbaProject.bin";
protected static String VBA_PROJECT_POIFS = "VBA";
private NPOIFSFileSystem fs;
public VBAMacroReader(InputStream rstream)
{
PushbackInputStream stream = new PushbackInputStream(rstream, 8);
byte[] header8 = IOUtils.PeekFirst8Bytes(stream);
if (NPOIFSFileSystem.HasPOIFSHeader(header8))
{
fs = new NPOIFSFileSystem(stream);
}
else
{
OpenOOXML(stream);
}
}
public VBAMacroReader(FileInfo file)
{
try
{
this.fs = new NPOIFSFileSystem(file);
}
catch (OfficeXmlFileException)
{
OpenOOXML(file.OpenRead());
}
}
public VBAMacroReader(NPOIFSFileSystem fs)
{
this.fs = fs;
}
private void OpenOOXML(Stream zipFile)
{
ZipInputStream zis = new ZipInputStream(zipFile);
ZipEntry zipEntry;
while ((zipEntry = zis.GetNextEntry()) != null)
{
if (zipEntry.Name.EndsWith(VBA_PROJECT_OOXML, StringComparison.OrdinalIgnoreCase))
{
try
{
// Make a NPOIFS from the contents, and close the stream
this.fs = new NPOIFSFileSystem(zis);
return;
}
catch (IOException e)
{
// Tidy up
zis.Close();
// Pass on
throw e;
}
}
}
zis.Close();
throw new ArgumentException("No VBA project found");
}
public void Close()
{
fs.Close();
fs = null;
}
/**
* Reads all macros from all modules of the opened office file.
* @return All the macros and their contents
*
* @since 3.15-beta2
*/
public Dictionary<String, String> ReadMacros()
{
ModuleMap modules = new ModuleMap();
FindMacros(fs.Root, modules);
Dictionary<String, String> moduleSources = new Dictionary<String, String>();
foreach (KeyValuePair<String, Module> entry in modules)
{
Module module = entry.Value;
if (module.buf != null && module.buf.Length > 0)
{ // Skip empty modules
moduleSources.Add(entry.Key, ModuleMap.charset.GetString(module.buf));
}
}
return moduleSources;
}
protected class Module
{
public int? offset;
public byte[] buf;
public void Read(Stream in1)
{
MemoryStream out1 = new MemoryStream();
IOUtils.Copy(in1, out1);
out1.Close();
buf = out1.ToArray();
}
}
protected class ModuleMap : Dictionary<String, Module>
{
static ModuleMap()
{
#if NETSTANDARD2_1 || NETSTANDARD2_0
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endif
charset =Encoding.GetEncoding(1252);
}
public static Encoding charset = null;
//Charset charset = Charset.ForName("Cp1252"); // default charset
public Module Get(string key)
{
return ContainsKey(key) ? this[key] : null;
}
public Module Put(string key, Module value)
{
Module oldValue = null;
if (ContainsKey(key))
{
oldValue = this[key];
this[key] = value;
}
else
{
Add(key, value);
}
return oldValue;
}
}
/**
* Recursively traverses directory structure rooted at <tt>dir</tt>.
* For each macro module that is found, the module's name and code are
* Added to <tt>modules</tt>.
*
* @param dir
* @param modules
* @throws IOException
* @since 3.15-beta2
*/
protected void FindMacros(DirectoryNode dir, ModuleMap modules)
{
if (VBA_PROJECT_POIFS.Equals(dir.Name, StringComparison.OrdinalIgnoreCase))
{
// VBA project directory, process
ReadMacros(dir, modules);
}
else
{
// Check children
foreach (Entry child in dir)
{
if (child is DirectoryNode)
{
FindMacros((DirectoryNode)child, modules);
}
}
}
}
/**
* Read <tt>length</tt> bytes of MBCS (multi-byte character Set) characters from the stream
*
* @param stream the inputstream to read from
* @param length number of bytes to read from stream
* @param charset the character Set encoding of the bytes in the stream
* @return a java String in the supplied character Set
* @throws IOException
*/
private static String ReadString(InputStream stream, int length, Encoding charset)
{
byte[] buffer = new byte[length];
int count = stream.Read(buffer);
//return new String(buffer, 0, count, charset);
return charset.GetString(buffer, 0, count);
}
/**
* Reads module from DIR node in input stream and Adds it to the modules map for decompression later
* on the second pass through this function, the module will be decompressed
*
* Side-effects: Adds a new module to the module map or Sets the buf field on the module
* to the decompressed stream contents (the VBA code for one module)
*
* @param in the Run-length encoded input stream to read from
* @param streamName the stream name of the module
* @param modules a map to store the modules
* @throws IOException
*/
private static void ReadModule(RLEDecompressingInputStream in1, String streamName, ModuleMap modules)
{
int moduleOffset = in1.ReadInt();
Module module = modules.Get(streamName);
if (module == null)
{
// First time we've seen the module. Add it to the ModuleMap and decompress it later
module = new Module();
module.offset = moduleOffset;
modules.Put(streamName, module);
// Would Adding module.Read(in1) here be correct?
}
else
{
// Decompress a previously found module and store the decompressed result into module.buf
InputStream stream = new RLEDecompressingInputStream(
new MemoryStream(module.buf, moduleOffset, module.buf.Length - moduleOffset)
);
module.Read(stream);
stream.Close();
}
}
private static void ReadModule(DocumentInputStream dis, String name, ModuleMap modules)
{
Module module = modules.Get(name);
// TODO Refactor this to fetch dir then do the rest
if (module == null)
{
// no DIR stream with offsets yet, so store the compressed bytes for later
module = new Module();
modules.Put(name, module);
module.Read(dis);
}
else
{
if (module.offset == null)
{
//This should not happen. bug 59858
throw new IOException("Module offset for '" + name + "' was never Read.");
}
// we know the offset already, so decompress immediately on-the-fly
long skippedBytes = dis.Skip(module.offset.Value);
if (skippedBytes != module.offset)
{
throw new IOException("tried to skip " + module.offset + " bytes, but actually skipped " + skippedBytes + " bytes");
}
InputStream stream = new RLEDecompressingInputStream(dis);
module.Read(stream);
stream.Close();
}
}
/**
* Skips <tt>n</tt> bytes in an input stream, throwing IOException if the
* number of bytes skipped is different than requested.
* @throws IOException
*/
private static void TrySkip(InputStream in1, long n)
{
long skippedBytes = in1.Skip(n);
if (skippedBytes != n)
{
if (skippedBytes < 0)
{
throw new IOException(
"Tried skipping " + n + " bytes, but no bytes were skipped. "
+ "The end of the stream has been reached or the stream is closed.");
}
else
{
throw new IOException(
"Tried skipping " + n + " bytes, but only " + skippedBytes + " bytes were skipped. "
+ "This should never happen.");
}
}
}
// Constants from MS-OVBA: https://msdn.microsoft.com/en-us/library/office/cc313094(v=office.12).aspx
private const int EOF = -1;
private const int VERSION_INDEPENDENT_TERMINATOR = 0x0010;
private const int VERSION_DEPENDENT_TERMINATOR = 0x002B;
private const int PROJECTVERSION = 0x0009;
private const int PROJECTCODEPAGE = 0x0003;
private const int STREAMNAME = 0x001A;
private const int MODULEOFFSET = 0x0031;
private const int MODULETYPE_PROCEDURAL = 0x0021;
private const int MODULETYPE_DOCUMENT_CLASS_OR_DESIGNER = 0x0022;
private const int PROJECTLCID = 0x0002;
/**
* Reads VBA Project modules from a VBA Project directory located at
* <tt>macroDir</tt> into <tt>modules</tt>.
*
* @since 3.15-beta2
*/
protected void ReadMacros(DirectoryNode macroDir, ModuleMap modules)
{
foreach (Entry entry in macroDir)
{
if (!(entry is DocumentNode)) { continue; }
String name = entry.Name;
DocumentNode document = (DocumentNode)entry;
DocumentInputStream dis = new DocumentInputStream(document);
try
{
if ("dir".Equals(name, StringComparison.OrdinalIgnoreCase))
{
// process DIR
RLEDecompressingInputStream in1 = new RLEDecompressingInputStream(dis);
String streamName = null;
int recordId = 0;
try
{
while (true)
{
recordId = in1.ReadShort();
if (EOF == recordId
|| VERSION_INDEPENDENT_TERMINATOR == recordId)
{
break;
}
int recordLength = in1.ReadInt();
switch (recordId)
{
case PROJECTVERSION:
TrySkip(in1, 6);
break;
case PROJECTCODEPAGE:
int codepage = in1.ReadShort();
ModuleMap.charset = Encoding.GetEncoding(codepage); //Charset.ForName("Cp" + codepage);
break;
case STREAMNAME:
streamName = ReadString(in1, recordLength, ModuleMap.charset);
break;
case MODULEOFFSET:
ReadModule(in1, streamName, modules);
break;
default:
TrySkip(in1, recordLength);
break;
}
}
}
catch (IOException e)
{
throw new IOException(
"Error occurred while Reading macros at section id "
+ recordId + " (" + HexDump.ShortToHex(recordId) + ")", e);
}
finally
{
in1.Close();
}
}
else if (!name.StartsWith("__SRP", StringComparison.OrdinalIgnoreCase)
&& !name.StartsWith("_VBA_PROJECT", StringComparison.OrdinalIgnoreCase))
{
// process module, skip __SRP and _VBA_PROJECT since these do not contain macros
ReadModule(dis, name, modules);
}
}
finally
{
dis.Close();
}
}
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace Kurouzu.SWF
{
/// <summary>
/// Class that makes it easier to read SWF (Flash) files
/// Written by Michael Swanson (http://blogs.msdn.com/mswanson)
/// </summary>
public class SwfReader
{
private static readonly uint[] BitValues; // For pre-computed bit values
private static readonly float[] Powers; // For pre-computed fixed-point powers
private byte _bitPosition; // Current bit position within byte (only used for reading bit fields)
private byte _currentByte; // Value of the current byte (only used for reading bit fields)
#region Properties
public Stream Stream { get; set; }
#endregion
#region Constructors
static SwfReader()
{
// Setup bit values for later lookup
BitValues = new uint[32];
for (byte power = 0; power < 32; power++)
{
BitValues[power] = (uint) (1 << power);
}
// Setup power values for later lookup
Powers = new float[32];
for (byte power = 0; power < 32; power++)
{
Powers[power] = (float) Math.Pow(2, power - 16);
}
}
public SwfReader(Stream stream)
{
Stream = stream;
}
#endregion
#region Stream manipulation
public byte ReadByte()
{
var byteRead = Stream.ReadByte();
_bitPosition = 8; // So that ReadBit() knows that we've "used" this byte already
if (byteRead == -1)
{
throw new ApplicationException("Attempted to read past end of stream");
}
return (byte) byteRead;
}
public bool ReadBit()
{
// Do we need another byte?
if (_bitPosition > 7)
{
_currentByte = ReadByte();
_bitPosition = 0; // Reset, since we haven't "used" this byte yet
}
// Read the current bit
var result = ((_currentByte & BitValues[(7 - _bitPosition)]) != 0);
// Move to the next bit
_bitPosition++;
return result;
}
#endregion
#region Byte-aligned types (SI8, SI16, SI32, UI8, UI16, UI32, FIXED, STRING, ARGB[])
// Read an unsigned 8-bit integer
public byte ReadUI8()
{
return ReadByte();
}
// Read an array of unsigned 8-bit integers
public byte[] ReadUI8(int n)
{
var result = new byte[n];
for (var index = 0; index < n; index++)
{
result[index] = ReadUI8();
}
return result;
}
// Read a signed byte
public sbyte ReadSI8()
{
return (sbyte) ReadByte();
}
// Read an unsigned 16-bit integer
public ushort ReadUI16()
{
ushort result = 0;
result |= ReadByte();
result |= (ushort) (ReadByte() << 8);
return result;
}
// Read a signed 16-bit integer
public short ReadSI16() => (short) ReadUI16();
// Read an unsigned 32-bit integer
public uint ReadUI32()
{
uint result = 0;
result |= ReadByte();
result |= (uint) (ReadByte() << 8);
result |= (uint) (ReadByte() << 16);
result |= (uint) (ReadByte() << 24);
return result;
}
// Read a signed 32-bit integer
public int ReadSI32()
{
return (int) ReadUI32();
}
// Read a 32-bit 16.16 fixed-point number
public float ReadFIXED()
{
float result = 0;
result += ReadByte()*Powers[0];
result += ReadByte()*Powers[7];
result += ReadByte()*Powers[15];
result += ReadByte()*Powers[31];
return result;
}
// Read a string
// TODO: Is StringBuilder worth it for these small strings?
public string ReadSTRING()
{
var result = string.Empty;
byte[] character = {0x00};
// Grab characters until we hit 0x00
do
{
character[0] = ReadByte();
if (character[0] != 0x00)
{
result += Encoding.ASCII.GetString(character);
}
} while (character[0] != 0x00);
return result;
}
#endregion
#region Non-byte-aligned bit types (SB[nBits], UB[nBits], FB[nBits])
// Read an unsigned bit value
public uint ReadUB(int nBits)
{
uint result = 0;
// Is there anything to read?
if (nBits > 0)
{
// Calculate value
for (var index = nBits - 1; index > -1; index--)
{
if (ReadBit())
{
result |= BitValues[index];
}
}
}
return result;
}
// Read a signed bit value
public int ReadSB(int nBits)
{
var result = 0;
// Is there anything to read?
if (nBits > 0)
{
// Is this a negative number (MSB will be set)?
if (ReadBit())
{
result -= (int) BitValues[nBits - 1];
}
// Calculate rest of value
for (var index = nBits - 2; index > -1; index--)
{
if (ReadBit())
{
result |= (int) BitValues[index];
}
}
}
return result;
}
// Read a signed fixed-point bit value
// TODO: Math.Pow probably isn't the fastest method of accomplishing this
public float ReadFB(int nBits)
{
float result = 0;
// Is there anything to read?
if (nBits > 0)
{
// Is this a negative number (MSB will be set)?
if (ReadBit())
{
result -= Powers[nBits - 1];
}
// Calculate rest of value
for (var index = nBits - 1; index > 0; index--)
{
if (ReadBit())
{
result += Powers[index - 1];
}
}
}
return result;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
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 Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// VirtualNetworkOperations operations.
/// </summary>
internal partial class VirtualNetworkOperations : IServiceOperations<DevTestLabsClient>, IVirtualNetworkOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworkOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualNetworkOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List virtual networks in a given lab.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, ODataQuery<VirtualNetwork> odataQuery = default(ODataQuery<VirtualNetwork>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> GetResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or replace an existing virtual network. This operation can take a
/// while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetwork'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, VirtualNetwork virtualNetwork, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetwork> _response = await BeginCreateOrUpdateResourceWithHttpMessagesAsync(
resourceGroupName, labName, name, virtualNetwork, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Create or replace an existing virtual network. This operation can take a
/// while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetwork'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, VirtualNetwork virtualNetwork, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (virtualNetwork == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetwork");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("virtualNetwork", virtualNetwork);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdateResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(virtualNetwork != null)
{
_requestContent = SafeJsonConvert.SerializeObject(virtualNetwork, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete virtual network. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteResourceWithHttpMessagesAsync(
resourceGroupName, labName, name, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Delete virtual network. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDeleteResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Modify properties of virtual networks.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetwork'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> PatchResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, VirtualNetwork virtualNetwork, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (virtualNetwork == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetwork");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("virtualNetwork", virtualNetwork);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PatchResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(virtualNetwork != null)
{
_requestContent = SafeJsonConvert.SerializeObject(virtualNetwork, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List virtual networks in a given lab.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Encog.Engine.Network.Activation;
using Encog.Neural.Flat;
using Encog.Persist;
using Encog.Util;
using Encog.Util.CSV;
namespace Encog.Neural.Networks
{
/// <summary>
/// Persist a basic network.
/// </summary>
///
public class PersistBasicNetwork : IEncogPersistor
{
#region EncogPersistor Members
/// <summary>
/// The file version.
/// </summary>
public virtual int FileVersion
{
get { return 1; }
}
/// <summary>
/// The persist class string.
/// </summary>
public virtual String PersistClassString
{
get { return "BasicNetwork"; }
}
/// <summary>
/// Read an object.
/// </summary>
///
public Object Read(Stream mask0)
{
var result = new BasicNetwork();
var flat = new FlatNetwork();
var ins0 = new EncogReadHelper(mask0);
EncogFileSection section;
while ((section = ins0.ReadNextSection()) != null)
{
if (section.SectionName.Equals("BASIC")
&& section.SubSectionName.Equals("PARAMS"))
{
IDictionary<String, String> paras = section.ParseParams();
EngineArray.PutAll(paras, result.Properties);
}
if (section.SectionName.Equals("BASIC")
&& section.SubSectionName.Equals("NETWORK"))
{
IDictionary<String, String> p = section.ParseParams();
flat.BeginTraining = EncogFileSection.ParseInt(p,
BasicNetwork.TagBeginTraining);
flat.ConnectionLimit = EncogFileSection.ParseDouble(p,
BasicNetwork.TagConnectionLimit);
flat.ContextTargetOffset = EncogFileSection.ParseIntArray(
p, BasicNetwork.TagContextTargetOffset);
flat.ContextTargetSize = EncogFileSection.ParseIntArray(
p, BasicNetwork.TagContextTargetSize);
flat.EndTraining = EncogFileSection.ParseInt(p,
BasicNetwork.TagEndTraining);
flat.HasContext = EncogFileSection.ParseBoolean(p,
BasicNetwork.TagHasContext);
flat.InputCount = EncogFileSection.ParseInt(p,
PersistConst.InputCount);
flat.LayerCounts = EncogFileSection.ParseIntArray(p,
BasicNetwork.TagLayerCounts);
flat.LayerFeedCounts = EncogFileSection.ParseIntArray(p,
BasicNetwork.TagLayerFeedCounts);
flat.LayerContextCount = EncogFileSection.ParseIntArray(
p, BasicNetwork.TagLayerContextCount);
flat.LayerIndex = EncogFileSection.ParseIntArray(p,
BasicNetwork.TagLayerIndex);
flat.LayerOutput = section.ParseDoubleArray(p,PersistConst.Output);
flat.LayerSums = new double[flat.LayerOutput.Length];
flat.OutputCount = EncogFileSection.ParseInt(p,
PersistConst.OutputCount);
flat.WeightIndex = EncogFileSection.ParseIntArray(p,
BasicNetwork.TagWeightIndex);
flat.Weights = section.ParseDoubleArray(p, PersistConst.Weights);
flat.BiasActivation = section.ParseDoubleArray(p, BasicNetwork.TagBiasActivation);
}
else if (section.SectionName.Equals("BASIC")
&& section.SubSectionName.Equals("ACTIVATION"))
{
int index = 0;
flat.ActivationFunctions = new IActivationFunction[flat.LayerCounts.Length];
foreach (String line in section.Lines)
{
IActivationFunction af;
IList<String> cols = EncogFileSection
.SplitColumns(line);
String name = ReflectionUtil.AfPath
+ cols[0];
try
{
af = (IActivationFunction) ReflectionUtil.LoadObject(name);
}
catch (TypeLoadException e)
{
throw new PersistError(e);
}
catch (TargetException e)
{
throw new PersistError(e);
}
catch (MemberAccessException e)
{
throw new PersistError(e);
}
for (int i = 0; i < af.ParamNames.Length; i++)
{
af.Params[i] =
CSVFormat.EgFormat.Parse(cols[i + 1]);
}
flat.ActivationFunctions[index++] = af;
}
}
}
result.Structure.Flat = flat;
return result;
}
/// <inheritdoc/>
public void Save(Stream os, Object obj)
{
var xout = new EncogWriteHelper(os);
var net = (BasicNetwork) obj;
FlatNetwork flat = net.Structure.Flat;
xout.AddSection("BASIC");
xout.AddSubSection("PARAMS");
xout.AddProperties(net.Properties);
xout.AddSubSection("NETWORK");
xout.WriteProperty(BasicNetwork.TagBeginTraining,
flat.BeginTraining);
xout.WriteProperty(BasicNetwork.TagConnectionLimit,
flat.ConnectionLimit);
xout.WriteProperty(BasicNetwork.TagContextTargetOffset,
flat.ContextTargetOffset);
xout.WriteProperty(BasicNetwork.TagContextTargetSize,
flat.ContextTargetSize);
xout.WriteProperty(BasicNetwork.TagEndTraining, flat.EndTraining);
xout.WriteProperty(BasicNetwork.TagHasContext, flat.HasContext);
xout.WriteProperty(PersistConst.InputCount, flat.InputCount);
xout.WriteProperty(BasicNetwork.TagLayerCounts, flat.LayerCounts);
xout.WriteProperty(BasicNetwork.TagLayerFeedCounts,
flat.LayerFeedCounts);
xout.WriteProperty(BasicNetwork.TagLayerContextCount,
flat.LayerContextCount);
xout.WriteProperty(BasicNetwork.TagLayerIndex, flat.LayerIndex);
xout.WriteProperty(PersistConst.Output, flat.LayerOutput);
xout.WriteProperty(PersistConst.OutputCount, flat.OutputCount);
xout.WriteProperty(BasicNetwork.TagWeightIndex, flat.WeightIndex);
xout.WriteProperty(PersistConst.Weights, flat.Weights);
xout.WriteProperty(BasicNetwork.TagBiasActivation,
flat.BiasActivation);
xout.AddSubSection("ACTIVATION");
foreach (IActivationFunction af in flat.ActivationFunctions)
{
xout.AddColumn(af.GetType().Name);
for (int i = 0; i < af.Params.Length; i++)
{
xout.AddColumn(af.Params[i]);
}
xout.WriteLine();
}
xout.Flush();
}
/// <inheritdoc/>
public Type NativeType
{
get { return typeof(BasicNetwork); }
}
#endregion
}
}
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Logging;
using osu.Framework.MathUtils;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Tools;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Edit.Screens.Compose;
using osu.Game.Screens.Edit.Screens.Compose.Layers;
using osu.Game.Screens.Edit.Screens.Compose.RadioButtons;
namespace osu.Game.Rulesets.Edit
{
public abstract class HitObjectComposer : CompositeDrawable
{
private readonly Ruleset ruleset;
protected ICompositionTool CurrentTool { get; private set; }
private RulesetContainer rulesetContainer;
private readonly List<Container> layerContainers = new List<Container>();
private readonly Bindable<WorkingBeatmap> beatmap = new Bindable<WorkingBeatmap>();
private readonly BindableBeatDivisor beatDivisor = new BindableBeatDivisor();
private IAdjustableClock adjustableClock;
protected HitObjectComposer(Ruleset ruleset)
{
this.ruleset = ruleset;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader(true)]
private void load([NotNull] OsuGameBase osuGame, [NotNull] IAdjustableClock adjustableClock, [NotNull] IFrameBasedClock framedClock, [CanBeNull] BindableBeatDivisor beatDivisor)
{
this.adjustableClock = adjustableClock;
if (beatDivisor != null)
this.beatDivisor.BindTo(beatDivisor);
beatmap.BindTo(osuGame.Beatmap);
try
{
rulesetContainer = CreateRulesetContainer(ruleset, beatmap.Value);
rulesetContainer.Clock = framedClock;
}
catch (Exception e)
{
Logger.Error(e, "Could not load beatmap sucessfully!");
return;
}
HitObjectMaskLayer hitObjectMaskLayer = new HitObjectMaskLayer(this);
SelectionLayer selectionLayer = new SelectionLayer(rulesetContainer.Playfield);
var layerBelowRuleset = new BorderLayer
{
RelativeSizeAxes = Axes.Both,
Child = CreateLayerContainer()
};
var layerAboveRuleset = CreateLayerContainer();
layerAboveRuleset.Children = new Drawable[]
{
selectionLayer, // Below object overlays for input
hitObjectMaskLayer,
selectionLayer.CreateProxy() // Proxy above object overlays for selections
};
layerContainers.Add(layerBelowRuleset);
layerContainers.Add(layerAboveRuleset);
RadioButtonCollection toolboxCollection;
InternalChild = new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
new FillFlowContainer
{
Name = "Sidebar",
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Right = 10 },
Children = new Drawable[]
{
new ToolboxGroup { Child = toolboxCollection = new RadioButtonCollection { RelativeSizeAxes = Axes.X } }
}
},
new Container
{
Name = "Content",
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
layerBelowRuleset,
rulesetContainer,
layerAboveRuleset
}
}
},
},
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 200),
}
};
selectionLayer.ObjectSelected += hitObjectMaskLayer.AddOverlay;
selectionLayer.ObjectDeselected += hitObjectMaskLayer.RemoveOverlay;
selectionLayer.SelectionCleared += hitObjectMaskLayer.RemoveSelectionOverlay;
selectionLayer.SelectionFinished += hitObjectMaskLayer.AddSelectionOverlay;
toolboxCollection.Items =
new[] { new RadioButton("Select", () => setCompositionTool(null)) }
.Concat(
CompositionTools.Select(t => new RadioButton(t.Name, () => setCompositionTool(t)))
)
.ToList();
toolboxCollection.Items[0].Select();
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
layerContainers.ForEach(l =>
{
l.Anchor = rulesetContainer.Playfield.Anchor;
l.Origin = rulesetContainer.Playfield.Origin;
l.Position = rulesetContainer.Playfield.Position;
l.Size = rulesetContainer.Playfield.Size;
});
}
protected override bool OnWheel(InputState state)
{
if (state.Mouse.WheelDelta > 0)
SeekBackward(true);
else
SeekForward(true);
return true;
}
/// <summary>
/// Seeks the current time one beat-snapped beat-length backwards.
/// </summary>
/// <param name="snapped">Whether to snap to the closest beat.</param>
public void SeekBackward(bool snapped = false) => seek(-1, snapped);
/// <summary>
/// Seeks the current time one beat-snapped beat-length forwards.
/// </summary>
/// <param name="snapped">Whether to snap to the closest beat.</param>
public void SeekForward(bool snapped = false) => seek(1, snapped);
private void seek(int direction, bool snapped)
{
var cpi = beatmap.Value.Beatmap.ControlPointInfo;
var timingPoint = cpi.TimingPointAt(adjustableClock.CurrentTime);
if (direction < 0 && timingPoint.Time == adjustableClock.CurrentTime)
{
// When going backwards and we're at the boundary of two timing points, we compute the seek distance with the timing point which we are seeking into
int activeIndex = cpi.TimingPoints.IndexOf(timingPoint);
while (activeIndex > 0 && adjustableClock.CurrentTime == timingPoint.Time)
timingPoint = cpi.TimingPoints[--activeIndex];
}
double seekAmount = timingPoint.BeatLength / beatDivisor;
double seekTime = adjustableClock.CurrentTime + seekAmount * direction;
if (!snapped || cpi.TimingPoints.Count == 0)
{
adjustableClock.Seek(seekTime);
return;
}
// We will be snapping to beats within timingPoint
seekTime -= timingPoint.Time;
// Determine the index from timingPoint of the closest beat to seekTime, accounting for scrolling direction
int closestBeat;
if (direction > 0)
closestBeat = (int)Math.Floor(seekTime / seekAmount);
else
closestBeat = (int)Math.Ceiling(seekTime / seekAmount);
seekTime = timingPoint.Time + closestBeat * seekAmount;
// Due to the rounding above, we may end up on the current beat. This will effectively cause 0 seeking to happen, but we don't want this.
// Instead, we'll go to the next beat in the direction when this is the case
if (Precision.AlmostEquals(adjustableClock.CurrentTime, seekTime))
{
closestBeat += direction > 0 ? 1 : -1;
seekTime = timingPoint.Time + closestBeat * seekAmount;
}
if (seekTime < timingPoint.Time && timingPoint != cpi.TimingPoints.First())
seekTime = timingPoint.Time;
var nextTimingPoint = cpi.TimingPoints.FirstOrDefault(t => t.Time > timingPoint.Time);
if (seekTime > nextTimingPoint?.Time)
seekTime = nextTimingPoint.Time;
adjustableClock.Seek(seekTime);
}
public void SeekTo(double seekTime, bool snapped = false)
{
if (!snapped)
{
adjustableClock.Seek(seekTime);
return;
}
var timingPoint = beatmap.Value.Beatmap.ControlPointInfo.TimingPointAt(seekTime);
double beatSnapLength = timingPoint.BeatLength / beatDivisor;
// We will be snapping to beats within the timing point
seekTime -= timingPoint.Time;
// Determine the index from the current timing point of the closest beat to seekTime
int closestBeat = (int)Math.Round(seekTime / beatSnapLength);
seekTime = timingPoint.Time + closestBeat * beatSnapLength;
// Depending on beatSnapLength, we may snap to a beat that is beyond timingPoint's end time, but we want to instead snap to
// the next timing point's start time
var nextTimingPoint = beatmap.Value.Beatmap.ControlPointInfo.TimingPoints.FirstOrDefault(t => t.Time > timingPoint.Time);
if (seekTime > nextTimingPoint?.Time)
seekTime = nextTimingPoint.Time;
adjustableClock.Seek(seekTime);
}
private void setCompositionTool(ICompositionTool tool) => CurrentTool = tool;
protected virtual RulesetContainer CreateRulesetContainer(Ruleset ruleset, WorkingBeatmap beatmap) => ruleset.CreateRulesetContainerWith(beatmap, true);
protected abstract IReadOnlyList<ICompositionTool> CompositionTools { get; }
/// <summary>
/// Creates a <see cref="HitObjectMask"/> for a specific <see cref="DrawableHitObject"/>.
/// </summary>
/// <param name="hitObject">The <see cref="DrawableHitObject"/> to create the overlay for.</param>
public virtual HitObjectMask CreateMaskFor(DrawableHitObject hitObject) => null;
/// <summary>
/// Creates a <see cref="SelectionBox"/> which outlines <see cref="DrawableHitObject"/>s
/// and handles all hitobject movement/pattern adjustments.
/// </summary>
/// <param name="overlays">The <see cref="DrawableHitObject"/> overlays.</param>
public virtual SelectionBox CreateSelectionOverlay(IReadOnlyList<HitObjectMask> overlays) => new SelectionBox(overlays);
/// <summary>
/// Creates a <see cref="ScalableContainer"/> which provides a layer above or below the <see cref="Playfield"/>.
/// </summary>
protected virtual ScalableContainer CreateLayerContainer() => new ScalableContainer { RelativeSizeAxes = Axes.Both };
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using Xunit;
public class TupleTests
{
private class TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>
{
private int _nItems;
private readonly object Tuple;
private readonly Tuple<T1> Tuple1;
private readonly Tuple<T1, T2> Tuple2;
private readonly Tuple<T1, T2, T3> Tuple3;
private readonly Tuple<T1, T2, T3, T4> Tuple4;
private readonly Tuple<T1, T2, T3, T4, T5> Tuple5;
private readonly Tuple<T1, T2, T3, T4, T5, T6> Tuple6;
private readonly Tuple<T1, T2, T3, T4, T5, T6, T7> Tuple7;
private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Tuple8;
private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> Tuple9;
private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> Tuple10;
internal TupleTestDriver(params object[] values)
{
if (values.Length == 0)
throw new ArgumentOutOfRangeException(nameof(values), "You must provide at least one value");
if (values.Length > 10)
throw new ArgumentOutOfRangeException(nameof(values), "You must provide at most 10 values");
_nItems = values.Length;
switch (_nItems)
{
case 1:
Tuple1 = new Tuple<T1>((T1)values[0]);
Tuple = Tuple1;
break;
case 2:
Tuple2 = new Tuple<T1, T2>((T1)values[0], (T2)values[1]);
Tuple = Tuple2;
break;
case 3:
Tuple3 = new Tuple<T1, T2, T3>((T1)values[0], (T2)values[1], (T3)values[2]);
Tuple = Tuple3;
break;
case 4:
Tuple4 = new Tuple<T1, T2, T3, T4>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3]);
Tuple = Tuple4;
break;
case 5:
Tuple5 = new Tuple<T1, T2, T3, T4, T5>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4]);
Tuple = Tuple5;
break;
case 6:
Tuple6 = new Tuple<T1, T2, T3, T4, T5, T6>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5]);
Tuple = Tuple6;
break;
case 7:
Tuple7 = new Tuple<T1, T2, T3, T4, T5, T6, T7>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6]);
Tuple = Tuple7;
break;
case 8:
Tuple8 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8>((T8)values[7]));
Tuple = Tuple8;
break;
case 9:
Tuple9 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8, T9>((T8)values[7], (T9)values[8]));
Tuple = Tuple9;
break;
case 10:
Tuple10 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8, T9, T10>((T8)values[7], (T9)values[8], (T10)values[9]));
Tuple = Tuple10;
break;
}
}
private void VerifyItem(int itemPos, object Item1, object Item2)
{
Assert.True(object.Equals(Item1, Item2));
}
public void TestConstructor(params object[] expectedValue)
{
if (expectedValue.Length != _nItems)
throw new ArgumentOutOfRangeException("expectedValues", "You must provide " + _nItems + " expectedvalues");
switch (_nItems)
{
case 1:
VerifyItem(1, Tuple1.Item1, expectedValue[0]);
break;
case 2:
VerifyItem(1, Tuple2.Item1, expectedValue[0]);
VerifyItem(2, Tuple2.Item2, expectedValue[1]);
break;
case 3:
VerifyItem(1, Tuple3.Item1, expectedValue[0]);
VerifyItem(2, Tuple3.Item2, expectedValue[1]);
VerifyItem(3, Tuple3.Item3, expectedValue[2]);
break;
case 4:
VerifyItem(1, Tuple4.Item1, expectedValue[0]);
VerifyItem(2, Tuple4.Item2, expectedValue[1]);
VerifyItem(3, Tuple4.Item3, expectedValue[2]);
VerifyItem(4, Tuple4.Item4, expectedValue[3]);
break;
case 5:
VerifyItem(1, Tuple5.Item1, expectedValue[0]);
VerifyItem(2, Tuple5.Item2, expectedValue[1]);
VerifyItem(3, Tuple5.Item3, expectedValue[2]);
VerifyItem(4, Tuple5.Item4, expectedValue[3]);
VerifyItem(5, Tuple5.Item5, expectedValue[4]);
break;
case 6:
VerifyItem(1, Tuple6.Item1, expectedValue[0]);
VerifyItem(2, Tuple6.Item2, expectedValue[1]);
VerifyItem(3, Tuple6.Item3, expectedValue[2]);
VerifyItem(4, Tuple6.Item4, expectedValue[3]);
VerifyItem(5, Tuple6.Item5, expectedValue[4]);
VerifyItem(6, Tuple6.Item6, expectedValue[5]);
break;
case 7:
VerifyItem(1, Tuple7.Item1, expectedValue[0]);
VerifyItem(2, Tuple7.Item2, expectedValue[1]);
VerifyItem(3, Tuple7.Item3, expectedValue[2]);
VerifyItem(4, Tuple7.Item4, expectedValue[3]);
VerifyItem(5, Tuple7.Item5, expectedValue[4]);
VerifyItem(6, Tuple7.Item6, expectedValue[5]);
VerifyItem(7, Tuple7.Item7, expectedValue[6]);
break;
case 8: // Extended Tuple
VerifyItem(1, Tuple8.Item1, expectedValue[0]);
VerifyItem(2, Tuple8.Item2, expectedValue[1]);
VerifyItem(3, Tuple8.Item3, expectedValue[2]);
VerifyItem(4, Tuple8.Item4, expectedValue[3]);
VerifyItem(5, Tuple8.Item5, expectedValue[4]);
VerifyItem(6, Tuple8.Item6, expectedValue[5]);
VerifyItem(7, Tuple8.Item7, expectedValue[6]);
VerifyItem(8, Tuple8.Rest.Item1, expectedValue[7]);
break;
case 9: // Extended Tuple
VerifyItem(1, Tuple9.Item1, expectedValue[0]);
VerifyItem(2, Tuple9.Item2, expectedValue[1]);
VerifyItem(3, Tuple9.Item3, expectedValue[2]);
VerifyItem(4, Tuple9.Item4, expectedValue[3]);
VerifyItem(5, Tuple9.Item5, expectedValue[4]);
VerifyItem(6, Tuple9.Item6, expectedValue[5]);
VerifyItem(7, Tuple9.Item7, expectedValue[6]);
VerifyItem(8, Tuple9.Rest.Item1, expectedValue[7]);
VerifyItem(9, Tuple9.Rest.Item2, expectedValue[8]);
break;
case 10: // Extended Tuple
VerifyItem(1, Tuple10.Item1, expectedValue[0]);
VerifyItem(2, Tuple10.Item2, expectedValue[1]);
VerifyItem(3, Tuple10.Item3, expectedValue[2]);
VerifyItem(4, Tuple10.Item4, expectedValue[3]);
VerifyItem(5, Tuple10.Item5, expectedValue[4]);
VerifyItem(6, Tuple10.Item6, expectedValue[5]);
VerifyItem(7, Tuple10.Item7, expectedValue[6]);
VerifyItem(8, Tuple10.Rest.Item1, expectedValue[7]);
VerifyItem(9, Tuple10.Rest.Item2, expectedValue[8]);
VerifyItem(10, Tuple10.Rest.Item3, expectedValue[9]);
break;
default:
throw new ArgumentException("Must specify between 1 and 10 expected values (inclusive).");
}
}
public void TestToString(string expected)
{
Assert.Equal(expected, Tuple.ToString());
}
public void TestEquals_GetHashCode(TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, bool expectEqual, bool expectStructuallyEqual)
{
if (expectEqual)
{
Assert.True(Tuple.Equals(other.Tuple));
Assert.Equal(Tuple.GetHashCode(), other.Tuple.GetHashCode());
}
else
{
Assert.False(Tuple.Equals(other.Tuple));
Assert.NotEqual(Tuple.GetHashCode(), other.Tuple.GetHashCode());
}
if (expectStructuallyEqual)
{
var equatable = ((IStructuralEquatable)Tuple);
var otherEquatable = ((IStructuralEquatable)other.Tuple);
Assert.True(equatable.Equals(other.Tuple, TestEqualityComparer.Instance));
Assert.Equal(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance));
}
else
{
var equatable = ((IStructuralEquatable)Tuple);
var otherEquatable = ((IStructuralEquatable)other.Tuple);
Assert.False(equatable.Equals(other.Tuple, TestEqualityComparer.Instance));
Assert.NotEqual(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance));
}
Assert.False(Tuple.Equals(null));
Assert.False(((IStructuralEquatable)Tuple).Equals(null));
}
public void TestCompareTo(TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, int expectedResult, int expectedStructuralResult)
{
Assert.Equal(expectedResult, ((IComparable)Tuple).CompareTo(other.Tuple));
Assert.Equal(expectedStructuralResult, ((IStructuralComparable)Tuple).CompareTo(other.Tuple, TestComparer.Instance));
Assert.Equal(1, ((IComparable)Tuple).CompareTo(null));
}
public void TestNotEqual()
{
Tuple<int> tupleB = new Tuple<int>((int)10000);
Assert.NotEqual(Tuple, tupleB);
}
internal void TestCompareToThrows()
{
Tuple<int> tupleB = new Tuple<int>((int)10000);
Assert.Throws<ArgumentException>(() => ((IComparable)Tuple).CompareTo(tupleB));
}
}
[Fact]
public static void TestConstructor()
{
TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA;
//Tuple-1
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue);
tupleDriverA.TestConstructor(short.MaxValue);
//Tuple-2
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
tupleDriverA.TestConstructor(short.MinValue, int.MaxValue);
//Tuple-3
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
tupleDriverA.TestConstructor((short)0, (int)0, long.MaxValue);
//Tuple-4
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
tupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This");
//Tuple-5
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
tupleDriverA.TestConstructor((short)(-1), (int)(-1), (long)0, "is", 'A');
//Tuple-6
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
tupleDriverA.TestConstructor((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
//Tuple-7
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue);
tupleDriverA.TestConstructor((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue);
object myObj = new object();
//Tuple-10
DateTime now = DateTime.Now;
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero);
tupleDriverA.TestConstructor((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero);
}
[Fact]
public static void TestToString()
{
TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA;
//Tuple-1
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue);
tupleDriverA.TestToString("(" + short.MaxValue + ")");
//Tuple-2
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
tupleDriverA.TestToString("(" + short.MinValue + ", " + int.MaxValue + ")");
//Tuple-3
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
tupleDriverA.TestToString("(" + ((short)0) + ", " + ((int)0) + ", " + long.MaxValue + ")");
//Tuple-4
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
tupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This");
tupleDriverA.TestToString("(" + ((short)1) + ", " + ((int)1) + ", " + long.MinValue + ", This)");
//Tuple-5
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
tupleDriverA.TestToString("(" + ((short)(-1)) + ", " + ((int)(-1)) + ", " + ((long)0) + ", is, A)");
//Tuple-6
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
tupleDriverA.TestToString("(" + ((short)10) + ", " + ((int)100) + ", " + ((long)1) + ", testing, Z, " + Single.MaxValue + ")");
//Tuple-7
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue);
tupleDriverA.TestToString("(" + ((short)(-100)) + ", " + ((int)(-1000)) + ", " + ((long)(-1)) + ", Tuples, , " + Single.MinValue + ", " + Double.MaxValue + ")");
object myObj = new object();
//Tuple-10
DateTime now = DateTime.Now;
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero);
// .NET Native bug 438149 - object.ToString in incorrect
tupleDriverA.TestToString("(" + ((short)10000) + ", " + ((int)1000000) + ", " + ((long)10000000) + ", 2008?7?2?, 0, " + ((Single)0.0001) + ", " + ((Double)0.0000001) + ", " + now + ", (False, System.Object), " + TimeSpan.Zero + ")");
}
[Fact]
public static void TestEquals_GetHashCode()
{
TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA, tupleDriverB, tupleDriverC, tupleDriverD;
//Tuple-1
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue);
tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue);
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
tupleDriverA.TestEquals_GetHashCode(tupleDriverD, false, false);
//Tuple-2
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue);
tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue);
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
tupleDriverA.TestEquals_GetHashCode(tupleDriverD, false, false);
//Tuple-3
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue);
tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this");
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
tupleDriverA.TestEquals_GetHashCode(tupleDriverD, false, false);
//Tuple-4
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this");
tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a');
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
tupleDriverA.TestEquals_GetHashCode(tupleDriverD, false, false);
//Tuple-5
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a');
tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue);
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
tupleDriverA.TestEquals_GetHashCode(tupleDriverD, false, false);
//Tuple-6
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue);
tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "tuples", ' ', Single.MinValue, (Double)0.0);
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
tupleDriverA.TestEquals_GetHashCode(tupleDriverD, false, false);
//Tuple-7
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "tuples", ' ', Single.MinValue, (Double)0.0);
tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, DateTime.Now.AddMilliseconds(1));
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
tupleDriverA.TestEquals_GetHashCode(tupleDriverD, false, false);
object myObj = new object();
//Tuple-10
DateTime now = DateTime.Now;
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), Tuple.Create(true, myObj), TimeSpan.MaxValue);
tupleDriverA.TestEquals_GetHashCode(tupleDriverB, true, true);
tupleDriverA.TestEquals_GetHashCode(tupleDriverC, false, false);
}
[Fact]
public static void TestCompareTo()
{
TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA, tupleDriverB, tupleDriverC;
//Tuple-1
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue);
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, 65535, 5);
//Tuple-2
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue);
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, 1, 5);
//Tuple-3
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue);
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, 1, 5);
//Tuple-4
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this");
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, 1, 5);
//Tuple-5
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a');
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, -1, 5);
//Tuple-6
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue);
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, 1, 5);
//Tuple-7
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "tuples", ' ', Single.MinValue, (Double)0.0);
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, 1, 5);
object myObj = new object();
//Tuple-10
DateTime now = DateTime.Now;
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero);
tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero);
tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), Tuple.Create(true, myObj), TimeSpan.MaxValue);
tupleDriverA.TestCompareTo(tupleDriverB, 0, 5);
tupleDriverA.TestCompareTo(tupleDriverC, -1, 5);
}
[Fact]
public static void TestNotEqual()
{
TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan> tupleDriverA;
//Tuple-1
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000);
tupleDriverA.TestNotEqual();
// This is for code coverage purposes
//Tuple-2
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000);
tupleDriverA.TestNotEqual();
//Tuple-3
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000);
tupleDriverA.TestNotEqual();
//Tuple-4
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?");
tupleDriverA.TestNotEqual();
//Tuple-5
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0');
tupleDriverA.TestNotEqual();
//Tuple-6
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN);
tupleDriverA.TestNotEqual();
//Tuple-7
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity);
tupleDriverA.TestNotEqual();
//Tuple-8, extended tuple
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now);
tupleDriverA.TestNotEqual();
//Tuple-9 and Tuple-10 are not necessary because they use the same code path as Tuple-8
}
[Fact]
public static void IncomparableTypes()
{
TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan> tupleDriverA;
//Tuple-1
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000);
tupleDriverA.TestCompareToThrows();
// This is for code coverage purposes
//Tuple-2
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000);
tupleDriverA.TestCompareToThrows();
//Tuple-3
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000);
tupleDriverA.TestCompareToThrows();
//Tuple-4
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?");
tupleDriverA.TestCompareToThrows();
//Tuple-5
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0');
tupleDriverA.TestCompareToThrows();
//Tuple-6
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN);
tupleDriverA.TestCompareToThrows();
//Tuple-7
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity);
tupleDriverA.TestCompareToThrows();
//Tuple-8, extended tuple
tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now);
tupleDriverA.TestCompareToThrows();
//Tuple-9 and Tuple-10 are not necessary because they use the same code path as Tuple-8
}
[Fact]
public static void FloatingPointNaNCases()
{
var a = Tuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN);
var b = Tuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN);
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
}
[Fact]
public static void TestCustomTypeParameter1()
{
// Special case of Tuple<T1> where T1 is a custom type
var testClass = new TestClass();
var a = Tuple.Create(testClass);
var b = Tuple.Create(testClass);
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
}
[Fact]
public static void TestCustomTypeParameter2()
{
// Special case of Tuple<T1, T2> where T2 is a custom type
var testClass = new TestClass(1);
var a = Tuple.Create(1, testClass);
var b = Tuple.Create(1, testClass);
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
}
[Fact]
public static void TestCustomTypeParameter3()
{
// Special case of Tuple<T1, T2> where T1 and T2 are custom types
var testClassA = new TestClass(100);
var testClassB = new TestClass(101);
var a = Tuple.Create(testClassA, testClassB);
var b = Tuple.Create(testClassB, testClassA);
Assert.False(a.Equals(b));
Assert.Equal(-1, ((IComparable)a).CompareTo(b));
Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
// Equals(IEqualityComparer) is false, ignore hash code
}
[Fact]
public static void TestCustomTypeParameter4()
{
// Special case of Tuple<T1, T2> where T1 and T2 are custom types
var testClassA = new TestClass(100);
var testClassB = new TestClass(101);
var a = Tuple.Create(testClassA, testClassB);
var b = Tuple.Create(testClassA, testClassA);
Assert.False(a.Equals(b));
Assert.Equal(1, ((IComparable)a).CompareTo(b));
Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
// Equals(IEqualityComparer) is false, ignore hash code
}
[Fact]
public static void NestedTuples1()
{
var a = Tuple.Create(1, 2, Tuple.Create(31, 32), 4, 5, 6, 7, Tuple.Create(8, 9));
var b = Tuple.Create(1, 2, Tuple.Create(31, 32), 4, 5, 6, 7, Tuple.Create(8, 9));
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal("(1, 2, (31, 32), 4, 5, 6, 7, (8, 9))", a.ToString());
Assert.Equal("(31, 32)", a.Item3.ToString());
Assert.Equal("((8, 9))", a.Rest.ToString());
}
[Fact]
public static void NestedTuples2()
{
var a = Tuple.Create(0, 1, 2, 3, 4, 5, 6, Tuple.Create(7, 8, 9, 10, 11, 12, 13, Tuple.Create(14, 15)));
var b = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16)));
Assert.False(a.Equals(b));
Assert.Equal(-1, ((IComparable)a).CompareTo(b));
Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
Assert.Equal("(0, 1, 2, 3, 4, 5, 6, (7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.ToString());
Assert.Equal("(1, 2, 3, 4, 5, 6, 7, (8, 9, 10, 11, 12, 13, 14, (15, 16)))", b.ToString());
Assert.Equal("((7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.Rest.ToString());
}
[Fact]
public static void IncomparableTypesSpecialCase()
{
// Special case when T does not implement IComparable
var testClassA = new TestClass2(100);
var testClassB = new TestClass2(100);
var a = Tuple.Create(testClassA);
var b = Tuple.Create(testClassB);
Assert.True(a.Equals(b));
Assert.Throws<ArgumentException>(() => ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal("([100])", a.ToString());
}
private class TestClass : IComparable
{
private readonly int _value;
internal TestClass()
: this(0)
{ }
internal TestClass(int value)
{
this._value = value;
}
public override string ToString()
{
return "{" + _value.ToString() + "}";
}
public int CompareTo(object x)
{
TestClass tmp = x as TestClass;
if (tmp != null)
return this._value.CompareTo(tmp._value);
else
return 1;
}
}
private class TestClass2
{
private readonly int _value;
internal TestClass2()
: this(0)
{ }
internal TestClass2(int value)
{
this._value = value;
}
public override string ToString()
{
return "[" + _value.ToString() + "]";
}
public override bool Equals(object x)
{
TestClass2 tmp = x as TestClass2;
if (tmp != null)
return _value.Equals(tmp._value);
else
return false;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
}
private class TestComparer : IComparer
{
public static readonly TestComparer Instance = new TestComparer();
public int Compare(object x, object y)
{
return 5;
}
}
private class TestEqualityComparer : IEqualityComparer
{
public static readonly TestEqualityComparer Instance = new TestEqualityComparer();
public new bool Equals(object x, object y)
{
return x.Equals(y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
}
}
| |
// Copyright (c) 2007-2014 Joe White
//
// 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 DGrok.Framework;
using NUnit.Framework;
namespace DGrok.Tests
{
[TestFixture]
public class TypeTests : ParserTestCase
{
protected override RuleType RuleType
{
get { return RuleType.Type; }
}
[Test]
public void EmptyEnumDoesNotParse()
{
AssertDoesNotParse("()");
}
[Test]
public void Enum()
{
Assert.That("(fooBar)", ParsesAs(
"EnumeratedTypeNode",
" OpenParenthesisNode: OpenParenthesis |(|",
" ItemListNode: ListNode",
" Items[0]: DelimitedItemNode",
" ItemNode: EnumeratedTypeElementNode",
" NameNode: Identifier |fooBar|",
" EqualSignNode: (none)",
" ValueNode: (none)",
" DelimiterNode: (none)",
" CloseParenthesisNode: CloseParenthesis |)|"));
}
[Test]
public void QualifiedIdentifier()
{
Assert.That("System.Integer", ParsesAs(
"BinaryOperationNode",
" LeftNode: Identifier |System|",
" OperatorNode: Dot |.|",
" RightNode: Identifier |Integer|"));
}
[Test]
public void Range()
{
Assert.That("24..42", ParsesAs(
"BinaryOperationNode",
" LeftNode: Number |24|",
" OperatorNode: DotDot |..|",
" RightNode: Number |42|"));
}
[Test]
public void Array()
{
Assert.That("array of Integer", ParsesAs(
"ArrayTypeNode",
" ArrayKeywordNode: ArrayKeyword |array|",
" OpenBracketNode: (none)",
" IndexListNode: ListNode",
" CloseBracketNode: (none)",
" OfKeywordNode: OfKeyword |of|",
" TypeNode: Identifier |Integer|"));
}
[Test]
public void Set()
{
Assert.That("set of Byte", ParsesAs(
"SetOfNode",
" SetKeywordNode: SetKeyword |set|",
" OfKeywordNode: OfKeyword |of|",
" TypeNode: Identifier |Byte|"));
}
[Test]
public void File()
{
Assert.That("file", ParsesAs(
"FileTypeNode",
" FileKeywordNode: FileKeyword |file|",
" OfKeywordNode: (none)",
" TypeNode: (none)"));
}
[Test]
public void RecordHelper()
{
Assert.That("record helper for TPoint end", ParsesAs(
"TypeHelperNode",
" TypeKeywordNode: RecordKeyword |record|",
" HelperSemikeywordNode: HelperSemikeyword |helper|",
" OpenParenthesisNode: (none)",
" BaseHelperTypeNode: (none)",
" CloseParenthesisNode: (none)",
" ForKeywordNode: ForKeyword |for|",
" TypeNode: Identifier |TPoint|",
" ContentListNode: ListNode",
" EndKeywordNode: EndKeyword |end|"));
}
[Test]
public void Record()
{
Assert.That("record end", ParsesAs(
"RecordTypeNode",
" RecordKeywordNode: RecordKeyword |record|",
" ContentListNode: ListNode",
" VariantSectionNode: (none)",
" EndKeywordNode: EndKeyword |end|"));
}
[Test]
public void Pointer()
{
Assert.That("^TFoo", ParsesAs(
"PointerTypeNode",
" CaretNode: Caret |^|",
" TypeNode: Identifier |TFoo|"));
}
[Test]
public void String()
{
Assert.That("string[42]", ParsesAs(
"StringOfLengthNode",
" StringKeywordNode: StringKeyword |string|",
" OpenBracketNode: OpenBracket |[|",
" LengthNode: Number |42|",
" CloseBracketNode: CloseBracket |]|"));
}
[Test]
public void ProcedureType()
{
Assert.That("procedure of object", ParsesAs(
"ProcedureTypeNode",
" MethodTypeNode: ProcedureKeyword |procedure|",
" OpenParenthesisNode: (none)",
" ParameterListNode: ListNode",
" CloseParenthesisNode: (none)",
" ColonNode: (none)",
" ReturnTypeNode: (none)",
" FirstDirectiveListNode: ListNode",
" OfKeywordNode: OfKeyword |of|",
" ObjectKeywordNode: ObjectKeyword |object|",
" SecondDirectiveListNode: ListNode"));
}
[Test]
public void ClassHelper()
{
Assert.That("class helper for TObject end", ParsesAs(
"TypeHelperNode",
" TypeKeywordNode: ClassKeyword |class|",
" HelperSemikeywordNode: HelperSemikeyword |helper|",
" OpenParenthesisNode: (none)",
" BaseHelperTypeNode: (none)",
" CloseParenthesisNode: (none)",
" ForKeywordNode: ForKeyword |for|",
" TypeNode: Identifier |TObject|",
" ContentListNode: ListNode",
" EndKeywordNode: EndKeyword |end|"));
}
[Test]
public void ClassOf()
{
Assert.That("class of TObject", ParsesAs(
"ClassOfNode",
" ClassKeywordNode: ClassKeyword |class|",
" OfKeywordNode: OfKeyword |of|",
" TypeNode: Identifier |TObject|"));
}
[Test]
public void Class()
{
Assert.That("class end", ParsesAs(
"ClassTypeNode",
" ClassKeywordNode: ClassKeyword |class|",
" DispositionNode: (none)",
" OpenParenthesisNode: (none)",
" InheritanceListNode: ListNode",
" CloseParenthesisNode: (none)",
" ContentListNode: ListNode",
" EndKeywordNode: EndKeyword |end|"));
}
[Test]
public void Interface()
{
Assert.That("interface end", ParsesAs(
"InterfaceTypeNode",
" InterfaceKeywordNode: InterfaceKeyword |interface|",
" OpenParenthesisNode: (none)",
" BaseInterfaceNode: (none)",
" CloseParenthesisNode: (none)",
" OpenBracketNode: (none)",
" GuidNode: (none)",
" CloseBracketNode: (none)",
" MethodAndPropertyListNode: ListNode",
" EndKeywordNode: EndKeyword |end|"));
}
[Test]
public void PackedType()
{
Assert.That("packed array of Byte", ParsesAs(
"PackedTypeNode",
" PackedKeywordNode: PackedKeyword |packed|",
" TypeNode: ArrayTypeNode",
" ArrayKeywordNode: ArrayKeyword |array|",
" OpenBracketNode: (none)",
" IndexListNode: ListNode",
" CloseBracketNode: (none)",
" OfKeywordNode: OfKeyword |of|",
" TypeNode: Identifier |Byte|"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using RestSharp;
using Client;
using Model;
namespace Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IResourceApi
{
/// <summary>
/// List Resources
/// </summary>
/// <remarks>
/// You can retrieve a list of resources
/// </remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ManagedResources</returns>
ManagedResources FindAll(bool? parameter = null, int? depth = null);
/// <summary>
/// List Resources
/// </summary>
/// <remarks>
/// You can retrieve a list of resources
/// </remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ApiResponse of ManagedResources</returns>
ApiResponse<ManagedResources> FindAllWithHttpInfo(bool? parameter = null, int? depth = null);
/// <summary>
/// List Resources
/// </summary>
/// <remarks>
/// You can retrieve a list of resources
/// </remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ManagedResources</returns>
System.Threading.Tasks.Task<ManagedResources> FindAllAsync(bool? parameter = null, int? depth = null);
/// <summary>
/// List Resources
/// </summary>
/// <remarks>
/// You can retrieve a list of resources
/// </remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ApiResponse (ManagedResources)</returns>
System.Threading.Tasks.Task<ApiResponse<ManagedResources>> FindAllAsyncWithHttpInfo(bool? parameter = null, int? depth = null);
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ManagedResources</returns>
ManagedResources FindAllByType(ResourceType type, bool? parameter = null, int? depth = null);
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ApiResponse of ManagedResources</returns>
ApiResponse<ManagedResources> FindAllByTypeWithHttpInfo(ResourceType type, bool? parameter = null, int? depth = null);
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ManagedResources</returns>
System.Threading.Tasks.Task<ManagedResources> FindAllByTypeAsync(ResourceType type, bool? parameter = null, int? depth = null);
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ApiResponse (ManagedResources)</returns>
System.Threading.Tasks.Task<ApiResponse<ManagedResources>> FindAllByTypeAsyncWithHttpInfo(ResourceType type, bool? parameter = null, int? depth = null);
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ManagedResource</returns>
ManagedResource FindSpecificByType(ResourceType type, string resourceId, bool? parameter = null, int? depth = null);
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ApiResponse of ManagedResource</returns>
ApiResponse<ManagedResource> FindSpecificByTypeWithHttpInfo(ResourceType type, string resourceId, bool? parameter = null, int? depth = null);
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ManagedResource</returns>
System.Threading.Tasks.Task<ManagedResource> FindSpecificByTypeAsync(ResourceType type, string resourceId, bool? parameter = null, int? depth = null);
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ApiResponse (ManagedResource)</returns>
System.Threading.Tasks.Task<ApiResponse<ManagedResource>> FindSpecificByTypeAsyncWithHttpInfo(ResourceType type, string resourceId, bool? parameter = null, int? depth = null);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class ResourceApi : IResourceApi
{
/// <summary>
/// Initializes a new instance of the <see cref="ResourceApi"/> class.
/// </summary>
/// <returns></returns>
public ResourceApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
}
/// <summary>
/// Initializes a new instance of the <see cref="ResourceApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ResourceApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration { get; set; }
/// <summary>
/// List Resources
/// </summary>
/// <remarks>You can retrieve a list of resources</remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ManagedResources</returns>
public ManagedResources FindAll(bool? parameter = null, int? depth = null)
{
ApiResponse<ManagedResources> response = FindAllWithHttpInfo(parameter, depth);
return response.Data;
}
/// <summary>
/// List Resources
/// </summary>
/// <remarks>You can retrieve a list of resources</remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ApiResponse of ManagedResources</returns>
public ApiResponse<ManagedResources> FindAllWithHttpInfo(bool? parameter = null, int? depth = null)
{
var path_ = "/um/resources";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
// to determine the Content-Type header
String[] httpContentTypes = new String[] {
"*/*"
};
String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);
// to determine the Accept header
String[] httpHeaderAccepts = new String[] {
"application/json"
};
String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
// set "format" to json by default
pathParams.Add("format", "json");
if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter
// http basic authentication required
if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
{
headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
}
// make the HTTP request
IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_,
Method.GET, queryParams, null, headerParams, formParams, fileParams,
pathParams, httpContentType);
int statusCode = (int)response.StatusCode;
if (statusCode >= 400)
throw new ApiException(statusCode, "Error calling FindAll: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException(statusCode, "Error calling FindAll: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<ManagedResources>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ManagedResources)Configuration.ApiClient.Deserialize(response, typeof(ManagedResources)));
}
/// <summary>
/// List Resources
/// </summary>
/// <remarks>You can retrieve a list of resources</remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ManagedResources</returns>
public async System.Threading.Tasks.Task<ManagedResources> FindAllAsync(bool? parameter = null, int? depth = null)
{
ApiResponse<ManagedResources> response = await FindAllAsyncWithHttpInfo(parameter, depth);
return response.Data;
}
/// <summary>
/// List Resources
/// </summary>
/// <remarks>You can retrieve a list of resources</remarks>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ApiResponse (ManagedResources)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ManagedResources>> FindAllAsyncWithHttpInfo(bool? parameter = null, int? depth = null)
{
var path_ = "/um/resources";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
// to determine the Content-Type header
String[] httpContentTypes = new String[] {
"*/*"
};
String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);
// to determine the Accept header
String[] httpHeaderAccepts = new String[] {
"application/json"
};
String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
// set "format" to json by default
pathParams.Add("format", "json");
if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter
// http basic authentication required
if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
{
headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
}
// make the HTTP request
IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_,
Method.GET, queryParams, null, headerParams, formParams, fileParams,
pathParams, httpContentType);
int statusCode = (int)response.StatusCode;
if (statusCode >= 400)
throw new ApiException(statusCode, "Error calling FindAllAsync: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException(statusCode, "Error calling FindAllAsync: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<ManagedResources>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ManagedResources)Configuration.ApiClient.Deserialize(response, typeof(ManagedResources)));
}
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ManagedResources</returns>
public ManagedResources FindAllByType(ResourceType type, bool? parameter = null, int? depth = null)
{
ApiResponse<ManagedResources> response = FindAllByTypeWithHttpInfo(type, parameter, depth);
return response.Data;
}
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ApiResponse of ManagedResources</returns>
public ApiResponse<ManagedResources> FindAllByTypeWithHttpInfo(ResourceType type, bool? parameter = null, int? depth = null)
{
var path_ = "/um/resources/{type}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
// to determine the Content-Type header
String[] httpContentTypes = new String[] {
"*/*"
};
String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);
// to determine the Accept header
String[] httpHeaderAccepts = new String[] {
"application/json"
};
String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
// set "format" to json by default
pathParams.Add("format", "json");
pathParams.Add("type", Configuration.ApiClient.ParameterToString(type.ToString())); // path parameter
if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter
// http basic authentication required
if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
{
headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
}
// make the HTTP request
IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_,
Method.GET, queryParams, null, headerParams, formParams, fileParams,
pathParams, httpContentType);
int statusCode = (int)response.StatusCode;
if (statusCode >= 400)
throw new ApiException(statusCode, "Error calling FindAllByType: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException(statusCode, "Error calling FindAllByType: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<ManagedResources>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ManagedResources)Configuration.ApiClient.Deserialize(response, typeof(ManagedResources)));
}
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ManagedResources</returns>
public async System.Threading.Tasks.Task<ManagedResources> FindAllByTypeAsync(ResourceType type, bool? parameter = null, int? depth = null)
{
ApiResponse<ManagedResources> response = await FindAllByTypeAsyncWithHttpInfo(type, parameter, depth);
return response.Data;
}
/// <summary>
/// List resources by type
/// </summary>
/// <remarks>
/// You can retrieve a list of resources of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ApiResponse (ManagedResources)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ManagedResources>> FindAllByTypeAsyncWithHttpInfo(ResourceType type, bool? parameter = null, int? depth = null)
{
var path_ = "/um/resources/{type}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
// to determine the Content-Type header
String[] httpContentTypes = new String[] {
"*/*"
};
String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);
// to determine the Accept header
String[] httpHeaderAccepts = new String[] {
"application/json"
};
String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
// set "format" to json by default
pathParams.Add("format", "json");
pathParams.Add("type", Configuration.ApiClient.ParameterToString(type.ToString())); // path parameter
if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter
// http basic authentication required
if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
{
headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
}
// make the HTTP request
IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_,
Method.GET, queryParams, null, headerParams, formParams, fileParams,
pathParams, httpContentType);
int statusCode = (int)response.StatusCode;
if (statusCode >= 400)
throw new ApiException(statusCode, "Error calling FindAllByTypeAsync: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException(statusCode, "Error calling FindAllByTypeAsync: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<ManagedResources>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ManagedResources)Configuration.ApiClient.Deserialize(response, typeof(ManagedResources)));
}
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ManagedResources</returns>
public ManagedResource FindSpecificByType(ResourceType type, string resourceId, bool? parameter = null, int? depth = null)
{
ApiResponse<ManagedResource> response = FindSpecificByTypeWithHttpInfo(type, resourceId, parameter, depth);
return response.Data;
}
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>ApiResponse of ManagedResource</returns>
public ApiResponse<ManagedResource> FindSpecificByTypeWithHttpInfo(ResourceType type, string resourceId, bool? parameter = null, int? depth = null)
{
// verify the required parameter 'resourceId' is set
if (string.IsNullOrEmpty(resourceId))
throw new ApiException(400, "Missing required parameter 'resourceId' when calling ResourceApi->FindSpecificByType");
var path_ = "/um/resources/{type}/{resourceId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
// to determine the Content-Type header
String[] httpContentTypes = new String[] {
"*/*"
};
String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);
// to determine the Accept header
String[] httpHeaderAccepts = new String[] {
"application/json"
};
String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
// set "format" to json by default
pathParams.Add("format", "json");
pathParams.Add("type", Configuration.ApiClient.ParameterToString(type.ToString())); // path parameter
pathParams.Add("resourceId", Configuration.ApiClient.ParameterToString(resourceId)); // path parameter
if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter
// http basic authentication required
if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
{
headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
}
// make the HTTP request
IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_,
Method.GET, queryParams, null, headerParams, formParams, fileParams,
pathParams, httpContentType);
int statusCode = (int)response.StatusCode;
if (statusCode >= 400)
throw new ApiException(statusCode, "Error calling FindSpecificByType: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException(statusCode, "Error calling FindSpecificByType: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<ManagedResource>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ManagedResource)Configuration.ApiClient.Deserialize(response, typeof(ManagedResource)));
}
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ManagedResource</returns>
public async System.Threading.Tasks.Task<ManagedResource> FindSpecificByTypeAsync(ResourceType type, string resourceId, bool? parameter = null, int? depth = null)
{
ApiResponse<ManagedResource> response = await FindSpecificByTypeAsyncWithHttpInfo(type, resourceId, parameter, depth);
return response.Data;
}
/// <summary>
/// Find a resource of a type
/// </summary>
/// <remarks>
/// Retrieves a specific resource of a particular type
/// </remarks>
/// <param name="type">Resource type to list</param>
/// <param name="resourceId">The unique ID of the resource</param>
/// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
/// <param name="depth">Controls the details depth of response objects.</param>
/// <returns>Task of ApiResponse (ManagedResource)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ManagedResource>> FindSpecificByTypeAsyncWithHttpInfo(ResourceType type, string resourceId, bool? parameter = null, int? depth = null)
{
// verify the required parameter 'resourceId' is set
if (string.IsNullOrEmpty(resourceId))
throw new ApiException(400, "Missing required parameter 'resourceId' when calling ResourceApi->FindSpecificByType");
var path_ = "/um/resources/{type}/{resourceId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
// to determine the Content-Type header
String[] httpContentTypes = new String[] {
"*/*"
};
String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);
// to determine the Accept header
String[] httpHeaderAccepts = new String[] {
"application/json"
};
String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
// set "format" to json by default
pathParams.Add("format", "json");
pathParams.Add("type", Configuration.ApiClient.ParameterToString(type.ToString())); // path parameter
pathParams.Add("resourceId", Configuration.ApiClient.ParameterToString(resourceId)); // path parameter
if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter
// http basic authentication required
if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
{
headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
}
// make the HTTP request
IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_,
Method.GET, queryParams, null, headerParams, formParams, fileParams,
pathParams, httpContentType);
int statusCode = (int)response.StatusCode;
if (statusCode >= 400)
throw new ApiException(statusCode, "Error calling FindSpecificByTypeAsync: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException(statusCode, "Error calling FindSpecificByTypeAsync: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<ManagedResource>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ManagedResource)Configuration.ApiClient.Deserialize(response, typeof(ManagedResource)));
}
}
}
| |
/*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace GemFireXDDBI
{
/// <summary>
/// Main user interface
/// </summary>
public partial class GemFireXDDBI : Form
{
public GemFireXDDBI()
{
InitializeComponent();
}
private void migrateToGemFireXDToolStripMenuItem_Click(object sender, EventArgs e)
{
DBMigrate.MigrateCfg cfg = new DBMigrate.MigrateCfg();
try
{
if (cfg.ShowDialog() == DialogResult.OK)
{
DBMigrate.Progressor progessor = new DBMigrate.Progressor();
Thread pThread = new Thread(new ThreadStart(progessor.Run));
pThread.Start();
//pThread.Join();
if (progessor.DialogResult == DialogResult.Abort)
MessageBox.Show(
"Operation canceled!", "GemFireXDDBI", MessageBoxButtons.OK, MessageBoxIcon.Information);
else if (progessor.DialogResult == DialogResult.OK)
{
if (DBMigrate.Migrator.Errorred)
MessageBox.Show(
"Database migration completed with errors. Check log for details!", "GemFireXDDBI",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
else
MessageBox.Show("Database migration completed successfully!", "GemFireXDDBI",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Encountered exception during database migration. Check log for detail",
"DB Migration Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Util.Helper.Log(ex);
}
}
private void openDBToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenDB openDB = new OpenDB();
try
{
if (openDB.ShowDialog() == DialogResult.OK)
{
if (treeViewDB.Nodes[openDB.SelectedDBConn] != null)
CloseDB(openDB.SelectedDBConn);
LoadDB(openDB.SelectedDBConn);
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format(
"Failed to open connection to {0}", openDB.SelectedDBConn),
"DB Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Util.Helper.Log(ex);
}
}
private void openToolStripButton_Click(object sender, EventArgs e)
{
openDBToolStripMenuItem_Click(sender, e);
}
private void LoadDB(String dbConnName)
{
DBI.SQLBase dbi = DBI.SQLFactory.GetSqlDBI(dbConnName);
// Get tables
DataTable dt = dbi.GetTableNames();
TreeNode tnode1 = treeViewDB.Nodes.Add(dbConnName);
tnode1.Name = dbConnName;
tnode1.ContextMenuStrip = contextMenuStrip1;
TreeNode tnode2 = tnode1.Nodes.Add("Tables");
foreach (DataRow row in dt.Rows)
tnode2.Nodes.Add(
String.Format("{0}.{1}", row[0].ToString(), row[1].ToString()));
// Get views
dt.Clear();
dt = dbi.GetViews();
tnode2 = tnode1.Nodes.Add("Views");
foreach (DataRow row in dt.Rows)
tnode2.Nodes.Add(
String.Format("{0}.{1}", row[0].ToString(), row[1].ToString()));
// Get indexes
dt.Clear();
dt = dbi.GetIndexes();
tnode2 = tnode1.Nodes.Add("Indexes");
foreach (DataRow row in dt.Rows)
tnode2.Nodes.Add(
String.Format("{0}.{1}.{2}", row[0].ToString(), row[1].ToString(), row[2].ToString()));
// Get stored procedures
dt.Clear();
dt = dbi.GetStoredProcedures();
tnode2 = tnode1.Nodes.Add("Procedures");
foreach (DataRow row in dt.Rows)
tnode2.Nodes.Add(
String.Format("{0}.{1}", row[0].ToString(), row[1].ToString()));
// Get functions
dt.Clear();
dt = dbi.GetFunctions();
tnode2 = tnode1.Nodes.Add("Functions");
foreach (DataRow row in dt.Rows)
tnode2.Nodes.Add(
String.Format("{0}.{1}", row[0].ToString(), row[1].ToString()));
// Get triggers
dt.Clear();
dt = dbi.GetTriggers();
tnode2 = tnode1.Nodes.Add("Triggers");
foreach (DataRow row in dt.Rows)
tnode2.Nodes.Add(
String.Format("{0}.{1}", row[0].ToString(), row[1].ToString()));
}
private void treeViewDB_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Node.Parent == null)
return;
TreeNode tnode = e.Node;
while(tnode.Parent != null)
tnode = tnode.Parent;
DBI.SQLBase dbi = DBI.SQLFactory.GetSqlDBI(tnode.Text);
if (e.Node.Text == "Tables")
dataGridViewDB.DataSource = dbi.GetTableNames();
else if (e.Node.Text == "Views")
;
else if (e.Node.Text == "Indexes")
dataGridViewDB.DataSource = dbi.GetIndexes();
else if (e.Node.Text == "Procedures")
dataGridViewDB.DataSource = dbi.GetStoredProcedures();
else if (e.Node.Text == "Functions")
dataGridViewDB.DataSource = dbi.GetFunctions();
else if (e.Node.Text == "Triggers")
dataGridViewDB.DataSource = dbi.GetTriggers();
else if (e.Node.Parent.Text == "Tables")
dataGridViewDB.DataSource = dbi.GetTableData(e.Node.Text);
else if(e.Node.Parent.Text == "Views")
dataGridViewDB.DataSource = dbi.GetViewData(e.Node.Text);
else if (e.Node.Parent.Text == "Indexes")
dataGridViewDB.DataSource = dbi.GetIndex(e.Node.Text);
else if (e.Node.Parent.Text == "Procedures")
dataGridViewDB.DataSource = dbi.GetStoredProcedure(e.Node.Text);
else if (e.Node.Parent.Text == "Functions")
dataGridViewDB.DataSource = dbi.GetFunction(e.Node.Text);
else if (e.Node.Parent.Text == "Triggers")
dataGridViewDB.DataSource = dbi.GetTrigger(e.Node.Text);
}
private void dataGridViewDB_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
Util.Helper.Log(e.Exception);
}
private void CloseDB(String dbConnName)
{
treeViewDB.Nodes[dbConnName].Remove();
}
private void closeToolStripMenuItem1_Click(object sender, EventArgs e)
{
CloseDB(treeViewDB.SelectedNode.Name);
}
private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
{
String dbConnName = treeViewDB.SelectedNode.Name;
CloseDB(dbConnName);
LoadDB(dbConnName);
}
private void treeViewDB_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
treeViewDB.SelectedNode = treeViewDB.GetNodeAt(e.X, e.Y);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void dBConnectionsToolStripMenuItem_Click(object sender, EventArgs e)
{
Configuration.DbConnection dbConfig = new Configuration.DbConnection();
dbConfig.ShowDialog();
}
private void loggingToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.