context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Android.Gms.Maps; using Android.Gms.Maps.Model; using Android.OS; using Java.Lang; using Xamarin.Forms.Platform.Android; using Math = System.Math; using Android.Runtime; using System.Collections; namespace Xamarin.Forms.Maps.Android { public class MapRenderer : ViewRenderer, GoogleMap.IOnCameraChangeListener { public MapRenderer () { AutoPackage = false; } static Bundle s_bundle; internal static Bundle Bundle { set { s_bundle = value; } } List<Marker> _markers; const string MoveMessageName = "MapMoveToRegion"; #pragma warning disable 618 protected GoogleMap NativeMap => ((MapView) Control).Map; #pragma warning restore 618 protected Map Map => (Map) Element; public override SizeRequest GetDesiredSize (int widthConstraint, int heightConstraint) { return new SizeRequest (new Size (Context.ToPixels (40), Context.ToPixels (40))); } protected override void OnElementChanged (ElementChangedEventArgs<View> e) { base.OnElementChanged (e); var oldMapView = (MapView)Control; var mapView = new MapViewEx (Context) as MapView; mapView.OnCreate (s_bundle); mapView.OnResume (); SetNativeControl (mapView); if (e.OldElement != null) { var oldMapModel = (Map) e.OldElement; ((ObservableCollection<Pin>)oldMapModel.Pins).CollectionChanged -= OnCollectionChanged; MessagingCenter.Unsubscribe<Map, MapSpan> (this, MoveMessageName); #pragma warning disable 618 if (oldMapView.Map != null) { #pragma warning restore 618 #pragma warning disable 618 oldMapView.Map.SetOnCameraChangeListener (null); #pragma warning restore 618 NativeMap.InfoWindowClick -= MapOnMarkerClick; } oldMapView.Dispose(); } var map = NativeMap; if (map != null) { map.SetOnCameraChangeListener (this); NativeMap.InfoWindowClick += MapOnMarkerClick; map.UiSettings.ZoomControlsEnabled = Map.HasZoomEnabled; map.UiSettings.ZoomGesturesEnabled = Map.HasZoomEnabled; map.UiSettings.ScrollGesturesEnabled = Map.HasScrollEnabled; map.MyLocationEnabled = map.UiSettings.MyLocationButtonEnabled = Map.IsShowingUser; SetMapType (); } MessagingCenter.Subscribe<Map, MapSpan> (this, MoveMessageName, OnMoveToRegionMessage, Map); var incc = Map.Pins as INotifyCollectionChanged; if (incc != null) incc.CollectionChanged += OnCollectionChanged; } void OnCollectionChanged (object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { switch (notifyCollectionChangedEventArgs.Action) { case NotifyCollectionChangedAction.Add: AddPins (notifyCollectionChangedEventArgs.NewItems); break; case NotifyCollectionChangedAction.Remove: RemovePins (notifyCollectionChangedEventArgs.OldItems); break; case NotifyCollectionChangedAction.Replace: RemovePins (notifyCollectionChangedEventArgs.OldItems); AddPins (notifyCollectionChangedEventArgs.NewItems); break; case NotifyCollectionChangedAction.Reset: _markers?.ForEach (m => m.Remove ()); _markers = null; AddPins ((IList)(Element as Map).Pins); break; case NotifyCollectionChangedAction.Move: //do nothing break; } } void OnMoveToRegionMessage (Map s, MapSpan a) { MoveToRegion (a, true); } void MoveToRegion (MapSpan span, bool animate) { var map = NativeMap; if (map == null) return; span = span.ClampLatitude (85, -85); var ne = new LatLng (span.Center.Latitude + span.LatitudeDegrees / 2, span.Center.Longitude + span.LongitudeDegrees / 2); var sw = new LatLng (span.Center.Latitude - span.LatitudeDegrees / 2, span.Center.Longitude - span.LongitudeDegrees / 2); var update = CameraUpdateFactory.NewLatLngBounds (new LatLngBounds (sw, ne), 0); try { if (animate) map.AnimateCamera (update); else map.MoveCamera (update); } catch (IllegalStateException exc) { System.Diagnostics.Debug.WriteLine ("MoveToRegion exception: " + exc); } } bool _init = true; protected override void OnLayout (bool changed, int l, int t, int r, int b) { base.OnLayout (changed, l, t, r, b); if (_init) { MoveToRegion (((Map)Element).LastMoveToRegion, false); OnCollectionChanged (((Map)Element).Pins, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset)); _init = false; } else if (changed) { UpdateVisibleRegion (NativeMap.CameraPosition.Target); } } protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged (sender, e); if (e.PropertyName == Map.MapTypeProperty.PropertyName) { SetMapType(); return; } var gmap = NativeMap; if (gmap == null) return; if (e.PropertyName == Map.IsShowingUserProperty.PropertyName) gmap.MyLocationEnabled = gmap.UiSettings.MyLocationButtonEnabled = Map.IsShowingUser; else if (e.PropertyName == Map.HasScrollEnabledProperty.PropertyName) gmap.UiSettings.ScrollGesturesEnabled = Map.HasScrollEnabled; else if (e.PropertyName == Map.HasZoomEnabledProperty.PropertyName) { gmap.UiSettings.ZoomControlsEnabled = Map.HasZoomEnabled; gmap.UiSettings.ZoomGesturesEnabled = Map.HasZoomEnabled; } } void SetMapType () { var map = NativeMap; if (map == null) return; switch (Map.MapType) { case MapType.Street: map.MapType = GoogleMap.MapTypeNormal; break; case MapType.Satellite: map.MapType = GoogleMap.MapTypeSatellite; break; case MapType.Hybrid: map.MapType = GoogleMap.MapTypeHybrid; break; default: throw new ArgumentOutOfRangeException (); } } public void OnCameraChange (CameraPosition pos) { UpdateVisibleRegion (pos.Target); } void UpdateVisibleRegion (LatLng pos) { var map = NativeMap; if (map == null) return; var projection = map.Projection; var width = Control.Width; var height = Control.Height; var ul = projection.FromScreenLocation (new global::Android.Graphics.Point (0, 0)); var ur = projection.FromScreenLocation (new global::Android.Graphics.Point (width, 0)); var ll = projection.FromScreenLocation (new global::Android.Graphics.Point (0, height)); var lr = projection.FromScreenLocation (new global::Android.Graphics.Point (width, height)); var dlat = Math.Max (Math.Abs (ul.Latitude - lr.Latitude), Math.Abs (ur.Latitude - ll.Latitude)); var dlong = Math.Max (Math.Abs (ul.Longitude - lr.Longitude), Math.Abs (ur.Longitude - ll.Longitude)); ((Map)Element).VisibleRegion = new MapSpan ( new Position ( pos.Latitude, pos.Longitude ), dlat, dlong ); } void AddPins (IList pins) { var map = NativeMap; if (map == null) return; if (_markers == null) _markers = new List<Marker> (); _markers.AddRange( pins.Cast<Pin>().Select (p => { var pin = (Pin)p; var opts = new MarkerOptions (); opts.SetPosition (new LatLng (pin.Position.Latitude, pin.Position.Longitude)); opts.SetTitle (pin.Label); opts.SetSnippet (pin.Address); var marker = map.AddMarker (opts); // associate pin with marker for later lookup in event handlers pin.Id = marker.Id; return marker; })); } void RemovePins (IList pins) { var map = NativeMap; if (map == null) return; if (_markers == null) return; foreach (Pin p in pins) { var marker = _markers.FirstOrDefault (m => (object)m.Id == p.Id); if (marker == null) continue; marker.Remove (); _markers.Remove (marker); } } void MapOnMarkerClick (object sender, GoogleMap.InfoWindowClickEventArgs eventArgs) { // clicked marker var marker = eventArgs.Marker; // lookup pin Pin targetPin = null; for (var i = 0; i < Map.Pins.Count; i++) { var pin = Map.Pins[i]; if ((string)pin.Id != marker.Id) continue; targetPin = pin; break; } // only consider event handled if a handler is present. // Else allow default behavior of displaying an info window. targetPin?.SendTap (); } bool _disposed; protected override void Dispose (bool disposing) { if (disposing && !_disposed) { _disposed = true; var mapModel = Element as Map; if (mapModel != null) { MessagingCenter.Unsubscribe<Map, MapSpan> (this, MoveMessageName); ((ObservableCollection<Pin>)mapModel.Pins).CollectionChanged -= OnCollectionChanged; } var gmap = NativeMap; if (gmap == null) return; gmap.MyLocationEnabled = false; gmap.InfoWindowClick -= MapOnMarkerClick; gmap.Dispose (); } base.Dispose (disposing); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Text; namespace UMA { /// <summary> /// Utility class for merging multiple skinned meshes. /// </summary> public static class SkinnedMeshCombiner { /// <summary> /// Container for source mesh data. /// </summary> public class CombineInstance { public UMAMeshData meshData; public int[] targetSubmeshIndices; } private enum MeshComponents { none = 0, has_normals = 1, has_tangents = 2, has_colors32 = 4, has_uv = 8, has_uv2 = 16, has_uv3 = 32, has_uv4 = 64 } static Dictionary<int, BoneIndexEntry> bonesCollection; static List<Matrix4x4> bindPoses; static List<int> bonesList; /// <summary> /// Combines a set of meshes into the target mesh. /// </summary> /// <param name="target">Target.</param> /// <param name="sources">Sources.</param> public static void CombineMeshes(UMAMeshData target, CombineInstance[] sources) { int vertexCount = 0; int bindPoseCount = 0; int transformHierarchyCount = 0; MeshComponents meshComponents = MeshComponents.none; int subMeshCount = FindTargetSubMeshCount(sources); var subMeshTriangleLength = new int[subMeshCount]; AnalyzeSources(sources, subMeshTriangleLength, ref vertexCount, ref bindPoseCount, ref transformHierarchyCount, ref meshComponents); int[][] submeshTriangles = new int[subMeshCount][]; for (int i = 0; i < subMeshTriangleLength.Length; i++) { submeshTriangles[i] = new int[subMeshTriangleLength[i]]; subMeshTriangleLength[i] = 0; } bool has_normals = (meshComponents & MeshComponents.has_normals) != MeshComponents.none; bool has_tangents = (meshComponents & MeshComponents.has_tangents) != MeshComponents.none; bool has_uv = (meshComponents & MeshComponents.has_uv) != MeshComponents.none; bool has_uv2 = (meshComponents & MeshComponents.has_uv2) != MeshComponents.none; bool has_uv3 = (meshComponents & MeshComponents.has_uv3) != MeshComponents.none; bool has_uv4 = (meshComponents & MeshComponents.has_uv4) != MeshComponents.none; bool has_colors32 = (meshComponents & MeshComponents.has_colors32) != MeshComponents.none; Vector3[] vertices = EnsureArrayLength(target.vertices, vertexCount); BoneWeight[] boneWeights = EnsureArrayLength(target.unityBoneWeights, vertexCount); Vector3[] normals = has_normals ? EnsureArrayLength(target.normals, vertexCount) : null; Vector4[] tangents = has_tangents ? EnsureArrayLength(target.tangents, vertexCount) : null; Vector2[] uv = has_uv ? EnsureArrayLength(target.uv, vertexCount) : null; Vector2[] uv2 = has_uv2 ? EnsureArrayLength(target.uv2, vertexCount) : null; Vector2[] uv3 = has_uv3 ? EnsureArrayLength(target.uv3, vertexCount) : null; Vector2[] uv4 = has_uv4 ? EnsureArrayLength(target.uv4, vertexCount) : null; Color32[] colors32 = has_colors32 ? EnsureArrayLength(target.colors32, vertexCount) : null; UMATransform[] umaTransforms = EnsureArrayLength(target.umaBones, transformHierarchyCount); int boneCount = 0; foreach (var source in sources) { MergeSortedTransforms(umaTransforms, ref boneCount, source.meshData.umaBones); } int vertexIndex = 0; if (bonesCollection == null) bonesCollection = new Dictionary<int, BoneIndexEntry>(boneCount); else bonesCollection.Clear(); if (bindPoses == null) bindPoses = new List<Matrix4x4>(bindPoseCount); else bindPoses.Clear(); if (bonesList == null) bonesList = new List<int>(boneCount); else bonesList.Clear(); foreach (var source in sources) { vertexCount = source.meshData.vertices.Length; BuildBoneWeights(source.meshData.boneWeights, 0, boneWeights, vertexIndex, vertexCount, source.meshData.boneNameHashes, source.meshData.bindPoses, bonesCollection, bindPoses, bonesList); Array.Copy(source.meshData.vertices, 0, vertices, vertexIndex, vertexCount); if (has_normals) { if (source.meshData.normals != null && source.meshData.normals.Length > 0) { Array.Copy(source.meshData.normals, 0, normals, vertexIndex, vertexCount); } else { FillArray(tangents, vertexIndex, vertexCount, Vector3.zero); } } if (has_tangents) { if (source.meshData.tangents != null && source.meshData.tangents.Length > 0) { Array.Copy(source.meshData.tangents, 0, tangents, vertexIndex, vertexCount); } else { FillArray(tangents, vertexIndex, vertexCount, Vector4.zero); } } if (has_uv) { if (source.meshData.uv != null && source.meshData.uv.Length >= vertexCount) { Array.Copy(source.meshData.uv, 0, uv, vertexIndex, vertexCount); } else { FillArray(uv, vertexIndex, vertexCount, Vector4.zero); } } if (has_uv2) { if (source.meshData.uv2 != null && source.meshData.uv2.Length >= vertexCount) { Array.Copy(source.meshData.uv2, 0, uv2, vertexIndex, vertexCount); } else { FillArray(uv2, vertexIndex, vertexCount, Vector4.zero); } } if (has_uv3) { if (source.meshData.uv3 != null && source.meshData.uv3.Length >= vertexCount) { Array.Copy(source.meshData.uv3, 0, uv3, vertexIndex, vertexCount); } else { FillArray(uv3, vertexIndex, vertexCount, Vector4.zero); } } if (has_uv4) { if (source.meshData.uv4 != null && source.meshData.uv4.Length >= vertexCount) { Array.Copy(source.meshData.uv4, 0, uv4, vertexIndex, vertexCount); } else { FillArray(uv4, vertexIndex, vertexCount, Vector4.zero); } } if (has_colors32) { if (source.meshData.colors32 != null && source.meshData.colors32.Length > 0) { Array.Copy(source.meshData.colors32, 0, colors32, vertexIndex, vertexCount); } else { Color32 white32 = Color.white; FillArray(colors32, vertexIndex, vertexCount, white32); } } for (int i = 0; i < source.meshData.subMeshCount; i++) { if (source.targetSubmeshIndices[i] >= 0) { int[] subTriangles = source.meshData.submeshes[i].triangles; int triangleLength = subTriangles.Length; int destMesh = source.targetSubmeshIndices[i]; CopyIntArrayAdd(subTriangles, 0, submeshTriangles[destMesh], subMeshTriangleLength[destMesh], triangleLength, vertexIndex); subMeshTriangleLength[destMesh] += triangleLength; } } vertexIndex += vertexCount; } vertexCount = vertexIndex; // fill in new values. target.vertexCount = vertexCount; target.vertices = vertices; target.unityBoneWeights = boneWeights; target.bindPoses = bindPoses.ToArray(); target.normals = normals; target.tangents = tangents; target.uv = uv; target.uv2 = uv2; target.uv3 = uv3; target.uv4 = uv4; target.colors32 = colors32; target.subMeshCount = subMeshCount; target.submeshes = new SubMeshTriangles[subMeshCount]; target.umaBones = umaTransforms; target.umaBoneCount = boneCount; for (int i = 0; i < subMeshCount; i++) { target.submeshes[i].triangles = submeshTriangles[i]; } target.boneNameHashes = bonesList.ToArray(); } private static void MergeSortedTransforms(UMATransform[] mergedTransforms, ref int len1, UMATransform[] umaTransforms) { int newBones = 0; int pos1 = 0; int pos2 = 0; int len2 = umaTransforms.Length; while(pos1 < len1 && pos2 < len2 ) { long i = ((long)mergedTransforms[pos1].hash) - ((long)umaTransforms[pos2].hash); if (i == 0) { pos1++; pos2++; } else if (i < 0) { pos1++; } else { pos2++; newBones++; } } newBones += len2 - pos2; pos1 = len1 - 1; pos2 = len2 - 1; len1 += newBones; int dest = len1-1; while (pos1 >= 0 && pos2 >= 0) { long i = ((long)mergedTransforms[pos1].hash) - ((long)umaTransforms[pos2].hash); if (i == 0) { mergedTransforms[dest] = mergedTransforms[pos1]; pos1--; pos2--; } else if (i > 0) { mergedTransforms[dest] = mergedTransforms[pos1]; pos1--; } else { mergedTransforms[dest] = umaTransforms[pos2]; pos2--; } dest--; } while (pos2 >= 0) { mergedTransforms[dest] = umaTransforms[pos2]; pos2--; dest--; } } private static void AnalyzeSources(CombineInstance[] sources, int[] subMeshTriangleLength, ref int vertexCount, ref int bindPoseCount, ref int transformHierarchyCount, ref MeshComponents meshComponents) { for (int i = 0; i < subMeshTriangleLength.Length; i++) { subMeshTriangleLength[i] = 0; } foreach (var source in sources) { vertexCount += source.meshData.vertices.Length; bindPoseCount += source.meshData.bindPoses.Length; transformHierarchyCount += source.meshData.umaBones.Length; if (source.meshData.normals != null && source.meshData.normals.Length != 0) meshComponents |= MeshComponents.has_normals; if (source.meshData.tangents != null && source.meshData.tangents.Length != 0) meshComponents |= MeshComponents.has_tangents; if (source.meshData.uv != null && source.meshData.uv.Length != 0) meshComponents |= MeshComponents.has_uv; if (source.meshData.uv2 != null && source.meshData.uv2.Length != 0) meshComponents |= MeshComponents.has_uv2; if (source.meshData.uv3 != null && source.meshData.uv3.Length != 0) meshComponents |= MeshComponents.has_uv3; if (source.meshData.uv4 != null && source.meshData.uv4.Length != 0) meshComponents |= MeshComponents.has_uv4; if (source.meshData.colors32 != null && source.meshData.colors32.Length != 0) meshComponents |= MeshComponents.has_colors32; for (int i = 0; i < source.meshData.subMeshCount; i++) { if (source.targetSubmeshIndices[i] >= 0) { int triangleLength = source.meshData.submeshes[i].triangles.Length; subMeshTriangleLength[source.targetSubmeshIndices[i]] += triangleLength; } } } } private static int FindTargetSubMeshCount(CombineInstance[] sources) { int highestTargetIndex = -1; foreach (var source in sources) { foreach (var targetIndex in source.targetSubmeshIndices) { if (highestTargetIndex < targetIndex) { highestTargetIndex = targetIndex; } } } return highestTargetIndex + 1; } private static void BuildBoneWeights(UMABoneWeight[] source, int sourceIndex, BoneWeight[] dest, int destIndex, int count, int[] bones, Matrix4x4[] bindPoses, Dictionary<int, BoneIndexEntry> bonesCollection, List<Matrix4x4> bindPosesList, List<int> bonesList) { int[] boneMapping = new int[bones.Length]; for (int i = 0; i < boneMapping.Length; i++) { boneMapping[i] = TranslateBoneIndex(i, bones, bindPoses, bonesCollection, bindPosesList, bonesList); } while (count-- > 0) { TranslateBoneWeight(ref source[sourceIndex++], ref dest[destIndex++], boneMapping); } } private static void TranslateBoneWeight(ref UMABoneWeight source, ref BoneWeight dest, int[] boneMapping) { dest.weight0 = source.weight0; dest.weight1 = source.weight1; dest.weight2 = source.weight2; dest.weight3 = source.weight3; dest.boneIndex0 = boneMapping[source.boneIndex0]; dest.boneIndex1 = boneMapping[source.boneIndex1]; dest.boneIndex2 = boneMapping[source.boneIndex2]; dest.boneIndex3 = boneMapping[source.boneIndex3]; } private struct BoneIndexEntry { public int index; public List<int> indices; public int Count { get { return index >= 0 ? 1 : indices.Count; } } public int this[int idx] { get { if (index >= 0) { if (idx == 0) return index; throw new ArgumentOutOfRangeException(); } return indices[idx]; } } internal void AddIndex(int idx) { if (index >= 0) { indices = new List<int>(10); indices.Add(index); index = -1; } indices.Add(idx); } } private static bool CompareSkinningMatrices(Matrix4x4 m1, ref Matrix4x4 m2) { if (Mathf.Abs(m1.m00 - m2.m00) > 0.0001) return false; if (Mathf.Abs(m1.m01 - m2.m01) > 0.0001) return false; if (Mathf.Abs(m1.m02 - m2.m02) > 0.0001) return false; if (Mathf.Abs(m1.m03 - m2.m03) > 0.0001) return false; if (Mathf.Abs(m1.m10 - m2.m10) > 0.0001) return false; if (Mathf.Abs(m1.m11 - m2.m11) > 0.0001) return false; if (Mathf.Abs(m1.m12 - m2.m12) > 0.0001) return false; if (Mathf.Abs(m1.m13 - m2.m13) > 0.0001) return false; if (Mathf.Abs(m1.m20 - m2.m20) > 0.0001) return false; if (Mathf.Abs(m1.m21 - m2.m21) > 0.0001) return false; if (Mathf.Abs(m1.m22 - m2.m22) > 0.0001) return false; if (Mathf.Abs(m1.m23 - m2.m23) > 0.0001) return false; // These never change in a TRS Matrix4x4 // if (Mathf.Abs(m1.m30 - m2.m30) > 0.0001) return false; // if (Mathf.Abs(m1.m31 - m2.m31) > 0.0001) return false; // if (Mathf.Abs(m1.m32 - m2.m32) > 0.0001) return false; // if (Mathf.Abs(m1.m33 - m2.m33) > 0.0001) return false; return true; } private static int TranslateBoneIndex(int index, int[] bonesHashes, Matrix4x4[] bindPoses, Dictionary<int, BoneIndexEntry> bonesCollection, List<Matrix4x4> bindPosesList, List<int> bonesList) { var boneTransform = bonesHashes[index]; BoneIndexEntry entry; if (bonesCollection.TryGetValue(boneTransform, out entry)) { for (int i = 0; i < entry.Count; i++) { var res = entry[i]; if (CompareSkinningMatrices(bindPosesList[res], ref bindPoses[index])) { return res; } } var idx = bindPosesList.Count; entry.AddIndex(idx); bindPosesList.Add(bindPoses[index]); bonesList.Add(boneTransform); return idx; } else { var idx = bindPosesList.Count; bonesCollection.Add(boneTransform, new BoneIndexEntry() { index = idx }); bindPosesList.Add(bindPoses[index]); bonesList.Add(boneTransform); return idx; } } private static void CopyColorsToColors32(Color[] source, int sourceIndex, Color32[] dest, int destIndex, int count) { while (count-- > 0) { var sColor = source[sourceIndex++]; dest[destIndex++] = new Color32((byte)Mathf.RoundToInt(sColor.r * 255f), (byte)Mathf.RoundToInt(sColor.g * 255f), (byte)Mathf.RoundToInt(sColor.b * 255f), (byte)Mathf.RoundToInt(sColor.a * 255f)); } } private static void FillArray(Vector4[] array, int index, int count, Vector4 value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Vector3[] array, int index, int count, Vector3 value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Vector2[] array, int index, int count, Vector2 value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Color[] array, int index, int count, Color value) { while (count-- > 0) { array[index++] = value; } } private static void FillArray(Color32[] array, int index, int count, Color32 value) { while (count-- > 0) { array[index++] = value; } } private static void CopyIntArrayAdd(int[] source, int sourceIndex, int[] dest, int destIndex, int count, int add) { for (int i = 0; i < count; i++) { dest[destIndex++] = source[sourceIndex++] + add; } } private static T[] EnsureArrayLength<T>(T[] oldArray, int newLength) { if (newLength <= 0) return null; if (oldArray != null && oldArray.Length >= newLength) return oldArray; return new T[newLength]; } } }
using System; using System.Collections.Generic; using UnityEngine.Serialization; using UnityEngine.EventSystems; namespace UnityEngine.UI { // Simple selectable object - derived from to create a control. [AddComponentMenu("UI/Selectable", 70)] [ExecuteInEditMode] [SelectionBase] [DisallowMultipleComponent] public class Selectable : UIBehaviour, IMoveHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler { // Selection state // List of all the selectable objects currently active in the scene private static List<Selectable> s_List = new List<Selectable>(); public static List<Selectable> allSelectables { get { return s_List; } } // Navigation information. [FormerlySerializedAs("navigation")] [SerializeField] private Navigation m_Navigation = Navigation.defaultNavigation; // Highlighting state public enum Transition { None, ColorTint, SpriteSwap, Animation } // Type of the transition that occurs when the button state changes. [FormerlySerializedAs("transition")] [SerializeField] private Transition m_Transition = Transition.ColorTint; // Colors used for a color tint-based transition. [FormerlySerializedAs("colors")] [SerializeField] private ColorBlock m_Colors = ColorBlock.defaultColorBlock; // Sprites used for a Image swap-based transition. [FormerlySerializedAs("spriteState")] [SerializeField] private SpriteState m_SpriteState; [FormerlySerializedAs("animationTriggers")] [SerializeField] private AnimationTriggers m_AnimationTriggers = new AnimationTriggers(); [Tooltip("Can the Selectable be interacted with?")] [SerializeField] private bool m_Interactable = true; // Graphic that will be colored. [FormerlySerializedAs("highlightGraphic")] [FormerlySerializedAs("m_HighlightGraphic")] [SerializeField] private Graphic m_TargetGraphic; private bool m_GroupsAllowInteraction = true; private SelectionState m_CurrentSelectionState; public Navigation navigation { get { return m_Navigation; } set { if (SetPropertyUtility.SetStruct(ref m_Navigation, value)) OnSetProperty(); } } public Transition transition { get { return m_Transition; } set { if (SetPropertyUtility.SetStruct(ref m_Transition, value)) OnSetProperty(); } } public ColorBlock colors { get { return m_Colors; } set { if (SetPropertyUtility.SetStruct(ref m_Colors, value)) OnSetProperty(); } } public SpriteState spriteState { get { return m_SpriteState; } set { if (SetPropertyUtility.SetStruct(ref m_SpriteState, value)) OnSetProperty(); } } public AnimationTriggers animationTriggers { get { return m_AnimationTriggers; } set { if (SetPropertyUtility.SetClass(ref m_AnimationTriggers, value)) OnSetProperty(); } } public Graphic targetGraphic { get { return m_TargetGraphic; } set { if (SetPropertyUtility.SetClass(ref m_TargetGraphic, value)) OnSetProperty(); } } public bool interactable { get { return m_Interactable; } set { if (SetPropertyUtility.SetStruct(ref m_Interactable, value)) OnSetProperty(); } } private bool isPointerInside { get; set; } private bool isPointerDown { get; set; } private bool hasSelection { get; set; } protected Selectable() { } // Convenience function that converts the Graphic to a Image, if possible public Image image { get { return m_TargetGraphic as Image; } set { m_TargetGraphic = value; } } // Get the animator public Animator animator { get { return GetComponent<Animator>(); } } protected override void Awake() { if (m_TargetGraphic == null) m_TargetGraphic = GetComponent<Graphic>(); } private readonly List<CanvasGroup> m_CanvasGroupCache = new List<CanvasGroup>(); protected override void OnCanvasGroupChanged() { // Figure out if parent groups allow interaction // If no interaction is alowed... then we need // to not do that :) var groupAllowInteraction = true; Transform t = transform; while (t != null) { t.GetComponents(m_CanvasGroupCache); bool shouldBreak = false; for (var i = 0; i < m_CanvasGroupCache.Count; i++) { // if the parent group does not allow interaction // we need to break if (!m_CanvasGroupCache[i].interactable) { groupAllowInteraction = false; shouldBreak = true; } // if this is a 'fresh' group, then break // as we should not consider parents if (m_CanvasGroupCache[i].ignoreParentGroups) shouldBreak = true; } if (shouldBreak) break; t = t.parent; } if (groupAllowInteraction != m_GroupsAllowInteraction) { m_GroupsAllowInteraction = groupAllowInteraction; OnSetProperty(); } } public virtual bool IsInteractable() { return m_GroupsAllowInteraction && m_Interactable; } // Call from unity if animation properties have changed protected override void OnDidApplyAnimationProperties() { OnSetProperty(); } // Select on enable and add to the list. protected override void OnEnable() { base.OnEnable(); s_List.Add(this); var state = SelectionState.Normal; // The button will be highlighted even in some cases where it shouldn't. // For example: We only want to set the State as Highlighted if the StandaloneInputModule.m_CurrentInputMode == InputMode.Buttons // But we dont have access to this, and it might not apply to other InputModules. // TODO: figure out how to solve this. Case 617348. if (hasSelection) state = SelectionState.Highlighted; m_CurrentSelectionState = state; InternalEvaluateAndTransitionToSelectionState(true); } private void OnSetProperty() { #if UNITY_EDITOR if (!Application.isPlaying) InternalEvaluateAndTransitionToSelectionState(true); else #endif InternalEvaluateAndTransitionToSelectionState(false); } // Remove from the list. protected override void OnDisable() { s_List.Remove(this); InstantClearState(); base.OnDisable(); } #if UNITY_EDITOR protected override void OnValidate() { base.OnValidate(); m_Colors.fadeDuration = Mathf.Max(m_Colors.fadeDuration, 0.0f); // OnValidate can be called before OnEnable, this makes it unsafe to access other components // since they might not have been initialized yet. // OnSetProperty potentially access Animator or Graphics. (case 618186) if (isActiveAndEnabled) { // Need to clear out the override image on the target... DoSpriteSwap(null); // If the transition mode got changed, we need to clear all the transitions, since we don't know what the old transition mode was. StartColorTween(Color.white, true); TriggerAnimation(m_AnimationTriggers.normalTrigger); // And now go to the right state. InternalEvaluateAndTransitionToSelectionState(true); } } protected override void Reset() { m_TargetGraphic = GetComponent<Graphic>(); } #endif // if UNITY_EDITOR protected SelectionState currentSelectionState { get { return m_CurrentSelectionState; } } protected virtual void InstantClearState() { string triggerName = m_AnimationTriggers.normalTrigger; isPointerInside = false; isPointerDown = false; hasSelection = false; switch (m_Transition) { case Transition.ColorTint: StartColorTween(Color.white, true); break; case Transition.SpriteSwap: DoSpriteSwap(null); break; case Transition.Animation: TriggerAnimation(triggerName); break; } } protected virtual void DoStateTransition(SelectionState state, bool instant) { Color tintColor; Sprite transitionSprite; string triggerName; switch (state) { case SelectionState.Normal: tintColor = m_Colors.normalColor; transitionSprite = null; triggerName = m_AnimationTriggers.normalTrigger; break; case SelectionState.Highlighted: tintColor = m_Colors.highlightedColor; transitionSprite = m_SpriteState.highlightedSprite; triggerName = m_AnimationTriggers.highlightedTrigger; break; case SelectionState.Pressed: tintColor = m_Colors.pressedColor; transitionSprite = m_SpriteState.pressedSprite; triggerName = m_AnimationTriggers.pressedTrigger; break; case SelectionState.Disabled: tintColor = m_Colors.disabledColor; transitionSprite = m_SpriteState.disabledSprite; triggerName = m_AnimationTriggers.disabledTrigger; break; default: tintColor = Color.black; transitionSprite = null; triggerName = string.Empty; break; } if (gameObject.activeInHierarchy) { switch (m_Transition) { case Transition.ColorTint: StartColorTween(tintColor * m_Colors.colorMultiplier, instant); break; case Transition.SpriteSwap: DoSpriteSwap(transitionSprite); break; case Transition.Animation: TriggerAnimation(triggerName); break; } } } protected enum SelectionState { Normal, Highlighted, Pressed, Disabled } // Selection logic // Find the next selectable object in the specified world-space direction. public Selectable FindSelectable(Vector3 dir) { dir = dir.normalized; Vector3 localDir = Quaternion.Inverse(transform.rotation) * dir; Vector3 pos = transform.TransformPoint(GetPointOnRectEdge(transform as RectTransform, localDir)); float maxScore = Mathf.NegativeInfinity; Selectable bestPick = null; for (int i = 0; i < s_List.Count; ++i) { Selectable sel = s_List[i]; if (sel == this || sel == null) continue; if (!sel.IsInteractable() || sel.navigation.mode == Navigation.Mode.None) continue; var selRect = sel.transform as RectTransform; Vector3 selCenter = selRect != null ? (Vector3)selRect.rect.center : Vector3.zero; Vector3 myVector = sel.transform.TransformPoint(selCenter) - pos; // Value that is the distance out along the direction. float dot = Vector3.Dot(dir, myVector); // Skip elements that are in the wrong direction or which have zero distance. // This also ensures that the scoring formula below will not have a division by zero error. if (dot <= 0) continue; // This scoring function has two priorities: // - Score higher for positions that are closer. // - Score higher for positions that are located in the right direction. // This scoring function combines both of these criteria. // It can be seen as this: // Dot (dir, myVector.normalized) / myVector.magnitude // The first part equals 1 if the direction of myVector is the same as dir, and 0 if it's orthogonal. // The second part scores lower the greater the distance is by dividing by the distance. // The formula below is equivalent but more optimized. // // If a given score is chosen, the positions that evaluate to that score will form a circle // that touches pos and whose center is located along dir. A way to visualize the resulting functionality is this: // From the position pos, blow up a circular balloon so it grows in the direction of dir. // The first Selectable whose center the circular balloon touches is the one that's chosen. float score = dot / myVector.sqrMagnitude; if (score > maxScore) { maxScore = score; bestPick = sel; } } return bestPick; } private static Vector3 GetPointOnRectEdge(RectTransform rect, Vector2 dir) { if (rect == null) return Vector3.zero; if (dir != Vector2.zero) dir /= Mathf.Max(Mathf.Abs(dir.x), Mathf.Abs(dir.y)); dir = rect.rect.center + Vector2.Scale(rect.rect.size, dir * 0.5f); return dir; } // Convenience function -- change the selection to the specified object if it's not null and happens to be active. void Navigate(AxisEventData eventData, Selectable sel) { if (sel != null && sel.IsActive()) eventData.selectedObject = sel.gameObject; } // Find the selectable object to the left of this one. public virtual Selectable FindSelectableOnLeft() { if (m_Navigation.mode == Navigation.Mode.Explicit) { return m_Navigation.selectOnLeft; } if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0) { return FindSelectable(transform.rotation * Vector3.left); } return null; } // Find the selectable object to the right of this one. public virtual Selectable FindSelectableOnRight() { if (m_Navigation.mode == Navigation.Mode.Explicit) { return m_Navigation.selectOnRight; } if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0) { return FindSelectable(transform.rotation * Vector3.right); } return null; } // Find the selectable object above this one public virtual Selectable FindSelectableOnUp() { if (m_Navigation.mode == Navigation.Mode.Explicit) { return m_Navigation.selectOnUp; } if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0) { return FindSelectable(transform.rotation * Vector3.up); } return null; } // Find the selectable object below this one. public virtual Selectable FindSelectableOnDown() { if (m_Navigation.mode == Navigation.Mode.Explicit) { return m_Navigation.selectOnDown; } if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0) { return FindSelectable(transform.rotation * Vector3.down); } return null; } public virtual void OnMove(AxisEventData eventData) { switch (eventData.moveDir) { case MoveDirection.Right: Navigate(eventData, FindSelectableOnRight()); break; case MoveDirection.Up: Navigate(eventData, FindSelectableOnUp()); break; case MoveDirection.Left: Navigate(eventData, FindSelectableOnLeft()); break; case MoveDirection.Down: Navigate(eventData, FindSelectableOnDown()); break; } } void StartColorTween(Color targetColor, bool instant) { if (m_TargetGraphic == null) return; m_TargetGraphic.CrossFadeColor(targetColor, instant ? 0f : m_Colors.fadeDuration, true, true); } void DoSpriteSwap(Sprite newSprite) { if (image == null) return; image.overrideSprite = newSprite; } void TriggerAnimation(string triggername) { if (animator == null || !animator.enabled || !animator.isActiveAndEnabled || animator.runtimeAnimatorController == null || string.IsNullOrEmpty(triggername)) return; animator.ResetTrigger(m_AnimationTriggers.normalTrigger); animator.ResetTrigger(m_AnimationTriggers.pressedTrigger); animator.ResetTrigger(m_AnimationTriggers.highlightedTrigger); animator.ResetTrigger(m_AnimationTriggers.disabledTrigger); animator.SetTrigger(triggername); } // Whether the control should be 'selected'. protected bool IsHighlighted(BaseEventData eventData) { if (!IsActive()) return false; if (IsPressed()) return false; bool selected = hasSelection; if (eventData is PointerEventData) { var pointerData = eventData as PointerEventData; selected |= (isPointerDown && !isPointerInside && pointerData.pointerPress == gameObject) // This object pressed, but pointer moved off || (!isPointerDown && isPointerInside && pointerData.pointerPress == gameObject) // This object pressed, but pointer released over (PointerUp event) || (!isPointerDown && isPointerInside && pointerData.pointerPress == null); // Nothing pressed, but pointer is over } else { selected |= isPointerInside; } return selected; } [Obsolete("Is Pressed no longer requires eventData", false)] protected bool IsPressed(BaseEventData eventData) { return IsPressed(); } // Whether the control should be pressed. protected bool IsPressed() { if (!IsActive()) return false; return isPointerInside && isPointerDown; } // The current visual state of the control. protected void UpdateSelectionState(BaseEventData eventData) { if (IsPressed()) { m_CurrentSelectionState = SelectionState.Pressed; return; } if (IsHighlighted(eventData)) { m_CurrentSelectionState = SelectionState.Highlighted; return; } m_CurrentSelectionState = SelectionState.Normal; } // Change the button to the correct state private void EvaluateAndTransitionToSelectionState(BaseEventData eventData) { if (!IsActive()) return; UpdateSelectionState(eventData); InternalEvaluateAndTransitionToSelectionState(false); } private void InternalEvaluateAndTransitionToSelectionState(bool instant) { var transitionState = m_CurrentSelectionState; if (IsActive() && !IsInteractable()) transitionState = SelectionState.Disabled; DoStateTransition(transitionState, instant); } public virtual void OnPointerDown(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return; // Selection tracking if (IsInteractable() && navigation.mode != Navigation.Mode.None) EventSystem.current.SetSelectedGameObject(gameObject, eventData); isPointerDown = true; EvaluateAndTransitionToSelectionState(eventData); } public virtual void OnPointerUp(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return; isPointerDown = false; EvaluateAndTransitionToSelectionState(eventData); } public virtual void OnPointerEnter(PointerEventData eventData) { isPointerInside = true; EvaluateAndTransitionToSelectionState(eventData); } public virtual void OnPointerExit(PointerEventData eventData) { isPointerInside = false; EvaluateAndTransitionToSelectionState(eventData); } public virtual void OnSelect(BaseEventData eventData) { hasSelection = true; EvaluateAndTransitionToSelectionState(eventData); } public virtual void OnDeselect(BaseEventData eventData) { hasSelection = false; EvaluateAndTransitionToSelectionState(eventData); } public virtual void Select() { if (EventSystem.current.alreadySelecting) return; EventSystem.current.SetSelectedGameObject(gameObject); } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableGreaterThanOrEqualTests { #region Test methods [Fact] public static void CheckNullableByteGreaterThanOrEqualTest() { byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableCharGreaterThanOrEqualTest() { char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableDecimalGreaterThanOrEqualTest() { decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableDoubleGreaterThanOrEqualTest() { double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableFloatGreaterThanOrEqualTest() { float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableIntGreaterThanOrEqualTest() { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableLongGreaterThanOrEqualTest() { long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteGreaterThanOrEqualTest() { sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableShortGreaterThanOrEqualTest() { short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableUIntGreaterThanOrEqualTest() { uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableULongGreaterThanOrEqualTest() { ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongGreaterThanOrEqual(array[i], array[j]); } } } [Fact] public static void CheckNullableUShortGreaterThanOrEqualTest() { ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortGreaterThanOrEqual(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteGreaterThanOrEqual(byte? a, byte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableCharGreaterThanOrEqual(char? a, char? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDecimalGreaterThanOrEqual(decimal? a, decimal? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDoubleGreaterThanOrEqual(double? a, double? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableFloatGreaterThanOrEqual(float? a, float? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableIntGreaterThanOrEqual(int? a, int? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableLongGreaterThanOrEqual(long? a, long? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableSByteGreaterThanOrEqual(sbyte? a, sbyte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableShortGreaterThanOrEqual(short? a, short? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableUIntGreaterThanOrEqual(uint? a, uint? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableULongGreaterThanOrEqual(ulong? a, ulong? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableUShortGreaterThanOrEqual(ushort? a, ushort? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a >= b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } #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 System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Thrift; using Thrift.Protocol; using Thrift.Server; using Thrift.Transport; using Thrift.Transport.Server; using tutorial; using shared; using Thrift.Processor; using System.Diagnostics; namespace Server { public class Program { private static ServiceCollection ServiceCollection = new ServiceCollection(); private static ILogger Logger; private static readonly TConfiguration Configuration = null; // new TConfiguration() if needed public static void Main(string[] args) { args = args ?? new string[0]; ServiceCollection.AddLogging(logging => ConfigureLogging(logging)); using (var serviceProvider = ServiceCollection.BuildServiceProvider()) { Logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger(nameof(Server)); if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase))) { DisplayHelp(); return; } using (var source = new CancellationTokenSource()) { RunAsync(args, source.Token).GetAwaiter().GetResult(); Logger.LogInformation("Press any key to stop..."); Console.ReadLine(); source.Cancel(); } Logger.LogInformation("Server stopped"); } } private static void ConfigureLogging(ILoggingBuilder logging) { logging.SetMinimumLevel(LogLevel.Trace); logging.AddConsole(); logging.AddDebug(); } private static void DisplayHelp() { Logger.LogInformation(@" Usage: Server -help will diplay help information Server -tr:<transport> -bf:<buffering> -pr:<protocol> will run server with specified arguments (tcp transport, no buffering, and binary protocol by default) Options: -tr (transport): tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090) namedpipe - namedpipe transport will be used (pipe address - "".test"") http - http transport will be used (http address - ""localhost:9090"") tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090) -bf (buffering): none - (default) no buffering will be used buffered - buffered transport will be used framed - framed transport will be used -pr (protocol): binary - (default) binary protocol will be used compact - compact protocol will be used json - json protocol will be used multiplexed - multiplexed protocol will be used Sample: Server -tr:tcp "); } private static async Task RunAsync(string[] args, CancellationToken cancellationToken) { var selectedTransport = GetTransport(args); var selectedBuffering = GetBuffering(args); var selectedProtocol = GetProtocol(args); if (selectedTransport == Transport.Http) { new HttpServerSample().Run(cancellationToken); } else { await RunSelectedConfigurationAsync(selectedTransport, selectedBuffering, selectedProtocol, cancellationToken); } } private static Protocol GetProtocol(string[] args) { var transport = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1]; Enum.TryParse(transport, true, out Protocol selectedProtocol); return selectedProtocol; } private static Buffering GetBuffering(string[] args) { var buffering = args.FirstOrDefault(x => x.StartsWith("-bf"))?.Split(":")?[1]; Enum.TryParse<Buffering>(buffering, out var selectedBuffering); return selectedBuffering; } private static Transport GetTransport(string[] args) { var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1]; Enum.TryParse(transport, true, out Transport selectedTransport); return selectedTransport; } private static async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, CancellationToken cancellationToken) { var handler = new CalculatorAsyncHandler(); TServerTransport serverTransport = null; switch (transport) { case Transport.Tcp: serverTransport = new TServerSocketTransport(9090, Configuration); break; case Transport.NamedPipe: serverTransport = new TNamedPipeServerTransport(".test", Configuration); break; case Transport.TcpTls: serverTransport = new TTlsServerSocketTransport(9090, Configuration, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback); break; } TTransportFactory inputTransportFactory = null; TTransportFactory outputTransportFactory = null; switch (buffering) { case Buffering.Buffered: inputTransportFactory = new TBufferedTransport.Factory(); outputTransportFactory = new TBufferedTransport.Factory(); break; case Buffering.Framed: inputTransportFactory = new TFramedTransport.Factory(); outputTransportFactory = new TFramedTransport.Factory(); break; default: // layered transport(s) are optional Debug.Assert(buffering == Buffering.None, "unhandled case"); break; } TProtocolFactory inputProtocolFactory = null; TProtocolFactory outputProtocolFactory = null; ITAsyncProcessor processor = null; switch (protocol) { case Protocol.Binary: inputProtocolFactory = new TBinaryProtocol.Factory(); outputProtocolFactory = new TBinaryProtocol.Factory(); processor = new Calculator.AsyncProcessor(handler); break; case Protocol.Compact: inputProtocolFactory = new TCompactProtocol.Factory(); outputProtocolFactory = new TCompactProtocol.Factory(); processor = new Calculator.AsyncProcessor(handler); break; case Protocol.Json: inputProtocolFactory = new TJsonProtocol.Factory(); outputProtocolFactory = new TJsonProtocol.Factory(); processor = new Calculator.AsyncProcessor(handler); break; case Protocol.Multiplexed: inputProtocolFactory = new TBinaryProtocol.Factory(); outputProtocolFactory = new TBinaryProtocol.Factory(); var calcHandler = new CalculatorAsyncHandler(); var calcProcessor = new Calculator.AsyncProcessor(calcHandler); var sharedServiceHandler = new SharedServiceAsyncHandler(); var sharedServiceProcessor = new SharedService.AsyncProcessor(sharedServiceHandler); var multiplexedProcessor = new TMultiplexedProcessor(); multiplexedProcessor.RegisterProcessor(nameof(Calculator), calcProcessor); multiplexedProcessor.RegisterProcessor(nameof(SharedService), sharedServiceProcessor); processor = multiplexedProcessor; break; default: throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null); } try { Logger.LogInformation( $"Selected TAsyncServer with {serverTransport} transport, {processor} processor and {inputProtocolFactory} protocol factories"); var loggerFactory = ServiceCollection.BuildServiceProvider().GetService<ILoggerFactory>(); var server = new TSimpleAsyncServer( itProcessorFactory: new TSingletonProcessorFactory(processor), serverTransport: serverTransport, inputTransportFactory: inputTransportFactory, outputTransportFactory: outputTransportFactory, inputProtocolFactory: inputProtocolFactory, outputProtocolFactory: outputProtocolFactory, logger: loggerFactory.CreateLogger<TSimpleAsyncServer>()); Logger.LogInformation("Starting the server..."); await server.ServeAsync(cancellationToken); } catch (Exception x) { Logger.LogInformation(x.ToString()); } } private static X509Certificate2 GetCertificate() { // due to files location in net core better to take certs from top folder var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory())); return new X509Certificate2(certFile, "ThriftTest"); } private static string GetCertPath(DirectoryInfo di, int maxCount = 6) { var topDir = di; var certFile = topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories) .FirstOrDefault(); if (certFile == null) { if (maxCount == 0) throw new FileNotFoundException("Cannot find file in directories"); return GetCertPath(di.Parent, maxCount - 1); } return certFile.FullName; } private static X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return GetCertificate(); } private static bool ClientCertValidator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } private enum Transport { Tcp, NamedPipe, Http, TcpTls, } private enum Buffering { None, Buffered, Framed, } private enum Protocol { Binary, Compact, Json, Multiplexed } public class HttpServerSample { public void Run(CancellationToken cancellationToken) { var config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseUrls("http://localhost:9090") .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .ConfigureLogging((ctx,logging) => ConfigureLogging(logging)) .Build(); Logger.LogTrace("test"); Logger.LogCritical("test"); host.RunAsync(cancellationToken).GetAwaiter().GetResult(); } public class Startup { public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddTransient<Calculator.IAsync, CalculatorAsyncHandler>(); services.AddTransient<ITAsyncProcessor, Calculator.AsyncProcessor>(); services.AddTransient<THttpServerTransport, THttpServerTransport>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { app.UseMiddleware<THttpServerTransport>(); } } } public class CalculatorAsyncHandler : Calculator.IAsync { private readonly Dictionary<int, SharedStruct> _log = new Dictionary<int, SharedStruct>(); public CalculatorAsyncHandler() { } public async Task<SharedStruct> getStructAsync(int key, CancellationToken cancellationToken) { Logger.LogInformation("GetStructAsync({0})", key); return await Task.FromResult(_log[key]); } public async Task pingAsync(CancellationToken cancellationToken) { Logger.LogInformation("PingAsync()"); await Task.CompletedTask; } public async Task<int> addAsync(int num1, int num2, CancellationToken cancellationToken) { Logger.LogInformation($"AddAsync({num1},{num2})"); return await Task.FromResult(num1 + num2); } public async Task<int> calculateAsync(int logid, Work w, CancellationToken cancellationToken) { Logger.LogInformation($"CalculateAsync({logid}, [{w.Op},{w.Num1},{w.Num2}])"); var val = 0; switch (w.Op) { case Operation.ADD: val = w.Num1 + w.Num2; break; case Operation.SUBTRACT: val = w.Num1 - w.Num2; break; case Operation.MULTIPLY: val = w.Num1 * w.Num2; break; case Operation.DIVIDE: if (w.Num2 == 0) { var io = new InvalidOperation { WhatOp = (int) w.Op, Why = "Cannot divide by 0" }; throw io; } val = w.Num1 / w.Num2; break; default: { var io = new InvalidOperation { WhatOp = (int) w.Op, Why = "Unknown operation" }; throw io; } } var entry = new SharedStruct { Key = logid, Value = val.ToString() }; _log[logid] = entry; return await Task.FromResult(val); } public async Task zipAsync(CancellationToken cancellationToken) { Logger.LogInformation("ZipAsync() with delay 100mc"); await Task.Delay(100, CancellationToken.None); } } public class SharedServiceAsyncHandler : SharedService.IAsync { public async Task<SharedStruct> getStructAsync(int key, CancellationToken cancellationToken) { Logger.LogInformation("GetStructAsync({0})", key); return await Task.FromResult(new SharedStruct() { Key = key, Value = "GetStructAsync" }); } } } }
// // parameter.cs: Parameter definition. // // Author: Miguel de Icaza ([email protected]) // Marek Safar ([email protected]) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2008 Novell, Inc. // Copyright 2011 Xamarin Inc // // using System; using System.Text; #if STATIC using MetaType = IKVM.Reflection.Type; using IKVM.Reflection; using IKVM.Reflection.Emit; #else using MetaType = System.Type; using System.Reflection; using System.Reflection.Emit; #endif namespace Mono.CSharp { /// <summary> /// Abstract Base class for parameters of a method. /// </summary> public abstract class ParameterBase : Attributable { protected ParameterBuilder builder; public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { #if false if (a.Type == pa.MarshalAs) { UnmanagedMarshal marshal = a.GetMarshal (this); if (marshal != null) { builder.SetMarshal (marshal); } return; } #endif if (a.HasSecurityAttribute) { a.Error_InvalidSecurityParent (); return; } if (a.Type == pa.Dynamic) { a.Error_MisusedDynamicAttribute (); return; } builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata); } public ParameterBuilder Builder { get { return builder; } } public override bool IsClsComplianceRequired() { return false; } } /// <summary> /// Class for applying custom attributes on the return type /// </summary> public class ReturnParameter : ParameterBase { MemberCore method; // TODO: merge method and mb public ReturnParameter (MemberCore method, MethodBuilder mb, Location location) { this.method = method; try { builder = mb.DefineParameter (0, ParameterAttributes.None, ""); } catch (ArgumentOutOfRangeException) { method.Compiler.Report.RuntimeMissingSupport (location, "custom attributes on the return type"); } } public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (a.Type == pa.CLSCompliant) { method.Compiler.Report.Warning (3023, 1, a.Location, "CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead"); } // This occurs after Warning -28 if (builder == null) return; base.ApplyAttributeBuilder (a, ctor, cdata, pa); } public override AttributeTargets AttributeTargets { get { return AttributeTargets.ReturnValue; } } /// <summary> /// Is never called /// </summary> public override string[] ValidAttributeTargets { get { return null; } } } public class ImplicitLambdaParameter : Parameter { public ImplicitLambdaParameter (string name, Location loc) : base (null, name, Modifier.NONE, null, loc) { } public override TypeSpec Resolve (IMemberContext ec, int index) { if (parameter_type == null) throw new InternalErrorException ("A type of implicit lambda parameter `{0}' is not set", Name); base.idx = index; return parameter_type; } public void SetParameterType (TypeSpec type) { parameter_type = type; } } public class ParamsParameter : Parameter { public ParamsParameter (FullNamedExpression type, string name, Attributes attrs, Location loc): base (type, name, Parameter.Modifier.PARAMS, attrs, loc) { } public override TypeSpec Resolve (IMemberContext ec, int index) { if (base.Resolve (ec, index) == null) return null; var ac = parameter_type as ArrayContainer; if (ac == null || ac.Rank != 1) { ec.Module.Compiler.Report.Error (225, Location, "The params parameter must be a single dimensional array"); return null; } return parameter_type; } public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa) { base.ApplyAttributes (mb, cb, index, pa); pa.ParamArray.EmitAttribute (builder); } } public class ArglistParameter : Parameter { // Doesn't have proper type because it's never chosen for better conversion public ArglistParameter (Location loc) : base (null, String.Empty, Parameter.Modifier.NONE, null, loc) { parameter_type = InternalType.Arglist; } public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa) { // Nothing to do } public override bool CheckAccessibility (InterfaceMemberBase member) { return true; } public override TypeSpec Resolve (IMemberContext ec, int index) { return parameter_type; } } public interface IParameterData { Expression DefaultValue { get; } bool HasExtensionMethodModifier { get; } bool HasDefaultValue { get; } Parameter.Modifier ModFlags { get; } string Name { get; } } // // Parameter information created by parser // public class Parameter : ParameterBase, IParameterData, ILocalVariable // TODO: INamedBlockVariable { [Flags] public enum Modifier : byte { NONE = 0, PARAMS = 1 << 0, REF = 1 << 1, OUT = 1 << 2, This = 1 << 3, CallerMemberName = 1 << 4, CallerLineNumber = 1 << 5, CallerFilePath = 1 << 6, RefOutMask = REF | OUT, ModifierMask = PARAMS | REF | OUT | This, CallerMask = CallerMemberName | CallerLineNumber | CallerFilePath } static readonly string[] attribute_targets = new string[] { "param" }; FullNamedExpression texpr; Modifier modFlags; string name; Expression default_expr; protected TypeSpec parameter_type; readonly Location loc; protected int idx; public bool HasAddressTaken; TemporaryVariableReference expr_tree_variable; HoistedParameter hoisted_variant; public Parameter (FullNamedExpression type, string name, Modifier mod, Attributes attrs, Location loc) { this.name = name; modFlags = mod; this.loc = loc; texpr = type; // Only assign, attributes will be attached during resolve base.attributes = attrs; } #region Properties public Expression DefaultExpression { get { return default_expr; } } public DefaultParameterValueExpression DefaultValue { get { return default_expr as DefaultParameterValueExpression; } set { default_expr = value; } } Expression IParameterData.DefaultValue { get { var expr = default_expr as DefaultParameterValueExpression; return expr == null ? default_expr : expr.Child; } } bool HasOptionalExpression { get { return default_expr is DefaultParameterValueExpression; } } public Location Location { get { return loc; } } public Modifier ParameterModifier { get { return modFlags; } } public TypeSpec Type { get { return parameter_type; } set { parameter_type = value; } } public FullNamedExpression TypeExpression { get { return texpr; } } public override string[] ValidAttributeTargets { get { return attribute_targets; } } #endregion public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (a.Type == pa.In && ModFlags == Modifier.OUT) { a.Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute"); return; } if (a.Type == pa.ParamArray) { a.Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead"); return; } if (a.Type == pa.Out && (ModFlags & Modifier.REF) != 0 && !OptAttributes.Contains (pa.In)) { a.Report.Error (662, a.Location, "Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither"); return; } if (a.Type == pa.CLSCompliant) { a.Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead"); } else if (a.Type == pa.DefaultParameterValue || a.Type == pa.OptionalParameter) { if (HasOptionalExpression) { a.Report.Error (1745, a.Location, "Cannot specify `{0}' attribute on optional parameter `{1}'", TypeManager.CSharpName (a.Type).Replace ("Attribute", ""), Name); } if (a.Type == pa.DefaultParameterValue) return; } else if (a.Type == pa.CallerMemberNameAttribute) { if ((modFlags & Modifier.CallerMemberName) == 0) { a.Report.Error (4022, a.Location, "The CallerMemberName attribute can only be applied to parameters with default value"); } } else if (a.Type == pa.CallerLineNumberAttribute) { if ((modFlags & Modifier.CallerLineNumber) == 0) { a.Report.Error (4020, a.Location, "The CallerLineNumber attribute can only be applied to parameters with default value"); } } else if (a.Type == pa.CallerFilePathAttribute) { if ((modFlags & Modifier.CallerFilePath) == 0) { a.Report.Error (4021, a.Location, "The CallerFilePath attribute can only be applied to parameters with default value"); } } base.ApplyAttributeBuilder (a, ctor, cdata, pa); } public virtual bool CheckAccessibility (InterfaceMemberBase member) { if (parameter_type == null) return true; return member.IsAccessibleAs (parameter_type); } // <summary> // Resolve is used in method definitions // </summary> public virtual TypeSpec Resolve (IMemberContext rc, int index) { if (parameter_type != null) return parameter_type; if (attributes != null) attributes.AttachTo (this, rc); parameter_type = texpr.ResolveAsType (rc); if (parameter_type == null) return null; this.idx = index; if ((modFlags & Parameter.Modifier.RefOutMask) != 0 && parameter_type.IsSpecialRuntimeType) { rc.Module.Compiler.Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'", GetSignatureForError ()); return null; } TypeManager.CheckTypeVariance (parameter_type, (modFlags & Parameter.Modifier.RefOutMask) != 0 ? Variance.None : Variance.Contravariant, rc); if (parameter_type.IsStatic) { rc.Module.Compiler.Report.Error (721, Location, "`{0}': static types cannot be used as parameters", texpr.GetSignatureForError ()); return parameter_type; } if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)) { rc.Module.Compiler.Report.Error (1103, Location, "The extension method cannot be of type `{0}'", TypeManager.CSharpName (parameter_type)); } return parameter_type; } void ResolveCallerAttributes (ResolveContext rc) { var pa = rc.Module.PredefinedAttributes; TypeSpec caller_type; foreach (var attr in attributes.Attrs) { var atype = attr.ResolveType (); if (atype == null) continue; if (atype == pa.CallerMemberNameAttribute) { caller_type = rc.BuiltinTypes.String; if (caller_type != parameter_type && !Convert.ImplicitReferenceConversionExists (caller_type, parameter_type)) { rc.Report.Error (4019, attr.Location, "The CallerMemberName attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'", caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ()); } modFlags |= Modifier.CallerMemberName; continue; } if (atype == pa.CallerLineNumberAttribute) { caller_type = rc.BuiltinTypes.Int; if (caller_type != parameter_type && !Convert.ImplicitNumericConversionExists (caller_type, parameter_type)) { rc.Report.Error (4017, attr.Location, "The CallerMemberName attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'", caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ()); } modFlags |= Modifier.CallerLineNumber; continue; } if (atype == pa.CallerFilePathAttribute) { caller_type = rc.BuiltinTypes.String; if (caller_type != parameter_type && !Convert.ImplicitReferenceConversionExists (caller_type, parameter_type)) { rc.Report.Error (4018, attr.Location, "The CallerFilePath attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'", caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ()); } modFlags |= Modifier.CallerFilePath; continue; } } } public void ResolveDefaultValue (ResolveContext rc) { // // Default value was specified using an expression // if (default_expr != null) { ((DefaultParameterValueExpression)default_expr).Resolve (rc, this); if (attributes != null) ResolveCallerAttributes (rc); return; } if (attributes == null) return; var pa = rc.Module.PredefinedAttributes; var def_attr = attributes.Search (pa.DefaultParameterValue); if (def_attr != null) { if (def_attr.Resolve () == null) return; var default_expr_attr = def_attr.GetParameterDefaultValue (); if (default_expr_attr == null) return; var dpa_rc = def_attr.CreateResolveContext (); default_expr = default_expr_attr.Resolve (dpa_rc); if (default_expr is BoxedCast) default_expr = ((BoxedCast) default_expr).Child; Constant c = default_expr as Constant; if (c == null) { if (parameter_type.BuiltinType == BuiltinTypeSpec.Type.Object) { rc.Report.Error (1910, default_expr.Location, "Argument of type `{0}' is not applicable for the DefaultParameterValue attribute", default_expr.Type.GetSignatureForError ()); } else { rc.Report.Error (1909, default_expr.Location, "The DefaultParameterValue attribute is not applicable on parameters of type `{0}'", default_expr.Type.GetSignatureForError ()); ; } default_expr = null; return; } if (TypeSpecComparer.IsEqual (default_expr.Type, parameter_type) || (default_expr is NullConstant && TypeSpec.IsReferenceType (parameter_type) && !parameter_type.IsGenericParameter) || parameter_type.BuiltinType == BuiltinTypeSpec.Type.Object) { return; } // // LAMESPEC: Some really weird csc behaviour which we have to mimic // User operators returning same type as parameter type are considered // valid for this attribute only // // struct S { public static implicit operator S (int i) {} } // // void M ([DefaultParameterValue (3)]S s) // var expr = Convert.ImplicitUserConversion (dpa_rc, default_expr, parameter_type, loc); if (expr != null && TypeSpecComparer.IsEqual (expr.Type, parameter_type)) { return; } rc.Report.Error (1908, default_expr.Location, "The type of the default value should match the type of the parameter"); return; } var opt_attr = attributes.Search (pa.OptionalParameter); if (opt_attr != null) { default_expr = EmptyExpression.MissingValue; } } public bool HasDefaultValue { get { return default_expr != null; } } public bool HasExtensionMethodModifier { get { return (modFlags & Modifier.This) != 0; } } // // Hoisted parameter variant // public HoistedParameter HoistedVariant { get { return hoisted_variant; } set { hoisted_variant = value; } } public Modifier ModFlags { get { return modFlags & ~Modifier.This; } } public string Name { get { return name; } set { name = value; } } public override AttributeTargets AttributeTargets { get { return AttributeTargets.Parameter; } } public void Error_DuplicateName (Report r) { r.Error (100, Location, "The parameter name `{0}' is a duplicate", Name); } public virtual string GetSignatureForError () { string type_name; if (parameter_type != null) type_name = TypeManager.CSharpName (parameter_type); else type_name = texpr.GetSignatureForError (); string mod = GetModifierSignature (modFlags); if (mod.Length > 0) return String.Concat (mod, " ", type_name); return type_name; } public static string GetModifierSignature (Modifier mod) { switch (mod) { case Modifier.OUT: return "out"; case Modifier.PARAMS: return "params"; case Modifier.REF: return "ref"; case Modifier.This: return "this"; default: return ""; } } public void IsClsCompliant (IMemberContext ctx) { if (parameter_type.IsCLSCompliant ()) return; ctx.Module.Compiler.Report.Warning (3001, 1, Location, "Argument type `{0}' is not CLS-compliant", parameter_type.GetSignatureForError ()); } public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa) { if (builder != null) throw new InternalErrorException ("builder already exists"); var pattrs = ParametersCompiled.GetParameterAttribute (modFlags); if (HasOptionalExpression) pattrs |= ParameterAttributes.Optional; if (mb == null) builder = cb.DefineParameter (index, pattrs, Name); else builder = mb.DefineParameter (index, pattrs, Name); if (OptAttributes != null) OptAttributes.Emit (); if (HasDefaultValue) { // // Emit constant values for true constants only, the other // constant-like expressions will rely on default value expression // var def_value = DefaultValue; Constant c = def_value != null ? def_value.Child as Constant : default_expr as Constant; if (c != null) { if (c.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal) { pa.DecimalConstant.EmitAttribute (builder, (decimal) c.GetValue (), c.Location); } else { builder.SetConstant (c.GetValue ()); } } else if (default_expr.Type.IsStruct) { // // Handles special case where default expression is used with value-type // // void Foo (S s = default (S)) {} // builder.SetConstant (null); } } if (parameter_type != null) { if (parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { pa.Dynamic.EmitAttribute (builder); } else if (parameter_type.HasDynamicElement) { pa.Dynamic.EmitAttribute (builder, parameter_type, Location); } } } public Parameter Clone () { Parameter p = (Parameter) MemberwiseClone (); if (attributes != null) p.attributes = attributes.Clone (); return p; } public ExpressionStatement CreateExpressionTreeVariable (BlockContext ec) { if ((modFlags & Modifier.RefOutMask) != 0) ec.Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier"); expr_tree_variable = TemporaryVariableReference.Create (ResolveParameterExpressionType (ec, Location).Type, ec.CurrentBlock.ParametersBlock, Location); expr_tree_variable = (TemporaryVariableReference) expr_tree_variable.Resolve (ec); Arguments arguments = new Arguments (2); arguments.Add (new Argument (new TypeOf (parameter_type, Location))); arguments.Add (new Argument (new StringConstant (ec.BuiltinTypes, Name, Location))); return new SimpleAssign (ExpressionTreeVariableReference (), Expression.CreateExpressionFactoryCall (ec, "Parameter", null, arguments, Location)); } public void Emit (EmitContext ec) { ec.EmitArgumentLoad (idx); } public void EmitAssign (EmitContext ec) { ec.EmitArgumentStore (idx); } public void EmitAddressOf (EmitContext ec) { if ((ModFlags & Modifier.RefOutMask) != 0) { ec.EmitArgumentLoad (idx); } else { ec.EmitArgumentAddress (idx); } } public TemporaryVariableReference ExpressionTreeVariableReference () { return expr_tree_variable; } // // System.Linq.Expressions.ParameterExpression type // public static TypeExpr ResolveParameterExpressionType (IMemberContext ec, Location location) { TypeSpec p_type = ec.Module.PredefinedTypes.ParameterExpression.Resolve (); return new TypeExpression (p_type, location); } public void Warning_UselessOptionalParameter (Report Report) { Report.Warning (1066, 1, Location, "The default value specified for optional parameter `{0}' will never be used", Name); } } // // Imported or resolved parameter information // public class ParameterData : IParameterData { readonly string name; readonly Parameter.Modifier modifiers; readonly Expression default_value; public ParameterData (string name, Parameter.Modifier modifiers) { this.name = name; this.modifiers = modifiers; } public ParameterData (string name, Parameter.Modifier modifiers, Expression defaultValue) : this (name, modifiers) { this.default_value = defaultValue; } #region IParameterData Members public Expression DefaultValue { get { return default_value; } } public bool HasExtensionMethodModifier { get { return (modifiers & Parameter.Modifier.This) != 0; } } public bool HasDefaultValue { get { return default_value != null; } } public Parameter.Modifier ModFlags { get { return modifiers; } } public string Name { get { return name; } } #endregion } public abstract class AParametersCollection { protected bool has_arglist; protected bool has_params; // Null object pattern protected IParameterData [] parameters; protected TypeSpec [] types; public CallingConventions CallingConvention { get { return has_arglist ? CallingConventions.VarArgs : CallingConventions.Standard; } } public int Count { get { return parameters.Length; } } public TypeSpec ExtensionMethodType { get { if (Count == 0) return null; return FixedParameters [0].HasExtensionMethodModifier ? types [0] : null; } } public IParameterData [] FixedParameters { get { return parameters; } } public static ParameterAttributes GetParameterAttribute (Parameter.Modifier modFlags) { return (modFlags & Parameter.Modifier.OUT) != 0 ? ParameterAttributes.Out : ParameterAttributes.None; } // Very expensive operation public MetaType[] GetMetaInfo () { MetaType[] types; if (has_arglist) { if (Count == 1) return MetaType.EmptyTypes; types = new MetaType[Count - 1]; } else { if (Count == 0) return MetaType.EmptyTypes; types = new MetaType[Count]; } for (int i = 0; i < types.Length; ++i) { types[i] = Types[i].GetMetaInfo (); if ((FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) == 0) continue; // TODO MemberCache: Should go to MetaInfo getter types [i] = types [i].MakeByRefType (); } return types; } // // Returns the parameter information based on the name // public int GetParameterIndexByName (string name) { for (int idx = 0; idx < Count; ++idx) { if (parameters [idx].Name == name) return idx; } return -1; } public string GetSignatureForDocumentation () { if (IsEmpty) return string.Empty; StringBuilder sb = new StringBuilder ("("); for (int i = 0; i < Count; ++i) { if (i != 0) sb.Append (","); sb.Append (types [i].GetSignatureForDocumentation ()); if ((parameters[i].ModFlags & Parameter.Modifier.RefOutMask) != 0) sb.Append ("@"); } sb.Append (")"); return sb.ToString (); } public string GetSignatureForError () { return GetSignatureForError ("(", ")", Count); } public string GetSignatureForError (string start, string end, int count) { StringBuilder sb = new StringBuilder (start); for (int i = 0; i < count; ++i) { if (i != 0) sb.Append (", "); sb.Append (ParameterDesc (i)); } sb.Append (end); return sb.ToString (); } public bool HasArglist { get { return has_arglist; } } public bool HasExtensionMethodType { get { if (Count == 0) return false; return FixedParameters [0].HasExtensionMethodModifier; } } public bool HasParams { get { return has_params; } } public bool IsEmpty { get { return parameters.Length == 0; } } public AParametersCollection Inflate (TypeParameterInflator inflator) { TypeSpec[] inflated_types = null; bool default_value = false; for (int i = 0; i < Count; ++i) { var inflated_param = inflator.Inflate (types[i]); if (inflated_types == null) { if (inflated_param == types[i]) continue; default_value |= FixedParameters[i] is DefaultValueExpression; inflated_types = new TypeSpec[types.Length]; Array.Copy (types, inflated_types, types.Length); } inflated_types[i] = inflated_param; } if (inflated_types == null) return this; var clone = (AParametersCollection) MemberwiseClone (); clone.types = inflated_types; if (default_value) { for (int i = 0; i < Count; ++i) { var dve = clone.FixedParameters[i] as DefaultValueExpression; if (dve != null) { throw new NotImplementedException ("net"); // clone.FixedParameters [i].DefaultValue = new DefaultValueExpression (); } } } return clone; } public string ParameterDesc (int pos) { if (types == null || types [pos] == null) return ((Parameter)FixedParameters [pos]).GetSignatureForError (); string type = TypeManager.CSharpName (types [pos]); if (FixedParameters [pos].HasExtensionMethodModifier) return "this " + type; Parameter.Modifier mod = FixedParameters [pos].ModFlags; if (mod == 0) return type; return Parameter.GetModifierSignature (mod) + " " + type; } public TypeSpec[] Types { get { return types; } set { types = value; } } } // // A collection of imported or resolved parameters // public class ParametersImported : AParametersCollection { public ParametersImported (IParameterData [] parameters, TypeSpec [] types, bool hasArglist, bool hasParams) { this.parameters = parameters; this.types = types; this.has_arglist = hasArglist; this.has_params = hasParams; } public ParametersImported (IParameterData[] param, TypeSpec[] types, bool hasParams) { this.parameters = param; this.types = types; this.has_params = hasParams; } } /// <summary> /// Represents the methods parameters /// </summary> public class ParametersCompiled : AParametersCollection { public static readonly ParametersCompiled EmptyReadOnlyParameters = new ParametersCompiled (); // Used by C# 2.0 delegates public static readonly ParametersCompiled Undefined = new ParametersCompiled (); private ParametersCompiled () { parameters = new Parameter [0]; types = TypeSpec.EmptyTypes; } private ParametersCompiled (IParameterData[] parameters, TypeSpec[] types) { this.parameters = parameters; this.types = types; } public ParametersCompiled (params Parameter[] parameters) { if (parameters == null || parameters.Length == 0) throw new ArgumentException ("Use EmptyReadOnlyParameters"); this.parameters = parameters; int count = parameters.Length; for (int i = 0; i < count; i++){ has_params |= (parameters [i].ModFlags & Parameter.Modifier.PARAMS) != 0; } } public ParametersCompiled (Parameter [] parameters, bool has_arglist) : this (parameters) { this.has_arglist = has_arglist; } public static ParametersCompiled CreateFullyResolved (Parameter p, TypeSpec type) { return new ParametersCompiled (new Parameter [] { p }, new TypeSpec [] { type }); } public static ParametersCompiled CreateFullyResolved (Parameter[] parameters, TypeSpec[] types) { return new ParametersCompiled (parameters, types); } // // TODO: This does not fit here, it should go to different version of AParametersCollection // as the underlying type is not Parameter and some methods will fail to cast // public static AParametersCollection CreateFullyResolved (params TypeSpec[] types) { var pd = new ParameterData [types.Length]; for (int i = 0; i < pd.Length; ++i) pd[i] = new ParameterData (null, Parameter.Modifier.NONE, null); return new ParametersCompiled (pd, types); } public static ParametersCompiled CreateImplicitParameter (FullNamedExpression texpr, Location loc) { return new ParametersCompiled ( new[] { new Parameter (texpr, "value", Parameter.Modifier.NONE, null, loc) }, null); } public void CheckConstraints (IMemberContext mc) { foreach (Parameter p in parameters) { // // It's null for compiler generated types or special types like __arglist // if (p.TypeExpression != null) ConstraintChecker.Check (mc, p.Type, p.TypeExpression.Location); } } // // Returns non-zero value for equal CLS parameter signatures // public static int IsSameClsSignature (AParametersCollection a, AParametersCollection b) { int res = 0; for (int i = 0; i < a.Count; ++i) { var a_type = a.Types[i]; var b_type = b.Types[i]; if (TypeSpecComparer.Override.IsEqual (a_type, b_type)) { if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask)) res |= 1; continue; } var ac_a = a_type as ArrayContainer; if (ac_a == null) return 0; var ac_b = b_type as ArrayContainer; if (ac_b == null) return 0; if (ac_a.Element is ArrayContainer || ac_b.Element is ArrayContainer) { res |= 2; continue; } if (ac_a.Rank != ac_b.Rank && TypeSpecComparer.Override.IsEqual (ac_a.Element, ac_b.Element)) { res |= 1; continue; } return 0; } return res; } public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter compilerParams, TypeSpec compilerTypes) { return MergeGenerated (ctx, userParams, checkConflicts, new Parameter [] { compilerParams }, new TypeSpec [] { compilerTypes }); } // // Use this method when you merge compiler generated parameters with user parameters // public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter[] compilerParams, TypeSpec[] compilerTypes) { Parameter[] all_params = new Parameter [userParams.Count + compilerParams.Length]; userParams.FixedParameters.CopyTo(all_params, 0); TypeSpec [] all_types; if (userParams.types != null) { all_types = new TypeSpec [all_params.Length]; userParams.Types.CopyTo (all_types, 0); } else { all_types = null; } int last_filled = userParams.Count; int index = 0; foreach (Parameter p in compilerParams) { for (int i = 0; i < last_filled; ++i) { while (p.Name == all_params [i].Name) { if (checkConflicts && i < userParams.Count) { ctx.Report.Error (316, userParams[i].Location, "The parameter name `{0}' conflicts with a compiler generated name", p.Name); } p.Name = '_' + p.Name; } } all_params [last_filled] = p; if (all_types != null) all_types [last_filled] = compilerTypes [index++]; ++last_filled; } ParametersCompiled parameters = new ParametersCompiled (all_params, all_types); parameters.has_params = userParams.has_params; return parameters; } // // Parameters checks for members which don't have a block // public void CheckParameters (MemberCore member) { for (int i = 0; i < parameters.Length; ++i) { var name = parameters[i].Name; for (int ii = i + 1; ii < parameters.Length; ++ii) { if (parameters[ii].Name == name) this[ii].Error_DuplicateName (member.Compiler.Report); } } } public bool Resolve (IMemberContext ec) { if (types != null) return true; types = new TypeSpec [Count]; bool ok = true; Parameter p; for (int i = 0; i < FixedParameters.Length; ++i) { p = this [i]; TypeSpec t = p.Resolve (ec, i); if (t == null) { ok = false; continue; } types [i] = t; } return ok; } public void ResolveDefaultValues (MemberCore m) { ResolveContext rc = null; for (int i = 0; i < parameters.Length; ++i) { Parameter p = (Parameter) parameters [i]; // // Try not to enter default values resolution if there are is not any default value possible // if (p.HasDefaultValue || p.OptAttributes != null) { if (rc == null) rc = new ResolveContext (m); p.ResolveDefaultValue (rc); } } } // Define each type attribute (in/out/ref) and // the argument names. public void ApplyAttributes (IMemberContext mc, MethodBase builder) { if (Count == 0) return; MethodBuilder mb = builder as MethodBuilder; ConstructorBuilder cb = builder as ConstructorBuilder; var pa = mc.Module.PredefinedAttributes; for (int i = 0; i < Count; i++) { this [i].ApplyAttributes (mb, cb, i + 1, pa); } } public void VerifyClsCompliance (IMemberContext ctx) { foreach (Parameter p in FixedParameters) p.IsClsCompliant (ctx); } public Parameter this [int pos] { get { return (Parameter) parameters [pos]; } } public Expression CreateExpressionTree (BlockContext ec, Location loc) { var initializers = new ArrayInitializer (Count, loc); foreach (Parameter p in FixedParameters) { // // Each parameter expression is stored to local variable // to save some memory when referenced later. // StatementExpression se = new StatementExpression (p.CreateExpressionTreeVariable (ec), Location.Null); if (se.Resolve (ec)) { ec.CurrentBlock.AddScopeStatement (new TemporaryVariableReference.Declarator (p.ExpressionTreeVariableReference ())); ec.CurrentBlock.AddScopeStatement (se); } initializers.Add (p.ExpressionTreeVariableReference ()); } return new ArrayCreation ( Parameter.ResolveParameterExpressionType (ec, loc), initializers, loc); } public ParametersCompiled Clone () { ParametersCompiled p = (ParametersCompiled) MemberwiseClone (); p.parameters = new IParameterData [parameters.Length]; for (int i = 0; i < Count; ++i) p.parameters [i] = this [i].Clone (); return p; } } // // Default parameter value expression. We need this wrapper to handle // default parameter values of folded constants (e.g. indexer parameters). // The expression is resolved only once but applied to two methods which // both share reference to this expression and we ensure that resolving // this expression always returns same instance // public class DefaultParameterValueExpression : CompositeExpression { public DefaultParameterValueExpression (Expression expr) : base (expr) { } protected override Expression DoResolve (ResolveContext rc) { return base.DoResolve (rc); } public void Resolve (ResolveContext rc, Parameter p) { var expr = Resolve (rc); if (expr == null) return; expr = Child; if (!(expr is Constant || expr is DefaultValueExpression || (expr is New && ((New) expr).IsDefaultStruct))) { rc.Report.Error (1736, Location, "The expression being assigned to optional parameter `{0}' must be a constant or default value", p.Name); return; } var parameter_type = p.Type; if (type == parameter_type) return; var res = Convert.ImplicitConversionStandard (rc, expr, parameter_type, Location); if (res != null) { if (parameter_type.IsNullableType && res is Nullable.Wrap) { Nullable.Wrap wrap = (Nullable.Wrap) res; res = wrap.Child; if (!(res is Constant)) { rc.Report.Error (1770, Location, "The expression being assigned to nullable optional parameter `{0}' must be default value", p.Name); return; } } if (!expr.IsNull && TypeSpec.IsReferenceType (parameter_type) && parameter_type.BuiltinType != BuiltinTypeSpec.Type.String) { rc.Report.Error (1763, Location, "Optional parameter `{0}' of type `{1}' can only be initialized with `null'", p.Name, parameter_type.GetSignatureForError ()); return; } this.expr = res; return; } rc.Report.Error (1750, Location, "Optional parameter expression of type `{0}' cannot be converted to parameter type `{1}'", type.GetSignatureForError (), parameter_type.GetSignatureForError ()); } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } }
// 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.IO; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class UnixDomainSocketTest { private readonly ITestOutputHelper _log; public UnixDomainSocketTest(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void Socket_CreateUnixDomainSocket_Throws_OnWindows() { SocketException e = Assert.Throws<SocketException>(() => new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)); Assert.Equal(SocketError.AddressFamilyNotSupported, e.SocketErrorCode); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_Success() { string path = null; SocketTestServer server = null; UnixDomainSocketEndPoint endPoint = null; for (int attempt = 0; attempt < 5; attempt++) { path = GetRandomNonExistingFilePath(); endPoint = new UnixDomainSocketEndPoint(path); try { server = SocketTestServer.SocketTestServerFactory(endPoint, ProtocolType.Unspecified); break; } catch (SocketException) { //Path selection is contingent on a successful Bind(). //If it fails, the next iteration will try another path. } } try { Assert.NotNull(server); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = endPoint; args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true); var complete = new TaskCompletionSource<bool>(); args.UserToken = complete; using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { Assert.True(sock.ConnectAsync(args)); await complete.Task; Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); } } finally { server.Dispose(); try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = endPoint; args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true); var complete = new TaskCompletionSource<bool>(); args.UserToken = complete; using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { await complete.Task; } Assert.Equal(SocketError.AddressNotAvailable, args.SocketError); } } finally { try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_SendReceive_Success() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(endPoint); server.Listen(1); client.Connect(endPoint); using (Socket accepted = server.Accept()) { var data = new byte[1]; for (int i = 0; i < 10; i++) { data[0] = (byte)i; accepted.Send(data); data[0] = 0; Assert.Equal(1, client.Receive(data)); Assert.Equal(i, data[0]); } } } } finally { try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public async Task Socket_SendReceiveAsync_Success() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(endPoint); server.Listen(1); await client.ConnectAsync(endPoint); using (Socket accepted = await server.AcceptAsync()) { var data = new byte[1]; for (int i = 0; i < 10; i++) { data[0] = (byte)i; await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None); data[0] = 0; Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None)); Assert.Equal(i, data[0]); } } } } finally { try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void ConcurrentSendReceive() { using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { const int Iters = 500; const int Chunk = 1024; byte[] sendData = new byte[Chunk * Iters]; byte[] receiveData = new byte[sendData.Length]; new Random().NextBytes(sendData); string path = GetRandomNonExistingFilePath(); server.Bind(new UnixDomainSocketEndPoint(path)); server.Listen(1); Task<Socket> acceptTask = server.AcceptAsync(); client.Connect(new UnixDomainSocketEndPoint(path)); acceptTask.Wait(); Socket accepted = acceptTask.Result; Task[] writes = new Task[Iters]; Task<int>[] reads = new Task<int>[Iters]; for (int i = 0; i < Iters; i++) { writes[i] = client.SendAsync(new ArraySegment<byte>(sendData, i * Chunk, Chunk), SocketFlags.None); } for (int i = 0; i < Iters; i++) { reads[i] = accepted.ReceiveAsync(new ArraySegment<byte>(receiveData, i * Chunk, Chunk), SocketFlags.None); } Task.WaitAll(writes); Task.WaitAll(reads); for (int i = 0; i < sendData.Length; i++) { Assert.True(sendData[i] == receiveData[i], $"Different at {i}"); } } } private static string GetRandomNonExistingFilePath() { string result; do { result = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); } while (File.Exists(result)); return result; } } }
/* * OEML - REST API * * This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) * * The version of the OpenAPI document: v1 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = CoinAPI.OMS.API.SDK.Client.OpenAPIDateConverter; namespace CoinAPI.OMS.API.SDK.Model { /// <summary> /// The order execution report object. /// </summary> [DataContract(Name = "OrderExecutionReport")] public partial class OrderExecutionReport : IEquatable<OrderExecutionReport>, IValidatableObject { /// <summary> /// Gets or Sets Side /// </summary> [DataMember(Name = "side", IsRequired = true, EmitDefaultValue = false)] public OrdSide Side { get; set; } /// <summary> /// Gets or Sets OrderType /// </summary> [DataMember(Name = "order_type", IsRequired = true, EmitDefaultValue = false)] public OrdType OrderType { get; set; } /// <summary> /// Gets or Sets TimeInForce /// </summary> [DataMember(Name = "time_in_force", IsRequired = true, EmitDefaultValue = false)] public TimeInForce TimeInForce { get; set; } /// <summary> /// Defines ExecInst /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ExecInstEnum { /// <summary> /// Enum MAKERORCANCEL for value: MAKER_OR_CANCEL /// </summary> [EnumMember(Value = "MAKER_OR_CANCEL")] MAKERORCANCEL = 1, /// <summary> /// Enum AUCTIONONLY for value: AUCTION_ONLY /// </summary> [EnumMember(Value = "AUCTION_ONLY")] AUCTIONONLY = 2, /// <summary> /// Enum INDICATIONOFINTEREST for value: INDICATION_OF_INTEREST /// </summary> [EnumMember(Value = "INDICATION_OF_INTEREST")] INDICATIONOFINTEREST = 3 } /// <summary> /// Order execution instructions are documented in the separate section: &lt;a href&#x3D;\&quot;#oeml-order-params-exec\&quot;&gt;OEML / Starter Guide / Order parameters / Execution instructions&lt;/a&gt; /// </summary> /// <value>Order execution instructions are documented in the separate section: &lt;a href&#x3D;\&quot;#oeml-order-params-exec\&quot;&gt;OEML / Starter Guide / Order parameters / Execution instructions&lt;/a&gt; </value> [DataMember(Name = "exec_inst", EmitDefaultValue = false)] public List<ExecInstEnum> ExecInst { get; set; } /// <summary> /// Gets or Sets Status /// </summary> [DataMember(Name = "status", IsRequired = true, EmitDefaultValue = false)] public OrdStatus Status { get; set; } /// <summary> /// Initializes a new instance of the <see cref="OrderExecutionReport" /> class. /// </summary> [JsonConstructorAttribute] protected OrderExecutionReport() { } /// <summary> /// Initializes a new instance of the <see cref="OrderExecutionReport" /> class. /// </summary> /// <param name="exchangeId">Exchange identifier used to identify the routing destination. (required).</param> /// <param name="clientOrderId">The unique identifier of the order assigned by the client. (required).</param> /// <param name="symbolIdExchange">Exchange symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order..</param> /// <param name="symbolIdCoinapi">CoinAPI symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order..</param> /// <param name="amountOrder">Order quantity. (required).</param> /// <param name="price">Order price. (required).</param> /// <param name="side">side (required).</param> /// <param name="orderType">orderType (required).</param> /// <param name="timeInForce">timeInForce (required).</param> /// <param name="expireTime">Expiration time. Conditionaly required for orders with time_in_force &#x3D; &#x60;GOOD_TILL_TIME_EXCHANGE&#x60; or &#x60;GOOD_TILL_TIME_OEML&#x60;..</param> /// <param name="execInst">Order execution instructions are documented in the separate section: &lt;a href&#x3D;\&quot;#oeml-order-params-exec\&quot;&gt;OEML / Starter Guide / Order parameters / Execution instructions&lt;/a&gt; .</param> /// <param name="clientOrderIdFormatExchange">The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. (required).</param> /// <param name="exchangeOrderId">Unique identifier of the order assigned by the exchange or executing system..</param> /// <param name="amountOpen">Quantity open for further execution. &#x60;amount_open&#x60; &#x3D; &#x60;amount_order&#x60; - &#x60;amount_filled&#x60; (required).</param> /// <param name="amountFilled">Total quantity filled. (required).</param> /// <param name="avgPx">Calculated average price of all fills on this order..</param> /// <param name="status">status (required).</param> /// <param name="statusHistory">Timestamped history of order status changes..</param> /// <param name="errorMessage">Error message..</param> /// <param name="fills">Relay fill information on working orders..</param> public OrderExecutionReport(string exchangeId = default(string), string clientOrderId = default(string), string symbolIdExchange = default(string), string symbolIdCoinapi = default(string), decimal amountOrder = default(decimal), decimal price = default(decimal), OrdSide side = default(OrdSide), OrdType orderType = default(OrdType), TimeInForce timeInForce = default(TimeInForce), DateTime expireTime = default(DateTime), List<ExecInstEnum> execInst = default(List<ExecInstEnum>), string clientOrderIdFormatExchange = default(string), string exchangeOrderId = default(string), decimal amountOpen = default(decimal), decimal amountFilled = default(decimal), decimal avgPx = default(decimal), OrdStatus status = default(OrdStatus), List<List<string>> statusHistory = default(List<List<string>>), string errorMessage = default(string), List<Fills> fills = default(List<Fills>)) { // to ensure "exchangeId" is required (not null) if (exchangeId == null) { throw new ArgumentNullException("exchangeId is a required property for OrderExecutionReport and cannot be null"); } this.ExchangeId = exchangeId; // to ensure "clientOrderId" is required (not null) if (clientOrderId == null) { throw new ArgumentNullException("clientOrderId is a required property for OrderExecutionReport and cannot be null"); } this.ClientOrderId = clientOrderId; this.AmountOrder = amountOrder; this.Price = price; this.Side = side; this.OrderType = orderType; this.TimeInForce = timeInForce; // to ensure "clientOrderIdFormatExchange" is required (not null) if (clientOrderIdFormatExchange == null) { throw new ArgumentNullException("clientOrderIdFormatExchange is a required property for OrderExecutionReport and cannot be null"); } this.ClientOrderIdFormatExchange = clientOrderIdFormatExchange; this.AmountOpen = amountOpen; this.AmountFilled = amountFilled; this.Status = status; this.SymbolIdExchange = symbolIdExchange; this.SymbolIdCoinapi = symbolIdCoinapi; this.ExpireTime = expireTime; this.ExecInst = execInst; this.ExchangeOrderId = exchangeOrderId; this.AvgPx = avgPx; this.StatusHistory = statusHistory; this.ErrorMessage = errorMessage; this.Fills = fills; } /// <summary> /// Exchange identifier used to identify the routing destination. /// </summary> /// <value>Exchange identifier used to identify the routing destination.</value> [DataMember(Name = "exchange_id", IsRequired = true, EmitDefaultValue = false)] public string ExchangeId { get; set; } /// <summary> /// The unique identifier of the order assigned by the client. /// </summary> /// <value>The unique identifier of the order assigned by the client.</value> [DataMember(Name = "client_order_id", IsRequired = true, EmitDefaultValue = false)] public string ClientOrderId { get; set; } /// <summary> /// Exchange symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order. /// </summary> /// <value>Exchange symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order.</value> [DataMember(Name = "symbol_id_exchange", EmitDefaultValue = false)] public string SymbolIdExchange { get; set; } /// <summary> /// CoinAPI symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order. /// </summary> /// <value>CoinAPI symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order.</value> [DataMember(Name = "symbol_id_coinapi", EmitDefaultValue = false)] public string SymbolIdCoinapi { get; set; } /// <summary> /// Order quantity. /// </summary> /// <value>Order quantity.</value> [DataMember(Name = "amount_order", IsRequired = true, EmitDefaultValue = false)] public decimal AmountOrder { get; set; } /// <summary> /// Order price. /// </summary> /// <value>Order price.</value> [DataMember(Name = "price", IsRequired = true, EmitDefaultValue = false)] public decimal Price { get; set; } /// <summary> /// Expiration time. Conditionaly required for orders with time_in_force &#x3D; &#x60;GOOD_TILL_TIME_EXCHANGE&#x60; or &#x60;GOOD_TILL_TIME_OEML&#x60;. /// </summary> /// <value>Expiration time. Conditionaly required for orders with time_in_force &#x3D; &#x60;GOOD_TILL_TIME_EXCHANGE&#x60; or &#x60;GOOD_TILL_TIME_OEML&#x60;.</value> [DataMember(Name = "expire_time", EmitDefaultValue = false)] public DateTime ExpireTime { get; set; } /// <summary> /// The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. /// </summary> /// <value>The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it.</value> [DataMember(Name = "client_order_id_format_exchange", IsRequired = true, EmitDefaultValue = false)] public string ClientOrderIdFormatExchange { get; set; } /// <summary> /// Unique identifier of the order assigned by the exchange or executing system. /// </summary> /// <value>Unique identifier of the order assigned by the exchange or executing system.</value> [DataMember(Name = "exchange_order_id", EmitDefaultValue = false)] public string ExchangeOrderId { get; set; } /// <summary> /// Quantity open for further execution. &#x60;amount_open&#x60; &#x3D; &#x60;amount_order&#x60; - &#x60;amount_filled&#x60; /// </summary> /// <value>Quantity open for further execution. &#x60;amount_open&#x60; &#x3D; &#x60;amount_order&#x60; - &#x60;amount_filled&#x60;</value> [DataMember(Name = "amount_open", IsRequired = true, EmitDefaultValue = false)] public decimal AmountOpen { get; set; } /// <summary> /// Total quantity filled. /// </summary> /// <value>Total quantity filled.</value> [DataMember(Name = "amount_filled", IsRequired = true, EmitDefaultValue = false)] public decimal AmountFilled { get; set; } /// <summary> /// Calculated average price of all fills on this order. /// </summary> /// <value>Calculated average price of all fills on this order.</value> [DataMember(Name = "avg_px", EmitDefaultValue = false)] public decimal AvgPx { get; set; } /// <summary> /// Timestamped history of order status changes. /// </summary> /// <value>Timestamped history of order status changes.</value> [DataMember(Name = "status_history", EmitDefaultValue = false)] public List<List<string>> StatusHistory { get; set; } /// <summary> /// Error message. /// </summary> /// <value>Error message.</value> [DataMember(Name = "error_message", EmitDefaultValue = false)] public string ErrorMessage { get; set; } /// <summary> /// Relay fill information on working orders. /// </summary> /// <value>Relay fill information on working orders.</value> [DataMember(Name = "fills", EmitDefaultValue = false)] public List<Fills> Fills { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class OrderExecutionReport {\n"); sb.Append(" ExchangeId: ").Append(ExchangeId).Append("\n"); sb.Append(" ClientOrderId: ").Append(ClientOrderId).Append("\n"); sb.Append(" SymbolIdExchange: ").Append(SymbolIdExchange).Append("\n"); sb.Append(" SymbolIdCoinapi: ").Append(SymbolIdCoinapi).Append("\n"); sb.Append(" AmountOrder: ").Append(AmountOrder).Append("\n"); sb.Append(" Price: ").Append(Price).Append("\n"); sb.Append(" Side: ").Append(Side).Append("\n"); sb.Append(" OrderType: ").Append(OrderType).Append("\n"); sb.Append(" TimeInForce: ").Append(TimeInForce).Append("\n"); sb.Append(" ExpireTime: ").Append(ExpireTime).Append("\n"); sb.Append(" ExecInst: ").Append(ExecInst).Append("\n"); sb.Append(" ClientOrderIdFormatExchange: ").Append(ClientOrderIdFormatExchange).Append("\n"); sb.Append(" ExchangeOrderId: ").Append(ExchangeOrderId).Append("\n"); sb.Append(" AmountOpen: ").Append(AmountOpen).Append("\n"); sb.Append(" AmountFilled: ").Append(AmountFilled).Append("\n"); sb.Append(" AvgPx: ").Append(AvgPx).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" StatusHistory: ").Append(StatusHistory).Append("\n"); sb.Append(" ErrorMessage: ").Append(ErrorMessage).Append("\n"); sb.Append(" Fills: ").Append(Fills).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as OrderExecutionReport); } /// <summary> /// Returns true if OrderExecutionReport instances are equal /// </summary> /// <param name="input">Instance of OrderExecutionReport to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderExecutionReport input) { if (input == null) { return false; } return ( this.ExchangeId == input.ExchangeId || (this.ExchangeId != null && this.ExchangeId.Equals(input.ExchangeId)) ) && ( this.ClientOrderId == input.ClientOrderId || (this.ClientOrderId != null && this.ClientOrderId.Equals(input.ClientOrderId)) ) && ( this.SymbolIdExchange == input.SymbolIdExchange || (this.SymbolIdExchange != null && this.SymbolIdExchange.Equals(input.SymbolIdExchange)) ) && ( this.SymbolIdCoinapi == input.SymbolIdCoinapi || (this.SymbolIdCoinapi != null && this.SymbolIdCoinapi.Equals(input.SymbolIdCoinapi)) ) && ( this.AmountOrder == input.AmountOrder || this.AmountOrder.Equals(input.AmountOrder) ) && ( this.Price == input.Price || this.Price.Equals(input.Price) ) && ( this.Side == input.Side || this.Side.Equals(input.Side) ) && ( this.OrderType == input.OrderType || this.OrderType.Equals(input.OrderType) ) && ( this.TimeInForce == input.TimeInForce || this.TimeInForce.Equals(input.TimeInForce) ) && ( this.ExpireTime == input.ExpireTime || (this.ExpireTime != null && this.ExpireTime.Equals(input.ExpireTime)) ) && ( this.ExecInst == input.ExecInst || this.ExecInst.SequenceEqual(input.ExecInst) ) && ( this.ClientOrderIdFormatExchange == input.ClientOrderIdFormatExchange || (this.ClientOrderIdFormatExchange != null && this.ClientOrderIdFormatExchange.Equals(input.ClientOrderIdFormatExchange)) ) && ( this.ExchangeOrderId == input.ExchangeOrderId || (this.ExchangeOrderId != null && this.ExchangeOrderId.Equals(input.ExchangeOrderId)) ) && ( this.AmountOpen == input.AmountOpen || this.AmountOpen.Equals(input.AmountOpen) ) && ( this.AmountFilled == input.AmountFilled || this.AmountFilled.Equals(input.AmountFilled) ) && ( this.AvgPx == input.AvgPx || this.AvgPx.Equals(input.AvgPx) ) && ( this.Status == input.Status || this.Status.Equals(input.Status) ) && ( this.StatusHistory == input.StatusHistory || this.StatusHistory != null && input.StatusHistory != null && this.StatusHistory.SequenceEqual(input.StatusHistory) ) && ( this.ErrorMessage == input.ErrorMessage || (this.ErrorMessage != null && this.ErrorMessage.Equals(input.ErrorMessage)) ) && ( this.Fills == input.Fills || this.Fills != null && input.Fills != null && this.Fills.SequenceEqual(input.Fills) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ExchangeId != null) { hashCode = (hashCode * 59) + this.ExchangeId.GetHashCode(); } if (this.ClientOrderId != null) { hashCode = (hashCode * 59) + this.ClientOrderId.GetHashCode(); } if (this.SymbolIdExchange != null) { hashCode = (hashCode * 59) + this.SymbolIdExchange.GetHashCode(); } if (this.SymbolIdCoinapi != null) { hashCode = (hashCode * 59) + this.SymbolIdCoinapi.GetHashCode(); } hashCode = (hashCode * 59) + this.AmountOrder.GetHashCode(); hashCode = (hashCode * 59) + this.Price.GetHashCode(); hashCode = (hashCode * 59) + this.Side.GetHashCode(); hashCode = (hashCode * 59) + this.OrderType.GetHashCode(); hashCode = (hashCode * 59) + this.TimeInForce.GetHashCode(); if (this.ExpireTime != null) { hashCode = (hashCode * 59) + this.ExpireTime.GetHashCode(); } hashCode = (hashCode * 59) + this.ExecInst.GetHashCode(); if (this.ClientOrderIdFormatExchange != null) { hashCode = (hashCode * 59) + this.ClientOrderIdFormatExchange.GetHashCode(); } if (this.ExchangeOrderId != null) { hashCode = (hashCode * 59) + this.ExchangeOrderId.GetHashCode(); } hashCode = (hashCode * 59) + this.AmountOpen.GetHashCode(); hashCode = (hashCode * 59) + this.AmountFilled.GetHashCode(); hashCode = (hashCode * 59) + this.AvgPx.GetHashCode(); hashCode = (hashCode * 59) + this.Status.GetHashCode(); if (this.StatusHistory != null) { hashCode = (hashCode * 59) + this.StatusHistory.GetHashCode(); } if (this.ErrorMessage != null) { hashCode = (hashCode * 59) + this.ErrorMessage.GetHashCode(); } if (this.Fills != null) { hashCode = (hashCode * 59) + this.Fills.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Management.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Management\Get-Content command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class GetContent : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public GetContent() { this.DisplayName = "Get-Content"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Management\\Get-Content"; } } // Arguments /// <summary> /// Provides access to the ReadCount parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int64> ReadCount { get; set; } /// <summary> /// Provides access to the TotalCount parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int64> TotalCount { get; set; } /// <summary> /// Provides access to the Tail parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> Tail { get; set; } /// <summary> /// Provides access to the Path parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Path { get; set; } /// <summary> /// Provides access to the LiteralPath parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> LiteralPath { get; set; } /// <summary> /// Provides access to the Filter parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Filter { get; set; } /// <summary> /// Provides access to the Include parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Include { get; set; } /// <summary> /// Provides access to the Exclude parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Exclude { get; set; } /// <summary> /// Provides access to the Force parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Force { get; set; } /// <summary> /// Provides access to the Credential parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSCredential> Credential { get; set; } /// <summary> /// Provides access to the Delimiter parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Delimiter { get; set; } /// <summary> /// Provides access to the Wait parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Wait { get; set; } /// <summary> /// Provides access to the Raw parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Raw { get; set; } /// <summary> /// Provides access to the Encoding parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding> Encoding { get; set; } /// <summary> /// Provides access to the Stream parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Stream { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(ReadCount.Expression != null) { targetCommand.AddParameter("ReadCount", ReadCount.Get(context)); } if(TotalCount.Expression != null) { targetCommand.AddParameter("TotalCount", TotalCount.Get(context)); } if(Tail.Expression != null) { targetCommand.AddParameter("Tail", Tail.Get(context)); } if(Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } if(LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } if(Filter.Expression != null) { targetCommand.AddParameter("Filter", Filter.Get(context)); } if(Include.Expression != null) { targetCommand.AddParameter("Include", Include.Get(context)); } if(Exclude.Expression != null) { targetCommand.AddParameter("Exclude", Exclude.Get(context)); } if(Force.Expression != null) { targetCommand.AddParameter("Force", Force.Get(context)); } if(Credential.Expression != null) { targetCommand.AddParameter("Credential", Credential.Get(context)); } if(Delimiter.Expression != null) { targetCommand.AddParameter("Delimiter", Delimiter.Get(context)); } if(Wait.Expression != null) { targetCommand.AddParameter("Wait", Wait.Get(context)); } if(Raw.Expression != null) { targetCommand.AddParameter("Raw", Raw.Get(context)); } if(Encoding.Expression != null) { targetCommand.AddParameter("Encoding", Encoding.Get(context)); } if(Stream.Expression != null) { targetCommand.AddParameter("Stream", Stream.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Android.Content; using Android.Util; using Android.Views; using Android.Widget; using AView = Android.Views.View; using AListView = Android.Widget.ListView; namespace Xamarin.Forms.Platform.Android { internal sealed class ListViewAdapter : CellAdapter { const int DefaultGroupHeaderTemplateId = 0; const int DefaultItemTemplateId = 1; static int s_dividerHorizontalDarkId = int.MinValue; internal static readonly BindableProperty IsSelectedProperty = BindableProperty.CreateAttached("IsSelected", typeof(bool), typeof(Cell), false); readonly Context _context; readonly ListView _listView; readonly AListView _realListView; readonly Dictionary<DataTemplate, int> _templateToId = new Dictionary<DataTemplate, int>(); int _dataTemplateIncrementer = 2; // lets start at not 0 because Cell _enabledCheckCell; bool _fromNative; AView _lastSelected; WeakReference<Cell> _selectedCell; public ListViewAdapter(Context context, AListView realListView, ListView listView) : base(context) { _context = context; _realListView = realListView; _listView = listView; if (listView.SelectedItem != null) SelectItem(listView.SelectedItem); listView.TemplatedItems.CollectionChanged += OnCollectionChanged; listView.TemplatedItems.GroupedCollectionChanged += OnGroupedCollectionChanged; listView.ItemSelected += OnItemSelected; realListView.OnItemClickListener = this; realListView.OnItemLongClickListener = this; MessagingCenter.Subscribe<Platform>(this, Platform.CloseContextActionsSignalName, p => CloseContextAction()); } public override int Count { get { int count = _listView.TemplatedItems.Count; if (_listView.IsGroupingEnabled) { for (var i = 0; i < _listView.TemplatedItems.Count; i++) count += _listView.TemplatedItems.GetGroup(i).Count; } return count; } } public AView FooterView { get; set; } public override bool HasStableIds { get { return false; } } public AView HeaderView { get; set; } public bool IsAttachedToWindow { get; set; } public override object this[int index] { get { if (_listView.IsGroupingEnabled) { Cell cell = GetCellForPosition(index); return cell.BindingContext; } return _listView.ListProxy[index]; } } public override int ViewTypeCount { get { return 20; } } public override bool AreAllItemsEnabled() { return false; } public override long GetItemId(int position) { return position; } public override int GetItemViewType(int position) { var group = 0; var row = 0; DataTemplate itemTemplate; if (!_listView.IsGroupingEnabled) itemTemplate = _listView.ItemTemplate; else { group = _listView.TemplatedItems.GetGroupIndexFromGlobal(position, out row); if (row == 0) { itemTemplate = _listView.GroupHeaderTemplate; if (itemTemplate == null) return DefaultGroupHeaderTemplateId; } else { itemTemplate = _listView.ItemTemplate; row--; } } if (itemTemplate == null) return DefaultItemTemplateId; var selector = itemTemplate as DataTemplateSelector; if (selector != null) { object item = null; if (_listView.IsGroupingEnabled) item = _listView.TemplatedItems.GetGroup(group).ListProxy[row]; else item = _listView.TemplatedItems.ListProxy[position]; itemTemplate = selector.SelectTemplate(item, _listView); } int key; if (!_templateToId.TryGetValue(itemTemplate, out key)) { _dataTemplateIncrementer++; key = _dataTemplateIncrementer; _templateToId[itemTemplate] = key; } return key; } public override AView GetView(int position, AView convertView, ViewGroup parent) { Cell cell = null; Performance.Start(); ListViewCachingStrategy cachingStrategy = _listView.CachingStrategy; var nextCellIsHeader = false; if (cachingStrategy == ListViewCachingStrategy.RetainElement || convertView == null) { if (_listView.IsGroupingEnabled) { List<Cell> cells = GetCellsFromPosition(position, 2); if (cells.Count > 0) cell = cells[0]; if (cells.Count == 2) nextCellIsHeader = TemplatedItemsList<ItemsView<Cell>, Cell>.GetIsGroupHeader(cells[1]); } if (cell == null) { cell = GetCellForPosition(position); if (cell == null) return new AView(_context); } } var makeBline = true; var layout = convertView as ConditionalFocusLayout; if (layout != null) { makeBline = false; convertView = layout.GetChildAt(0); } else layout = new ConditionalFocusLayout(_context) { Orientation = Orientation.Vertical }; if (cachingStrategy == ListViewCachingStrategy.RecycleElement && convertView != null) { var boxedCell = (INativeElementView)convertView; if (boxedCell == null) { throw new InvalidOperationException($"View for cell must implement {nameof(INativeElementView)} to enable recycling."); } cell = (Cell)boxedCell.Element; if (ActionModeContext == cell) { // This appears to never happen, the theory is android keeps all views alive that are currently selected for long-press (preventing them from being recycled). // This is convenient since we wont have to worry about the user scrolling the cell offscreen and us losing our context actions. ActionModeContext = null; ContextView = null; } // We are going to re-set the Platform here because in some cases (headers mostly) its possible this is unset and // when the binding context gets updated the measure passes will all fail. By applying this hear the Update call // further down will result in correct layouts. cell.Platform = _listView.Platform; cell.SendDisappearing(); int row = position; var group = 0; if (_listView.IsGroupingEnabled) group = _listView.TemplatedItems.GetGroupIndexFromGlobal(position, out row); TemplatedItemsList<ItemsView<Cell>, Cell> templatedList = _listView.TemplatedItems.GetGroup(group); if (_listView.IsGroupingEnabled) { if (row == 0) templatedList.UpdateHeader(cell, group); else templatedList.UpdateContent(cell, row - 1); } else templatedList.UpdateContent(cell, row); cell.SendAppearing(); if (cell.BindingContext == ActionModeObject) { ActionModeContext = cell; ContextView = layout; } if (ReferenceEquals(_listView.SelectedItem, cell.BindingContext)) Select(_listView.IsGroupingEnabled ? row - 1 : row, layout); else if (cell.BindingContext == ActionModeObject) SetSelectedBackground(layout, true); else UnsetSelectedBackground(layout); Performance.Stop(); return layout; } AView view = CellFactory.GetCell(cell, convertView, parent, _context, _listView); Performance.Start("AddView"); if (!makeBline) { if (convertView != view) { layout.RemoveViewAt(0); layout.AddView(view, 0); } } else layout.AddView(view, 0); Performance.Stop("AddView"); AView bline; if (makeBline) { bline = new AView(_context) { LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 1) }; layout.AddView(bline); } else bline = layout.GetChildAt(1); bool isHeader = TemplatedItemsList<ItemsView<Cell>, Cell>.GetIsGroupHeader(cell); Color separatorColor = _listView.SeparatorColor; if (nextCellIsHeader || _listView.SeparatorVisibility == SeparatorVisibility.None) bline.SetBackgroundColor(global::Android.Graphics.Color.Transparent); else if (isHeader || !separatorColor.IsDefault) bline.SetBackgroundColor(separatorColor.ToAndroid(Color.Accent)); else { if (s_dividerHorizontalDarkId == int.MinValue) { using (var value = new TypedValue()) { int id = global::Android.Resource.Drawable.DividerHorizontalDark; if (_context.Theme.ResolveAttribute(global::Android.Resource.Attribute.ListDivider, value, true)) id = value.ResourceId; else if (_context.Theme.ResolveAttribute(global::Android.Resource.Attribute.Divider, value, true)) id = value.ResourceId; s_dividerHorizontalDarkId = id; } } bline.SetBackgroundResource(s_dividerHorizontalDarkId); } if ((bool)cell.GetValue(IsSelectedProperty)) Select(position, layout); else UnsetSelectedBackground(layout); layout.ApplyTouchListenersToSpecialCells(cell); Performance.Stop(); return layout; } public override bool IsEnabled(int position) { ListView list = _listView; if (list.IsGroupingEnabled) { int leftOver; list.TemplatedItems.GetGroupIndexFromGlobal(position, out leftOver); return leftOver > 0; } if (list.CachingStrategy == ListViewCachingStrategy.RecycleElement) { if (_enabledCheckCell == null) _enabledCheckCell = GetCellForPosition(position); else list.TemplatedItems.UpdateContent(_enabledCheckCell, position); return _enabledCheckCell.IsEnabled; } Cell item = GetCellForPosition(position); return item.IsEnabled; } protected override void Dispose(bool disposing) { if (disposing) { CloseContextAction(); MessagingCenter.Unsubscribe<Platform>(this, Platform.CloseContextActionsSignalName); _realListView.OnItemClickListener = null; _realListView.OnItemLongClickListener = null; _listView.TemplatedItems.CollectionChanged -= OnCollectionChanged; _listView.TemplatedItems.GroupedCollectionChanged -= OnGroupedCollectionChanged; _listView.ItemSelected -= OnItemSelected; if (_lastSelected != null) { _lastSelected.Dispose(); _lastSelected = null; } } base.Dispose(disposing); } protected override Cell GetCellForPosition(int position) { return GetCellsFromPosition(position, 1).FirstOrDefault(); } protected override void HandleItemClick(AdapterView parent, AView view, int position, long id) { Cell cell = null; if (_listView.CachingStrategy == ListViewCachingStrategy.RecycleElement) { AView cellOwner = view; var layout = cellOwner as ConditionalFocusLayout; if (layout != null) cellOwner = layout.GetChildAt(0); cell = (Cell)((INativeElementView)cellOwner).Element; } // All our ListView's have called AddHeaderView. This effectively becomes index 0, so our index 0 is index 1 to the listView. position--; if (position < 0 || position >= Count) return; Select(position, view); _fromNative = true; _listView.NotifyRowTapped(position, cell); } // TODO: We can optimize this by storing the last position, group index and global index // and increment/decrement from that starting place. List<Cell> GetCellsFromPosition(int position, int take) { var cells = new List<Cell>(take); if (position < 0) return cells; if (!_listView.IsGroupingEnabled) { for (var x = 0; x < take; x++) { if (position + x >= _listView.TemplatedItems.Count) return cells; cells.Add(_listView.TemplatedItems[x + position]); } return cells; } var i = 0; var global = 0; for (; i < _listView.TemplatedItems.Count; i++) { TemplatedItemsList<ItemsView<Cell>, Cell> group = _listView.TemplatedItems.GetGroup(i); if (global == position || cells.Count > 0) { cells.Add(group.HeaderContent); if (cells.Count == take) return cells; } global++; if (global + group.Count < position) { global += group.Count; continue; } for (var g = 0; g < group.Count; g++) { if (global == position || cells.Count > 0) { cells.Add(group[g]); if (cells.Count == take) return cells; } global++; } } return cells; } void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { OnDataChanged(); } void OnDataChanged() { if (IsAttachedToWindow) NotifyDataSetChanged(); else { // In a TabbedPage page with two pages, Page A and Page B with ListView, if A changes B's ListView, // we need to reset the ListView's adapter to reflect the changes on page B // If there header and footer are present at the reset time of the adapter // they will be DOUBLE added to the ViewGround (the ListView) causing indexes to be off by one. _realListView.RemoveHeaderView(HeaderView); _realListView.RemoveFooterView(FooterView); _realListView.Adapter = _realListView.Adapter; _realListView.AddHeaderView(HeaderView); _realListView.AddFooterView(FooterView); } } void OnGroupedCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { OnDataChanged(); } void OnItemSelected(object sender, SelectedItemChangedEventArgs eventArg) { if (_fromNative) { _fromNative = false; return; } SelectItem(eventArg.SelectedItem); } void Select(int index, AView view) { if (_lastSelected != null) { UnsetSelectedBackground(_lastSelected); Cell previousCell; if (_selectedCell.TryGetTarget(out previousCell)) previousCell.SetValue(IsSelectedProperty, false); } _lastSelected = view; if (index == -1) return; Cell cell = GetCellForPosition(index); cell.SetValue(IsSelectedProperty, true); _selectedCell = new WeakReference<Cell>(cell); if (view != null) SetSelectedBackground(view); } void SelectItem(object item) { int position = _listView.TemplatedItems.GetGlobalIndexOfItem(item); AView view = null; if (position != -1) view = _realListView.GetChildAt(position + 1 - _realListView.FirstVisiblePosition); Select(position, view); } enum CellType { Row, Header } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; using System.Xml.Serialization; namespace OpenTK { /// <summary>Represents a 4D vector using four double-precision floating-point numbers.</summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector4d : IEquatable<Vector4d> { #region Fields /// <summary> /// The X component of the Vector4d. /// </summary> public double X; /// <summary> /// The Y component of the Vector4d. /// </summary> public double Y; /// <summary> /// The Z component of the Vector4d. /// </summary> public double Z; /// <summary> /// The W component of the Vector4d. /// </summary> public double W; /// <summary> /// Defines a unit-length Vector4d that points towards the X-axis. /// </summary> public static Vector4d UnitX = new Vector4d(1, 0, 0, 0); /// <summary> /// Defines a unit-length Vector4d that points towards the Y-axis. /// </summary> public static Vector4d UnitY = new Vector4d(0, 1, 0, 0); /// <summary> /// Defines a unit-length Vector4d that points towards the Z-axis. /// </summary> public static Vector4d UnitZ = new Vector4d(0, 0, 1, 0); /// <summary> /// Defines a unit-length Vector4d that points towards the W-axis. /// </summary> public static Vector4d UnitW = new Vector4d(0, 0, 0, 1); /// <summary> /// Defines a zero-length Vector4d. /// </summary> public static Vector4d Zero = new Vector4d(0, 0, 0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector4d One = new Vector4d(1, 1, 1, 1); /// <summary> /// Defines the size of the Vector4d struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector4d()); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector4d(double value) { X = value; Y = value; Z = value; W = value; } /// <summary> /// Constructs a new Vector4d. /// </summary> /// <param name="x">The x component of the Vector4d.</param> /// <param name="y">The y component of the Vector4d.</param> /// <param name="z">The z component of the Vector4d.</param> /// <param name="w">The w component of the Vector4d.</param> public Vector4d(double x, double y, double z, double w) { X = x; Y = y; Z = z; W = w; } /// <summary> /// Constructs a new Vector4d from the given Vector2d. /// </summary> /// <param name="v">The Vector2d to copy components from.</param> public Vector4d(Vector2d v) { X = v.X; Y = v.Y; Z = 0.0f; W = 0.0f; } /// <summary> /// Constructs a new Vector4d from the given Vector3d. /// The w component is initialized to 0. /// </summary> /// <param name="v">The Vector3d to copy components from.</param> /// <remarks><seealso cref="Vector4d(Vector3d, double)"/></remarks> public Vector4d(Vector3d v) { X = v.X; Y = v.Y; Z = v.Z; W = 0.0f; } /// <summary> /// Constructs a new Vector4d from the specified Vector3d and w component. /// </summary> /// <param name="v">The Vector3d to copy components from.</param> /// <param name="w">The w component of the new Vector4.</param> public Vector4d(Vector3d v, double w) { X = v.X; Y = v.Y; Z = v.Z; W = w; } /// <summary> /// Constructs a new Vector4d from the given Vector4d. /// </summary> /// <param name="v">The Vector4d to copy components from.</param> public Vector4d(Vector4d v) { X = v.X; Y = v.Y; Z = v.Z; W = v.W; } #endregion #region Public Members #region Instance #region public void Add() /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Add() method instead.")] public void Add(Vector4d right) { this.X += right.X; this.Y += right.Y; this.Z += right.Z; this.W += right.W; } /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(ref Vector4d right) { this.X += right.X; this.Y += right.Y; this.Z += right.Z; this.W += right.W; } #endregion public void Add() #region public void Sub() /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Subtract() method instead.")] public void Sub(Vector4d right) { this.X -= right.X; this.Y -= right.Y; this.Z -= right.Z; this.W -= right.W; } /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(ref Vector4d right) { this.X -= right.X; this.Y -= right.Y; this.Z -= right.Z; this.W -= right.W; } #endregion public void Sub() #region public void Mult() /// <summary>Multiply this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Multiply() method instead.")] public void Mult(double f) { this.X *= f; this.Y *= f; this.Z *= f; this.W *= f; } #endregion public void Mult() #region public void Div() /// <summary>Divide this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Divide() method instead.")] public void Div(double f) { double mult = 1.0 / f; this.X *= mult; this.Y *= mult; this.Z *= mult; this.W *= mult; } #endregion public void Div() #region public double Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <see cref="LengthFast"/> /// <seealso cref="LengthSquared"/> public double Length { get { return System.Math.Sqrt(X * X + Y * Y + Z * Z + W * W); } } #endregion #region public double LengthFast /// <summary> /// Gets an approximation of the vector length (magnitude). /// </summary> /// <remarks> /// This property uses an approximation of the square root function to calculate vector magnitude, with /// an upper error bound of 0.001. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthSquared"/> public double LengthFast { get { return 1.0 / MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W); } } #endregion #region public double LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public double LengthSquared { get { return X * X + Y * Y + Z * Z + W * W; } } #endregion #region public void Normalize() /// <summary> /// Scales the Vector4d to unit length. /// </summary> public void Normalize() { double scale = 1.0 / this.Length; X *= scale; Y *= scale; Z *= scale; W *= scale; } #endregion #region public void NormalizeFast() /// <summary> /// Scales the Vector4d to approximately unit length. /// </summary> public void NormalizeFast() { double scale = MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W); X *= scale; Y *= scale; Z *= scale; W *= scale; } #endregion #region public void Scale() /// <summary> /// Scales the current Vector4d by the given amounts. /// </summary> /// <param name="sx">The scale of the X component.</param> /// <param name="sy">The scale of the Y component.</param> /// <param name="sz">The scale of the Z component.</param> /// <param name="sw">The scale of the Z component.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(double sx, double sy, double sz, double sw) { this.X = X * sx; this.Y = Y * sy; this.Z = Z * sz; this.W = W * sw; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(Vector4d scale) { this.X *= scale.X; this.Y *= scale.Y; this.Z *= scale.Z; this.W *= scale.W; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(ref Vector4d scale) { this.X *= scale.X; this.Y *= scale.Y; this.Z *= scale.Z; this.W *= scale.W; } #endregion public void Scale() #endregion #region Static #region Obsolete #region Sub /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> [Obsolete("Use static Subtract() method instead.")] public static Vector4d Sub(Vector4d a, Vector4d b) { a.X -= b.X; a.Y -= b.Y; a.Z -= b.Z; a.W -= b.W; return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> [Obsolete("Use static Subtract() method instead.")] public static void Sub(ref Vector4d a, ref Vector4d b, out Vector4d result) { result.X = a.X - b.X; result.Y = a.Y - b.Y; result.Z = a.Z - b.Z; result.W = a.W - b.W; } #endregion #region Mult /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the multiplication</returns> [Obsolete("Use static Multiply() method instead.")] public static Vector4d Mult(Vector4d a, double f) { a.X *= f; a.Y *= f; a.Z *= f; a.W *= f; return a; } /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the multiplication</param> [Obsolete("Use static Multiply() method instead.")] public static void Mult(ref Vector4d a, double f, out Vector4d result) { result.X = a.X * f; result.Y = a.Y * f; result.Z = a.Z * f; result.W = a.W * f; } #endregion #region Div /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the division</returns> [Obsolete("Use static Divide() method instead.")] public static Vector4d Div(Vector4d a, double f) { double mult = 1.0 / f; a.X *= mult; a.Y *= mult; a.Z *= mult; a.W *= mult; return a; } /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the division</param> [Obsolete("Use static Divide() method instead.")] public static void Div(ref Vector4d a, double f, out Vector4d result) { double mult = 1.0 / f; result.X = a.X * mult; result.Y = a.Y * mult; result.Z = a.Z * mult; result.W = a.W * mult; } #endregion #endregion #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector4d Add(Vector4d a, Vector4d b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector4d a, ref Vector4d b, out Vector4d result) { result = new Vector4d(a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + b.W); } #endregion #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector4d Subtract(Vector4d a, Vector4d b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector4d a, ref Vector4d b, out Vector4d result) { result = new Vector4d(a.X - b.X, a.Y - b.Y, a.Z - b.Z, a.W - b.W); } #endregion #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Multiply(Vector4d vector, double scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4d vector, double scale, out Vector4d result) { result = new Vector4d(vector.X * scale, vector.Y * scale, vector.Z * scale, vector.W * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Multiply(Vector4d vector, Vector4d scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4d vector, ref Vector4d scale, out Vector4d result) { result = new Vector4d(vector.X * scale.X, vector.Y * scale.Y, vector.Z * scale.Z, vector.W * scale.W); } #endregion #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Divide(Vector4d vector, double scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4d vector, double scale, out Vector4d result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4d Divide(Vector4d vector, Vector4d scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4d vector, ref Vector4d scale, out Vector4d result) { result = new Vector4d(vector.X / scale.X, vector.Y / scale.Y, vector.Z / scale.Z, vector.W / scale.W); } #endregion #region Min /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector4d Min(Vector4d a, Vector4d b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; a.Z = a.Z < b.Z ? a.Z : b.Z; a.W = a.W < b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector4d a, ref Vector4d b, out Vector4d result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; result.Z = a.Z < b.Z ? a.Z : b.Z; result.W = a.W < b.W ? a.W : b.W; } #endregion #region Max /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector4d Max(Vector4d a, Vector4d b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; a.Z = a.Z > b.Z ? a.Z : b.Z; a.W = a.W > b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector4d a, ref Vector4d b, out Vector4d result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; result.Z = a.Z > b.Z ? a.Z : b.Z; result.W = a.W > b.W ? a.W : b.W; } #endregion #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector4d Clamp(Vector4d vec, Vector4d min, Vector4d max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; vec.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; vec.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector4d vec, ref Vector4d min, ref Vector4d max, out Vector4d result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; result.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; result.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W; } #endregion #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector4d Normalize(Vector4d vec) { double scale = 1.0 / vec.Length; vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector4d vec, out Vector4d result) { double scale = 1.0 / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; result.W = vec.W * scale; } #endregion #region NormalizeFast /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector4d NormalizeFast(Vector4d vec) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W); vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector4d vec, out Vector4d result) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W); result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; result.W = vec.W * scale; } #endregion #region Dot /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static double Dot(Vector4d left, Vector4d right) { return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector4d left, ref Vector4d right, out double result) { result = left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } #endregion #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector4d Lerp(Vector4d a, Vector4d b, double blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; a.Z = blend * (b.Z - a.Z) + a.Z; a.W = blend * (b.W - a.W) + a.W; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector4d a, ref Vector4d b, double blend, out Vector4d result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; result.Z = blend * (b.Z - a.Z) + a.Z; result.W = blend * (b.W - a.W) + a.W; } #endregion #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector4d BaryCentric(Vector4d a, Vector4d b, Vector4d c, double u, double v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector4d a, ref Vector4d b, ref Vector4d c, double u, double v, out Vector4d result) { result = a; // copy Vector4d temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion #region Transform /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector4d Transform(Vector4d vec, Matrix4d mat) { Vector4d result; Transform(ref vec, ref mat, out result); return result; } /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector4d vec, ref Matrix4d mat, out Vector4d result) { result = new Vector4d( vec.X * mat.Row0.X + vec.Y * mat.Row1.X + vec.Z * mat.Row2.X + vec.W * mat.Row3.X, vec.X * mat.Row0.Y + vec.Y * mat.Row1.Y + vec.Z * mat.Row2.Y + vec.W * mat.Row3.Y, vec.X * mat.Row0.Z + vec.Y * mat.Row1.Z + vec.Z * mat.Row2.Z + vec.W * mat.Row3.Z, vec.X * mat.Row0.W + vec.Y * mat.Row1.W + vec.Z * mat.Row2.W + vec.W * mat.Row3.W); } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector4d Transform(Vector4d vec, Quaterniond quat) { Vector4d result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector4d vec, ref Quaterniond quat, out Vector4d result) { Quaterniond v = new Quaterniond(vec.X, vec.Y, vec.Z, vec.W), i, t; Quaterniond.Invert(ref quat, out i); Quaterniond.Multiply(ref quat, ref v, out t); Quaterniond.Multiply(ref t, ref i, out v); result = new Vector4d(v.X, v.Y, v.Z, v.W); } #endregion #endregion #region Swizzle /// <summary> /// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance. /// </summary> [XmlIgnore] public Vector2d Xy { get { return new Vector2d(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector3d with the X, Y and Z components of this instance. /// </summary> [XmlIgnore] public Vector3d Xyz { get { return new Vector3d(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } } #endregion #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator +(Vector4d left, Vector4d right) { left.X += right.X; left.Y += right.Y; left.Z += right.Z; left.W += right.W; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator -(Vector4d left, Vector4d right) { left.X -= right.X; left.Y -= right.Y; left.Z -= right.Z; left.W -= right.W; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator -(Vector4d vec) { vec.X = -vec.X; vec.Y = -vec.Y; vec.Z = -vec.Z; vec.W = -vec.W; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator *(Vector4d vec, double scale) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator *(double scale, Vector4d vec) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4d operator /(Vector4d vec, double scale) { double mult = 1 / scale; vec.X *= mult; vec.Y *= mult; vec.Z *= mult; vec.W *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Vector4d left, Vector4d right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equa lright; false otherwise.</returns> public static bool operator !=(Vector4d left, Vector4d right) { return !left.Equals(right); } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> [CLSCompliant(false)] unsafe public static explicit operator double*(Vector4d v) { return &v.X; } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> public static explicit operator IntPtr(Vector4d v) { unsafe { return (IntPtr)(&v.X); } } /// <summary>Converts OpenTK.Vector4 to OpenTK.Vector4d.</summary> /// <param name="v4">The Vector4 to convert.</param> /// <returns>The resulting Vector4d.</returns> public static explicit operator Vector4d(Vector4 v4) { return new Vector4d(v4.X, v4.Y, v4.Z, v4.W); } /// <summary>Converts OpenTK.Vector4d to OpenTK.Vector4.</summary> /// <param name="v4d">The Vector4d to convert.</param> /// <returns>The resulting Vector4.</returns> public static explicit operator Vector4(Vector4d v4d) { return new Vector4((float)v4d.X, (float)v4d.Y, (float)v4d.Z, (float)v4d.W); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Vector4d. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0}, {1}, {2}, {3})", X, Y, Z, W); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector4d)) return false; return this.Equals((Vector4d)obj); } #endregion #endregion #endregion #region IEquatable<Vector4d> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector4d other) { return X == other.X && Y == other.Y && Z == other.Z && W == other.W; } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public enum State { Falling, Jumping, Hanging, Walking, Climbing, Limbo, Dead } public enum Command { Jumped, ApexReached, GrabbedLedge, LetGo, TouchedCeiling, LeftGround, TouchedGround, EnterLimbo, ExitLimbo, Die } public class Process { class StateTransition { readonly State CurrentState; readonly Command Command; public StateTransition(State currentState, Command command) { CurrentState = currentState; Command = command; } public override int GetHashCode() { return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode(); } public override bool Equals(object obj) { StateTransition other = obj as StateTransition; return other != null && this.CurrentState == other.CurrentState && this.Command == other.Command; } } Dictionary<StateTransition, State> transitions; public State CurrentState { get; private set; } public Process() { CurrentState = State.Falling; transitions = new Dictionary<StateTransition, State> { { new StateTransition(State.Walking, Command.Jumped), State.Jumping }, { new StateTransition(State.Walking, Command.LeftGround), State.Falling }, { new StateTransition(State.Jumping, Command.TouchedCeiling), State.Falling }, { new StateTransition(State.Jumping, Command.ApexReached), State.Falling }, { new StateTransition(State.Jumping, Command.GrabbedLedge), State.Hanging }, { new StateTransition(State.Falling, Command.TouchedGround), State.Walking }, { new StateTransition(State.Falling, Command.GrabbedLedge), State.Hanging }, { new StateTransition(State.Falling, Command.EnterLimbo), State.Limbo }, { new StateTransition(State.Jumping, Command.EnterLimbo), State.Limbo }, { new StateTransition(State.Walking, Command.EnterLimbo), State.Limbo }, { new StateTransition(State.Limbo, Command.ExitLimbo), State.Falling }, { new StateTransition(State.Walking, Command.Die), State.Dead }, { new StateTransition(State.Falling, Command.Die), State.Dead }, { new StateTransition(State.Jumping, Command.Die), State.Dead }, }; } public State GetNext(Command command) { StateTransition transition = new StateTransition(CurrentState, command); State nextState; if (!transitions.TryGetValue(transition, out nextState)) throw new Exception("Invalid transition: " + CurrentState + " -> " + command); return nextState; } public State MoveNext(Command command) { CurrentState = GetNext(command); return CurrentState; } } public class BreadController : MonoBehaviour { OTSprite m_Sprite; private Process m_StateMachine = new Process(); private CharacterController controller; [SerializeField] private float m_Gravity = 15f; [SerializeField] private float m_MaxFallSpeed = -20.0f; [SerializeField] private float m_WalkSpeed = 6f; [SerializeField] private float m_InAirSpeed = 3f; [SerializeField] private float m_JumpTime = 0.2f; [SerializeField] private float m_JumpSpeed = 100f; private float m_LastJumpTime = 0f; private Vector3 m_Velocity = Vector3.zero; private int m_ToastTimer = 0; private ToasterCounter m_CounterRef; void Awake() { controller = GetComponent<CharacterController>(); m_Sprite = GetComponent<OTSprite>(); } void Start () { m_Sprite.rotation = 0; m_Sprite.depth = 0; m_Sprite.frameIndex = 3; m_CounterRef = (ToasterCounter)GameObject.Find("GUIContainer").GetComponent(typeof(ToasterCounter)); } void Update () { //Update the sprites position based on the gameobjects position. m_Sprite.position = new Vector2(transform.position.x, transform.position.y); SetSprite(); if(m_StateMachine.CurrentState == State.Jumping || m_StateMachine.CurrentState == State.Falling) { MoveInAir(); } else if (m_StateMachine.CurrentState == State.Walking) { Move(); } if (Input.GetButtonDown("Jump") && m_StateMachine.CurrentState != State.Falling && m_StateMachine.CurrentState != State.Jumping && m_StateMachine.CurrentState != State.Limbo) { m_LastJumpTime = Time.time; m_StateMachine.MoveNext(Command.Jumped); } else if (Input.GetButtonDown("Jump") && m_StateMachine.CurrentState == State.Limbo) { ToasterPop(); } if (m_StateMachine.CurrentState == State.Limbo) { //pass } if (m_StateMachine.CurrentState == State.Dead) { //Spin while falling; m_Sprite.rotation += 2; } ApplyJump(); ApplyGravity(); //Debug.Log(m_StateMachine.CurrentState); //Debug.Log(m_StateMachine.CurrentState.ToString()); //Debug.Log(m_Velocity.x); controller.Move(m_Velocity * Time.smoothDeltaTime); } void Move() { float horizontal = Input.GetAxisRaw("Horizontal"); //MOVING LEFT if (horizontal != 0) { m_Velocity.x = m_WalkSpeed * horizontal; } else { if (m_StateMachine.CurrentState == State.Walking) { m_Velocity.x = 0; } } } void MoveInAir() { float horizontal = Input.GetAxisRaw("Horizontal"); if (m_InAirSpeed > 0) { //Moving left, but want to go right if (horizontal == 1 && m_Velocity.x < 0) { m_Velocity.x = m_InAirSpeed * horizontal; } //Moving right, but want to go left else if (horizontal == -1 && m_Velocity.x > 0) { m_Velocity.x = m_InAirSpeed * horizontal; } } } void OnTriggerEnter(Collider c) { if (c.tag == "BasicToaster") { m_StateMachine.MoveNext(Command.EnterLimbo); m_Velocity.x = 0; m_Velocity.y = 0; controller.transform.position = c.transform.position; m_CounterRef.Increment(); } else if (c.tag == "Death") { m_StateMachine.MoveNext(Command.Die); m_Velocity.x = 0; m_Sprite.frameIndex = 1; m_Sprite.depth = -50; } } void OnTriggerExit(Collider c) { if (c.tag == "Boundary") { Application.LoadLevel(Application.loadedLevel); } } void OnControllerColliderHit() { if (m_StateMachine.CurrentState == State.Falling) { m_StateMachine.MoveNext(Command.TouchedGround); } else if (m_StateMachine.CurrentState == State.Jumping) { m_StateMachine.MoveNext(Command.TouchedCeiling); } } void ApplyJump() { if (m_StateMachine.CurrentState == State.Jumping) { m_Velocity.y = m_JumpSpeed * Time.smoothDeltaTime; if (m_LastJumpTime + m_JumpTime <= Time.time) { m_StateMachine.MoveNext(Command.ApexReached); } } } void ApplyGravity() { if (m_StateMachine.CurrentState != State.Jumping && m_StateMachine.CurrentState != State.Limbo) { if (m_Velocity.y > m_MaxFallSpeed) { m_Velocity.y -= m_Gravity * Time.smoothDeltaTime; } } else if (m_StateMachine.CurrentState == State.Dead) { if (m_Velocity.y > m_MaxFallSpeed) { m_Velocity.y -= m_Gravity * Time.smoothDeltaTime; } } } void ToasterPop() { float horizontal = Input.GetAxisRaw("Horizontal"); m_StateMachine.MoveNext(Command.ExitLimbo); float time = 800f; m_Velocity = new Vector3(horizontal * time, time); } void SetSprite() { float horizontal = Input.GetAxisRaw("Horizontal"); if (m_StateMachine.CurrentState == State.Walking && horizontal == 1) { m_Sprite.frameIndex = 5; } else if (m_StateMachine.CurrentState == State.Walking && horizontal == -1) { m_Sprite.frameIndex = 4; } else { switch (m_StateMachine.CurrentState) { case State.Falling: if (m_Sprite.frameIndex != 2) { m_Sprite.frameIndex = 2; } break; case State.Jumping: if (m_Sprite.frameIndex != 6) { m_Sprite.frameIndex = 6; } break; case State.Walking: if (m_Sprite.frameIndex != 3) { m_Sprite.frameIndex = 3; } break; } } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace Microsoft.Tools.ServiceModel.WsatConfig { using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Globalization; using System.Diagnostics; using System.Threading; using System.Security.Cryptography.X509Certificates; class ConsoleEntryPoint { enum Operations { None = 0, Help, Change } // the configuration received from the user WsatConfiguration newConfig; // the current configuration loaded from the registry WsatConfiguration previousConfig; // possible operations Operations operation; // restart required bool restartRequired = false; bool showRequired = false; // DTC cluster server name string virtualServer; // console entry point [STAThread] public static int Main(String[] args) { try { ValidateUICulture(); PrintBanner(); ConsoleEntryPoint tool = new ConsoleEntryPoint(args); tool.Run(); return 0; } catch (WsatAdminException wsatEx) { Console.WriteLine(); Console.WriteLine(wsatEx.Message); return (int)wsatEx.ErrorCode; } #pragma warning suppress 56500 catch (Exception e) { Console.WriteLine(SR.GetString(SR.UnexpectedError, e.Message)); return (int)WsatAdminErrorCode.UNEXPECTED_ERROR; } } static void PrintBanner() { // Using CommonResStrings.WcfTrademarkForCmdLine for the trademark: the proper resource for command line tools. Console.WriteLine(); Console.WriteLine(SR.GetString(SR.ConsoleBannerLine01)); Console.WriteLine(SR.GetString(SR.ConsoleBannerLine02, CommonResStrings.WcfTrademarkForCmdLine, ThisAssembly.InformationalVersion)); Console.WriteLine(SR.GetString(SR.ConsoleBannerLine03, CommonResStrings.CopyrightForCmdLine)); } static void PrintUsage() { OptionUsage.Print(); } ConsoleEntryPoint(string[] argv) { List<string> arguments = PrescanArgs(argv); if (this.operation != Operations.Help) { previousConfig = new WsatConfiguration(null, this.virtualServer, null, true); previousConfig.LoadFromRegistry(); newConfig = new WsatConfiguration(null, this.virtualServer, previousConfig, true); ParseArgs(arguments); } } // Execute the user's command void Run() { switch (operation) { case Operations.Change: newConfig.ValidateThrow(); if (restartRequired) { Console.WriteLine(SR.GetString(SR.InfoRestartingMSDTC)); } newConfig.Save(restartRequired); if (restartRequired) { Console.WriteLine(SR.GetString(SR.InfoRestartedMSDTC)); } if (newConfig.IsClustered) { Console.WriteLine(SR.GetString(SR.ClusterConfigUpdatedSuccessfully)); } else { Console.WriteLine(SR.GetString(SR.ConfigUpdatedSuccessfully)); } break; case Operations.None: // does nothing break; case Operations.Help: // fall through default: PrintUsage(); break; } if (operation != Operations.Change && restartRequired) { try { MsdtcWrapper msdtc = newConfig.GetMsdtcWrapper(); Console.WriteLine(SR.GetString(SR.InfoRestartingMSDTC)); msdtc.RestartDtcService(); Console.WriteLine(SR.GetString(SR.InfoRestartedMSDTC)); } catch (WsatAdminException) { throw; } #pragma warning suppress 56500 catch (Exception e) { if (Utilities.IsCriticalException(e)) { throw; } throw new WsatAdminException(WsatAdminErrorCode.DTC_RESTART_ERROR, SR.GetString(SR.ErrorRestartMSDTC), e); } } if (this.showRequired) { Console.WriteLine(); Console.WriteLine(SR.GetString(SR.ConsoleShowInformation)); Console.WriteLine(operation == Operations.Change ? this.newConfig.ToString() : this.previousConfig.ToString()); } } List<string> PrescanArgs(string[] argv) { List<string> arguments = new List<string>(); if (argv.Length < 1) { this.operation = Operations.Help; } else { this.operation = Operations.None; foreach (string rawArg in argv) { // -?, -h, -help string arg = ProcessArg(rawArg); if (Utilities.SafeCompare(arg, CommandLineOption.Help) || Utilities.SafeCompare(arg, CommandLineOption.Help_short1) || Utilities.SafeCompare(arg, CommandLineOption.Help_short2)) { this.operation = Operations.Help; break; } // -show if (Utilities.SafeCompare(arg, CommandLineOption.Show)) { this.showRequired = true; continue; } // -restart if (Utilities.SafeCompare(arg, CommandLineOption.Restart)) { this.restartRequired = true; continue; } // -virtualServer string value; if (Utilities.SafeCompare(ArgumentsParser.ExtractOption(arg, out value), CommandLineOption.ClusterVirtualServer)) { this.virtualServer = value; continue; } arguments.Add(arg); } } return arguments; } void ParseArgs(List<string> arguments) { ArgumentsParser parser = new ArgumentsParser(newConfig); foreach (string arg in arguments) { if (parser.ParseOptionAndArgument(arg)) { this.operation = Operations.Change; } else { // otherwise, we have encountered something we dont recognize throw new WsatAdminException(WsatAdminErrorCode.INVALID_ARGUMENT, SR.GetString(SR.ErrorArgument)); } } parser.ValidateArgumentsThrow(); } // strip off the switch prefix and get the real argument static string ProcessArg(string rawArg) { if (String.IsNullOrEmpty(rawArg)) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_ARGUMENT, SR.GetString(SR.ErrorArgument)); } if (rawArg[0] != '/' && rawArg[0] != '-') { throw new WsatAdminException(WsatAdminErrorCode.INVALID_ARGUMENT, SR.GetString(SR.ErrorArgument)); } return rawArg.Substring(1); } // Since we are outputing to the console, force the current UI culture to be the // console fallback UI culture since the console cannot support all code pages for // certain cultures (i.e. it will print garbage characters). Unfortunately, there // are some console fallback cultures that still use code pages incompatible with // the console. Catch those cases and fall back to English because ASCII is widely // accepted in OEM code pages. static void ValidateUICulture() { Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture.GetConsoleFallbackUICulture(); if ((System.Console.OutputEncoding.CodePage != Encoding.UTF8.CodePage) && (System.Console.OutputEncoding.CodePage != Thread.CurrentThread.CurrentUICulture.TextInfo.OEMCodePage)) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } } } }
using System.Collections.Generic; namespace SemanticVersionTest { using SemVersion; using Xunit; public class TryParseTests { [Fact] public void TryParseReturnsVersion() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.3", out version); Assert.True(result); Assert.Equal(new SemanticVersion(1, 2, 3), version); } [Fact] public void TryParseNullReturnsFalse() { SemanticVersion version; var result = SemanticVersion.TryParse(null, out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseEmptyStringReturnsFalse() { SemanticVersion version; var result = SemanticVersion.TryParse(string.Empty, out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseInvalidStringReturnsFalse() { SemanticVersion version; var result = SemanticVersion.TryParse("invalid-version", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseMissingMinorReturnsFalse() { SemanticVersion version; var result = SemanticVersion.TryParse("1", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseMissingPatchReturnsFalse() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseMissingPatchValueReturnsFalse() { SemanticVersion version; // Trailing separator but no value var result = SemanticVersion.TryParse("1.2.", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseMissingPatchValueWithPrereleaseReturnsFalse() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2-alpha", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseMissingPatchWithPrereleaseReturnsFalse() { SemanticVersion version; // Trailing separator but no value var result = SemanticVersion.TryParse("1.2-alpha.", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseMajorWildcard() { SemanticVersion version; var result = SemanticVersion.TryParse("*", out version); Assert.True(result); Assert.Null(version.Major); Assert.Null(version.Minor); Assert.Null(version.Patch); } [Fact] public void TryParseMajorWildcardWithTrailingSeparator() { SemanticVersion version; var result = SemanticVersion.TryParse("*. ", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseMinorWildcard() { SemanticVersion version; var result = SemanticVersion.TryParse("1.*", out version); Assert.True(result); Assert.Equal(1, version.Major); Assert.Null(version.Minor); Assert.Null(version.Patch); } [Fact] public void TryParseMinorWildcardWithTrailingSeparator() { SemanticVersion version; var result = SemanticVersion.TryParse("1.*. ", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParsePatchWildcard() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.*", out version); Assert.True(result); Assert.Equal(1, version.Major); Assert.Equal(2, version.Minor); Assert.Null(version.Patch); } [Fact] public void TryParsePatchWildcardWithTrailingSeparator() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.*. ", out version); Assert.False(result); Assert.Null(version); } [Fact] public void TryParseInvalidMajorMinorPatchValues() { SemanticVersion version; var invalidAtoms = new string[] {"-01", "-1", "00", "01", "0 2"}; var validAtoms = new string[] {"0", "1", "10", "1234"}; var list = new List<string>(); list.AddRange(invalidAtoms); list.AddRange(validAtoms); var testValues = list.ToArray(); bool result = false; string verStr; foreach (var major in invalidAtoms) { foreach (var minor in validAtoms) { foreach (var patch in validAtoms) { verStr = string.Format("{0}.{1}.{2}", major, minor, patch); result = SemanticVersion.TryParse(verStr, out version); Assert.False(result, verStr); Assert.Null(version); foreach (var prerelease in validAtoms) { verStr = string.Format("{0}.{1}.{2}-{3}", major, minor, patch, prerelease); result = SemanticVersion.TryParse(verStr, out version); Assert.False(result, verStr); Assert.Null(version); foreach (var build in validAtoms) { verStr = string.Format("{0}.{1}.{2}-{3}+{4}", major, minor, patch, prerelease, build); result = SemanticVersion.TryParse(verStr, out version); Assert.False(result); Assert.Null(version); } } } } } } [Fact] //(Skip = "Needs check with specification and regex refactoring")] public void TryParseWildcardInMajor() { SemanticVersion version; var result = SemanticVersion.TryParse("*", out version); Assert.True(result); Assert.Equal("*", version.ToString()); } [Fact] public void TryParseWildcardInMinor() { SemanticVersion version; var result = SemanticVersion.TryParse("1.*", out version); Assert.True(result); Assert.Equal("1.*", version.ToString()); } [Fact] public void TryParseWildcardInPatch() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.*", out version); Assert.True(result); Assert.Equal("1.2.*", version.ToString()); } [Fact] public void TryParseWildcardInPrerelease() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.3-*", out version); Assert.True(result); Assert.Equal("1.2.3-*", version.ToString()); } [Fact] public void TryParseWildcardInPrereleaseWithBuild() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.3-*+bld", out version); Assert.True(result); Assert.Equal("1.2.3-*+bld", version.ToString()); } [Fact] public void TryParseWildcardInPrereleaseAndBuild() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.3-*+*", out version); Assert.True(result); Assert.Equal("1.2.3-*", version.ToString()); } [Fact] public void TryParseWildcardInBuild() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.3+*", out version); Assert.True(result); // The test result below is intended, as build shouldn't factor // into version precedence (and therefore equality). Assert.Equal("1.2.3", version.ToString()); } [Fact] //(Skip="Broken")] public void TryParseWildcardInBuildWithPrerelease() { SemanticVersion version; var result = SemanticVersion.TryParse("1.2.3-preR+*", out version); Assert.True(result); // The test result below is intended, as build shouldn't factor // into version precedence (and therefore equality). Assert.Equal("1.2.3-preR", version.ToString()); } [Theory] [InlineData("1.2.*-pre")] [InlineData("1.*.3")] [InlineData("*.2")] [InlineData("*.2.3-pre")] public void TryParseValuesAfterWildcards(string versionString) { var result = SemanticVersion.TryParse(versionString, out var version); Assert.False(result); } } }
using System; using PcapDotNet.Base; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.IpV6 { /// <summary> /// RFC 2406. /// <pre> /// +-----+------------+-------------+ /// | Bit | 0-7 | 8-15 | /// +-----+------------+-------------+ /// | 0 | Security Parameters | /// | | Index (SPI) | /// +-----+--------------------------+ /// | 32 | Sequence Number | /// | | | /// +-----+--------------------------+ /// | 64 | Payload Data | /// | ... | | /// +-----+--------------------------+ /// | | Padding | /// | ... | | /// +-----+------------+-------------+ /// | | Pad Length | Next Header | /// +-----+------------+-------------+ /// | | Authentication Data | /// | ... | | /// +-----+--------------------------+ /// </pre> /// /// <pre> /// +-----+------------+-------------+ /// | Bit | 0-7 | 8-15 | /// +-----+------------+-------------+ /// | 0 | Security Parameters | /// | | Index (SPI) | /// +-----+--------------------------+ /// | 32 | Sequence Number | /// | | | /// +-----+--------------------------+ /// | 64 | Encrypted Data | /// | ... | | /// +-----+--------------------------+ /// | | Authentication Data | /// | ... | | /// +-----+--------------------------+ /// </pre> /// </summary> public sealed class IpV6ExtensionHeaderEncapsulatingSecurityPayload : IpV6ExtensionHeader, IEquatable<IpV6ExtensionHeaderEncapsulatingSecurityPayload> { private static class Offset { public const int SecurityParametersIndex = 0; public const int SequenceNumber = SecurityParametersIndex + sizeof(uint); public const int PayloadData = SequenceNumber + sizeof(uint); } /// <summary> /// The minimum number of bytes the extension header takes. /// </summary> public const int MinimumLength = Offset.PayloadData; /// <summary> /// Creates an instance from security parameter index, sequence number and encrypted data and authentication data. /// </summary> /// <param name="securityParametersIndex"> /// The SPI is an arbitrary 32-bit value that, in combination with the destination IP address and security protocol (ESP), /// uniquely identifies the Security Association for this datagram. /// The set of SPI values in the range 1 through 255 are reserved by the Internet Assigned Numbers Authority (IANA) for future use; /// a reserved SPI value will not normally be assigned by IANA unless the use of the assigned SPI value is specified in an RFC. /// It is ordinarily selected by the destination system upon establishment of an SA (see the Security Architecture document for more details). /// The SPI field is mandatory. /// </param> /// <param name="sequenceNumber"> /// Contains a monotonically increasing counter value (sequence number). /// It is mandatory and is always present even if the receiver does not elect to enable the anti-replay service for a specific SA. /// Processing of the Sequence Number field is at the discretion of the receiver, i.e., the sender must always transmit this field, /// but the receiver need not act upon it. /// </param> /// <param name="encryptedDataAndAuthenticationData"> /// Contains the encrypted Payload Data, Padding, Pad Length and Next Header and the Authentication Data. /// </param> public IpV6ExtensionHeaderEncapsulatingSecurityPayload(uint securityParametersIndex, uint sequenceNumber, DataSegment encryptedDataAndAuthenticationData) : base(null) { SecurityParametersIndex = securityParametersIndex; SequenceNumber = sequenceNumber; EncryptedDataAndAuthenticationData = encryptedDataAndAuthenticationData; } /// <summary> /// Identifies the type of this extension header. /// </summary> public override IpV4Protocol Protocol { get { return IpV4Protocol.EncapsulatingSecurityPayload; } } /// <summary> /// The number of bytes this extension header takes. /// </summary> public override int Length { get { return MinimumLength + EncryptedDataAndAuthenticationData.Length; } } /// <summary> /// True iff the extension header parsing didn't encounter an issue. /// </summary> public override bool IsValid { get { return true; } } /// <summary> /// True iff the given extension header is equal to this extension header. /// </summary> public override bool Equals(IpV6ExtensionHeader other) { return Equals(other as IpV6ExtensionHeaderEncapsulatingSecurityPayload); } /// <summary> /// True iff the given extension header is equal to this extension header. /// </summary> public bool Equals(IpV6ExtensionHeaderEncapsulatingSecurityPayload other) { return other != null && SecurityParametersIndex == other.SecurityParametersIndex && SequenceNumber == other.SequenceNumber && EncryptedDataAndAuthenticationData.Equals(other.EncryptedDataAndAuthenticationData); } /// <summary> /// Returns a hash code of the extension header. /// </summary> public override int GetHashCode() { return Sequence.GetHashCode(SecurityParametersIndex, SequenceNumber, EncryptedDataAndAuthenticationData); } /// <summary> /// <para> /// The SPI is an arbitrary 32-bit value that, in combination with the destination IP address and security protocol (ESP), /// uniquely identifies the Security Association for this datagram. /// The set of SPI values in the range 1 through 255 are reserved by the Internet Assigned Numbers Authority (IANA) for future use; /// a reserved SPI value will not normally be assigned by IANA unless the use of the assigned SPI value is specified in an RFC. /// It is ordinarily selected by the destination system upon establishment of an SA (see the Security Architecture document for more details). /// The SPI field is mandatory. /// </para> /// <para> /// The SPI value of zero (0) is reserved for local, implementation-specific use and must not be sent on the wire. /// For example, a key management implementation MAY use the zero SPI value to mean "No Security Association Exists" /// during the period when the IPsec implementation has requested that its key management entity establish a new SA, /// but the SA has not yet been established. /// </para> /// </summary> public uint SecurityParametersIndex { get; private set; } /// <summary> /// <para> /// Contains a monotonically increasing counter value (sequence number). /// It is mandatory and is always present even if the receiver does not elect to enable the anti-replay service for a specific SA. /// Processing of the Sequence Number field is at the discretion of the receiver, i.e., the sender must always transmit this field, /// but the receiver need not act upon it. /// </para> /// <para> /// The sender's counter and the receiver's counter are initialized to 0 when an SA is established. /// (The first packet sent using a given SA will have a Sequence Number of 1.) /// If anti-replay is enabled (the default), the transmitted Sequence Number must never be allowed to cycle. /// Thus, the sender's counter and the receiver's counter must be reset (by establishing a new SA and thus a new key) /// prior to the transmission of the 2^32nd packet on an SA. /// </para> /// </summary> public uint SequenceNumber { get; private set; } /// <summary> /// Contains the encrypted Payload Data, Padding, Pad Length and Next Header and the Authentication Data. /// <para> /// Payload Data is a variable-length field containing data described by the Next Header field. /// The Payload Data field is mandatory and is an integral number of bytes in length. /// If the algorithm used to encrypt the payload requires cryptographic synchronization data, e.g., an Initialization Vector (IV), /// then this data may be carried explicitly in the Payload field. /// Any encryption algorithm that requires such explicit, per-packet synchronization data must indicate the length, any structure for such data, /// and the location of this data as part of an RFC specifying how the algorithm is used with ESP. /// If such synchronization data is implicit, the algorithm for deriving the data must be part of the RFC. /// </para> /// <para> /// The sender may add 0-255 bytes of padding. /// Inclusion of the Padding field in an ESP packet is optional, but all implementations must support generation and consumption of padding. /// </para> /// <para> /// The Pad Length field indicates the number of pad bytes immediately preceding it. /// The range of valid values is 0-255, where a value of zero indicates that no Padding bytes are present. /// The Pad Length field is mandatory. /// </para> /// <para> /// The Next Header is an 8-bit field that identifies the type of data contained in the Payload Data field, /// e.g., an extension header in IPv6 or an upper layer protocol identifier. /// The Next Header field is mandatory. /// </para> /// <para> /// The Authentication Data is a variable-length field containing an Integrity Check Value (ICV) /// computed over the ESP packet minus the Authentication Data. /// The length of the field is specified by the authentication function selected. /// The Authentication Data field is optional, and is included only if the authentication service has been selected for the SA in question. /// The authentication algorithm specification must specify the length of the ICV and the comparison rules and processing steps for validation. /// </para> /// </summary> public DataSegment EncryptedDataAndAuthenticationData { get; private set; } internal static IpV6ExtensionHeaderEncapsulatingSecurityPayload CreateInstance(DataSegment extensionHeaderData, out int numBytesRead) { if (extensionHeaderData.Length < MinimumLength) { numBytesRead = 0; return null; } uint securityParametersIndex = extensionHeaderData.ReadUInt(Offset.SecurityParametersIndex, Endianity.Big); uint sequenceNumber = extensionHeaderData.ReadUInt(Offset.SequenceNumber, Endianity.Big); DataSegment encryptedDataAndAuthenticationData = extensionHeaderData.Subsegment(Offset.PayloadData, extensionHeaderData.Length - Offset.PayloadData); numBytesRead = extensionHeaderData.Length; return new IpV6ExtensionHeaderEncapsulatingSecurityPayload(securityParametersIndex, sequenceNumber, encryptedDataAndAuthenticationData); } internal override void Write(byte[] buffer, ref int offset, IpV4Protocol nextHeader) { buffer.Write(offset + Offset.SecurityParametersIndex, SecurityParametersIndex, Endianity.Big); buffer.Write(offset + Offset.SequenceNumber, SequenceNumber, Endianity.Big); EncryptedDataAndAuthenticationData.Write(buffer, offset + Offset.PayloadData); offset += Length; } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using Crownwood.Magic.Docking; using Crownwood.Magic.Common; using System.Diagnostics; using System.IO; using System.Drawing.Imaging; namespace SpiffCode { /// <summary> /// Summary description for MainForm. /// </summary> public class MainForm : System.Windows.Forms.Form { private string gstrAniMax = "AniMax"; private PreviewPanel m_ctlPreviewPanel; private Form m_frmStrips; private Content m_tntStrips; private Form m_frmBitmaps; private Content m_tntBitmaps; private StripForm m_frmFrames; private Content m_tntFrames; private Form m_frmCombiner; private Content m_tntCombiner; private DockingManager m_dkm; private AnimDoc m_doc; private WindowContent m_wcStrips; private System.Windows.Forms.MenuItem mniFile; private System.Windows.Forms.MenuItem menuItem9; private System.Windows.Forms.MenuItem menuItem10; private System.Windows.Forms.MenuItem menuItem11; private System.Windows.Forms.MenuItem menuItem12; private System.Windows.Forms.MenuItem menuItem13; private System.Windows.Forms.MenuItem menuItem14; private System.Windows.Forms.MenuItem mniNew; private System.Windows.Forms.MenuItem mniOpen; private System.Windows.Forms.MenuItem mniSave; private System.Windows.Forms.MenuItem mniExit; private System.Windows.Forms.MenuItem mniSaveAs; private System.Windows.Forms.MenuItem mniClose; private System.Windows.Forms.MenuItem mniImport; private System.Windows.Forms.MenuItem mniExport; private System.Windows.Forms.MainMenu mnuMain; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.MenuItem mniViewBitmaps; private System.Windows.Forms.MenuItem mniView; private System.Windows.Forms.MenuItem mniViewStrips; private System.Windows.Forms.MenuItem mniViewTracks; private System.Windows.Forms.MenuItem mniTools; private System.Windows.Forms.MenuItem mniOptions; private System.Windows.Forms.OpenFileDialog importFileDialog; private System.Windows.Forms.MenuItem mniRepairSideColors; private System.Windows.Forms.MenuItem mniNormalizeBitmaps; private System.Windows.Forms.MenuItem mniUndo; private System.Windows.Forms.MenuItem mniEdit; private System.Windows.Forms.MenuItem mniHelp; private System.Windows.Forms.MenuItem mniViewCombiner; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem mniHelpAbout; private System.Windows.Forms.MenuItem mniWallPreview; private System.Windows.Forms.MenuItem menuItem3; private System.Windows.Forms.MenuItem mniReplaceColors; private System.ComponentModel.IContainer components = null; public MainForm(string strOpenFileName) { // // Required for Windows Form Designer support // InitializeComponent(); m_dkm = new DockingManager(this, VisualStyle.IDE); Globals.ActiveDocumentChanged += new EventHandler(OnActiveDocumentChanged); m_doc = Globals.ActiveDocument; Globals.MainForm = this; // Create all the "Contents" used to display the various animation components m_ctlPreviewPanel = new PreviewPanel(m_doc); Globals.PreviewControl = m_ctlPreviewPanel.PreviewControl; m_ctlPreviewPanel.Dock = DockStyle.Fill; Controls.Add(m_ctlPreviewPanel); m_dkm.InnerControl = m_ctlPreviewPanel; m_frmStrips = new StripsForm(m_doc); Globals.StripsForm = m_frmStrips; m_tntStrips = m_dkm.Contents.Add(m_frmStrips, m_frmStrips.Text); m_tntStrips.DisplaySize = new Size(ClientSize.Width / 4, ClientSize.Height / 2); m_wcStrips = m_dkm.AddContentWithState(m_tntStrips, State.DockLeft); m_frmBitmaps = new BitmapsForm(m_doc); m_tntBitmaps = m_dkm.Contents.Add(m_frmBitmaps, m_frmBitmaps.Text); m_tntBitmaps.DisplaySize = new Size(ClientSize.Width / 4, ClientSize.Height / 2); m_dkm.AddContentWithState(m_tntBitmaps, State.DockTop); // Add the Bitmaps form to the StripForm's Zone m_dkm.AddContentToZone(m_tntBitmaps, m_wcStrips.ParentZone, 1); m_frmFrames = new StripForm(m_doc); Globals.StripForm = m_frmFrames; m_tntFrames = m_dkm.Contents.Add(m_frmFrames, m_frmFrames.Text); m_frmFrames.Content = m_tntFrames; int cx = ClientSize.Width - (ClientSize.Width / 4); int cy = ClientSize.Height / 3; m_tntFrames.DisplaySize = new Size(cx, cy); m_dkm.AddContentWithState(m_tntFrames, State.DockBottom); m_frmCombiner = new CombinerForm(); m_tntCombiner = m_dkm.Contents.Add(m_frmCombiner, m_frmCombiner.Text); m_tntCombiner.DisplaySize = new Size(ClientSize.Width / 2, ClientSize.Height / 2); // m_dkm.AddContentWithState(m_tntCombiner, State.Floating); // m_dkm.HideContent(m_tntCombiner); // Do a little wiring ((StripControl)Globals.StripControl).FrameOffsetChanged += new FrameOffsetEventHandler(((PreviewControl)Globals.PreviewControl).OnFrameOffsetChanged); ((PreviewControl)Globals.PreviewControl).FrameOffsetChanged += new FrameOffsetEventHandler(((StripControl)Globals.StripControl).OnFrameOffsetChanged); // We always have a document around if (strOpenFileName == null) NewDocument(); else OpenDocument(strOpenFileName); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm)); this.mniFile = new System.Windows.Forms.MenuItem(); this.mniNew = new System.Windows.Forms.MenuItem(); this.mniOpen = new System.Windows.Forms.MenuItem(); this.mniClose = new System.Windows.Forms.MenuItem(); this.menuItem9 = new System.Windows.Forms.MenuItem(); this.mniSave = new System.Windows.Forms.MenuItem(); this.mniSaveAs = new System.Windows.Forms.MenuItem(); this.menuItem10 = new System.Windows.Forms.MenuItem(); this.mniImport = new System.Windows.Forms.MenuItem(); this.mniExport = new System.Windows.Forms.MenuItem(); this.menuItem14 = new System.Windows.Forms.MenuItem(); this.menuItem13 = new System.Windows.Forms.MenuItem(); this.menuItem12 = new System.Windows.Forms.MenuItem(); this.menuItem11 = new System.Windows.Forms.MenuItem(); this.mniExit = new System.Windows.Forms.MenuItem(); this.mniOptions = new System.Windows.Forms.MenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.mniViewTracks = new System.Windows.Forms.MenuItem(); this.mniViewBitmaps = new System.Windows.Forms.MenuItem(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.mniViewStrips = new System.Windows.Forms.MenuItem(); this.mnuMain = new System.Windows.Forms.MainMenu(); this.mniEdit = new System.Windows.Forms.MenuItem(); this.mniUndo = new System.Windows.Forms.MenuItem(); this.mniView = new System.Windows.Forms.MenuItem(); this.mniViewCombiner = new System.Windows.Forms.MenuItem(); this.mniTools = new System.Windows.Forms.MenuItem(); this.mniNormalizeBitmaps = new System.Windows.Forms.MenuItem(); this.mniRepairSideColors = new System.Windows.Forms.MenuItem(); this.mniWallPreview = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.mniHelp = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.mniHelpAbout = new System.Windows.Forms.MenuItem(); this.importFileDialog = new System.Windows.Forms.OpenFileDialog(); this.mniReplaceColors = new System.Windows.Forms.MenuItem(); // // mniFile // this.mniFile.Index = 0; this.mniFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mniNew, this.mniOpen, this.mniClose, this.menuItem9, this.mniSave, this.mniSaveAs, this.menuItem10, this.mniImport, this.mniExport, this.menuItem14, this.menuItem13, this.menuItem12, this.menuItem11, this.mniExit}); this.mniFile.Text = "&File"; this.mniFile.Popup += new System.EventHandler(this.mniFile_Popup); // // mniNew // this.mniNew.Index = 0; this.mniNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN; this.mniNew.Text = "&New"; this.mniNew.Click += new System.EventHandler(this.mniNew_Click); // // mniOpen // this.mniOpen.Index = 1; this.mniOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO; this.mniOpen.Text = "&Open..."; this.mniOpen.Click += new System.EventHandler(this.mniOpen_Click); // // mniClose // this.mniClose.Index = 2; this.mniClose.Text = "&Close"; this.mniClose.Click += new System.EventHandler(this.mniClose_Click); // // menuItem9 // this.menuItem9.Index = 3; this.menuItem9.Text = "-"; // // mniSave // this.mniSave.Index = 4; this.mniSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS; this.mniSave.Text = "&Save"; this.mniSave.Click += new System.EventHandler(this.mniSave_Click); // // mniSaveAs // this.mniSaveAs.Index = 5; this.mniSaveAs.Text = "Save &As..."; this.mniSaveAs.Click += new System.EventHandler(this.mniSaveAs_Click); // // menuItem10 // this.menuItem10.Index = 6; this.menuItem10.Text = "-"; // // mniImport // this.mniImport.Index = 7; this.mniImport.Text = "&Import..."; this.mniImport.Click += new System.EventHandler(this.mniImport_Click); // // mniExport // this.mniExport.Enabled = false; this.mniExport.Index = 8; this.mniExport.Text = "&Export..."; // // menuItem14 // this.menuItem14.Index = 9; this.menuItem14.Text = "-"; // // menuItem13 // this.menuItem13.Enabled = false; this.menuItem13.Index = 10; this.menuItem13.Text = "Recent Strips"; // // menuItem12 // this.menuItem12.Enabled = false; this.menuItem12.Index = 11; this.menuItem12.Text = "Recent Files"; // // menuItem11 // this.menuItem11.Index = 12; this.menuItem11.Text = "-"; // // mniExit // this.mniExit.Index = 13; this.mniExit.Text = "E&xit"; // // mniOptions // this.mniOptions.Index = 5; this.mniOptions.Text = "&Options..."; this.mniOptions.Click += new System.EventHandler(this.mniOptions_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "amx"; this.saveFileDialog.FileName = "untitled.amx"; this.saveFileDialog.Filter = "AniMax files (*.amx)|*.amx|Zipped AniMax files (*.zamx)|*.zamx|All files|*.*"; this.saveFileDialog.Title = "Save AniMax File"; // // mniViewTracks // this.mniViewTracks.Index = 2; this.mniViewTracks.Text = "&Frames Window"; this.mniViewTracks.Click += new System.EventHandler(this.mniViewTracks_Click); // // mniViewBitmaps // this.mniViewBitmaps.Index = 0; this.mniViewBitmaps.Text = "&Bitmaps Window"; this.mniViewBitmaps.Click += new System.EventHandler(this.mniViewBitmaps_Click); // // openFileDialog // this.openFileDialog.DefaultExt = "amx"; this.openFileDialog.Filter = "AniMax files (*.amx)|*.amx|Zipped AniMax files (*.zamx)|*.zamx|All files|*.*"; this.openFileDialog.Title = "Open AniMax File"; // // mniViewStrips // this.mniViewStrips.Index = 1; this.mniViewStrips.Text = "&Strips Window"; this.mniViewStrips.Click += new System.EventHandler(this.mniViewStrips_Click); // // mnuMain // this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mniFile, this.mniEdit, this.mniView, this.mniTools, this.mniHelp}); // // mniEdit // this.mniEdit.Index = 1; this.mniEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mniUndo}); this.mniEdit.Text = "&Edit"; this.mniEdit.Popup += new System.EventHandler(this.mniEdit_Popup); // // mniUndo // this.mniUndo.Index = 0; this.mniUndo.Shortcut = System.Windows.Forms.Shortcut.CtrlZ; this.mniUndo.Text = "&Undo"; this.mniUndo.Click += new System.EventHandler(this.mniUndo_Click); // // mniView // this.mniView.Index = 2; this.mniView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mniViewBitmaps, this.mniViewStrips, this.mniViewTracks, this.mniViewCombiner}); this.mniView.Text = "&View"; this.mniView.Popup += new System.EventHandler(this.mniView_Popup); // // mniViewCombiner // this.mniViewCombiner.Index = 3; this.mniViewCombiner.Text = "&Combiner Window"; this.mniViewCombiner.Click += new System.EventHandler(this.mniViewCombiner_Click); // // mniTools // this.mniTools.Index = 3; this.mniTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mniNormalizeBitmaps, this.mniRepairSideColors, this.mniWallPreview, this.mniReplaceColors, this.menuItem3, this.mniOptions}); this.mniTools.Text = "&Tools"; // // mniNormalizeBitmaps // this.mniNormalizeBitmaps.Enabled = false; this.mniNormalizeBitmaps.Index = 0; this.mniNormalizeBitmaps.Text = "Normalize Bitmaps"; // // mniRepairSideColors // this.mniRepairSideColors.Index = 1; this.mniRepairSideColors.Text = "Repair Side Colors"; this.mniRepairSideColors.Click += new System.EventHandler(this.mniRepairSideColors_Click); // // mniWallPreview // this.mniWallPreview.Index = 2; this.mniWallPreview.Text = "&Wall Preview"; this.mniWallPreview.Click += new System.EventHandler(this.mniWallPreview_Click); // // menuItem3 // this.menuItem3.Index = 4; this.menuItem3.Text = "-"; // // mniHelp // this.mniHelp.Index = 4; this.mniHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.mniHelpAbout}); this.mniHelp.Text = "&Help"; // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.Shortcut = System.Windows.Forms.Shortcut.F1; this.menuItem1.Text = "&Help"; this.menuItem1.Click += new System.EventHandler(this.mniHelp_Click); // // mniHelpAbout // this.mniHelpAbout.Index = 1; this.mniHelpAbout.Text = "&About SpiffCode AniMax..."; this.mniHelpAbout.Click += new System.EventHandler(this.mniHelpAbout_Click); // // importFileDialog // this.importFileDialog.Filter = "Bitmap files (*.bmp,*.png,*.gif,*.jpg,*.exif,*.tif)|*.bmp;*.png;*.gif;*.exif;*.jp" + "g|Framedata files|*.txt"; this.importFileDialog.Multiselect = true; this.importFileDialog.Title = "Import"; // // mniReplaceColors // this.mniReplaceColors.Index = 3; this.mniReplaceColors.Text = "Replace Colors..."; this.mniReplaceColors.Click += new System.EventHandler(this.mniReplaceColors_Click); // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(712, 478); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.Menu = this.mnuMain; this.Name = "MainForm"; this.Text = "AniMax"; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyDown); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainForm_KeyPress); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyUp); } #endregion private void OnActiveDocumentChanged(object obSender, EventArgs e) { m_doc = Globals.ActiveDocument; if (m_doc.FileName == null) Text = gstrAniMax; else Text = gstrAniMax + " - " + m_doc.FileName; } private void mniNew_Click(object sender, System.EventArgs e) { NewDocument(); } private void NewDocument() { // First close the open document (if any) if (!CloseDocument()) return; // Create a new one and show its views Globals.ActiveDocument = new AnimDoc(Globals.TileSize, Globals.FrameRate); ShowViews(); // I'm tired of being asked if I want to save untitled on exit even though I // haven't done anything to it. m_doc.Dirty = false; } private void mniSave_Click(object sender, System.EventArgs e) { SaveDocument(); } private void mniSaveAs_Click(object sender, System.EventArgs e) { SaveAsDocument(); } private void mniOpen_Click(object sender, System.EventArgs e) { // If the current doc is dirty give the user a chance to save it // before loading the new doc. if (!GiveUserChanceToSaveChangesOrCancel()) return; if (openFileDialog.ShowDialog() != DialogResult.OK) return; OpenDocument(openFileDialog.FileName); } public void CloseAndOpenDocument(string strFileName) { if (!GiveUserChanceToSaveChangesOrCancel()) return; OpenDocument(strFileName); } private void OpenDocument(string strFileName) { // Cursor.Current = Cursors.WaitCursor; Directory.SetCurrentDirectory(Path.GetDirectoryName(strFileName)); AnimDoc doc = AnimDoc.Load(strFileName); Cursor.Current = Cursors.Arrow; if (doc == null) { MessageBox.Show(this, String.Format("Unexpected error loading {0} " + "or one of the bitmap files it depends on. Sorry.", strFileName), "AniMax"); return; } Globals.ActiveDocument = doc; Globals.TileSize = doc.TileSize; Globals.ActiveStrip = doc.StripSet[0]; ShowViews(); } private void mniClose_Click(object sender, System.EventArgs e) { CloseDocument(); } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if (!CloseDocument()) e.Cancel = true; } private bool SaveDocument() { if (m_doc.FileName == null) { return SaveAsDocument(); } else { Cursor.Current = Cursors.WaitCursor; m_doc.Save(m_doc.FileName); Cursor.Current = Cursors.Arrow; return true; } } private bool SaveAsDocument() { saveFileDialog.FileName = m_doc.FileName; if (saveFileDialog.ShowDialog() != DialogResult.OK) return false; Cursor.Current = Cursors.WaitCursor; m_doc.Save(saveFileDialog.FileName); Cursor.Current = Cursors.Arrow; Text = "AniMax - " + m_doc.FileName; return true; } private bool GiveUserChanceToSaveChangesOrCancel() { if (m_doc.Dirty) { DialogResult dlgr = MessageBox.Show(this, String.Format("Do you want to save the changes to {0}?", m_doc.FileName), "AniMax", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation); if (dlgr == DialogResult.Cancel) return false; else if (dlgr == DialogResult.Yes) return SaveDocument(); } return true; } private bool CloseDocument() { if (!GiveUserChanceToSaveChangesOrCancel()) return false; Globals.ActiveDocument = Globals.NullDocument; return true; } private void mniViewBitmaps_Click(object sender, System.EventArgs e) { ShowContent(m_tntBitmaps); } private void mniViewStrips_Click(object sender, System.EventArgs e) { ShowContent(m_tntStrips); } private void mniViewTracks_Click(object sender, System.EventArgs e) { ShowContent(m_tntFrames); } private void mniViewCombiner_Click(object sender, System.EventArgs e) { ShowContent(m_tntCombiner); } private void ShowViews() { ShowContent(m_tntStrips); ShowContent(m_tntBitmaps); ShowContent(m_tntFrames); } private void ShowContent(Content tnt) { if (!tnt.Visible) m_dkm.ShowContent(tnt); } private void mniView_Popup(object sender, System.EventArgs e) { bool fDocExists = m_doc != null; mniViewBitmaps.Enabled = fDocExists; mniViewStrips.Enabled = fDocExists; mniViewTracks.Enabled = fDocExists; } private void mniFile_Popup(object sender, System.EventArgs e) { bool fDocExists = m_doc != null; mniClose.Enabled = fDocExists; mniSave.Enabled = fDocExists; mniSaveAs.Enabled = fDocExists; mniExport.Enabled = fDocExists; } private void mniOptions_Click(object sender, System.EventArgs e) { // UNDONE: the options form includes a mishmash of items, some of which are // scoped to the application, some to the current document. Document options // should be moved to a properties dialog or something. // CONSIDER: ye olde PropertyGrid? OptionsForm frm = new OptionsForm(); frm.FrameRate = m_doc != null ? m_doc.FrameRate : Globals.FrameRate; frm.GridWidth = Globals.GridWidth; frm.GridHeight = Globals.GridHeight; if (frm.ShowDialog(this) != DialogResult.OK) return; if (m_doc != null) m_doc.FrameRate = frm.FrameRate; else Globals.FrameRate = frm.FrameRate; Globals.GridWidth = frm.GridWidth; Globals.GridHeight = frm.GridHeight; frm.Dispose(); } private void mniImport_Click(object sender, System.EventArgs e) { if (importFileDialog.ShowDialog() != DialogResult.OK) return; string[] astrFileNames = importFileDialog.FileNames; // If a document doesn't already exist create a new one and show its views if (m_doc == Globals.NullDocument) { m_doc = new AnimDoc(Globals.TileSize, Globals.FrameRate); ShowViews(); } Cursor.Current = Cursors.WaitCursor; bool fSuccess = m_doc.Import(astrFileNames); Cursor.Current = Cursors.Arrow; if (!fSuccess) return; Globals.ActiveDocument = m_doc; Globals.ActiveStrip = m_doc.StripSet[0]; } // We have a universal key handler that any control or child form can register // with to take a crack at processing the key press. private void MainForm_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { Globals.OnKeyPress(sender, e); } private void MainForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { Globals.OnKeyDown(sender, e); } private void MainForm_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { Globals.OnKeyUp(sender, e); } private void mniRepairSideColors_Click(object sender, System.EventArgs e) { if (m_doc.XBitmapSet.Count == 0) { MessageBox.Show(this, "Hey dork, no Bitmaps have been loaded yet.", "Error"); return; } foreach (XBitmap xbm in m_doc.XBitmapSet) { bool fDirty = ReplaceColor(xbm.Bitmap, Color.FromArgb(0, 114, 232), Color.FromArgb(0, 116, 232), true); fDirty |= ReplaceColor(xbm.Bitmap, Color.FromArgb(0, 112, 232), Color.FromArgb(0, 116, 232), true); fDirty |= ReplaceColor(xbm.Bitmap, Color.FromArgb(0, 96, 192), Color.FromArgb(0, 96, 196), true); fDirty |= ReplaceColor(xbm.Bitmap, Color.FromArgb(0, 48, 88), Color.FromArgb(0, 48, 92), true); if (fDirty) { xbm.Dirty = fDirty; m_doc.Dirty = true; } } // UNDONE: this is a hack. Decide on the right way to force selective refreshes Globals.StripControl.Invalidate(); Globals.PreviewControl.Invalidate(); } #region Handy Helpers static public bool ReplaceColor(Bitmap bm, Color clrOld, Color clrNew, bool f6bit) { bool fFound = false; if (f6bit) { clrOld = Color.FromArgb(clrOld.R & 0xfc, clrOld.G & 0xfc, clrOld.B & 0xfc); clrNew = Color.FromArgb(clrNew.R & 0xfc, clrNew.G & 0xfc, clrNew.B & 0xfc); } for (int y = 0; y < bm.Height; y++) { for (int x = 0; x < bm.Width; x++) { Color clr = bm.GetPixel(x, y); if (f6bit) clr = Color.FromArgb(clr.R & 0xfc, clr.G & 0xfc, clr.B & 0xfc); if (clr == clrOld) { fFound = true; bm.SetPixel(x, y, clrNew); } } } return fFound; } #endregion private void mniUndo_Click(object sender, System.EventArgs e) { UndoManager.Undo(); } private void mniEdit_Popup(object sender, System.EventArgs e) { mniUndo.Enabled = UndoManager.AnyUndos(); } private void mniHelp_Click(object sender, System.EventArgs e) { Process.Start("http://www.tinybit.org/AniMax"); } private void mniToolsHack_Click(object sender, System.EventArgs e) { foreach (Strip stp in Globals.ActiveDocument.StripSet) { if (!stp.Name.ToLower().StartsWith("turret")) continue; foreach (Frame fr in stp) { Point pt = new Point(fr.SpecialPoint.X - 7, fr.SpecialPoint.Y - 3); fr.SpecialPoint = pt; foreach (BitmapPlacer plc in fr.BitmapPlacers) { plc.X += 7; plc.Y += 3; } } } // Force a redraw of everything Globals.ActiveDocument = Globals.ActiveDocument; } private void mniHelpAbout_Click(object sender, System.EventArgs e) { new AboutForm().ShowDialog(this); } private void mniWallPreview_Click(object sender, System.EventArgs e) { new WallPreviewForm().ShowDialog(this); } private void mniGenerateCompass_Click(object sender, System.EventArgs e) { Bitmap bm = new Bitmap(200, 200); Graphics g = Graphics.FromImage(bm); Pen pen = new Pen(Color.White); int xC = 100; int yC = 100; for (int i = 0; i < 16; i++) { double nAngle = (Math.PI * 2) * (i / 16.0); int xE = (int)(Math.Sin(nAngle) * 100); int yE = (int)(Math.Cos(nAngle) * 100); g.DrawLine(pen, xC, yC, xC + xE, yC + yE); } g.Dispose(); bm.Save(@"c:\compass.png", ImageFormat.Png); } private void mniReplaceColors_Click(object sender, System.EventArgs e) { if (m_doc.XBitmapSet.Count == 0) { MessageBox.Show(this, "Hey dork, no Bitmaps have been loaded yet.", "Error"); return; } new ReplaceColorsForm(m_doc).ShowDialog(this); } } }
// // CGImage.cs: Implements the managed CGImage // // Authors: Mono Team // // Copyright 2009 Novell, Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.CoreGraphics { #if MONOMAC [Flags] public enum CGWindowImageOption { Default = 0, BoundsIgnoreFraming = (1 << 0), ShouldBeOpaque = (1 << 1), OnlyShadows = (1 << 2) } [Flags] public enum CGWindowListOption { All = 0, OnScreenOnly = (1 << 0), OnScreenAboveWindow = (1 << 1), OnScreenBelowWindow = (1 << 2), IncludingWindow = (1 << 3), ExcludeDesktopElements = (1 << 4) } #endif public enum CGImageAlphaInfo { None, PremultipliedLast, PremultipliedFirst, Last, First, NoneSkipLast, NoneSkipFirst, Only } [Flags] public enum CGBitmapFlags { None, PremultipliedLast, PremultipliedFirst, Last, First, NoneSkipLast, NoneSkipFirst, Only, AlphaInfoMask = 0x1F, FloatComponents = (1 << 8), ByteOrderMask = 0x7000, ByteOrderDefault = (0 << 12), ByteOrder16Little = (1 << 12), ByteOrder32Little = (2 << 12), ByteOrder16Big = (3 << 12), ByteOrder32Big = (4 << 12) } public class CGImage : INativeObject, IDisposable { internal IntPtr handle; // invoked by marshallers public CGImage (IntPtr handle) : this (handle, false) { this.handle = handle; } [Preserve (Conditional=true)] internal CGImage (IntPtr handle, bool owns) { this.handle = handle; if (!owns) CGImageRetain (handle); } ~CGImage () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGImageRelease (IntPtr handle); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGImageRetain (IntPtr handle); protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CGImageRelease (handle); handle = IntPtr.Zero; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreate(int size_t_width, int size_t_height, int size_t_bitsPerComponent, int size_t_bitsPerPixel, int size_t_bytesPerRow, IntPtr /* CGColorSpaceRef */ space, CGBitmapFlags bitmapInfo, IntPtr /* CGDataProviderRef */ provider, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent); public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, CGColorSpace colorSpace, CGBitmapFlags bitmapFlags, CGDataProvider provider, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent) { if (colorSpace == null) throw new ArgumentNullException ("colorSpace"); if (width < 0) throw new ArgumentException ("width"); if (height < 0) throw new ArgumentException ("height"); if (bitsPerPixel < 0) throw new ArgumentException ("bitsPerPixel"); if (bitsPerComponent < 0) throw new ArgumentException ("bitsPerComponent"); if (bytesPerRow < 0) throw new ArgumentException ("bytesPerRow"); if (provider == null) throw new ArgumentNullException ("provider"); handle = CGImageCreate (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace.Handle, bitmapFlags, provider.Handle, decode, shouldInterpolate, intent); } public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, CGColorSpace colorSpace, CGImageAlphaInfo alphaInfo, CGDataProvider provider, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent) { if (colorSpace == null) throw new ArgumentNullException ("colorSpace"); if (width < 0) throw new ArgumentException ("width"); if (height < 0) throw new ArgumentException ("height"); if (bitsPerPixel < 0) throw new ArgumentException ("bitsPerPixel"); if (bitsPerComponent < 0) throw new ArgumentException ("bitsPerComponent"); if (bytesPerRow < 0) throw new ArgumentException ("bytesPerRow"); if (provider == null) throw new ArgumentNullException ("provider"); handle = CGImageCreate (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace.Handle, (CGBitmapFlags) alphaInfo, provider.Handle, decode, shouldInterpolate, intent); } #if MONOMAC [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGWindowListCreateImage(RectangleF screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption); public static CGImage ScreenImage (int windownumber, RectangleF bounds) { IntPtr imageRef = CGWindowListCreateImage(bounds, CGWindowListOption.IncludingWindow, (uint)windownumber, CGWindowImageOption.Default); return new CGImage(imageRef, true); } #else [DllImport (Constants.UIKitLibrary)] extern static IntPtr UIGetScreenImage (); public static CGImage ScreenImage { get { return new CGImage (UIGetScreenImage (), true); } } #endif [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreateWithJPEGDataProvider(IntPtr /* CGDataProviderRef */ source, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent); public static CGImage FromJPEG (CGDataProvider provider, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent) { if (provider == null) throw new ArgumentNullException ("provider"); var handle = CGImageCreateWithJPEGDataProvider (provider.Handle, decode, shouldInterpolate, intent); if (handle == IntPtr.Zero) return null; return new CGImage (handle, true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreateWithPNGDataProvider(IntPtr /*CGDataProviderRef*/ source, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent); public static CGImage FromPNG (CGDataProvider provider, float [] decode, bool shouldInterpolate, CGColorRenderingIntent intent) { if (provider == null) throw new ArgumentNullException ("provider"); var handle = CGImageCreateWithPNGDataProvider (provider.Handle, decode, shouldInterpolate, intent); if (handle == IntPtr.Zero) return null; return new CGImage (handle, true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageMaskCreate (int size_t_width, int size_t_height, int size_t_bitsPerComponent, int size_t_bitsPerPixel, int size_t_bytesPerRow, IntPtr /* CGDataProviderRef */ provider, float [] decode, bool shouldInterpolate); public static CGImage CreateMask (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, CGDataProvider provider, float [] decode, bool shouldInterpolate) { if (width < 0) throw new ArgumentException ("width"); if (height < 0) throw new ArgumentException ("height"); if (bitsPerPixel < 0) throw new ArgumentException ("bitsPerPixel"); if (bytesPerRow < 0) throw new ArgumentException ("bytesPerRow"); if (provider == null) throw new ArgumentNullException ("provider"); var handle = CGImageMaskCreate (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, provider.Handle, decode, shouldInterpolate); if (handle == IntPtr.Zero) return null; return new CGImage (handle, true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreateWithMaskingColors(IntPtr image, float [] components); public CGImage WithMaskingColors (float[] components) { int N = 2*ColorSpace.Components; if (components == null) throw new ArgumentNullException ("components"); if (components.Length != N) throw new ArgumentException ("The argument 'components' must have 2N values, where N is the number of components in the color space of the image.", "components"); return new CGImage (CGImageCreateWithMaskingColors (Handle, components), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreateCopy(IntPtr image); public CGImage Clone () { return new CGImage (CGImageCreateCopy (handle), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreateCopyWithColorSpace(IntPtr image, IntPtr space); public CGImage WithColorSpace (CGColorSpace cs) { return new CGImage (CGImageCreateCopyWithColorSpace (handle, cs.handle), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreateWithImageInRect(IntPtr image, RectangleF rect); public CGImage WithImageInRect (RectangleF rect) { return new CGImage (CGImageCreateWithImageInRect (handle, rect), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageCreateWithMask(IntPtr image, IntPtr mask); public CGImage WithMask (CGImage mask) { return new CGImage (CGImageCreateWithMask (handle, mask.handle), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGImageIsMask(IntPtr image); public bool IsMask { get { return CGImageIsMask (handle) != 0; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGImageGetWidth(IntPtr image); public int Width { get { return CGImageGetWidth (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGImageGetHeight(IntPtr image); public int Height { get { return CGImageGetHeight (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGImageGetBitsPerComponent(IntPtr image); public int BitsPerComponent { get { return CGImageGetBitsPerComponent (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGImageGetBitsPerPixel(IntPtr image); public int BitsPerPixel { get { return CGImageGetBitsPerPixel (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGImageGetBytesPerRow(IntPtr image); public int BytesPerRow { get { return CGImageGetBytesPerRow (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageGetColorSpace(IntPtr image); public CGColorSpace ColorSpace { get { return new CGColorSpace (CGImageGetColorSpace (handle)); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGImageAlphaInfo CGImageGetAlphaInfo(IntPtr image); public CGImageAlphaInfo AlphaInfo { get { return CGImageGetAlphaInfo (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGImageGetDataProvider(IntPtr image); public CGDataProvider DataProvider { get { return new CGDataProvider (CGImageGetDataProvider (handle)); } } [DllImport (Constants.CoreGraphicsLibrary)] unsafe extern static float * CGImageGetDecode(IntPtr image); public unsafe float *Decode { get { return CGImageGetDecode (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGImageGetShouldInterpolate(IntPtr image); public bool ShouldInterpolate { get { return CGImageGetShouldInterpolate (handle) != 0; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGColorRenderingIntent CGImageGetRenderingIntent(IntPtr image); public CGColorRenderingIntent RenderingIntent { get { return CGImageGetRenderingIntent (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGBitmapFlags CGImageGetBitmapInfo(IntPtr image); public CGBitmapFlags BitmapInfo { get { return CGImageGetBitmapInfo (handle); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // // The Original Code is DotSpatial // // The Initial Developer of this Original Code is Ted Dunsford. Created in February, 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using GeoAPI.Geometries; namespace DotSpatial.Data { /// <summary> /// A shapefile class that handles the special case where each features has multiple points /// </summary> public class MultiPointShapefile : Shapefile { #region Constant Fields private const int BLOCKSIZE = 16000000; #endregion #region Constructors /// <summary> /// Creates a new instance of a MultiPointShapefile for in-ram handling only. /// </summary> public MultiPointShapefile() : base(FeatureType.MultiPoint) { Attributes = new AttributeTable(); Header = new ShapefileHeader { FileLength = 100, ShapeType = ShapeType.MultiPoint }; } /// <summary> /// Creates a new instance of a MultiPointShapefile that is loaded from the supplied fileName. /// </summary> /// <param name="fileName">The string fileName of the polygon shapefile to load</param> public MultiPointShapefile(string fileName) : this() { Open(fileName, null); } #endregion #region Methods // X Y MultiPoints: Total Length = 28 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 8 Integer 1 Little // Byte 12 Xmin Double 1 Little // Byte 20 Ymin Double 1 Little // Byte 28 Xmax Double 1 Little // Byte 36 Ymax Double 1 Little // Byte 44 NumPoints Integer 1 Little // Byte 48 Points Point NumPoints Little // X Y M MultiPoints: Total Length = 34 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 28 Integer 1 Little // Byte 12 Box (Xmin - Ymax) Double 4 Little // Byte 44 NumPoints Integer 1 Little // Byte 48 Points Point NumPoints Little // Byte X* Mmin Double 1 Little // Byte X+8* Mmax Double 1 Little // Byte X+16* Marray Double NumPoints Little // X = 48 + (16 * NumPoints) // * = optional // X Y Z M MultiPoints: Total Length = 44 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 18 Integer 1 Little // Byte 12 Box Double 4 Little // Byte 44 NumPoints Integer 1 Little // Byte 48 Points Point NumPoints Little // Byte X Zmin Double 1 Little // Byte X+8 Zmax Double 1 Little // Byte X+16 Zarray Double NumPoints Little // Byte Y* Mmin Double 1 Little // Byte Y+8* Mmax Double 1 Little // Byte Y+16* Marray Double NumPoints Little // X = 48 + (16 * NumPoints) // Y = X + 16 + (8 * NumPoints) // * = optional private void FillPoints(string fileName, IProgressHandler progressHandler) { // Check to ensure the fileName is not null if (fileName == null) { throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", "fileName")); } if (File.Exists(fileName) == false) { throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", fileName)); } // Get the basic header information. var header = this.Header; // Check to ensure that the fileName is the correct shape type if (header.ShapeType != ShapeType.MultiPoint && header.ShapeType != ShapeType.MultiPointM && header.ShapeType != ShapeType.MultiPointZ) { throw new ArgumentException(DataStrings.FileNotLines_S.Replace("%S", fileName)); } if (new FileInfo(fileName).Length == 100) { // the file is empty so we are done reading return; } // Reading the headers gives us an easier way to track the number of shapes and their overall length etc. List<ShapeHeader> shapeHeaders = ReadIndexFile(fileName); int numShapes = shapeHeaders.Count; bool isM = (header.ShapeType == ShapeType.MultiPointZ || header.ShapeType == ShapeType.MultiPointM); bool isZ = (header.ShapeType == ShapeType.MultiPointZ); int totalPointsCount = 0; int totalPartsCount = 0; var shapeIndices = new List<ShapeRange>(numShapes); using (var reader = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 65536)) { var boundsBytes = new byte[4 * 8]; var bounds = new double[4]; for (int shp = 0; shp < numShapes; shp++) { // Read from the index file because some deleted records might still exist in the .shp file. long offset = (shapeHeaders[shp].ByteOffset); reader.Seek(offset, SeekOrigin.Begin); var shape = new ShapeRange(FeatureType.MultiPoint, CoordinateType) { RecordNumber = reader.ReadInt32(Endian.BigEndian), ContentLength = reader.ReadInt32(Endian.BigEndian), ShapeType = (ShapeType)reader.ReadInt32(), StartIndex = totalPointsCount, NumParts = 1 }; Debug.Assert(shape.RecordNumber == shp + 1); if (shape.ShapeType != ShapeType.NullShape) { // Bounds reader.Read(boundsBytes, 0, boundsBytes.Length); Buffer.BlockCopy(boundsBytes, 0, bounds, 0, boundsBytes.Length); shape.Extent.MinX = bounds[0]; shape.Extent.MinY = bounds[1]; shape.Extent.MaxX = bounds[2]; shape.Extent.MaxY = bounds[3]; //// Num Parts //shape.NumParts = reader.ReadInt32(); totalPartsCount += 1; // Num Points shape.NumPoints = reader.ReadInt32(); totalPointsCount += shape.NumPoints; } shapeIndices.Add(shape); } var vert = new double[totalPointsCount * 2]; var vertInd = 0; var parts = new int[totalPartsCount]; //var partsInd = 0; int mArrayInd = 0, zArrayInd = 0; double[] mArray = null, zArray = null; if (isM) mArray = new double[totalPointsCount]; if (isZ) zArray = new double[totalPointsCount]; int partsOffset = 0; for (int shp = 0; shp < numShapes; shp++) { var shape = shapeIndices[shp]; if (shape.ShapeType == ShapeType.NullShape) continue; reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin); reader.Seek(3 * 4 + 32 + 4, SeekOrigin.Current); // Skip first bytes (Record Number, Content Length, Shapetype + BoundingBox + NumPoints) //// Read parts //var partsBytes = reader.ReadBytes(4 * shape.NumParts); //Numparts * Integer(4) = existing Parts //Buffer.BlockCopy(partsBytes, 0, parts, partsInd, partsBytes.Length); //partsInd += 4 * shape.NumParts; // Read points var pointsBytes = reader.ReadBytes(8 * 2 * shape.NumPoints); //Numpoints * Point (X(8) + Y(8)) Buffer.BlockCopy(pointsBytes, 0, vert, vertInd, pointsBytes.Length); vertInd += 8 * 2 * shape.NumPoints; // Fill parts shape.Parts.Capacity = shape.NumParts; for (int part = 0; part < shape.NumParts; part++) { int endIndex = shape.NumPoints + shape.StartIndex; int startIndex = parts[partsOffset + part] + shape.StartIndex; if (part < shape.NumParts - 1) { endIndex = parts[partsOffset + part + 1] + shape.StartIndex; } int count = endIndex - startIndex; var partR = new PartRange(vert, shape.StartIndex, parts[partsOffset + part], FeatureType.MultiPoint) { NumVertices = count }; shape.Parts.Add(partR); } partsOffset += shape.NumParts; // Fill M and Z arrays switch (header.ShapeType) { case ShapeType.MultiPointM: if (shape.ContentLength * 2 > 44 + 4 * shape.NumParts + 16 * shape.NumPoints) { var mExt = (IExtentM)shape.Extent; mExt.MinM = reader.ReadDouble(); mExt.MaxM = reader.ReadDouble(); var mBytes = reader.ReadBytes(8 * shape.NumPoints); Buffer.BlockCopy(mBytes, 0, mArray, mArrayInd, mBytes.Length); mArrayInd += 8 * shape.NumPoints; } break; case ShapeType.MultiPointZ: var zExt = (IExtentZ)shape.Extent; zExt.MinZ = reader.ReadDouble(); zExt.MaxZ = reader.ReadDouble(); var zBytes = reader.ReadBytes(8 * shape.NumPoints); Buffer.BlockCopy(zBytes, 0, zArray, zArrayInd, zBytes.Length); zArrayInd += 8 * shape.NumPoints; // These are listed as "optional" but there isn't a good indicator of how to // determine if they were added. // To handle the "optional" M values, check the contentLength for the feature. // The content length does not include the 8-byte record header and is listed in 16-bit words. if (shape.ContentLength * 2 > 60 + 4 * shape.NumParts + 24 * shape.NumPoints) { goto case ShapeType.MultiPointM; } break; } } if (isM) M = mArray; if (isZ) Z = zArray; ShapeIndices = shapeIndices; Vertex = vert; } } /// <summary> /// Gets the feature at the specified index offset /// </summary> /// <param name="index">the integer index</param> /// <returns>An IFeature created from the shape at the specified offset</returns> public override IFeature GetFeature(int index) { IFeature f; if (!IndexMode) { f = Features[index]; } else { f = GetMultiPoint(index); if (f != null) { f.DataRow = AttributesPopulated ? DataTable.Rows[index] : Attributes.SupplyPageOfData(index, 1).Rows[0]; } } return f; } /// <summary> /// Opens a shapefile /// </summary> /// <param name="fileName">The string fileName of the point shapefile to load</param> /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param> public void Open(string fileName, IProgressHandler progressHandler) { IndexMode = true; Filename = fileName; FeatureType = FeatureType.MultiPoint; Header = new ShapefileHeader(Filename); switch (Header.ShapeType) { case ShapeType.MultiPointM: CoordinateType = CoordinateType.M; break; case ShapeType.MultiPointZ: CoordinateType = CoordinateType.Z; break; default: CoordinateType = CoordinateType.Regular; break; } Extent = Header.ToExtent(); Name = Path.GetFileNameWithoutExtension(fileName); Attributes.Open(Filename); FillPoints(Filename, progressHandler); ReadProjection(); } /// <summary> /// Saves the file to a new location /// </summary> /// <param name="fileName">The fileName to save</param> /// <param name="overwrite">Boolean that specifies whether or not to overwrite the existing file</param> public override void SaveAs(string fileName, bool overwrite) { EnsureValidFileToSave(fileName, overwrite); Filename = fileName; // Set ShapeType before setting extent. if (CoordinateType == CoordinateType.Regular) { Header.ShapeType = ShapeType.MultiPoint; } if (CoordinateType == CoordinateType.M) { Header.ShapeType = ShapeType.MultiPointM; } if (CoordinateType == CoordinateType.Z) { Header.ShapeType = ShapeType.MultiPointZ; } HeaderSaveAs(Filename); if (IndexMode) { SaveAsIndexed(Filename); return; } var bbWriter = new BufferedBinaryWriter(Filename); var indexWriter = new BufferedBinaryWriter(Header.ShxFilename); int fid = 0; int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words int contentLength = 0; ProgressMeter = new ProgressMeter(ProgressHandler, "Saving (Not Indexed)...", Features.Count); foreach (IFeature f in Features) { offset += contentLength; // adding the previous content length from each loop calculates the word offset List<Coordinate> points = new List<Coordinate>(); contentLength = 20; for (int iPart = 0; iPart < f.Geometry.NumGeometries; iPart++) { IList<Coordinate> coords = f.Geometry.GetGeometryN(iPart).Coordinates; foreach (Coordinate coord in coords) { points.Add(coord); } } if (Header.ShapeType == ShapeType.MultiPoint) { contentLength += points.Count * 8; } if (Header.ShapeType == ShapeType.MultiPointM) { contentLength += 8; // mmin, mmax contentLength += points.Count * 12; } if (Header.ShapeType == ShapeType.MultiPointZ) { contentLength += 16; // mmin, mmax, zmin, zmax contentLength += points.Count * 16; } // Index File // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- indexWriter.Write(offset, false); // Byte 0 Offset Integer 1 Big indexWriter.Write(contentLength, false); // Byte 4 Length Integer 1 Big // X Y Poly Lines // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- bbWriter.Write(fid + 1, false); // Byte 0 Record Integer 1 Big bbWriter.Write(contentLength, false); // Byte 4 Length Integer 1 Big bbWriter.Write((int)Header.ShapeType); // Byte 8 Shape Integer 1 Little if (Header.ShapeType == ShapeType.NullShape) { continue; } bbWriter.Write(f.Geometry.EnvelopeInternal.MinX); // Byte 12 Xmin Double 1 Little bbWriter.Write(f.Geometry.EnvelopeInternal.MinY); // Byte 20 Ymin Double 1 Little bbWriter.Write(f.Geometry.EnvelopeInternal.MaxX); // Byte 28 Xmax Double 1 Little bbWriter.Write(f.Geometry.EnvelopeInternal.MaxY); // Byte 36 Ymax Double 1 Little bbWriter.Write(points.Count); // Byte 44 #Points Integer 1 Little // Byte X Points Point #Points Little foreach (Coordinate coord in points) { bbWriter.Write(coord.X); bbWriter.Write(coord.Y); } if (Header.ShapeType == ShapeType.MultiPointZ) { bbWriter.Write(f.Geometry.EnvelopeInternal.Minimum.Z); bbWriter.Write(f.Geometry.EnvelopeInternal.Maximum.Z); foreach (Coordinate coord in points) { bbWriter.Write(coord.Z); } } if (Header.ShapeType == ShapeType.MultiPointM || Header.ShapeType == ShapeType.MultiPointZ) { if (f.Geometry.EnvelopeInternal == null) { bbWriter.Write(0.0); bbWriter.Write(0.0); } else { bbWriter.Write(f.Geometry.EnvelopeInternal.Minimum.M); bbWriter.Write(f.Geometry.EnvelopeInternal.Maximum.M); } foreach (Coordinate coord in points) { bbWriter.Write(coord.M); } } ProgressMeter.CurrentValue = fid; fid++; offset += 4; } ProgressMeter.Reset(); bbWriter.Close(); indexWriter.Close(); offset += contentLength; WriteFileLength(Filename, offset); UpdateAttributes(); SaveProjection(); } private void SaveAsIndexed(string fileName) { var shpStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None, 10000000); var shxStream = new FileStream(Header.ShxFilename, FileMode.Append, FileAccess.Write, FileShare.None, 10000000); int fid = 0; int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words int contentLength = 0; foreach (ShapeRange shape in ShapeIndices) { offset += contentLength; // adding the previous content length from each loop calculates the word offset contentLength = 20; if (Header.ShapeType == ShapeType.MultiPoint) { contentLength += shape.NumPoints * 8; } if (Header.ShapeType == ShapeType.MultiPointM) { contentLength += 8; // mmin, mmax contentLength += shape.NumPoints * 12; } if (Header.ShapeType == ShapeType.MultiPointZ) { contentLength += 16; // mmin, mmax, zmin, zmax contentLength += shape.NumPoints * 16; } // Index File // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- shxStream.WriteBe(offset); // Byte 0 Offset Integer 1 Big shxStream.WriteBe(contentLength); // Byte 4 Length Integer 1 Big // X Y Poly Lines // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- shpStream.WriteBe(fid + 1); // Byte 0 Record Integer 1 Big shpStream.WriteBe(contentLength); // Byte 4 Length Integer 1 Big shpStream.WriteLe((int)Header.ShapeType); // Byte 8 Type 3 Integer 1 Little if (Header.ShapeType == ShapeType.NullShape) { continue; } shpStream.WriteLe(shape.Extent.MinX); // Byte 12 Xmin Double 1 Little shpStream.WriteLe(shape.Extent.MinY); // Byte 20 Ymin Double 1 Little shpStream.WriteLe(shape.Extent.MaxX); // Byte 28 Xmax Double 1 Little shpStream.WriteLe(shape.Extent.MaxY); // Byte 36 Ymax Double 1 Little shpStream.WriteLe(shape.NumPoints); // Byte 44 #Points Integer 1 Little int start = shape.StartIndex; int count = shape.NumPoints; shpStream.WriteLe(Vertex, start * 2, count * 2); if (Header.ShapeType == ShapeType.MultiPointZ) { double[] shapeZ = new double[count]; Array.Copy(Z, start, shapeZ, 0, count); shpStream.WriteLe(shapeZ.Min()); shpStream.WriteLe(shapeZ.Max()); shpStream.WriteLe(Z, start, count); } if (Header.ShapeType == ShapeType.MultiPointM || Header.ShapeType == ShapeType.MultiPointZ) { if (M != null && M.Length >= start + count) { double[] shapeM = new double[count]; Array.Copy(M, start, shapeM, 0, count); shpStream.WriteLe(shapeM.Min()); shpStream.WriteLe(shapeM.Max()); shpStream.WriteLe(M, start, count); } } fid++; offset += 4; } shpStream.Close(); shxStream.Close(); offset += contentLength; WriteFileLength(fileName, offset); UpdateAttributes(); SaveProjection(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FluentAssertions.Common; using FluentAssertions.Execution; namespace FluentAssertions.Equivalency { /// <remarks> /// I think (but did not try) this would have been easier using 'dynamic' but that is /// precluded by some of the PCL targets. /// </remarks> public class GenericDictionaryEquivalencyStep : IEquivalencyStep { public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); return ((context.Subject != null) && GetIDictionaryInterfaces(subjectType).Any()); } private static Type[] GetIDictionaryInterfaces(Type type) { return Common.TypeExtensions.GetClosedGenericInterfaces( type, typeof(IDictionary<,>)); } public bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { if (PreconditionsAreMet(context, config)) { AssertDictionaryEquivalence(context, parent, config); } return true; } private static bool PreconditionsAreMet(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); return (AssertImplementsOnlyOneDictionaryInterface(context.Subject) && AssertExpectationIsNotNull(context.Subject, context.Expectation) && AssertIsCompatiblyTypedDictionary(subjectType, context.Expectation) && AssertSameLength(context.Subject, subjectType, context.Expectation)); } private static bool AssertExpectationIsNotNull(object subject, object expectation) { return AssertionScope.Current .ForCondition(!ReferenceEquals(expectation, null)) .FailWith("Expected {context:Subject} to be {0}, but found {1}.", null, subject); } private static bool AssertImplementsOnlyOneDictionaryInterface(object subject) { Type[] interfaces = GetIDictionaryInterfaces(subject.GetType()); bool multipleInterfaces = (interfaces.Count() > 1); if (multipleInterfaces) { AssertionScope.Current.FailWith( string.Format( "{{context:Subject}} implements multiple dictionary types. " + "It is not known which type should be use for equivalence.{0}" + "The following IDictionary interfaces are implemented: {1}", Environment.NewLine, String.Join(", ", (IEnumerable<Type>)interfaces))); return false; } return true; } private static bool AssertIsCompatiblyTypedDictionary(Type subjectType, object expectation) { Type subjectDictionaryType = GetIDictionaryInterface(subjectType); Type subjectKeyType = GetDictionaryKeyType(subjectDictionaryType); Type[] expectationDictionaryInterfaces = GetIDictionaryInterfaces(expectation.GetType()); if (!expectationDictionaryInterfaces.Any()) { AssertionScope.Current.FailWith( "{context:subject} is a dictionary and cannot be compared with a non-dictionary type."); return false; } Type[] suitableDictionaryInterfaces = expectationDictionaryInterfaces.Where( @interface => GetDictionaryKeyType(@interface).IsAssignableFrom(subjectKeyType)).ToArray(); if (suitableDictionaryInterfaces.Count() > 1) { // Code could be written to handle this better, but is it really worth the effort? AssertionScope.Current.FailWith( "The expected object implements multiple IDictionary interfaces. " + "If you need to use ShouldBeEquivalentTo in this case please file " + "a bug with the FluentAssertions devlopment team"); return false; } if (!suitableDictionaryInterfaces.Any()) { AssertionScope.Current.FailWith( string.Format( "The {{context:subject}} dictionary has keys of type {0}; " + "however, the expected dictionary is not keyed with any compatible types.{1}" + "The expected dictionary implements: {2}", subjectKeyType, Environment.NewLine, string.Join(",", (IEnumerable<Type>)expectationDictionaryInterfaces))); return false; } return true; } private static Type GetDictionaryKeyType(Type subjectType) { return subjectType.GetGenericArguments()[0]; } private static bool AssertSameLength(object subject, Type subjectType, object expectation) { string methodName = ExpressionExtensions.GetMethodName(() => AssertSameLength<object, object, object, object>(null, null)); MethodCallExpression assertSameLength = Expression.Call( typeof(GenericDictionaryEquivalencyStep), methodName, GetDictionaryTypeArguments(subjectType) .Concat(GetDictionaryTypeArguments(expectation.GetType())) .ToArray(), Expression.Constant(subject, GetIDictionaryInterface(subjectType)), Expression.Constant(expectation, GetIDictionaryInterface(expectation.GetType()))); return (bool)Expression.Lambda(assertSameLength).Compile().DynamicInvoke(); } private static IEnumerable<Type> GetDictionaryTypeArguments(Type subjectType) { var dictionaryType = GetIDictionaryInterface(subjectType); return dictionaryType.GetGenericArguments(); } private static Type GetIDictionaryInterface(Type subjectType) { return GetIDictionaryInterfaces(subjectType).Single(); } private static bool AssertSameLength<TSubjectKey, TSubjectValue, TExpectKey, TExpectedValue>( IDictionary<TSubjectKey, TSubjectValue> subject, IDictionary<TExpectKey, TExpectedValue> expectation) { return AssertionScope.Current.ForCondition(subject.Count == expectation.Count) .FailWith( "Expected {context:subject} to be a dictionary with {0} item(s), but found {1} item(s).", expectation.Count, subject.Count); } private static void AssertDictionaryEquivalence( IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); string methodName = ExpressionExtensions.GetMethodName( () => AssertDictionaryEquivalence<object, object, object, object>(null, null, null, null, null)); var assertDictionaryEquivalence = Expression.Call( typeof(GenericDictionaryEquivalencyStep), methodName, GetDictionaryTypeArguments(subjectType) .Concat(GetDictionaryTypeArguments(context.Expectation.GetType())) .ToArray(), Expression.Constant(context), Expression.Constant(parent), Expression.Constant(config), Expression.Constant(context.Subject, GetIDictionaryInterface(subjectType)), Expression.Constant(context.Expectation, GetIDictionaryInterface(context.Expectation.GetType()))); Expression.Lambda(assertDictionaryEquivalence).Compile().DynamicInvoke(); } private static void AssertDictionaryEquivalence<TSubjectKey, TSubjectValue, TExpectKey, TExpectedValue>( EquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config, IDictionary<TSubjectKey, TSubjectValue> subject, IDictionary<TExpectKey, TExpectedValue> expectation) where TSubjectKey : TExpectKey { foreach (TSubjectKey key in subject.Keys) { TExpectedValue expectedValue; if (expectation.TryGetValue(key, out expectedValue)) { if (config.IsRecursive) { parent.AssertEqualityUsing(context.CreateForDictionaryItem(key, subject[key], expectation[key])); } else { subject[key].Should().Be(expectation[key], context.Because, context.BecauseArgs); } } else { AssertionScope.Current.FailWith("{context:subject} contains unexpected key {0}", key); } } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. 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. #endregion using System; using System.Collections.Generic; using System.IO; using ProtoBuf; namespace Abc.Zebus.Serialization.Protobuf { /// <summary> /// Reads and decodes protocol message fields. /// </summary> /// <remarks> /// <para> /// This class is generally used by generated code to read appropriate /// primitives from the stream. It effectively encapsulates the lowest /// levels of protocol buffer format. /// </para> /// </remarks> internal sealed class CodedInputStream { /// <summary> /// Buffer of data read from the stream or provided at construction time. /// </summary> private readonly byte[] buffer; /// <summary> /// The index of the buffer at which we need to refill from the stream (if there is one). /// </summary> private readonly int bufferSize; /// <summary> /// The position within the current buffer (i.e. the next byte to read) /// </summary> private int bufferPos = 0; private readonly byte[] guidBuffer = new byte[16]; #region Construction /// <summary> /// Creates a new CodedInputStream reading data from the given /// stream and buffer, using the default limits. /// </summary> public CodedInputStream(byte[] buffer, int offset, int length) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset", "Offset must be within the buffer"); } if (length < 0 || offset + length > buffer.Length) { throw new ArgumentOutOfRangeException("length", "Length must be non-negative and within the buffer"); } this.buffer = buffer; this.bufferPos = offset; this.bufferSize = length; } #endregion /// <summary> /// Returns the current position in the input stream, or the position in the input buffer /// </summary> public long Position { get { return bufferPos; } } #region Reading of tags etc public bool TryReadTag(out uint number, out WireType wireType) { var tag = ReadTag(); if (tag == 0) { number = 0; wireType = WireType.None; return false; } number = tag >> 3; wireType = (WireType)(tag & 7); return true; } /// <summary> /// Reads a field tag, returning the tag of 0 for "end of stream". /// </summary> /// <remarks> /// If this method returns 0, it doesn't necessarily mean the end of all /// the data in this CodedInputStream; it may be the end of the logical stream /// for an embedded message, for example. /// </remarks> /// <returns>The next field tag, or 0 for end of stream. (0 is never a valid tag.)</returns> public uint ReadTag() { // Optimize for the incredibly common case of having at least one byte left in the buffer, // and this byte being enough to get the tag. This will be true for fields up to 31. if (bufferPos + 1 <= bufferSize) { uint tag = buffer[bufferPos]; if (tag < 128) { bufferPos++; if (tag == 0) { // If we actually read zero, that's not a valid tag. throw InvalidProtocolBufferException.InvalidTag(); } return tag; } } return ReadTagSlow(); } private uint ReadTagSlow() { if (IsAtEnd) { return 0; } uint tag = ReadRawVarint32(); if (tag == 0) { // If we actually read zero, that's not a valid tag. throw InvalidProtocolBufferException.InvalidTag(); } return tag; } /// <summary> /// Reads a double field from the stream. /// </summary> public double ReadDouble() { return BitConverter.Int64BitsToDouble((long) ReadRawLittleEndian64()); } /// <summary> /// Reads a float field from the stream. /// </summary> public float ReadFloat() { if (BitConverter.IsLittleEndian && 4 <= bufferSize - bufferPos) { float ret = BitConverter.ToSingle(buffer, bufferPos); bufferPos += 4; return ret; } else { byte[] rawBytes = ReadRawBytes(4); if (!BitConverter.IsLittleEndian) { ByteArray.Reverse(rawBytes); } return BitConverter.ToSingle(rawBytes, 0); } } /// <summary> /// Reads a uint64 field from the stream. /// </summary> public ulong ReadUInt64() { return ReadRawVarint64(); } /// <summary> /// Reads an int64 field from the stream. /// </summary> public long ReadInt64() { return (long) ReadRawVarint64(); } /// <summary> /// Reads an int32 field from the stream. /// </summary> public int ReadInt32() { return (int) ReadRawVarint32(); } /// <summary> /// Reads a fixed64 field from the stream. /// </summary> public ulong ReadFixed64() { return ReadRawLittleEndian64(); } /// <summary> /// Reads a fixed32 field from the stream. /// </summary> public uint ReadFixed32() { return ReadRawLittleEndian32(); } /// <summary> /// Reads a bool field from the stream. /// </summary> public bool ReadBool() { return ReadRawVarint32() != 0; } /// <summary> /// Reads a string field from the stream. /// </summary> public string ReadString() { int length = ReadLength(); // No need to read any data for an empty string. if (length == 0) { return ""; } if (length > bufferSize - bufferPos) { throw InvalidProtocolBufferException.TruncatedMessage(); } // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. var result = CodedOutputStream.Utf8Encoding.GetString(buffer, bufferPos, length); bufferPos += length; return result; } public void SkipString() { int length = ReadLength(); bufferPos += length; } /// <summary> /// Reads a uint32 field value from the stream. /// </summary> public uint ReadUInt32() { return ReadRawVarint32(); } /// <summary> /// Reads an enum field value from the stream. If the enum is valid for type T, /// then the ref value is set and it returns true. Otherwise the unknown output /// value is set and this method returns false. /// </summary> public int ReadEnum() { // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. return (int) ReadRawVarint32(); } /// <summary> /// Reads an sfixed32 field value from the stream. /// </summary> public int ReadSFixed32() { return (int) ReadRawLittleEndian32(); } /// <summary> /// Reads an sfixed64 field value from the stream. /// </summary> public long ReadSFixed64() { return (long) ReadRawLittleEndian64(); } /// <summary> /// Reads an sint32 field value from the stream. /// </summary> public int ReadSInt32() { return DecodeZigZag32(ReadRawVarint32()); } /// <summary> /// Reads an sint64 field value from the stream. /// </summary> public long ReadSInt64() { return DecodeZigZag64(ReadRawVarint64()); } public Guid ReadGuid() { ReadLength(); if (bufferSize - bufferPos >= CodedOutputStream.GuidSize) { ReadTag(); ByteArray.Copy(buffer, bufferPos, guidBuffer, 0, 8); bufferPos += 8; ReadTag(); ByteArray.Copy(buffer, bufferPos, guidBuffer, 8, 8); bufferPos += 8; return new Guid(guidBuffer); } throw InvalidProtocolBufferException.SizeLimitExceeded(); } /// <summary> /// Reads a length for length-delimited data. /// </summary> /// <remarks> /// This is internally just reading a varint, but this method exists /// to make the calling code clearer. /// </remarks> public int ReadLength() { return (int) ReadRawVarint32(); } #endregion #region Underlying reading primitives /// <summary> /// Same code as ReadRawVarint32, but read each byte individually, checking for /// buffer overflow. /// </summary> private uint SlowReadRawVarint32() { int tmp = ReadRawByte(); if (tmp < 128) { return (uint) tmp; } int result = tmp & 0x7f; if ((tmp = ReadRawByte()) < 128) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = ReadRawByte()) < 128) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = ReadRawByte()) < 128) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = ReadRawByte()) << 28; if (tmp >= 128) { // Discard upper 32 bits. for (int i = 0; i < 5; i++) { if (ReadRawByte() < 128) { return (uint) result; } } throw InvalidProtocolBufferException.MalformedVarint(); } } } } return (uint) result; } /// <summary> /// Reads a raw Varint from the stream. If larger than 32 bits, discard the upper bits. /// This method is optimised for the case where we've got lots of data in the buffer. /// That means we can check the size just once, then just read directly from the buffer /// without constant rechecking of the buffer length. /// </summary> internal uint ReadRawVarint32() { if (bufferPos + 5 > bufferSize) { return SlowReadRawVarint32(); } int tmp = buffer[bufferPos++]; if (tmp < 128) { return (uint) tmp; } int result = tmp & 0x7f; if ((tmp = buffer[bufferPos++]) < 128) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = buffer[bufferPos++]) < 128) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = buffer[bufferPos++]) < 128) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = buffer[bufferPos++]) << 28; if (tmp >= 128) { // Discard upper 32 bits. // Note that this has to use ReadRawByte() as we only ensure we've // got at least 5 bytes at the start of the method. This lets us // use the fast path in more cases, and we rarely hit this section of code. for (int i = 0; i < 5; i++) { if (ReadRawByte() < 128) { return (uint) result; } } throw InvalidProtocolBufferException.MalformedVarint(); } } } } return (uint) result; } /// <summary> /// Reads a varint from the input one byte at a time, so that it does not /// read any bytes after the end of the varint. If you simply wrapped the /// stream in a CodedInputStream and used ReadRawVarint32(Stream) /// then you would probably end up reading past the end of the varint since /// CodedInputStream buffers its input. /// </summary> /// <param name="input"></param> /// <returns></returns> internal static uint ReadRawVarint32(Stream input) { int result = 0; int offset = 0; for (; offset < 32; offset += 7) { int b = input.ReadByte(); if (b == -1) { throw InvalidProtocolBufferException.TruncatedMessage(); } result |= (b & 0x7f) << offset; if ((b & 0x80) == 0) { return (uint) result; } } // Keep reading up to 64 bits. for (; offset < 64; offset += 7) { int b = input.ReadByte(); if (b == -1) { throw InvalidProtocolBufferException.TruncatedMessage(); } if ((b & 0x80) == 0) { return (uint) result; } } throw InvalidProtocolBufferException.MalformedVarint(); } /// <summary> /// Reads a raw varint from the stream. /// </summary> internal ulong ReadRawVarint64() { int shift = 0; ulong result = 0; while (shift < 64) { byte b = ReadRawByte(); result |= (ulong) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } shift += 7; } throw InvalidProtocolBufferException.MalformedVarint(); } /// <summary> /// Reads a 32-bit little-endian integer from the stream. /// </summary> internal uint ReadRawLittleEndian32() { uint b1 = ReadRawByte(); uint b2 = ReadRawByte(); uint b3 = ReadRawByte(); uint b4 = ReadRawByte(); return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); } /// <summary> /// Reads a 64-bit little-endian integer from the stream. /// </summary> internal ulong ReadRawLittleEndian64() { ulong b1 = ReadRawByte(); ulong b2 = ReadRawByte(); ulong b3 = ReadRawByte(); ulong b4 = ReadRawByte(); ulong b5 = ReadRawByte(); ulong b6 = ReadRawByte(); ulong b7 = ReadRawByte(); ulong b8 = ReadRawByte(); return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56); } /// <summary> /// Decode a 32-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> internal static int DecodeZigZag32(uint n) { return (int)(n >> 1) ^ -(int)(n & 1); } /// <summary> /// Decode a 32-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> internal static long DecodeZigZag64(ulong n) { return (long)(n >> 1) ^ -(long)(n & 1); } #endregion #region Internal reading and buffer management /// <summary> /// Returns true if the stream has reached the end of the input. This is the /// case if either the end of the underlying input source has been reached or /// the stream has reached a limit created using PushLimit. /// </summary> public bool IsAtEnd { get { return bufferPos == bufferSize; } } /// <summary> /// Read one byte from the input. /// </summary> /// <exception cref="InvalidProtocolBufferException"> /// the end of the stream or the current limit was reached /// </exception> internal byte ReadRawByte() { if (bufferPos == bufferSize) { throw InvalidProtocolBufferException.TruncatedMessage(); } return buffer[bufferPos++]; } /// <summary> /// Reads a fixed size of bytes from the input. /// </summary> /// <exception cref="InvalidProtocolBufferException"> /// the end of the stream or the current limit was reached /// </exception> internal byte[] ReadRawBytes(int size) { if (size < 0) { throw InvalidProtocolBufferException.NegativeSize(); } if (size > bufferSize - bufferPos) { throw InvalidProtocolBufferException.TruncatedMessage(); } // We have all the bytes we need already. byte[] bytes = new byte[size]; ByteArray.Copy(buffer, bufferPos, bytes, 0, size); bufferPos += size; return bytes; } #endregion } }
// --------------------------------------------------------------------------------------------------- // <copyright file="HelpPageSampleKey.cs" company="Elephant Insurance Services, LLC"> // Copyright (c) 2014 All Right Reserved // </copyright> // <author>Gurpreet Singh</author> // <date>2015-04-10</date> // <summary> // The HelpPageSampleKey class // </summary> // --------------------------------------------------------------------------------------------------- namespace Elephant.Hank.Api.Areas.HelpPage.SampleGeneration { using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleKey" /> class. /// Creates a new <see cref="HelpPageSampleKey" /> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> /// <exception cref="System.ArgumentNullException"> /// mediaType /// or /// type /// </exception> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (type == null) { throw new ArgumentNullException("type"); } this.ControllerName = string.Empty; this.ActionName = string.Empty; this.ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); this.ParameterType = type; this.MediaType = mediaType; } /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleKey" /> class. /// Creates a new <see cref="HelpPageSampleKey" /> based on <see cref="SampleDirection" />, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection" />.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } this.ControllerName = controllerName; this.ActionName = actionName; this.ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); this.SampleDirection = sampleDirection; } /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleKey" /> class. /// Creates a new <see cref="HelpPageSampleKey" /> based on media type, <see cref="SampleDirection" />, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection" />.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } this.ControllerName = controllerName; this.ActionName = actionName; this.MediaType = mediaType; this.ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); this.SampleDirection = sampleDirection; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } /// <summary> /// Gets the parameter type. /// </summary> public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } /// <summary> /// The equals. /// </summary> /// <param name="obj">The obj.</param> /// <returns> /// The <see cref="bool" />. /// </returns> public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return string.Equals(this.ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && string.Equals(this.ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (this.MediaType == otherKey.MediaType || (this.MediaType != null && this.MediaType.Equals(otherKey.MediaType))) && this.ParameterType == otherKey.ParameterType && this.SampleDirection == otherKey.SampleDirection && this.ParameterNames.SetEquals(otherKey.ParameterNames); } /// <summary> /// The get hash code. /// </summary> /// <returns> /// The <see cref="int" />. /// </returns> public override int GetHashCode() { int hashCode = this.ControllerName.ToUpperInvariant().GetHashCode() ^ this.ActionName.ToUpperInvariant().GetHashCode(); if (this.MediaType != null) { hashCode ^= this.MediaType.GetHashCode(); } if (this.SampleDirection != null) { hashCode ^= this.SampleDirection.GetHashCode(); } if (this.ParameterType != null) { hashCode ^= this.ParameterType.GetHashCode(); } foreach (string parameterName in this.ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Autodesk.Revit; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.ViewPrinter.CS { public partial class PrintSetupForm : System.Windows.Forms.Form { private PrintSTP m_printSetup; private bool m_stopUpdateFlag; public PrintSetupForm(PrintSTP printSetup) { m_printSetup = printSetup; InitializeComponent(); } private void PrintSetupForm_Load(object sender, EventArgs e) { printerNameLabel.Text = m_printSetup.PrinterName; printSetupsComboBox.DataSource = m_printSetup.PrintSettingNames; printSetupsComboBox.SelectedItem = m_printSetup.SettingName; this.printSetupsComboBox.SelectedValueChanged += new System.EventHandler(this.printSetupsComboBox_SelectedValueChanged); renameButton.Enabled = deleteButton.Enabled = m_printSetup.SettingName.Equals("<In-Session>") ? false : true; paperSizeComboBox.DataSource = m_printSetup.PaperSizes; paperSizeComboBox.SelectedItem = m_printSetup.PaperSize; this.paperSizeComboBox.SelectedValueChanged += new System.EventHandler(this.sizeComboBox_SelectedValueChanged); paperSourceComboBox.DataSource = m_printSetup.PaperSources; paperSourceComboBox.SelectedItem = m_printSetup.PaperSource; this.paperSourceComboBox.SelectedValueChanged += new System.EventHandler(this.sourceComboBox_SelectedValueChanged); if (m_printSetup.PageOrientation == PageOrientationType.Landscape) { landscapeRadioButton.Checked = true; } else { portraitRadioButton.Checked = true; } this.landscapeRadioButton.CheckedChanged += new System.EventHandler(this.landscapeRadioButton_CheckedChanged); this.portraitRadioButton.CheckedChanged += new System.EventHandler(this.portraitRadioButton_CheckedChanged); marginTypeComboBox.DataSource = m_printSetup.MarginTypes; this.offsetRadioButton.CheckedChanged += new System.EventHandler(this.offsetRadioButton_CheckedChanged); this.centerRadioButton.CheckedChanged += new System.EventHandler(this.centerRadioButton_CheckedChanged); this.userDefinedMarginYTextBox.TextChanged += new System.EventHandler(this.userDefinedMarginYTextBox_TextChanged); this.userDefinedMarginXTextBox.TextChanged += new System.EventHandler(this.userDefinedMarginXTextBox_TextChanged); marginTypeComboBox.SelectedItem = m_printSetup.SelectedMarginType; this.marginTypeComboBox.SelectedValueChanged += new System.EventHandler(this.marginTypeComboBox_SelectedValueChanged); if (m_printSetup.PaperPlacement == PaperPlacementType.Center) { centerRadioButton.Checked = true; offsetRadioButton.Checked = false; } else { offsetRadioButton.Checked = true; centerRadioButton.Checked = false; } if (m_printSetup.HiddenLineViews == HiddenLineViewsType.RasterProcessing) { rasterRadioButton.Checked = true; } else { vectorRadioButton.Checked = true; } this.rasterRadioButton.CheckedChanged += new System.EventHandler(this.rasterRadioButton_CheckedChanged); this.vectorRadioButton.CheckedChanged += new System.EventHandler(this.vectorRadioButton_CheckedChanged); if (m_printSetup.ZoomType == ZoomType.Zoom) { zoomRadioButton.Checked = true; zoomPercentNumericUpDown.Value = m_printSetup.Zoom; } else { fitToPageRadioButton.Checked = true; } this.zoomRadioButton.CheckedChanged += new System.EventHandler(this.zoomRadioButton_CheckedChanged); this.fitToPageRadioButton.CheckedChanged += new System.EventHandler(this.fitToPageRadioButton_CheckedChanged); rasterQualityComboBox.DataSource = m_printSetup.RasterQualities; rasterQualityComboBox.SelectedItem = m_printSetup.RasterQuality; this.rasterQualityComboBox.SelectedValueChanged += new System.EventHandler(this.rasterQualityComboBox_SelectedValueChanged); colorsComboBox.DataSource = m_printSetup.Colors; colorsComboBox.SelectedItem = m_printSetup.Color; this.colorsComboBox.SelectedValueChanged += new System.EventHandler(this.colorsComboBox_SelectedValueChanged); ViewLinksInBlueCheckBox.Checked = m_printSetup.ViewLinksinBlue; this.ViewLinksInBlueCheckBox.CheckedChanged += new System.EventHandler(this.ViewLinksInBlueCheckBox_CheckedChanged); hideScopeBoxedCheckBox.Checked = m_printSetup.HideScopeBoxes; this.hideScopeBoxedCheckBox.CheckedChanged += new System.EventHandler(this.hideScopeBoxedCheckBox_CheckedChanged); hideRefWorkPlanesCheckBox.Checked = m_printSetup.HideReforWorkPlanes; this.hideRefWorkPlanesCheckBox.CheckedChanged += new System.EventHandler(this.hideRefWorkPlanesCheckBox_CheckedChanged); hideCropBoundariesCheckBox.Checked = m_printSetup.HideCropBoundaries; this.hideCropBoundariesCheckBox.CheckedChanged += new System.EventHandler(this.hideCropBoundariesCheckBox_CheckedChanged); hideUnreferencedViewTagsCheckBox.Checked = m_printSetup.HideUnreferencedViewTages; this.hideUnreferencedViewTagsCheckBox.CheckedChanged += new System.EventHandler(this.hideUnreferencedViewTagsCheckBox_CheckedChanged); } private void saveButton_Click(object sender, EventArgs e) { m_printSetup.Save(); } private void printSetupsComboBox_SelectedValueChanged(object sender, EventArgs e) { if (m_stopUpdateFlag) return; m_printSetup.SettingName = printSetupsComboBox.SelectedItem as string; paperSizeComboBox.SelectedItem = m_printSetup.PaperSize; paperSourceComboBox.SelectedItem = m_printSetup.PaperSource; if (m_printSetup.PageOrientation == PageOrientationType.Landscape) { landscapeRadioButton.Checked = true; } else { portraitRadioButton.Checked = true; } if (m_printSetup.PaperPlacement == PaperPlacementType.Center) { centerRadioButton.Checked = true; } else { offsetRadioButton.Checked = true; } if (m_printSetup.VerifyMarginType(marginTypeComboBox)) { marginTypeComboBox.SelectedItem = m_printSetup.SelectedMarginType; } if (m_printSetup.HiddenLineViews == HiddenLineViewsType.RasterProcessing) { rasterRadioButton.Checked = true; } else { vectorRadioButton.Checked = true; } if (m_printSetup.ZoomType == ZoomType.Zoom) { zoomRadioButton.Checked = true; zoomPercentNumericUpDown.Value = m_printSetup.Zoom; } else { fitToPageRadioButton.Checked = true; m_printSetup.ZoomType = ZoomType.Zoom; zoomPercentNumericUpDown.Value = m_printSetup.Zoom; m_printSetup.ZoomType = ZoomType.FitToPage; } rasterQualityComboBox.SelectedItem = m_printSetup.RasterQuality; colorsComboBox.SelectedItem = m_printSetup.Color; ViewLinksInBlueCheckBox.Checked = m_printSetup.ViewLinksinBlue; hideScopeBoxedCheckBox.Checked = m_printSetup.HideScopeBoxes; hideRefWorkPlanesCheckBox.Checked = m_printSetup.HideReforWorkPlanes; hideCropBoundariesCheckBox.Checked = m_printSetup.HideCropBoundaries; hideUnreferencedViewTagsCheckBox.Checked = m_printSetup.HideUnreferencedViewTages; renameButton.Enabled = deleteButton.Enabled = m_printSetup.SettingName.Equals("<In-Session>") ? false : true; revertButton.Enabled = false; } private void sizeComboBox_SelectedValueChanged(object sender, EventArgs e) { m_printSetup.PaperSize = paperSizeComboBox.SelectedItem as string; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void sourceComboBox_SelectedValueChanged(object sender, EventArgs e) { m_printSetup.PaperSource = paperSourceComboBox.SelectedItem as string; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void portraitRadioButton_CheckedChanged(object sender, EventArgs e) { if (portraitRadioButton.Checked) { m_printSetup.PageOrientation = PageOrientationType.Portrait; } if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void landscapeRadioButton_CheckedChanged(object sender, EventArgs e) { if (landscapeRadioButton.Checked) { m_printSetup.PageOrientation = PageOrientationType.Landscape; } if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void centerRadioButton_CheckedChanged(object sender, EventArgs e) { if (!centerRadioButton.Checked) return; m_printSetup.PaperPlacement = PaperPlacementType.Center; m_printSetup.VerifyMarginType(marginTypeComboBox); System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot = new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>(); controlsToEnableOrNot.Add(userDefinedMarginXTextBox); controlsToEnableOrNot.Add(userDefinedMarginYTextBox); if (m_printSetup.VerifyUserDefinedMargin(controlsToEnableOrNot)) { userDefinedMarginXTextBox.Text = m_printSetup.UserDefinedMarginX.ToString(); userDefinedMarginYTextBox.Text = m_printSetup.UserDefinedMarginY.ToString(); if (!revertButton.Enabled) { revertButton.Enabled = true; } } } private void offsetRadioButton_CheckedChanged(object sender, EventArgs e) { if (!offsetRadioButton.Checked) return; m_printSetup.PaperPlacement = PaperPlacementType.Margins; m_printSetup.VerifyMarginType(marginTypeComboBox); System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot = new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>(); controlsToEnableOrNot.Add(userDefinedMarginXTextBox); controlsToEnableOrNot.Add(userDefinedMarginYTextBox); if (m_printSetup.VerifyUserDefinedMargin(controlsToEnableOrNot)) { userDefinedMarginXTextBox.Text = m_printSetup.UserDefinedMarginX.ToString(); userDefinedMarginYTextBox.Text = m_printSetup.UserDefinedMarginY.ToString(); if (!revertButton.Enabled) { revertButton.Enabled = true; } } } private void marginTypeComboBox_SelectedValueChanged(object sender, EventArgs e) { m_printSetup.SelectedMarginType = (MarginType)marginTypeComboBox.SelectedItem; System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot = new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>(); controlsToEnableOrNot.Add(userDefinedMarginXTextBox); controlsToEnableOrNot.Add(userDefinedMarginYTextBox); if (m_printSetup.VerifyUserDefinedMargin(controlsToEnableOrNot)) { userDefinedMarginXTextBox.Text = m_printSetup.UserDefinedMarginX.ToString(); userDefinedMarginYTextBox.Text = m_printSetup.UserDefinedMarginY.ToString(); } if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void vectorRadioButton_CheckedChanged(object sender, EventArgs e) { if (vectorRadioButton.Checked) { m_printSetup.HiddenLineViews = HiddenLineViewsType.VectorProcessing; if (!revertButton.Enabled) { revertButton.Enabled = true; } } } private void rasterRadioButton_CheckedChanged(object sender, EventArgs e) { if (rasterRadioButton.Checked) { m_printSetup.HiddenLineViews = HiddenLineViewsType.RasterProcessing; if (!revertButton.Enabled) { revertButton.Enabled = true; } } } private void fitToPageRadioButton_CheckedChanged(object sender, EventArgs e) { if (fitToPageRadioButton.Checked) { m_printSetup.ZoomType = ZoomType.FitToPage; centerRadioButton.Checked = true; if (!revertButton.Enabled) { revertButton.Enabled = true; } } } private void zoomRadioButton_CheckedChanged(object sender, EventArgs e) { if (zoomRadioButton.Checked) { m_printSetup.ZoomType = ZoomType.Zoom; offsetRadioButton.Checked = true; m_printSetup.Zoom = (int)zoomPercentNumericUpDown.Value; if (!revertButton.Enabled) { revertButton.Enabled = true; } } } private void zoomPercentNumericUpDown_ValueChanged(object sender, EventArgs e) { if (zoomRadioButton.Checked) { m_printSetup.Zoom = (int)zoomPercentNumericUpDown.Value; if (!revertButton.Enabled) { revertButton.Enabled = true; } } } private void rasterQualityComboBox_SelectedValueChanged(object sender, EventArgs e) { m_printSetup.RasterQuality = (RasterQualityType)rasterQualityComboBox.SelectedItem; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void colorsComboBox_SelectedValueChanged(object sender, EventArgs e) { m_printSetup.Color = (ColorDepthType)colorsComboBox.SelectedItem; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void ViewLinksInBlueCheckBox_CheckedChanged(object sender, EventArgs e) { m_printSetup.ViewLinksinBlue = ViewLinksInBlueCheckBox.Checked; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void hideScopeBoxedCheckBox_CheckedChanged(object sender, EventArgs e) { m_printSetup.HideScopeBoxes = hideScopeBoxedCheckBox.Checked; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void hideRefWorkPlanesCheckBox_CheckedChanged(object sender, EventArgs e) { m_printSetup.HideReforWorkPlanes = hideRefWorkPlanesCheckBox.Checked; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void hideCropBoundariesCheckBox_CheckedChanged(object sender, EventArgs e) { m_printSetup.HideCropBoundaries = hideCropBoundariesCheckBox.Checked; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void hideUnreferencedViewTagsCheckBox_CheckedChanged(object sender, EventArgs e) { m_printSetup.HideUnreferencedViewTages = hideUnreferencedViewTagsCheckBox.Checked; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void userDefinedMarginXTextBox_TextChanged(object sender, EventArgs e) { double doubleValue; if (!double.TryParse(userDefinedMarginXTextBox.Text, out doubleValue)) { PrintMgr.MyMessageBox("Invalid input"); return; } m_printSetup.UserDefinedMarginX = doubleValue; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void userDefinedMarginYTextBox_TextChanged(object sender, EventArgs e) { double doubleValue; if (!double.TryParse(userDefinedMarginYTextBox.Text, out doubleValue)) { PrintMgr.MyMessageBox("Invalid input"); return; } m_printSetup.UserDefinedMarginY = doubleValue; if (!revertButton.Enabled) { revertButton.Enabled = true; } } private void saveAsButton_Click(object sender, EventArgs e) { using (SaveAsForm dlg = new SaveAsForm(m_printSetup)) { dlg.ShowDialog(); } m_stopUpdateFlag = true; printSetupsComboBox.DataSource = m_printSetup.PrintSettingNames; printSetupsComboBox.Update(); m_stopUpdateFlag = false; printSetupsComboBox.SelectedItem = m_printSetup.SettingName; } private void renameButton_Click(object sender, EventArgs e) { using (ReNameForm dlg = new ReNameForm(m_printSetup)) { dlg.ShowDialog(); } m_stopUpdateFlag = true; printSetupsComboBox.DataSource = m_printSetup.PrintSettingNames; printSetupsComboBox.Update(); m_stopUpdateFlag = false; printSetupsComboBox.SelectedItem = m_printSetup.SettingName; } private void revertButton_Click(object sender, EventArgs e) { m_printSetup.Revert(); printSetupsComboBox_SelectedValueChanged(null, null); } private void deleteButton_Click(object sender, EventArgs e) { m_printSetup.Delete(); m_stopUpdateFlag = true; printSetupsComboBox.DataSource = m_printSetup.PrintSettingNames; printSetupsComboBox.Update(); m_stopUpdateFlag = false; printSetupsComboBox.SelectedItem = m_printSetup.SettingName; } } }
// // WorkerRequest.cs: Extends MonoWorkerRequest by getting information from and // writing information to a Responder object. // // Author: // Brian Nickel ([email protected]) // // Copyright (C) 2007 Brian Nickel // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Globalization; using System.IO; namespace Mono.WebServer.FastCgi { public class WorkerRequest : MonoWorkerRequest { static string [] indexFiles = { "index.aspx", "default.aspx", "index.html", "index.htm" }; static WorkerRequest () { SetDefaultIndexFiles (System.Configuration.ConfigurationManager.AppSettings ["MonoServerDefaultIndexFiles"]); } StringBuilder headers = new StringBuilder (); readonly Responder responder; readonly byte [] input_data; string file_path; string raw_url; bool closed; string uri_path; string [][] unknownHeaders; string [] knownHeaders; readonly string path_info; public WorkerRequest (Responder responder, ApplicationHost appHost) : base (appHost) { this.responder = responder; input_data = responder.InputData; try { Paths.GetPathsFromUri (appHost, GetHttpVerbName (), GetFilePath (), out file_path, out path_info); } catch { path_info = null; file_path = null; } } #region Overrides #region Overrides: Transaction Oriented public override int RequestId { get {return responder.RequestID;} } protected override bool GetRequestData () { return true; } public override bool HeadersSent () { return headers == null; } public override void FlushResponse (bool finalFlush) { if (finalFlush) CloseConnection (); } public override void CloseConnection () { if (closed) return; closed = true; EnsureHeadersSent (); responder.CompleteRequest (0); } public override void SendResponseFromMemory (byte [] data, int length) { EnsureHeadersSent (); responder.SendOutput (data, length); } public override void SendStatus (int statusCode, string statusDescription) { AppendHeaderLine ("Status: {0} {1}", statusCode, statusDescription); } public override void SendUnknownResponseHeader (string name, string value) { AppendHeaderLine ("{0}: {1}", name, value); } public override bool IsClientConnected () { return responder.IsConnected; } public override bool IsEntireEntityBodyIsPreloaded () { return true; } #endregion #region Overrides: Request Oriented public override string GetPathInfo () { string pi = responder.GetParameter ("PATH_INFO"); if (!String.IsNullOrEmpty (pi)) return pi; return path_info ?? String.Empty; } public override string GetRawUrl () { if (raw_url != null) return raw_url; string fcgiRequestUri = responder.GetParameter ("REQUEST_URI"); if (fcgiRequestUri != null) { raw_url = fcgiRequestUri; return raw_url; } var builder = new StringBuilder (GetUriPath ()); string query = GetQueryString (); if (!String.IsNullOrEmpty(query)) { builder.Append ('?'); builder.Append (query); } raw_url = builder.ToString (); return raw_url; } public override bool IsSecure () { return responder.GetParameter ("HTTPS") == "on"; } public override string GetHttpVerbName () { return responder.GetParameter ("REQUEST_METHOD"); } public override string GetHttpVersion () { return responder.GetParameter ("SERVER_PROTOCOL"); } public override string GetLocalAddress () { string address = responder.GetParameter ("SERVER_ADDR"); if (!String.IsNullOrEmpty(address)) return address; address = AddressFromHostName ( responder.GetParameter ("HTTP_HOST")); if (!String.IsNullOrEmpty(address)) return address; address = AddressFromHostName ( responder.GetParameter ("SERVER_NAME")); if (!String.IsNullOrEmpty(address)) return address; return base.GetLocalAddress (); } public override int GetLocalPort () { try { return responder.PortNumber; } catch { return base.GetLocalPort (); } } public override string GetQueryString () { return responder.GetParameter ("QUERY_STRING"); } public override byte [] GetQueryStringRawBytes () { string query_string = GetQueryString (); if (query_string == null) return null; return Encoding.GetBytes (query_string); } public override string GetRemoteAddress () { string addr = responder.GetParameter ("REMOTE_ADDR"); return !String.IsNullOrEmpty(addr) ? addr : base.GetRemoteAddress (); } public override string GetRemoteName () { string ip = GetRemoteAddress (); string name; try { IPHostEntry entry = Dns.GetHostEntry (ip); name = entry.HostName; } catch { name = ip; } return name; } public override int GetRemotePort () { string port = responder.GetParameter ("REMOTE_PORT"); if (String.IsNullOrEmpty(port)) return base.GetRemotePort (); int ret; if (Int32.TryParse (port, out ret)) return ret; return base.GetRemotePort (); } public override string GetServerVariable (string name) { return (responder.GetParameter (name) ?? Environment.GetEnvironmentVariable (name)) ?? base.GetServerVariable (name); } public override string GetUriPath () { if (uri_path != null) return uri_path; uri_path = GetFilePath () + GetPathInfo (); return uri_path; } public override string GetFilePath () { if (file_path != null) return file_path; file_path = responder.Path; // The following will check if the request was made to a // directory, and if so, if attempts to find the correct // index file from the list. Case is ignored to improve // Windows compatability. string path = responder.PhysicalPath; var dir = new DirectoryInfo (path); if (!dir.Exists) return file_path; if (!file_path.EndsWith ("/")) file_path += "/"; FileInfo [] files = dir.GetFiles (); foreach (string file in indexFiles) { foreach (FileInfo info in files) { if (file.Equals (info.Name, StringComparison.InvariantCultureIgnoreCase)) { file_path += info.Name; return file_path; } } } return file_path; } public override string GetUnknownRequestHeader (string name) { foreach (string [] pair in GetUnknownRequestHeaders ()) { if (pair [0] == name) return pair [1]; } return base.GetUnknownRequestHeader (name); } public override string [][] GetUnknownRequestHeaders () { if (unknownHeaders != null) return unknownHeaders; IDictionary<string,string> pairs = responder.GetParameters (); knownHeaders = new string [RequestHeaderMaximum]; var headers = new string [pairs.Count][]; int count = 0; foreach (string key in pairs.Keys) { if (!key.StartsWith ("HTTP_")) continue; string name = ReformatHttpHeader (key); string value = pairs [key]; int id = GetKnownRequestHeaderIndex (name); if (id >= 0) { knownHeaders [id] = value; continue; } headers [count++] = new[] {name, value}; } unknownHeaders = new string [count][]; Array.Copy (headers, 0, unknownHeaders, 0, count); return unknownHeaders; } public override string GetKnownRequestHeader (int index) { string value; switch (index) { case HeaderContentType: value = responder.GetParameter ("CONTENT_TYPE"); break; case HeaderContentLength: value = responder.GetParameter ("CONTENT_LENGTH"); break; default: GetUnknownRequestHeaders (); value = knownHeaders [index]; break; } return value ?? base.GetKnownRequestHeader (index); } public override string GetServerName () { return (HostNameFromString (responder.GetParameter ("SERVER_NAME")) ?? HostNameFromString (responder.GetParameter ("HTTP_HOST"))) ?? GetLocalAddress (); } public override byte [] GetPreloadedEntityBody () { return input_data; } #endregion #endregion #region Private Methods void AppendHeaderLine (string format, params object [] args) { if (headers == null) return; headers.AppendFormat (CultureInfo.InvariantCulture, format, args); headers.Append ("\r\n"); } void EnsureHeadersSent () { if (headers == null) return; headers.Append ("\r\n"); string str = headers.ToString (); responder.SendOutput (str, HeaderEncoding); headers = null; } #endregion #region Private Static Methods static string AddressFromHostName (string host) { host = HostNameFromString (host); if (host == null || host.Length > 126) return null; IPAddress [] addresses; try { addresses = Dns.GetHostAddresses (host); } catch (System.Net.Sockets.SocketException) { return null; } catch (ArgumentException) { return null; } if (addresses == null || addresses.Length == 0) return null; return addresses [0].ToString (); } static string HostNameFromString (string host) { if (String.IsNullOrEmpty(host)) return null; int colon_index = host.IndexOf (':'); if (colon_index == -1) return host; if (colon_index == 0) return null; return host.Substring (0, colon_index); } static string ReformatHttpHeader (string header) { string [] parts = header.Substring (5).Split ('_'); for (int i = 0; i < parts.Length; i ++) { string s = parts [i]; if (String.IsNullOrEmpty (s)) { parts [i] = String.Empty; continue; } s = s.ToLower (); char [] a = s.ToCharArray (); a [0] = Char.ToUpper (a[0]); parts [i] = new String (a); } return String.Join ("-", parts); } static void SetDefaultIndexFiles (string list) { if (list == null) return; indexFiles = SplitAndTrim (list); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using Microsoft.Research.AbstractDomains; using Microsoft.Research.AbstractDomains.Numerical; using Microsoft.Research.CodeAnalysis; using System.Diagnostics; using Microsoft.Research.DataStructures; using Microsoft.Research.AbstractDomains.Expressions; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Research.CodeAnalysis { public static partial class AnalysisWrapper { public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { [ContractVerification(true)] public class ScalarFromArrayTracking : IAbstractDomainWithRenaming<ScalarFromArrayTracking, BoxedVariable<Variable>> { #region Object invariant [ContractInvariantMethod] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")] private void ObjectInvariant() { Contract.Invariant(this.left != null); Contract.Invariant(this.right != null); Contract.Invariant(this.conditions != null); Contract.Invariant(this.isUnmodifiedFromEntry != null); } #endregion #region State private readonly SetOfConstraints<BoxedVariable<Variable>> left; // meaning: all the elements are == private readonly SetOfConstraints<BoxedVariable<Variable>> right; // meaning: all the elements are == private readonly FlatAbstractDomain<bool> isUnmodifiedFromEntry; private readonly SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression> conditions; #endregion #region Constructor public ScalarFromArrayTracking( BoxedVariable<Variable> left, BoxedVariable<Variable> right, FlatAbstractDomain<bool> isUnmodifiedFromEntry, SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression> conditions) : this(new SetOfConstraints<BoxedVariable<Variable>>(left), new SetOfConstraints<BoxedVariable<Variable>>(right), isUnmodifiedFromEntry, conditions) { Contract.Requires(isUnmodifiedFromEntry != null); Contract.Requires(conditions != null); } public ScalarFromArrayTracking( SetOfConstraints<BoxedVariable<Variable>> left, SetOfConstraints<BoxedVariable<Variable>> right, FlatAbstractDomain<bool> isUnmodifiedFromEntry, SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression> conditions) { Contract.Requires(left != null); Contract.Requires(right != null); Contract.Requires(isUnmodifiedFromEntry != null); Contract.Requires(conditions != null); this.left = left; this.right = right; this.isUnmodifiedFromEntry = isUnmodifiedFromEntry; this.conditions = conditions; } #endregion #region Getters public SetOfConstraints<BoxedVariable<Variable>> Left { get { return this.left; } } public SetOfConstraints<BoxedVariable<Variable>> Right { get { return this.right; } } public FlatAbstractDomain<bool> IsUnmodifiedFromEntry { get { return this.isUnmodifiedFromEntry; } } public SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression> Conditions { get { return this.conditions; } } #endregion #region IAbstractDomainWithRenaming<CartestianAbstractDomain<LeftDomain,RightDomain,Variable>,Variable> Members ScalarFromArrayTracking IAbstractDomainWithRenaming<ScalarFromArrayTracking, BoxedVariable<Variable>>.Rename( Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> renaming) { return new ScalarFromArrayTracking(this.left.Rename(renaming), this.right.Rename(renaming), this.isUnmodifiedFromEntry, this.conditions); } #endregion #region Abstract Domain operations public bool LessEqual(ScalarFromArrayTracking a) { Contract.Requires(a != null); bool result; if (AbstractDomainsHelper.TryTrivialLessEqual(this, a, out result)) { return result; } return this.left.LessEqual(a.left) && this.right.LessEqual(a.right) && this.isUnmodifiedFromEntry.LessEqual(a.isUnmodifiedFromEntry) && this.conditions.LessEqual(a.conditions); } public ScalarFromArrayTracking Bottom { get { Contract.Ensures(Contract.Result<ScalarFromArrayTracking>() != null); return new ScalarFromArrayTracking( (SetOfConstraints<BoxedVariable<Variable>>)this.left.Bottom, (SetOfConstraints<BoxedVariable<Variable>>)this.right.Bottom, this.isUnmodifiedFromEntry.Bottom, SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression>.Unreached); } } public ScalarFromArrayTracking Top { get { Contract.Ensures(Contract.Result<ScalarFromArrayTracking>() != null); return new ScalarFromArrayTracking( (SetOfConstraints<BoxedVariable<Variable>>)this.left.Top, (SetOfConstraints<BoxedVariable<Variable>>)this.right.Top, this.isUnmodifiedFromEntry.Top, SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression>.Unknown); } } public ScalarFromArrayTracking Join(ScalarFromArrayTracking a) { Contract.Requires(a != null); Contract.Ensures(Contract.Result<ScalarFromArrayTracking>() != null); ScalarFromArrayTracking result; if (AbstractDomainsHelper.TryTrivialJoin(this, a, out result)) { return result; } return new ScalarFromArrayTracking( (SetOfConstraints<BoxedVariable<Variable>>)this.left.Join(a.left), (SetOfConstraints<BoxedVariable<Variable>>)this.right.Join(a.right), this.isUnmodifiedFromEntry.Join(a.isUnmodifiedFromEntry), this.conditions.Join(a.conditions)); } public ScalarFromArrayTracking Meet(ScalarFromArrayTracking a) { Contract.Requires(a != null); Contract.Ensures(Contract.Result<ScalarFromArrayTracking>() != null); ScalarFromArrayTracking result; if (AbstractDomainsHelper.TryTrivialMeet(this, a, out result)) { return result; } var meetWrite = this.isUnmodifiedFromEntry.IsTop? a.isUnmodifiedFromEntry : a.isUnmodifiedFromEntry.IsTop ? this.isUnmodifiedFromEntry: a.isUnmodifiedFromEntry.BoxedElement == this.isUnmodifiedFromEntry.BoxedElement? a.isUnmodifiedFromEntry : CheckOutcome.Top; Contract.Assume(meetWrite != null); return new ScalarFromArrayTracking( (SetOfConstraints<BoxedVariable<Variable>>)this.left.Meet(a.left), (SetOfConstraints<BoxedVariable<Variable>>)this.right.Meet(a.right), meetWrite, this.conditions.Meet(a.conditions)); } public ScalarFromArrayTracking Widening(ScalarFromArrayTracking prev) { Contract.Requires(prev != null); Contract.Ensures(Contract.Result<ScalarFromArrayTracking>() != null); ScalarFromArrayTracking result; if (AbstractDomainsHelper.TryTrivialJoin(this, prev, out result)) { return result; } return new ScalarFromArrayTracking( (SetOfConstraints<BoxedVariable<Variable>>)this.left.Widening(prev.left), (SetOfConstraints<BoxedVariable<Variable>>)this.right.Widening(prev.right), this.isUnmodifiedFromEntry.Join(prev.isUnmodifiedFromEntry), this.conditions.Join(prev.conditions)); } #endregion #region IAbstractDomain Members public bool IsBottom { get { return this.left.IsBottom || this.right.IsBottom || this.isUnmodifiedFromEntry.IsBottom || this.conditions.IsBottom; } } public bool IsTop { get { return this.left.IsTop && this.right.IsTop && this.isUnmodifiedFromEntry.IsTop && this.conditions.IsTop; } } bool IAbstractDomain.LessEqual(IAbstractDomain a) { var other = a as ScalarFromArrayTracking; Contract.Assume(other != null); return this.LessEqual(other); } IAbstractDomain IAbstractDomain.Bottom { get { return this.Bottom; } } IAbstractDomain IAbstractDomain.Top { get { return this.Top; } } IAbstractDomain IAbstractDomain.Join(IAbstractDomain a) { var other = a as ScalarFromArrayTracking; Contract.Assume(other != null); return this.Join(other); } IAbstractDomain IAbstractDomain.Meet(IAbstractDomain a) { var other = a as ScalarFromArrayTracking; Contract.Assume(other != null); return this.Meet(other); } IAbstractDomain IAbstractDomain.Widening(IAbstractDomain prev) { var other = prev as ScalarFromArrayTracking; Contract.Assume(other != null); return this.Widening(other); } public T To<T>(IFactory<T> factory) { return factory.And(this.left.To(factory), this.right.To(factory)); } #endregion #region ICloneable Members object ICloneable.Clone() { return new ScalarFromArrayTracking( (SetOfConstraints<BoxedVariable<Variable>>)this.left.Clone(), (SetOfConstraints<BoxedVariable<Variable>>)this.right.Clone(), this.isUnmodifiedFromEntry, this.conditions); } #endregion #region ToString public override string ToString() { if (this.IsBottom) return "_|_"; if (this.IsTop) return "Top"; var purity = ""; if (this.isUnmodifiedFromEntry.IsNormal()) { purity = this.isUnmodifiedFromEntry.IsTrue() ? "pure" : "not-pure?"; } return string.Format("({0}, {1}){2}{3}", this.left.ToString(), this.right.ToString(), purity, this.conditions.IsNormal()? this.conditions.ToString() : ""); } #endregion public ScalarFromArrayTracking AddCondition(BoxedVariable<Variable> var, BoxedExpression sourceExp) { Contract.Requires(sourceExp != null); Contract.Ensures(Contract.Result<ScalarFromArrayTracking>() != null); var conditions = this.conditions.Meet(new SymbolicExpressionTracker<BoxedVariable<Variable>, BoxedExpression>(var, sourceExp)); return new ScalarFromArrayTracking(this.left, this.right, this.isUnmodifiedFromEntry, conditions); } } /// <summary> /// A map var -> (array, index, unmodified), i.e. we track for a scalar variable 'var', if it can be refined to an array /// (in which case index != top) or if its value flows from an element of the array 'array'. /// If unmodified == true, it means that the value is the same as in the entry state (i.e. the array index has not been written meanwhile) /// </summary> /// [ContractVerification(false)] public class ArrayTracking : FunctionalAbstractDomainEnvironment<ArrayTracking, BoxedVariable<Variable>, ScalarFromArrayTracking, BoxedVariable<Variable>, BoxedExpression> { #region Constructor public ArrayTracking( ExpressionManager<BoxedVariable<Variable>, BoxedExpression> expManager) : base(expManager) { Contract.Requires(expManager != null); } private ArrayTracking(ArrayTracking other) : base(other) { Contract.Requires(other != null); } #endregion public override object Clone() { return new ArrayTracking(this); } protected override ArrayTracking Factory() { return new ArrayTracking(this.ExpressionManager); } public override List<BoxedVariable<Variable>> Variables { get { var result = new List<BoxedVariable<Variable>>(); if (this.IsNormal()) { foreach (var element in this.Elements) { result.Add(element.Key); if (element.Value.Left.IsNormal()) { result.AddRange(element.Value.Left.Values); } if (element.Value.Right.IsNormal()) { result.AddRange(element.Value.Right.Values); } } } return result; } } public override void Assign(BoxedExpression x, BoxedExpression exp) { // } public override void ProjectVariable(BoxedVariable<Variable> var) { if (this.ContainsKey(var)) { this.RemoveElement(var); } } public override void RemoveVariable(BoxedVariable<Variable> var) { if (this.ContainsKey(var)) { this.RemoveElement(var); } } public override ArrayTracking TestTrue(BoxedExpression guard) { return this; } public override ArrayTracking TestFalse(BoxedExpression guard) { return this; } public override FlatAbstractDomain<bool> CheckIfHolds(BoxedExpression exp) { return CheckOutcome.Top; } public override void RenameVariable(BoxedVariable<Variable> OldName, BoxedVariable<Variable> NewName) { // do nothing? } public override void AssignInParallel( Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> sourcesToTargets, Converter<BoxedVariable<Variable>, BoxedExpression> convert) { if(!this.IsNormal()) { return; } var result = new List<Pair<BoxedVariable<Variable>, ScalarFromArrayTracking>>(); foreach (var element in this.Elements) { FList<BoxedVariable<Variable>> newNames; if (sourcesToTargets.TryGetValue(element.Key, out newNames)) { var newLeft = element.Value.Left.Rename(sourcesToTargets); var newRight = element.Value.Right.Rename(sourcesToTargets); if (newLeft.IsNormal() || newRight.IsNormal()) { var renamedPair = new ScalarFromArrayTracking( newLeft, newRight, element.Value.IsUnmodifiedFromEntry, element.Value.Conditions); foreach (var newKey in newNames.GetEnumerable()) { result.Add(newKey, renamedPair); } } } } this.ClearElements(); foreach (var el in result) { this[el.One] = el.Two; } } #region To protected override T To<T>(BoxedVariable<Variable> d, ScalarFromArrayTracking c, IFactory<T> factory) { var result = factory.IdentityForAnd; if (c.Left.IsNormal()) { T name; if (factory.TryGetBoundVariable(out name)) { var first = true; foreach (var x in c.Left.Values) { T arrayLength; if (factory.TryArrayLengthName(factory.Variable(x), out arrayLength)) { var body = factory.EqualTo(factory.Variable(d), factory.ArrayIndex(factory.Variable(x), name)); var exists = factory.Exists(factory.Constant(0), arrayLength, body); if (first) { result = exists; first = false; } else { result = factory.And(result, exists); } } } } } return result; } #endregion } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedGeoTargetConstantServiceClientTest { [Category("Autogenerated")][Test] public void GetGeoTargetConstantRequestObject() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); GetGeoTargetConstantRequest request = new GetGeoTargetConstantRequest { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), }; gagvr::GeoTargetConstant expectedResponse = new gagvr::GeoTargetConstant { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Status = gagve::GeoTargetConstantStatusEnum.Types.GeoTargetConstantStatus.Enabled, ParentGeoTargetAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Id = -6774108720365892680L, GeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), CountryCode = "country_code8debec55", TargetType = "target_type1235462e", CanonicalName = "canonical_name5e3d81e6", }; mockGrpcClient.Setup(x => x.GetGeoTargetConstant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); gagvr::GeoTargetConstant response = client.GetGeoTargetConstant(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetGeoTargetConstantRequestObjectAsync() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); GetGeoTargetConstantRequest request = new GetGeoTargetConstantRequest { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), }; gagvr::GeoTargetConstant expectedResponse = new gagvr::GeoTargetConstant { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Status = gagve::GeoTargetConstantStatusEnum.Types.GeoTargetConstantStatus.Enabled, ParentGeoTargetAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Id = -6774108720365892680L, GeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), CountryCode = "country_code8debec55", TargetType = "target_type1235462e", CanonicalName = "canonical_name5e3d81e6", }; mockGrpcClient.Setup(x => x.GetGeoTargetConstantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::GeoTargetConstant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); gagvr::GeoTargetConstant responseCallSettings = await client.GetGeoTargetConstantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::GeoTargetConstant responseCancellationToken = await client.GetGeoTargetConstantAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetGeoTargetConstant() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); GetGeoTargetConstantRequest request = new GetGeoTargetConstantRequest { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), }; gagvr::GeoTargetConstant expectedResponse = new gagvr::GeoTargetConstant { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Status = gagve::GeoTargetConstantStatusEnum.Types.GeoTargetConstantStatus.Enabled, ParentGeoTargetAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Id = -6774108720365892680L, GeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), CountryCode = "country_code8debec55", TargetType = "target_type1235462e", CanonicalName = "canonical_name5e3d81e6", }; mockGrpcClient.Setup(x => x.GetGeoTargetConstant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); gagvr::GeoTargetConstant response = client.GetGeoTargetConstant(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetGeoTargetConstantAsync() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); GetGeoTargetConstantRequest request = new GetGeoTargetConstantRequest { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), }; gagvr::GeoTargetConstant expectedResponse = new gagvr::GeoTargetConstant { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Status = gagve::GeoTargetConstantStatusEnum.Types.GeoTargetConstantStatus.Enabled, ParentGeoTargetAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Id = -6774108720365892680L, GeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), CountryCode = "country_code8debec55", TargetType = "target_type1235462e", CanonicalName = "canonical_name5e3d81e6", }; mockGrpcClient.Setup(x => x.GetGeoTargetConstantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::GeoTargetConstant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); gagvr::GeoTargetConstant responseCallSettings = await client.GetGeoTargetConstantAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::GeoTargetConstant responseCancellationToken = await client.GetGeoTargetConstantAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetGeoTargetConstantResourceNames() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); GetGeoTargetConstantRequest request = new GetGeoTargetConstantRequest { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), }; gagvr::GeoTargetConstant expectedResponse = new gagvr::GeoTargetConstant { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Status = gagve::GeoTargetConstantStatusEnum.Types.GeoTargetConstantStatus.Enabled, ParentGeoTargetAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Id = -6774108720365892680L, GeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), CountryCode = "country_code8debec55", TargetType = "target_type1235462e", CanonicalName = "canonical_name5e3d81e6", }; mockGrpcClient.Setup(x => x.GetGeoTargetConstant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); gagvr::GeoTargetConstant response = client.GetGeoTargetConstant(request.ResourceNameAsGeoTargetConstantName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetGeoTargetConstantResourceNamesAsync() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); GetGeoTargetConstantRequest request = new GetGeoTargetConstantRequest { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), }; gagvr::GeoTargetConstant expectedResponse = new gagvr::GeoTargetConstant { ResourceNameAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Status = gagve::GeoTargetConstantStatusEnum.Types.GeoTargetConstantStatus.Enabled, ParentGeoTargetAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), Id = -6774108720365892680L, GeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"), CountryCode = "country_code8debec55", TargetType = "target_type1235462e", CanonicalName = "canonical_name5e3d81e6", }; mockGrpcClient.Setup(x => x.GetGeoTargetConstantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::GeoTargetConstant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); gagvr::GeoTargetConstant responseCallSettings = await client.GetGeoTargetConstantAsync(request.ResourceNameAsGeoTargetConstantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::GeoTargetConstant responseCancellationToken = await client.GetGeoTargetConstantAsync(request.ResourceNameAsGeoTargetConstantName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void SuggestGeoTargetConstantsRequestObject() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); SuggestGeoTargetConstantsRequest request = new SuggestGeoTargetConstantsRequest { LocationNames = new SuggestGeoTargetConstantsRequest.Types.LocationNames(), GeoTargets = new SuggestGeoTargetConstantsRequest.Types.GeoTargets(), Locale = "locale9e6d21fb", CountryCode = "country_code8debec55", }; SuggestGeoTargetConstantsResponse expectedResponse = new SuggestGeoTargetConstantsResponse { GeoTargetConstantSuggestions = { new GeoTargetConstantSuggestion(), }, }; mockGrpcClient.Setup(x => x.SuggestGeoTargetConstants(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); SuggestGeoTargetConstantsResponse response = client.SuggestGeoTargetConstants(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task SuggestGeoTargetConstantsRequestObjectAsync() { moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient> mockGrpcClient = new moq::Mock<GeoTargetConstantService.GeoTargetConstantServiceClient>(moq::MockBehavior.Strict); SuggestGeoTargetConstantsRequest request = new SuggestGeoTargetConstantsRequest { LocationNames = new SuggestGeoTargetConstantsRequest.Types.LocationNames(), GeoTargets = new SuggestGeoTargetConstantsRequest.Types.GeoTargets(), Locale = "locale9e6d21fb", CountryCode = "country_code8debec55", }; SuggestGeoTargetConstantsResponse expectedResponse = new SuggestGeoTargetConstantsResponse { GeoTargetConstantSuggestions = { new GeoTargetConstantSuggestion(), }, }; mockGrpcClient.Setup(x => x.SuggestGeoTargetConstantsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SuggestGeoTargetConstantsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GeoTargetConstantServiceClient client = new GeoTargetConstantServiceClientImpl(mockGrpcClient.Object, null); SuggestGeoTargetConstantsResponse responseCallSettings = await client.SuggestGeoTargetConstantsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); SuggestGeoTargetConstantsResponse responseCancellationToken = await client.SuggestGeoTargetConstantsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Text; using com.calitha.goldparser; namespace Epi.Core.EnterInterpreter.Rules { public class Rule_CompareExp : EnterRule { EnterRule ConcatExp = null; string op = null; EnterRule CompareExp = null; string STRING = null; public Rule_CompareExp(Rule_Context pContext, NonterminalToken pToken) : base(pContext) { // <Concat Exp> LIKE String // <Concat Exp> '=' <Compare Exp> // <Concat Exp> '<>' <Compare Exp> // <Concat Exp> '>' <Compare Exp> // <Concat Exp> '>=' <Compare Exp> // <Concat Exp> '<' <Compare Exp> // <Concat Exp> '<=' <Compare Exp> // <Concat Exp> this.ConcatExp = EnterRule.BuildStatments(pContext, pToken.Tokens[0]); if (pToken.Tokens.Length > 1) { op = pToken.Tokens[1].ToString().ToLower(); if (pToken.Tokens[1].ToString() == "LIKE") { this.STRING = pToken.Tokens[2].ToString(); this.CompareExp = EnterRule.BuildStatments(pContext, pToken.Tokens[2]); } else { this.CompareExp = EnterRule.BuildStatments(pContext, pToken.Tokens[2]); } } } /// <summary> /// perfoms comparison operations on expression ie (=, <=, >=, Like, >, <, and <)) returns a boolean /// </summary> /// <returns>object</returns> public override object Execute() { object result = null; if (op == null) { result = this.ConcatExp.Execute(); } else { object LHSO = this.ConcatExp.Execute(); object RHSO = this.CompareExp.Execute(); double TryValue = 0.0; int i; if (Util.IsEmpty(LHSO) && Util.IsEmpty(RHSO) && op.Equals("=")) { result = true; } else if (Util.IsEmpty(LHSO) && Util.IsEmpty(RHSO) && op.Equals("<>")) { return false; } else if ((Util.IsEmpty(LHSO) || Util.IsEmpty(RHSO))) { if (op.Equals("<>")) { return !(Util.IsEmpty(LHSO) && Util.IsEmpty(RHSO)); } else { result = false; } } else if (op.Equals("LIKE", StringComparison.OrdinalIgnoreCase)) { //string testValue = "^" + RHSO.ToString().Replace("*", "(\\s|\\w)*") + "$"; string testValue = "^" + RHSO.ToString().Replace("*", ".*") + "$"; System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(testValue, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (re.IsMatch(LHSO.ToString())) { result = true; } else { result = false; } } else { if (this.NumericTypeList.Contains(LHSO.GetType().Name.ToUpper()) && this.NumericTypeList.Contains(RHSO.GetType().Name.ToUpper())) { LHSO = Convert.ToDouble(LHSO); RHSO = Convert.ToDouble(RHSO); } if (!LHSO.GetType().Equals(RHSO.GetType())) { if (RHSO is Boolean && op.Equals("=")) { result = (RHSO.Equals(!Util.IsEmpty(LHSO))); } else if (LHSO is string && this.NumericTypeList.Contains(RHSO.GetType().Name.ToUpper()) && double.TryParse(LHSO.ToString(), out TryValue)) { i = TryValue.CompareTo(RHSO); switch (op) { case "=": result = (i == 0); break; case "<>": result = (i != 0); break; case "<": result = (i < 0); break; case ">": result = (i > 0); break; case ">=": result = (i >= 0); break; case "<=": result = (i <= 0); break; } } else if (RHSO is string && this.NumericTypeList.Contains(LHSO.GetType().Name.ToUpper()) && double.TryParse(RHSO.ToString(), out TryValue)) { i = TryValue.CompareTo(LHSO); switch (op) { case "=": result = (i == 0); break; case "<>": result = (i != 0); break; case "<": result = (i < 0); break; case ">": result = (i > 0); break; case ">=": result = (i >= 0); break; case "<=": result = (i <= 0); break; } } else if (op.Equals("=") && (LHSO is Boolean || RHSO is Boolean)) { if (LHSO is Boolean && RHSO is Boolean) { result = LHSO == RHSO; } else if (LHSO is Boolean) { result = (Boolean)LHSO == (Boolean) this.ConvertStringToBoolean(RHSO.ToString()); } else { result = (Boolean)this.ConvertStringToBoolean(LHSO.ToString()) == (Boolean)RHSO; } } else { i = StringComparer.CurrentCultureIgnoreCase.Compare(LHSO.ToString(), RHSO.ToString()); switch (op) { case "=": result = (i == 0); break; case "<>": result = (i != 0); break; case "<": result = (i < 0); break; case ">": result = (i > 0); break; case ">=": result = (i >= 0); break; case "<=": result = (i <= 0); break; } } } else { i = 0; if (LHSO.GetType().Name.ToUpper() == "STRING" && RHSO.GetType().Name.ToUpper() == "STRING") { i = StringComparer.CurrentCultureIgnoreCase.Compare(LHSO.ToString().Trim(), RHSO.ToString().Trim()); } else if (LHSO is IComparable && RHSO is IComparable) { i = ((IComparable)LHSO).CompareTo((IComparable)RHSO); } switch (op) { case "=": result = (i == 0); break; case "<>": result = (i != 0); break; case "<": result = (i < 0); break; case ">": result = (i > 0); break; case ">=": result = (i >= 0); break; case "<=": result = (i <= 0); break; } } } } return result; } public override void ToJavaScript(StringBuilder pJavaScriptBuilder) { if (op == null) { this.ConcatExp.ToJavaScript(pJavaScriptBuilder); } else { if (this.op == "like") { pJavaScriptBuilder.Append("CCE_Like("); this.ConcatExp.ToJavaScript(pJavaScriptBuilder); pJavaScriptBuilder.Append(","); this.CompareExp.ToJavaScript(pJavaScriptBuilder); pJavaScriptBuilder.Append(")"); } else { if (this.ConcatExp is Rule_Value) { WriteValueJavascript((Rule_Value)this.ConcatExp, pJavaScriptBuilder); } else { this.ConcatExp.ToJavaScript(pJavaScriptBuilder); } switch (op) { case "=": pJavaScriptBuilder.Append("=="); break; case "<>": pJavaScriptBuilder.Append("!="); break; default: pJavaScriptBuilder.Append(this.op); break; } if (this.CompareExp is Rule_Value) { WriteValueJavascript((Rule_Value)this.CompareExp, pJavaScriptBuilder); } else { this.CompareExp.ToJavaScript(pJavaScriptBuilder); } } } } private void WriteValueJavascript(Rule_Value pValue, StringBuilder pJavaScriptBuilder) { if (!string.IsNullOrEmpty(pValue.Id)) { PluginVariable var = (PluginVariable)this.Context.CurrentScope.resolve(pValue.Id); pValue.ToJavaScript(pJavaScriptBuilder); if (var != null) { switch (var.DataType) { case EpiInfo.Plugin.DataType.Boolean: case EpiInfo.Plugin.DataType.Date: case EpiInfo.Plugin.DataType.DateTime: case EpiInfo.Plugin.DataType.Number: case EpiInfo.Plugin.DataType.Time: break; case EpiInfo.Plugin.DataType.Text: case EpiInfo.Plugin.DataType.GUID: default: pJavaScriptBuilder.Append(".toLowerCase()"); break; } } } else { if (pValue.VariableDataType != EpiInfo.Plugin.DataType.Unknown) { pValue.ToJavaScript(pJavaScriptBuilder); switch (pValue.VariableDataType) { case EpiInfo.Plugin.DataType.Boolean: case EpiInfo.Plugin.DataType.Date: case EpiInfo.Plugin.DataType.DateTime: case EpiInfo.Plugin.DataType.Number: case EpiInfo.Plugin.DataType.Time: break; case EpiInfo.Plugin.DataType.Text: default: pJavaScriptBuilder.Append(".toLowerCase()"); break; } } else if (pValue.value is string) { pValue.ToJavaScript(pJavaScriptBuilder); pJavaScriptBuilder.Append(".toLowerCase()"); } else { pValue.ToJavaScript(pJavaScriptBuilder); } } } } }
#if !UNITY_2020_2_OR_NEWER using System; using System.Collections.Generic; using System.IO; using System.Linq; using Unity.CompilationPipeline.Common.Diagnostics; using Unity.CompilationPipeline.Common.ILPostProcessing; using UnityEditor; using UnityEditor.Compilation; using UnityEngine; using Assembly = System.Reflection.Assembly; using ILPPInterface = Unity.CompilationPipeline.Common.ILPostProcessing.ILPostProcessor; namespace MLAPI.Editor.CodeGen { // There is a behaviour difference between 2019.4 and 2020+ codegen // that essentially does checking on the existence of ILPP vs if a CodeGen assembly // is present. So in order to make sure ILPP runs properly in 2019.4 from a clean // import of the project we add this dummy ILPP which forces the callback to made // and meets the internal ScriptCompilation pipeline requirements internal sealed class ILPP2019CodegenWorkaround : ILPPInterface { public override ILPPInterface GetInstance() { return this; } public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) { return null; } public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName); } internal static class ILPostProcessProgram { private static ILPostProcessor[] s_ILPostProcessors { get; set; } [InitializeOnLoadMethod] private static void OnInitializeOnLoad() { CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished; s_ILPostProcessors = FindAllPostProcessors(); } private static ILPostProcessor[] FindAllPostProcessors() { var typesDerivedFrom = TypeCache.GetTypesDerivedFrom<ILPostProcessor>(); var localILPostProcessors = new List<ILPostProcessor>(typesDerivedFrom.Count); foreach (var typeCollection in typesDerivedFrom) { try { localILPostProcessors.Add((ILPostProcessor)Activator.CreateInstance(typeCollection)); } catch (Exception exception) { Debug.LogError($"Could not create {nameof(ILPostProcessor)} ({typeCollection.FullName}):{Environment.NewLine}{exception.StackTrace}"); } } // Default sort by type full name localILPostProcessors.Sort((left, right) => string.Compare(left.GetType().FullName, right.GetType().FullName, StringComparison.Ordinal)); return localILPostProcessors.ToArray(); } private static void OnCompilationFinished(string targetAssembly, CompilerMessage[] messages) { if (messages.Length > 0) { if (messages.Any(msg => msg.type == CompilerMessageType.Error)) { return; } } // Should not run on the editor only assemblies if (targetAssembly.Contains("-Editor") || targetAssembly.Contains(".Editor")) { return; } // Should not run on Unity Engine modules but we can run on the MLAPI Runtime DLL if ((targetAssembly.Contains("com.unity") || Path.GetFileName(targetAssembly).StartsWith("Unity")) && !targetAssembly.Contains("Unity.Multiplayer.")) { return; } // Debug.Log($"Running MLAPI ILPP on {targetAssembly}"); var outputDirectory = $"{Application.dataPath}/../{Path.GetDirectoryName(targetAssembly)}"; var unityEngine = string.Empty; var mlapiRuntimeAssemblyPath = string.Empty; var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var usesMLAPI = false; var foundThisAssembly = false; var depenencyPaths = new List<string>(); foreach (var assembly in assemblies) { // Find the assembly currently being compiled from domain assembly list and check if it's using unet if (assembly.GetName().Name == Path.GetFileNameWithoutExtension(targetAssembly)) { foundThisAssembly = true; foreach (var dependency in assembly.GetReferencedAssemblies()) { // Since this assembly is already loaded in the domain this is a no-op and returns the // already loaded assembly depenencyPaths.Add(Assembly.Load(dependency).Location); if (dependency.Name.Contains(CodeGenHelpers.RuntimeAssemblyName)) { usesMLAPI = true; } } } try { if (assembly.Location.Contains("UnityEngine.CoreModule")) { unityEngine = assembly.Location; } if (assembly.Location.Contains(CodeGenHelpers.RuntimeAssemblyName)) { mlapiRuntimeAssemblyPath = assembly.Location; } } catch (NotSupportedException) { // in memory assembly, can't get location } } if (!foundThisAssembly) { // Target assembly not found in current domain, trying to load it to check references // will lead to trouble in the build pipeline, so lets assume it should go to weaver. // Add all assemblies in current domain to dependency list since there could be a // dependency lurking there (there might be generated assemblies so ignore file not found exceptions). // (can happen in runtime test framework on editor platform and when doing full library reimport) foreach (var assembly in assemblies) { try { if (!(assembly.ManifestModule is System.Reflection.Emit.ModuleBuilder)) { depenencyPaths.Add(Assembly.Load(assembly.GetName().Name).Location); } } catch (FileNotFoundException) { } } usesMLAPI = true; } // We check if we are the MLAPI! if (!usesMLAPI) { // we shall also check and see if it we are ourself usesMLAPI = targetAssembly.Contains(CodeGenHelpers.RuntimeAssemblyName); } if (!usesMLAPI) { return; } if (string.IsNullOrEmpty(unityEngine)) { Debug.LogError("Failed to find UnityEngine assembly"); return; } if (string.IsNullOrEmpty(mlapiRuntimeAssemblyPath)) { Debug.LogError("Failed to find mlapi runtime assembly"); return; } var assemblyPathName = Path.GetFileName(targetAssembly); var targetCompiledAssembly = new ILPostProcessCompiledAssembly(assemblyPathName, depenencyPaths.ToArray(), null, outputDirectory); void WriteAssembly(InMemoryAssembly inMemoryAssembly, string outputPath, string assName) { if (inMemoryAssembly == null) { throw new ArgumentException("InMemoryAssembly has never been accessed or modified"); } var asmPath = Path.Combine(outputPath, assName); var pdbFileName = $"{Path.GetFileNameWithoutExtension(assName)}.pdb"; var pdbPath = Path.Combine(outputPath, pdbFileName); File.WriteAllBytes(asmPath, inMemoryAssembly.PeData); File.WriteAllBytes(pdbPath, inMemoryAssembly.PdbData); } foreach (var i in s_ILPostProcessors) { var result = i.Process(targetCompiledAssembly); if (result == null) continue; if (result.Diagnostics.Count > 0) { Debug.LogError($"{nameof(ILPostProcessor)} - {i.GetType().Name} failed to run on {targetCompiledAssembly.Name}"); foreach (var message in result.Diagnostics) { switch (message.DiagnosticType) { case DiagnosticType.Error: Debug.LogError($"{nameof(ILPostProcessor)} Error - {message.MessageData} {message.File}:{message.Line}"); break; case DiagnosticType.Warning: Debug.LogWarning($"{nameof(ILPostProcessor)} Warning - {message.MessageData} {message.File}:{message.Line}"); break; } } continue; } // we now need to write out the result? WriteAssembly(result.InMemoryAssembly, outputDirectory, assemblyPathName); } } } } #endif
// 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.Configuration.Install; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.Xml; using Microsoft.Deployment.WindowsInstaller; using WebsitePanel.Setup; namespace WebsitePanel.SchedulerServiceInstaller { public class CustomActions { public const string CustomDataDelimiter = "-=del=-"; [CustomAction] public static ActionResult CheckConnection(Session session) { string testConnectionString = session["AUTHENTICATIONTYPE"].Equals("Windows Authentication") ? GetConnectionString(session["SERVERNAME"], "master") : GetConnectionString(session["SERVERNAME"], "master", session["LOGIN"], session["PASSWORD"]); testConnectionString = testConnectionString.Replace(CustomDataDelimiter, ";"); if (CheckConnection(testConnectionString)) { session["CORRECTCONNECTION"] = "1"; session["CONNECTIONSTRING"] = session["AUTHENTICATIONTYPE"].Equals("Windows Authentication") ? GetConnectionString(session["SERVERNAME"], session["DATABASENAME"]) : GetConnectionString(session["SERVERNAME"], session["DATABASENAME"], session["LOGIN"], session["PASSWORD"]); } else { session["CORRECTCONNECTION"] = "0"; } return ActionResult.Success; } [CustomAction] public static ActionResult FinalizeInstall(Session session) { var connectionString = GetCustomActionProperty(session, "ConnectionString").Replace(CustomDataDelimiter, ";"); var serviceFolder = GetCustomActionProperty(session, "ServiceFolder"); var previousConnectionString = GetCustomActionProperty(session, "PreviousConnectionString").Replace(CustomDataDelimiter, ";"); var previousCryptoKey = GetCustomActionProperty(session, "PreviousCryptoKey"); if (string.IsNullOrEmpty(serviceFolder)) { return ActionResult.Success; } connectionString = string.IsNullOrEmpty(previousConnectionString) ? connectionString : previousConnectionString; ChangeConfigString("/configuration/connectionStrings/add[@name='EnterpriseServer']", "connectionString", connectionString, serviceFolder); ChangeConfigString("/configuration/appSettings/add[@key='WebsitePanel.CryptoKey']", "value", previousCryptoKey, serviceFolder); InstallService(serviceFolder); return ActionResult.Success; } [CustomAction] public static ActionResult FinalizeUnInstall(Session session) { UnInstallService(); return ActionResult.Success; } [CustomAction] public static ActionResult PreInstallationAction(Session session) { session["SKIPCONNECTIONSTRINGSTEP"] = "0"; session["SERVICEFOLDER"] = session["PI_SCHEDULER_INSTALL_DIR"]; var servicePath = SecurityUtils.GetServicePath("WebsitePanel Scheduler"); if (!string.IsNullOrEmpty(servicePath)) { string path = Path.Combine(servicePath, "WebsitePanel.SchedulerService.exe.config"); if (File.Exists(path)) { using (var reader = new StreamReader(path)) { string content = reader.ReadToEnd(); var pattern = new Regex(@"(?<=<add key=""WebsitePanel.CryptoKey"" .*?value\s*=\s*"")[^""]+(?="".*?>)"); Match match = pattern.Match(content); session["PREVIOUSCRYPTOKEY"] = match.Value; var connectionStringPattern = new Regex(@"(?<=<add name=""EnterpriseServer"" .*?connectionString\s*=\s*"")[^""]+(?="".*?>)"); match = connectionStringPattern.Match(content); session["PREVIOUSCONNECTIONSTRING"] = match.Value.Replace(";", CustomDataDelimiter); } session["SKIPCONNECTIONSTRINGSTEP"] = "1"; if (string.IsNullOrEmpty(session["SERVICEFOLDER"])) { session["SERVICEFOLDER"] = servicePath; } } } return ActionResult.Success; } private static void InstallService(string installFolder) { try { var schedulerService = ServiceController.GetServices().FirstOrDefault( s => s.DisplayName.Equals("WebsitePanel Scheduler", StringComparison.CurrentCultureIgnoreCase)); if (schedulerService != null) { StopService(schedulerService.ServiceName); SecurityUtils.DeleteService(schedulerService.ServiceName); } ManagedInstallerClass.InstallHelper(new[] { "/i", Path.Combine(installFolder, "WebsitePanel.SchedulerService.exe") }); StartService("WebsitePanel Scheduler"); } catch (Exception) { } } private static void UnInstallService() { try { var schedulerService = ServiceController.GetServices().FirstOrDefault( s => s.DisplayName.Equals("WebsitePanel Scheduler", StringComparison.CurrentCultureIgnoreCase)); if (schedulerService != null) { StopService(schedulerService.ServiceName); SecurityUtils.DeleteService(schedulerService.ServiceName); } } catch (Exception) { } } private static void ChangeConfigString(string nodePath, string attrToChange, string value, string installFolder) { string path = Path.Combine(installFolder, "WebsitePanel.SchedulerService.exe.config"); if (!File.Exists(path)) { return; } XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(path); XmlElement node = xmldoc.SelectSingleNode(nodePath) as XmlElement; if (node != null) { node.SetAttribute(attrToChange, value); xmldoc.Save(path); } } private static void StopService(string serviceName) { var sc = new ServiceController(serviceName); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); } } private static void StartService(string serviceName) { var sc = new ServiceController(serviceName); if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); } } private static string GetConnectionString(string serverName, string databaseName) { return string.Format("Server={0};database={1};Trusted_Connection=true;", serverName, databaseName).Replace(";", CustomDataDelimiter); } private static string GetConnectionString(string serverName, string databaseName, string login, string password) { return string.Format("Server={0};database={1};uid={2};password={3};", serverName, databaseName, login, password).Replace(";", CustomDataDelimiter); } private static bool CheckConnection(string connectionString) { var connection = new SqlConnection(connectionString); bool result = true; try { connection.Open(); } catch (Exception) { result = false; } finally { if (connection != null && connection.State == ConnectionState.Open) { connection.Close(); } } return result; } private static string GetCustomActionProperty(Session session, string key) { if (session.CustomActionData.ContainsKey(key)) { return session.CustomActionData[key].Replace("-=-", ";"); } return string.Empty; } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System.Collections.Generic; namespace NPOI.HPSF { using System; using System.IO; using System.Globalization; /// <summary> /// Supports Reading and writing of variant data. /// <strong>FIXME (3):</strong> /// Reading and writing should be made more /// uniform than it is now. The following items should be resolved: /// Reading requires a Length parameter that is 4 byte greater than the /// actual data, because the variant type field is included. /// Reading Reads from a byte array while writing Writes To an byte array /// output stream. /// @author Rainer Klute /// <a href="mailto:[email protected]">&lt;[email protected]&gt;</a> /// @since 2003-08-08 /// </summary> public class VariantSupport : Variant { private static bool logUnsupportedTypes = false; /// <summary> /// Checks whether logging of unsupported variant types warning is turned /// on or off. /// </summary> /// <value> /// <c>true</c> if logging is turned on; otherwise, <c>false</c>. /// </value> public static bool IsLogUnsupportedTypes { get { return logUnsupportedTypes; } set { logUnsupportedTypes = value; } } /** * Keeps a list of the variant types an "unsupported" message has alReady * been issued for. */ protected static List<long> unsupportedMessage; /// <summary> /// Writes a warning To System.err that a variant type Is /// unsupported by HPSF. Such a warning is written only once for each variant /// type. Log messages can be turned on or off by /// </summary> /// <param name="ex">The exception To log</param> public static void WriteUnsupportedTypeMessage (UnsupportedVariantTypeException ex) { if (IsLogUnsupportedTypes) { if (unsupportedMessage == null) unsupportedMessage = new List<long>(); long vt = ex.VariantType; if (!unsupportedMessage.Contains(vt)) { Console.Error.WriteLine(ex.Message); unsupportedMessage.Add(vt); } } } /** * HPSF is able To Read these {@link Variant} types. */ static public int[] SUPPORTED_TYPES = { Variant.VT_EMPTY, Variant.VT_I2, Variant.VT_I4, Variant.VT_I8, Variant.VT_R8, Variant.VT_FILETIME, Variant.VT_LPSTR, Variant.VT_LPWSTR, Variant.VT_CF, Variant.VT_BOOL }; /// <summary> /// Checks whether HPSF supports the specified variant type. Unsupported /// types should be implemented included in the {@link #SUPPORTED_TYPES} /// array. /// </summary> /// <param name="variantType">the variant type To check</param> /// <returns> /// <c>true</c> if HPFS supports this type,otherwise, <c>false</c>. /// </returns> public bool IsSupportedType(int variantType) { for (int i = 0; i < SUPPORTED_TYPES.Length; i++) if (variantType == SUPPORTED_TYPES[i]) return true; return false; } /// <summary> /// Reads a variant type from a byte array /// </summary> /// <param name="src">The byte array</param> /// <param name="offset">The offset in the byte array where the variant starts</param> /// <param name="length">The Length of the variant including the variant type field</param> /// <param name="type">The variant type To Read</param> /// <param name="codepage">The codepage To use for non-wide strings</param> /// <returns>A Java object that corresponds best To the variant field. For /// example, a VT_I4 is returned as a {@link long}, a VT_LPSTR as a /// {@link String}.</returns> public static Object Read(byte[] src, int offset, int length, long type, int codepage) { TypedPropertyValue typedPropertyValue = new TypedPropertyValue( (int)type, null); int unpadded; try { unpadded = typedPropertyValue.ReadValue(src, offset); } catch (InvalidOperationException) { int propLength = Math.Min(length, src.Length - offset); byte[] v = new byte[propLength]; System.Array.Copy(src, offset, v, 0, propLength); throw new ReadingNotSupportedException(type, v); } switch ((int)type) { case Variant.VT_EMPTY: case Variant.VT_I4: case Variant.VT_I8: case Variant.VT_R8: /* * we have more property types that can be converted into Java * objects, but current API need to be preserved, and it returns * other types as byte arrays. In future major versions it shall be * changed -- sergey */ return typedPropertyValue.Value; case Variant.VT_I2: { /* * also for backward-compatibility with prev. versions of POI * --sergey */ return (short)typedPropertyValue.Value; } case Variant.VT_FILETIME: { Filetime filetime = (Filetime)typedPropertyValue.Value; return Util.FiletimeToDate((int)filetime.High, (int)filetime.Low); } case Variant.VT_LPSTR: { CodePageString string1 = (CodePageString)typedPropertyValue.Value; return string1.GetJavaValue(codepage); } case Variant.VT_LPWSTR: { UnicodeString string1 = (UnicodeString)typedPropertyValue.Value; return string1.ToJavaString(); } case Variant.VT_CF: { // if(l1 < 0) { /* * YK: reading the ClipboardData packet (VT_CF) is not quite * correct. The size of the data is determined by the first four * bytes of the packet while the current implementation calculates * it in the Section constructor. Test files in Bugzilla 42726 and * 45583 clearly show that this approach does not always work. The * workaround below attempts to gracefully handle such cases instead * of throwing exceptions. * * August 20, 2009 */ // l1 = LittleEndian.getInt(src, o1); o1 += LittleEndian.INT_SIZE; // } // final byte[] v = new byte[l1]; // System.arraycopy(src, o1, v, 0, v.length); // value = v; // break; ClipboardData clipboardData = (ClipboardData)typedPropertyValue.Value; return clipboardData.ToByteArray(); } case Variant.VT_BOOL: { VariantBool bool1 = (VariantBool)typedPropertyValue.Value; return (bool)bool1.Value; } default: { /* * it is not very good, but what can do without breaking current * API? --sergey */ byte[] v = new byte[unpadded]; System.Array.Copy(src, offset, v, 0, unpadded); throw new ReadingNotSupportedException(type, v); } } } /** * <p>Turns a codepage number into the equivalent character encoding's * name.</p> * * @param codepage The codepage number * * @return The character encoding's name. If the codepage number is 65001, * the encoding name is "UTF-8". All other positive numbers are mapped to * "cp" followed by the number, e.g. if the codepage number is 1252 the * returned character encoding name will be "cp1252". * * @exception UnsupportedEncodingException if the specified codepage is * less than zero. */ public static String CodepageToEncoding(int codepage) { if (codepage <= 0) throw new UnsupportedEncodingException ("Codepage number may not be " + codepage); switch ((Constants)codepage) { case Constants.CP_UTF16: return "UTF-16"; case Constants.CP_UTF16_BE: return "UTF-16BE"; case Constants.CP_UTF8: return "UTF-8"; case Constants.CP_037: return "cp037"; case Constants.CP_GBK: return "GBK"; case Constants.CP_MS949: return "ms949"; case Constants.CP_WINDOWS_1250: return "windows-1250"; case Constants.CP_WINDOWS_1251: return "windows-1251"; case Constants.CP_WINDOWS_1252: return "windows-1252"; case Constants.CP_WINDOWS_1253: return "windows-1253"; case Constants.CP_WINDOWS_1254: return "windows-1254"; case Constants.CP_WINDOWS_1255: return "windows-1255"; case Constants.CP_WINDOWS_1256: return "windows-1256"; case Constants.CP_WINDOWS_1257: return "windows-1257"; case Constants.CP_WINDOWS_1258: return "windows-1258"; case Constants.CP_JOHAB: return "johab"; case Constants.CP_MAC_ROMAN: return "MacRoman"; case Constants.CP_MAC_JAPAN: return "SJIS"; case Constants.CP_MAC_CHINESE_TRADITIONAL: return "Big5"; case Constants.CP_MAC_KOREAN: return "EUC-KR"; case Constants.CP_MAC_ARABIC: return "MacArabic"; case Constants.CP_MAC_HEBREW: return "MacHebrew"; case Constants.CP_MAC_GREEK: return "MacGreek"; case Constants.CP_MAC_CYRILLIC: return "MacCyrillic"; case Constants.CP_MAC_CHINESE_SIMPLE: return "EUC_CN"; case Constants.CP_MAC_ROMANIA: return "MacRomania"; case Constants.CP_MAC_UKRAINE: return "MacUkraine"; case Constants.CP_MAC_THAI: return "MacThai"; case Constants.CP_MAC_CENTRAL_EUROPE: return "MacCentralEurope"; case Constants.CP_MAC_ICELAND: return "MacIceland"; case Constants.CP_MAC_TURKISH: return "MacTurkish"; case Constants.CP_MAC_CROATIAN: return "MacCroatian"; case Constants.CP_US_ACSII: case Constants.CP_US_ASCII2: return "US-ASCII"; case Constants.CP_KOI8_R: return "KOI8-R"; case Constants.CP_ISO_8859_1: return "ISO-8859-1"; case Constants.CP_ISO_8859_2: return "ISO-8859-2"; case Constants.CP_ISO_8859_3: return "ISO-8859-3"; case Constants.CP_ISO_8859_4: return "ISO-8859-4"; case Constants.CP_ISO_8859_5: return "ISO-8859-5"; case Constants.CP_ISO_8859_6: return "ISO-8859-6"; case Constants.CP_ISO_8859_7: return "ISO-8859-7"; case Constants.CP_ISO_8859_8: return "ISO-8859-8"; case Constants.CP_ISO_8859_9: return "ISO-8859-9"; case Constants.CP_ISO_2022_JP1: case Constants.CP_ISO_2022_JP2: case Constants.CP_ISO_2022_JP3: return "ISO-2022-JP"; case Constants.CP_ISO_2022_KR: return "ISO-2022-KR"; case Constants.CP_EUC_JP: return "EUC-JP"; case Constants.CP_EUC_KR: return "EUC-KR"; case Constants.CP_GB2312: return "GB2312"; case Constants.CP_GB18030: return "GB18030"; case Constants.CP_SJIS: return "SJIS"; default: return "cp" + codepage; } } /// <summary> /// Writes a variant value To an output stream. This method ensures that /// always a multiple of 4 bytes is written. /// If the codepage is UTF-16, which is encouraged, strings /// <strong>must</strong> always be written as {@link Variant#VT_LPWSTR} /// strings, not as {@link Variant#VT_LPSTR} strings. This method ensure this /// by Converting strings appropriately, if needed. /// </summary> /// <param name="out1">The stream To Write the value To.</param> /// <param name="type">The variant's type.</param> /// <param name="value">The variant's value.</param> /// <param name="codepage">The codepage To use To Write non-wide strings</param> /// <returns>The number of entities that have been written. In many cases an /// "entity" is a byte but this is not always the case.</returns> public static int Write(Stream out1, long type, Object value, int codepage) { int length = 0; switch ((int)type) { case Variant.VT_BOOL: { byte[] data = new byte[2]; if ((bool)value) { out1.WriteByte(0xFF); out1.WriteByte(0xFF); } else { out1.WriteByte(0x00); out1.WriteByte(0x00); } length += 2; break; } case Variant.VT_LPSTR: { CodePageString codePageString = new CodePageString((String)value, codepage); length += codePageString.Write(out1); break; } case Variant.VT_LPWSTR: { int nrOfChars = ((String)value).Length + 1; length += TypeWriter.WriteUIntToStream(out1, (uint)nrOfChars); char[] s = ((String)value).ToCharArray(); for (int i = 0; i < s.Length; i++) { int high = ((s[i] & 0x0000ff00) >> 8); int low = (s[i] & 0x000000ff); byte highb = (byte)high; byte lowb = (byte)low; out1.WriteByte(lowb); out1.WriteByte(highb); length += 2; } // NullTerminator out1.WriteByte(0x00); out1.WriteByte(0x00); length += 2; break; } case Variant.VT_CF: { byte[] b = (byte[])value; out1.Write(b, 0, b.Length); length = b.Length; break; } case Variant.VT_EMPTY: { length += TypeWriter.WriteUIntToStream(out1, Variant.VT_EMPTY); break; } case Variant.VT_I2: { short x; try { x = Convert.ToInt16(value, CultureInfo.InvariantCulture); } catch (OverflowException) { x = (short)((int)value); } length += TypeWriter.WriteToStream(out1, x); //length = LittleEndianConsts.SHORT_SIZE; break; } case Variant.VT_I4: { if (!(value is int)) { throw new Exception("Could not cast an object To " + "int" + ": " + value.GetType().Name + ", " + value.ToString()); } length += TypeWriter.WriteToStream(out1, (int)value); break; } case Variant.VT_I8: { length += TypeWriter.WriteToStream(out1, Convert.ToInt64(value, CultureInfo.CurrentCulture)); break; } case Variant.VT_R8: { length += TypeWriter.WriteToStream(out1, (Double)value); break; } case Variant.VT_FILETIME: { long filetime; if (value != null) { filetime = Util.DateToFileTime((DateTime)value); } else { filetime = 0; } int high = (int)((filetime >> 32) & 0x00000000FFFFFFFFL); int low = (int)(filetime & 0x00000000FFFFFFFFL); Filetime filetimeValue = new Filetime(low, high); length += filetimeValue.Write(out1); //length += TypeWriter.WriteUIntToStream // (out1, (uint)(0x0000000FFFFFFFFL & low)); //length += TypeWriter.WriteUIntToStream // (out1, (uint)(0x0000000FFFFFFFFL & high)); break; } default: { /* The variant type is not supported yet. However, if the value * is a byte array we can Write it nevertheless. */ if (value is byte[]) { byte[] b = (byte[])value; out1.Write(b, 0, b.Length); length = b.Length; WriteUnsupportedTypeMessage (new WritingNotSupportedException(type, value)); } else throw new WritingNotSupportedException(type, value); break; } } /* pad values to 4-bytes */ while ((length & 0x3) != 0) { out1.WriteByte(0x00); length++; } return length; } } }
/* * 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.Monitoring; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.CoreModules.World.Land; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using System.Threading; 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); /// <summary> /// Contains data used while dearchiving a single scene. /// </summary> private class DearchiveContext { public Scene Scene { get; set; } public List<string> SerialisedSceneObjects { get; set; } public List<string> SerialisedParcels { get; set; } public List<SceneObjectGroup> SceneObjects { get; set; } public DearchiveContext(Scene scene) { Scene = scene; SerialisedSceneObjects = new List<string>(); SerialisedParcels = new List<string>(); SceneObjects = new List<SceneObjectGroup>(); } } /// <summary> /// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version /// bumps here should be compatible. /// </summary> public static int MAX_MAJOR_VERSION = 1; /// <summary> /// Has the control file been loaded for this archive? /// </summary> public bool ControlFileLoaded { get; private set; } protected string m_loadPath; protected Scene m_rootScene; 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? /// Merging usually suppresses terrain and parcel loading /// </value> protected bool m_merge; /// <value> /// If true, force the loading of terrain from the oar file /// </value> protected bool m_forceTerrain; /// <value> /// If true, force the loading of parcels from the oar file /// </value> protected bool m_forceParcels; /// <value> /// Should we ignore any assets when reloading the archive? /// </value> protected bool m_skipAssets; /// <value> /// Displacement added to each object as it is added to the world /// </value> protected Vector3 m_displacement = Vector3.Zero; /// <value> /// Rotation (in radians) to apply to the objects as they are loaded. /// </value> protected float m_rotation = 0f; /// <value> /// original oar region size. not using Constants.RegionSize /// </value> protected Vector3 m_incomingRegionSize = new Vector3(256f, 256f, float.MaxValue); /// <value> /// Center around which to apply the rotation relative to the original oar position /// </value> protected Vector3 m_rotationCenter = new Vector3(128f, 128f, 0f); /// <value> /// Corner 1 of a bounding cuboid which specifies which objects we load from the oar /// </value> protected Vector3 m_boundingOrigin = Vector3.Zero; /// <value> /// Size of a bounding cuboid which specifies which objects we load from the oar /// </value> protected Vector3 m_boundingSize = new Vector3(Constants.MaximumRegionSize, Constants.MaximumRegionSize, float.MaxValue); protected bool m_noObjects = false; protected bool m_boundingBox = false; protected bool m_debug = false; /// <summary> /// Used to cache lookups for valid uuids. /// </summary> private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>(); private IUserManagement m_UserMan; private IUserManagement UserManager { get { if (m_UserMan == null) { m_UserMan = m_rootScene.RequestModuleInterface<IUserManagement>(); } return m_UserMan; } } /// <summary> /// Used to cache lookups for valid groups. /// </summary> private IDictionary<UUID, bool> m_validGroupUuids = new Dictionary<UUID, bool>(); private IGroupsModule m_groupsModule; private IAssetService m_assetService = null; private UUID m_defaultUser; public ArchiveReadRequest(Scene scene, string loadPath, Guid requestId, Dictionary<string, object> options) { m_rootScene = scene; if (options.ContainsKey("default-user")) { m_defaultUser = (UUID)options["default-user"]; m_log.InfoFormat("Using User {0} as default user", m_defaultUser.ToString()); } else { m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner; } m_loadPath = loadPath; 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 = options.ContainsKey("merge"); m_forceTerrain = options.ContainsKey("force-terrain"); m_forceParcels = options.ContainsKey("force-parcels"); m_noObjects = options.ContainsKey("no-objects"); m_skipAssets = options.ContainsKey("skipAssets"); m_requestId = requestId; m_displacement = options.ContainsKey("displacement") ? (Vector3)options["displacement"] : Vector3.Zero; m_rotation = options.ContainsKey("rotation") ? (float)options["rotation"] : 0f; m_boundingOrigin = Vector3.Zero; m_boundingSize = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, float.MaxValue); if (options.ContainsKey("bounding-origin")) { Vector3 boOption = (Vector3)options["bounding-origin"]; if (boOption != m_boundingOrigin) { m_boundingOrigin = boOption; } m_boundingBox = true; } if (options.ContainsKey("bounding-size")) { Vector3 bsOption = (Vector3)options["bounding-size"]; bool clip = false; if (bsOption.X <= 0 || bsOption.X > m_boundingSize.X) { bsOption.X = m_boundingSize.X; clip = true; } if (bsOption.Y <= 0 || bsOption.Y > m_boundingSize.Y) { bsOption.Y = m_boundingSize.Y; clip = true; } if (bsOption != m_boundingSize) { m_boundingSize = bsOption; m_boundingBox = true; } if (clip) m_log.InfoFormat("[ARCHIVER]: The bounding cube specified is larger than the destination region! Clipping to {0}.", m_boundingSize.ToString()); } m_debug = options.ContainsKey("debug"); // Zero can never be a valid user id (or group) m_validUserUuids[UUID.Zero] = false; m_validGroupUuids[UUID.Zero] = false; m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>(); m_assetService = m_rootScene.AssetService; } public ArchiveReadRequest(Scene scene, Stream loadStream, Guid requestId, Dictionary<string, object> options) { m_rootScene = scene; m_loadPath = null; m_loadStream = loadStream; m_skipAssets = options.ContainsKey("skipAssets"); m_merge = options.ContainsKey("merge"); m_requestId = requestId; m_defaultUser = scene.RegionInfo.EstateSettings.EstateOwner; // Zero can never be a valid user id m_validUserUuids[UUID.Zero] = false; m_groupsModule = m_rootScene.RequestModuleInterface<IGroupsModule>(); m_assetService = m_rootScene.AssetService; } /// <summary> /// Dearchive the region embodied in this request. /// </summary> public void DearchiveRegion() { DearchiveRegion(true); } public void DearchiveRegion(bool shouldStartScripts) { int successfulAssetRestores = 0; int failedAssetRestores = 0; DearchiveScenesInfo dearchivedScenes; // We dearchive all the scenes at once, because the files in the TAR archive might be mixed. // Therefore, we have to keep track of the dearchive context of all the scenes. Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>(); string fullPath = "NONE"; TarArchiveReader archive = null; byte[] data; TarArchiveReader.TarEntryType entryType; try { FindAndLoadControlFile(out archive, out dearchivedScenes); while ((data = archive.ReadEntry(out fullPath, out entryType)) != null) { //m_log.DebugFormat( // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType) continue; // Find the scene that this file belongs to Scene scene; string filePath; if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath)) continue; // this file belongs to a region that we're not loading DearchiveContext sceneContext = null; if (scene != null) { if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext)) { sceneContext = new DearchiveContext(scene); sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext); } } // Process the file if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH) && !m_noObjects) { sceneContext.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 (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH) && (!m_merge || m_forceTerrain)) { LoadTerrain(scene, filePath, data); } else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH)) { LoadRegionSettings(scene, filePath, data, dearchivedScenes); } else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH) && (!m_merge || m_forceParcels)) { sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data)); } else if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { // Ignore, because we already read the control file } } //m_log.Debug("[ARCHIVER]: Reached end of archive"); } catch (Exception e) { m_log.Error( String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e); m_errorMessage += e.ToString(); m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage); return; } finally { if (archive != null) 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); } } foreach (DearchiveContext sceneContext in sceneContexts.Values) { m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName); if (!m_merge) { m_log.Info("[ARCHIVER]: Clearing all existing scene objects"); sceneContext.Scene.DeleteAllSceneObjects(); } try { LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels); LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects); // Inform any interested parties that the region has changed. We waited until now so that all // of the region's objects will be loaded when we send this notification. IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>(); if (estateModule != null) estateModule.TriggerRegionInfoChange(); } catch (Exception e) { m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e); m_errorMessage += e.ToString(); m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage); return; } } // Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so // that users can enter the scene. If we allow the scripts to start in the loop above // then they significantly increase the time until the OAR finishes loading. if (shouldStartScripts) { WorkManager.RunInThread(o => { Thread.Sleep(15000); m_log.Info("[ARCHIVER]: Starting scripts in scene objects..."); foreach (DearchiveContext sceneContext in sceneContexts.Values) { foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects) { sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart sceneObject.ResumeScripts(); } sceneContext.SceneObjects.Clear(); } m_log.Info("[ARCHIVER]: Start scripts done"); }, null, string.Format("ReadArchiveStartScripts (request {0})", m_requestId)); } m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive"); m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, dearchivedScenes.GetLoadedScenes(), m_errorMessage); } /// <summary> /// Searches through the files in the archive for the control file, and reads it. /// We must read the control file first, in order to know which regions are available. /// </summary> /// <remarks> /// In most cases the control file *is* first, since that's how we create archives. However, /// it's possible that someone rewrote the archive externally so we can't rely on this fact. /// </remarks> /// <param name="archive"></param> /// <param name="dearchivedScenes"></param> private void FindAndLoadControlFile(out TarArchiveReader archive, out DearchiveScenesInfo dearchivedScenes) { archive = new TarArchiveReader(m_loadStream); dearchivedScenes = new DearchiveScenesInfo(); string filePath; byte[] data; TarArchiveReader.TarEntryType entryType; bool firstFile = true; while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType) continue; if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data, dearchivedScenes); // Find which scenes are available in the simulator ArchiveScenesGroup simulatorScenes = new ArchiveScenesGroup(); SceneManager.Instance.ForEachScene(delegate(Scene scene2) { simulatorScenes.AddScene(scene2); }); simulatorScenes.CalcSceneLocations(); dearchivedScenes.SetSimulatorScenes(m_rootScene, simulatorScenes); // If the control file wasn't the first file then reset the read pointer if (!firstFile) { m_log.Warn("[ARCHIVER]: Control file wasn't the first file in the archive"); if (m_loadStream.CanSeek) { m_loadStream.Seek(0, SeekOrigin.Begin); } else if (m_loadPath != null) { archive.Close(); archive = null; m_loadStream.Close(); m_loadStream = null; m_loadStream = new GZipStream(ArchiveHelpers.GetStream(m_loadPath), CompressionMode.Decompress); archive = new TarArchiveReader(m_loadStream); } else { // There isn't currently a scenario where this happens, but it's best to add a check just in case throw new Exception("[ARCHIVER]: Error reading archive: control file wasn't the first file, and the input stream doesn't allow seeking"); } } return; } firstFile = false; } throw new Exception("[ARCHIVER]: Control file not found"); } /// <summary> /// Load serialized scene objects. /// </summary> protected void LoadObjects(Scene scene, List<string> serialisedSceneObjects, List<SceneObjectGroup> sceneObjects) { // Reload serialized prims m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count); // Convert rotation to radians double rotation = Math.PI * m_rotation / 180f; OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, (float)rotation); UUID oldTelehubUUID = scene.RegionInfo.RegionSettings.TelehubObject; IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>(); int sceneObjectsLoadedCount = 0; Vector3 boundingExtent = new Vector3(m_boundingOrigin.X + m_boundingSize.X, m_boundingOrigin.Y + m_boundingSize.Y, m_boundingOrigin.Z + m_boundingSize.Z); 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); Vector3 pos = sceneObject.AbsolutePosition; if (m_debug) m_log.DebugFormat("[ARCHIVER]: Loading object from OAR with original scene position {0}.", pos.ToString()); // Happily this does not do much to the object since it hasn't been added to the scene yet if (!sceneObject.IsAttachment) { if (m_rotation != 0f) { //fix the rotation center to the middle of the incoming region now as it's otherwise hopelessly confusing on varRegions //as it only works with objects and terrain (using old Merge method) and not parcels m_rotationCenter.X = m_incomingRegionSize.X / 2; m_rotationCenter.Y = m_incomingRegionSize.Y / 2; // Rotate the object sceneObject.RootPart.RotationOffset = rot * sceneObject.GroupRotation; // Get object position relative to rotation axis Vector3 offset = pos - m_rotationCenter; // Rotate the object position offset *= rot; // Restore the object position back to relative to the region pos = m_rotationCenter + offset; if (m_debug) m_log.DebugFormat("[ARCHIVER]: After rotation, object from OAR is at scene position {0}.", pos.ToString()); } if (m_boundingBox) { if (pos.X < m_boundingOrigin.X || pos.X >= boundingExtent.X || pos.Y < m_boundingOrigin.Y || pos.Y >= boundingExtent.Y || pos.Z < m_boundingOrigin.Z || pos.Z >= boundingExtent.Z) { if (m_debug) m_log.DebugFormat("[ARCHIVER]: Skipping object from OAR in scene because it's position {0} is outside of bounding cube.", pos.ToString()); continue; } //adjust object position to be relative to <0,0> so we can apply the displacement pos.X -= m_boundingOrigin.X; pos.Y -= m_boundingOrigin.Y; } if (m_displacement != Vector3.Zero) { pos += m_displacement; if (m_debug) m_log.DebugFormat("[ARCHIVER]: After displacement, object from OAR is at scene position {0}.", pos.ToString()); } sceneObject.AbsolutePosition = pos; } if (m_debug) m_log.DebugFormat("[ARCHIVER]: Placing object from OAR in scene at position {0}. ", pos.ToString()); bool isTelehub = (sceneObject.UUID == oldTelehubUUID) && (oldTelehubUUID != UUID.Zero); // 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(); if (isTelehub) { // Change the Telehub Object to the new UUID scene.RegionInfo.RegionSettings.TelehubObject = sceneObject.UUID; scene.RegionInfo.RegionSettings.Save(); oldTelehubUUID = UUID.Zero; } ModifySceneObject(scene, sceneObject); if (scene.AddRestoredSceneObject(sceneObject, true, false)) { sceneObjectsLoadedCount++; sceneObject.CreateScriptInstances(0, false, 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 or were out of bounds", ignoredObjects); if (oldTelehubUUID != UUID.Zero) { m_log.WarnFormat("[ARCHIVER]: Telehub object not found: {0}", oldTelehubUUID); scene.RegionInfo.RegionSettings.TelehubObject = UUID.Zero; scene.RegionInfo.RegionSettings.ClearSpawnPoints(); } } /// <summary> /// Optionally modify a loaded SceneObjectGroup. Currently this just ensures that the /// User IDs and Group IDs are valid, but other manipulations could be done as well. /// </summary> private void ModifySceneObject(Scene scene, SceneObjectGroup sceneObject) { // Try to retain the original creator/owner/lastowner if their uuid is present on this grid // or creator data is present. Otherwise, use the estate owner instead. foreach (SceneObjectPart part in sceneObject.Parts) { if (string.IsNullOrEmpty(part.CreatorData)) { if (!ResolveUserUuid(scene, part.CreatorID)) part.CreatorID = m_defaultUser; } if (UserManager != null) UserManager.AddUser(part.CreatorID, part.CreatorData); if (!(ResolveUserUuid(scene, part.OwnerID) || ResolveGroupUuid(part.OwnerID))) part.OwnerID = m_defaultUser; if (!(ResolveUserUuid(scene, part.LastOwnerID) || ResolveGroupUuid(part.LastOwnerID))) part.LastOwnerID = m_defaultUser; if (!ResolveGroupUuid(part.GroupID)) part.GroupID = UUID.Zero; // 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) { /* avination code disabled for opensim // 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 part.TaskInventory.LockItemsForRead(true); TaskInventoryDictionary inv = part.TaskInventory; foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv) { if (!(ResolveUserUuid(scene, kvp.Value.OwnerID) || ResolveGroupUuid(kvp.Value.OwnerID))) { kvp.Value.OwnerID = m_defaultUser; } if (string.IsNullOrEmpty(kvp.Value.CreatorData)) { if (!ResolveUserUuid(scene, kvp.Value.CreatorID)) kvp.Value.CreatorID = m_defaultUser; } if (UserManager != null) UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData); if (!ResolveGroupUuid(kvp.Value.GroupID)) kvp.Value.GroupID = UUID.Zero; } part.TaskInventory.LockItemsForRead(false); } } } /// <summary> /// Load serialized parcels. /// </summary> /// <param name="scene"></param> /// <param name="serialisedParcels"></param> protected void LoadParcels(Scene scene, List<string> serialisedParcels) { // Reload serialized parcels m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count); List<LandData> landData = new List<LandData>(); ILandObject landObject = scene.RequestModuleInterface<ILandObject>(); List<ILandObject> parcels; Vector3 parcelDisp = new Vector3(m_displacement.X, m_displacement.Y, 0f); Vector2 displacement = new Vector2(m_displacement.X, m_displacement.Y); Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y); Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y); Vector2 regionSize = new Vector2(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY); // Gather any existing parcels before we add any more. Later as we add parcels we can check if the new parcel // data overlays any of the old data, and we can modify and remove (if empty) the old parcel so that there's no conflict parcels = scene.LandChannel.AllParcels(); foreach (string serialisedParcel in serialisedParcels) { LandData parcel = LandDataSerializer.Deserialize(serialisedParcel); bool overrideRegionSize = true; //use the src land parcel data size not the dst region size bool isEmptyNow; Vector3 AABBMin; Vector3 AABBMax; // create a new LandObject that we can use to manipulate the incoming source parcel data // this is ok, but just beware that some of the LandObject functions (that we haven't used here) still // assume we're always using the destination region size LandData ld = new LandData(); landObject = new LandObject(ld, scene); landObject.LandData = parcel; bool[,] srcLandBitmap = landObject.ConvertBytesToLandBitmap(overrideRegionSize); if (landObject.IsLandBitmapEmpty(srcLandBitmap)) { m_log.InfoFormat("[ARCHIVER]: Skipping source parcel {0} with GlobalID: {1} LocalID: {2} that has no claimed land.", parcel.Name, parcel.GlobalID, parcel.LocalID); continue; } //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for source parcel: {0} with GlobalID: {1} LocalID: {2}.", // parcel.Name, parcel.GlobalID, parcel.LocalID); //landObject.DebugLandBitmap(srcLandBitmap); bool[,] dstLandBitmap = landObject.RemapLandBitmap(srcLandBitmap, displacement, m_rotation, boundingOrigin, boundingSize, regionSize, out isEmptyNow, out AABBMin, out AABBMax); if (isEmptyNow) { m_log.WarnFormat("[ARCHIVER]: Not adding destination parcel {0} with GlobalID: {1} LocalID: {2} because, after applying rotation, bounding and displacement, it has no claimed land.", parcel.Name, parcel.GlobalID, parcel.LocalID); continue; } //m_log.DebugFormat("[ARCHIVER]: Showing claimed land for destination parcel: {0} with GlobalID: {1} LocalID: {2} after applying rotation, bounding and displacement.", // parcel.Name, parcel.GlobalID, parcel.LocalID); //landObject.DebugLandBitmap(dstLandBitmap); landObject.LandBitmap = dstLandBitmap; parcel.Bitmap = landObject.ConvertLandBitmapToBytes(); parcel.AABBMin = AABBMin; parcel.AABBMax = AABBMax; if (m_merge) { // give the remapped parcel a new GlobalID, in case we're using the same OAR twice and a bounding cube, displacement and --merge parcel.GlobalID = UUID.Random(); //now check if the area of this new incoming parcel overlays an area in any existing parcels //and if so modify or lose the existing parcels for (int i = 0; i < parcels.Count; i++) { if (parcels[i] != null) { bool[,] modLandBitmap = parcels[i].ConvertBytesToLandBitmap(overrideRegionSize); modLandBitmap = parcels[i].RemoveFromLandBitmap(modLandBitmap, dstLandBitmap, out isEmptyNow, out AABBMin, out AABBMax); if (isEmptyNow) { parcels[i] = null; } else { parcels[i].LandBitmap = modLandBitmap; parcels[i].LandData.Bitmap = parcels[i].ConvertLandBitmapToBytes(); parcels[i].LandData.AABBMin = AABBMin; parcels[i].LandData.AABBMax = AABBMax; } } } } // Validate User and Group UUID's if (!ResolveGroupUuid(parcel.GroupID)) parcel.GroupID = UUID.Zero; if (parcel.IsGroupOwned) { if (parcel.GroupID != UUID.Zero) { // In group-owned parcels, OwnerID=GroupID. This should already be the case, but let's make sure. parcel.OwnerID = parcel.GroupID; } else { parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner; parcel.IsGroupOwned = false; } } else { if (!ResolveUserUuid(scene, parcel.OwnerID)) parcel.OwnerID = m_rootScene.RegionInfo.EstateSettings.EstateOwner; } List<LandAccessEntry> accessList = new List<LandAccessEntry>(); foreach (LandAccessEntry entry in parcel.ParcelAccessList) { if (ResolveUserUuid(scene, entry.AgentID)) accessList.Add(entry); // else, drop this access rule } parcel.ParcelAccessList = accessList; if (m_debug) m_log.DebugFormat("[ARCHIVER]: Adding parcel {0}, local id {1}, owner {2}, group {3}, isGroupOwned {4}, area {5}", parcel.Name, parcel.LocalID, parcel.OwnerID, parcel.GroupID, parcel.IsGroupOwned, parcel.Area); landData.Add(parcel); } if (m_merge) { for (int i = 0; i < parcels.Count; i++) //if merging then we need to also add back in any existing parcels { if (parcels[i] != null) landData.Add(parcels[i].LandData); } } m_log.InfoFormat("[ARCHIVER]: Clearing {0} parcels.", parcels.Count); bool setupDefaultParcel = (landData.Count == 0); scene.LandChannel.Clear(setupDefaultParcel); scene.EventManager.TriggerIncomingLandDataFromStorage(landData); m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count); } /// <summary> /// Look up the given user id to check whether it's one that is valid for this grid. /// </summary> /// <param name="scene"></param> /// <param name="uuid"></param> /// <returns></returns> private bool ResolveUserUuid(Scene scene, UUID uuid) { lock (m_validUserUuids) { if (!m_validUserUuids.ContainsKey(uuid)) { // Note: we call GetUserAccount() inside the lock because this UserID is likely // to occur many times, and we only want to query the users service once. UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, uuid); m_validUserUuids.Add(uuid, account != null); } return m_validUserUuids[uuid]; } } /// <summary> /// Look up the given group id to check whether it's one that is valid for this grid. /// </summary> /// <param name="uuid"></param> /// <returns></returns> private bool ResolveGroupUuid(UUID uuid) { lock (m_validGroupUuids) { if (!m_validGroupUuids.ContainsKey(uuid)) { bool exists; if (m_groupsModule == null) { exists = false; } else { // Note: we call GetGroupRecord() inside the lock because this GroupID is likely // to occur many times, and we only want to query the groups service once. exists = (m_groupsModule.GetGroupRecord(uuid) != null); } m_validGroupUuids.Add(uuid, exists); } return m_validGroupUuids[uuid]; } } /// 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 (m_assetService.GetMetadata(uuid) != null) { sbyte asype = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; // m_log.DebugFormat("[ARCHIVER]: found existing asset {0}",uuid); return true; } 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); } else if (assetType == (sbyte)AssetType.Object) { data = SceneObjectSerializer.ModifySerializedObject(UUID.Parse(uuid), data, sog => { ModifySceneObject(m_rootScene, sog); return true; }); if (data == null) return false; } //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_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="scene"></param> /// <param name="settingsPath"></param> /// <param name="data"></param> /// <param name="dearchivedScenes"></param> /// <returns> /// true if settings were loaded successfully, false otherwise /// </returns> private bool LoadRegionSettings(Scene scene, string settingsPath, byte[] data, DearchiveScenesInfo dearchivedScenes) { 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 = 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.SunPosition = loadedRegionSettings.SunPosition; 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.TelehubObject = loadedRegionSettings.TelehubObject; currentRegionSettings.ClearSpawnPoints(); foreach (SpawnPoint sp in loadedRegionSettings.SpawnPoints()) currentRegionSettings.AddSpawnPoint(sp); currentRegionSettings.LoadedCreationDateTime = dearchivedScenes.LoadedCreationDateTime; currentRegionSettings.LoadedCreationID = dearchivedScenes.GetOriginalRegionID(scene.RegionInfo.RegionID).ToString(); currentRegionSettings.Save(); scene.TriggerEstateSunUpdate(); IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); if (estateModule != null) estateModule.sendRegionHandshakeToAll(); return true; } /// <summary> /// Load terrain data /// </summary> /// <param name="scene"></param> /// <param name="terrainPath"></param> /// <param name="data"></param> /// <returns> /// true if terrain was resolved successfully, false otherwise. /// </returns> private bool LoadTerrain(Scene scene, string terrainPath, byte[] data) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); using (MemoryStream ms = new MemoryStream(data)) { if (m_displacement != Vector3.Zero || m_rotation != 0f || m_boundingBox) { Vector2 boundingOrigin = new Vector2(m_boundingOrigin.X, m_boundingOrigin.Y); Vector2 boundingSize = new Vector2(m_boundingSize.X, m_boundingSize.Y); terrainModule.LoadFromStream(terrainPath, m_displacement, m_rotation, boundingOrigin, boundingSize, ms); ; } else { terrainModule.LoadFromStream(terrainPath, ms); } } m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath); return true; } /// <summary> /// Load oar control file /// </summary> /// <param name="path"></param> /// <param name="data"></param> /// <param name="dearchivedScenes"></param> public DearchiveScenesInfo LoadControlFile(string path, byte[] data, DearchiveScenesInfo dearchivedScenes) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context); // Loaded metadata will be empty if no information exists in the archive dearchivedScenes.LoadedCreationDateTime = 0; dearchivedScenes.DefaultOriginalID = ""; bool multiRegion = false; while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Element) { if (xtr.Name.ToString() == "archive") { int majorVersion = int.Parse(xtr["major_version"]); int minorVersion = int.Parse(xtr["minor_version"]); string version = string.Format("{0}.{1}", majorVersion, minorVersion); if (majorVersion > MAX_MAJOR_VERSION) { throw new Exception( string.Format( "The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below", majorVersion, MAX_MAJOR_VERSION)); } m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version); } else if (xtr.Name.ToString() == "datetime") { int value; if (Int32.TryParse(xtr.ReadElementContentAsString(), out value)) dearchivedScenes.LoadedCreationDateTime = value; } else if (xtr.Name.ToString() == "row") { multiRegion = true; dearchivedScenes.StartRow(); } else if (xtr.Name.ToString() == "region") { dearchivedScenes.StartRegion(); } else if (xtr.Name.ToString() == "id") { string id = xtr.ReadElementContentAsString(); dearchivedScenes.DefaultOriginalID = id; if(multiRegion) dearchivedScenes.SetRegionOriginalID(id); } else if (xtr.Name.ToString() == "dir") { dearchivedScenes.SetRegionDirectory(xtr.ReadElementContentAsString()); } else if (xtr.Name.ToString() == "size_in_meters") { Vector3 value; string size = "<" + xtr.ReadElementContentAsString() + ",0>"; if (Vector3.TryParse(size, out value)) { m_incomingRegionSize = value; if(multiRegion) dearchivedScenes.SetRegionSize(m_incomingRegionSize); m_log.DebugFormat("[ARCHIVER]: Found region_size info {0}", m_incomingRegionSize.ToString()); } } } } dearchivedScenes.MultiRegionFormat = multiRegion; if (!multiRegion) { // Add the single scene dearchivedScenes.StartRow(); dearchivedScenes.StartRegion(); dearchivedScenes.SetRegionOriginalID(dearchivedScenes.DefaultOriginalID); dearchivedScenes.SetRegionDirectory(""); dearchivedScenes.SetRegionSize(m_incomingRegionSize); } ControlFileLoaded = true; if(xtr != null) xtr.Close(); return dearchivedScenes; } } }
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // 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 was automatically generated and should not be edited directly. using System; namespace SharpVk { /// <summary> /// Opaque handle to a instance object. /// </summary> public partial class Instance : IProcLookup, IDisposable { internal readonly SharpVk.Interop.Instance handle; internal readonly CommandCache commandCache; internal Instance(CommandCache commandCache, SharpVk.Interop.Instance handle) { this.handle = handle; this.commandCache = new CommandCache(this, "instance", commandCache); this.commandCache.Initialise(); } /// <summary> /// The raw handle for this instance. /// </summary> public SharpVk.Interop.Instance RawHandle => this.handle; /// <summary> /// Create a new Vulkan instance. /// </summary> /// <param name="commandCache"> /// </param> /// <param name="flags"> /// Reserved for future use. /// </param> /// <param name="applicationInfo"> /// Null or an instance of ApplicationInfo. If not Null, this /// information helps implementations recognize behavior inherent to /// classes of applications. ApplicationInfo is defined in detail /// below. /// </param> /// <param name="enabledLayerNames"> /// An array of enabledLayerCount strings containing the names of /// layers to enable for the created instance. See the Layers section /// for further details. /// </param> /// <param name="enabledExtensionNames"> /// An array of enabledExtensionCount strings containing the names of /// extensions to enable. /// </param> /// <param name="debugReportCallbackCreateInfoExt"> /// Extension struct /// </param> /// <param name="validationFlagsExt"> /// Extension struct /// </param> /// <param name="validationFeaturesExt"> /// Extension struct /// </param> /// <param name="debugUtilsMessengerCreateInfoExt"> /// Extension struct /// </param> /// <param name="allocator"> /// An optional AllocationCallbacks instance that controls host memory /// allocation. /// </param> public static unsafe SharpVk.Instance Create(CommandCache commandCache, ArrayProxy<string>? enabledLayerNames, ArrayProxy<string>? enabledExtensionNames, SharpVk.InstanceCreateFlags? flags = default(SharpVk.InstanceCreateFlags?), SharpVk.ApplicationInfo? applicationInfo = default(SharpVk.ApplicationInfo?), SharpVk.Multivendor.DebugReportCallbackCreateInfo? debugReportCallbackCreateInfoExt = null, SharpVk.Multivendor.ValidationFlags? validationFlagsExt = null, SharpVk.Multivendor.ValidationFeatures? validationFeaturesExt = null, SharpVk.Multivendor.DebugUtilsMessengerCreateInfo? debugUtilsMessengerCreateInfoExt = null, SharpVk.AllocationCallbacks? allocator = default(SharpVk.AllocationCallbacks?)) { try { SharpVk.Instance result = default(SharpVk.Instance); SharpVk.Interop.InstanceCreateInfo* marshalledCreateInfo = default(SharpVk.Interop.InstanceCreateInfo*); void* vkInstanceCreateInfoNextPointer = default(void*); SharpVk.Interop.AllocationCallbacks* marshalledAllocator = default(SharpVk.Interop.AllocationCallbacks*); SharpVk.Interop.Instance marshalledInstance = default(SharpVk.Interop.Instance); if (debugReportCallbackCreateInfoExt != null) { SharpVk.Interop.Multivendor.DebugReportCallbackCreateInfo* extensionPointer = default(SharpVk.Interop.Multivendor.DebugReportCallbackCreateInfo*); extensionPointer = (SharpVk.Interop.Multivendor.DebugReportCallbackCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Multivendor.DebugReportCallbackCreateInfo>()); debugReportCallbackCreateInfoExt.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkInstanceCreateInfoNextPointer; vkInstanceCreateInfoNextPointer = extensionPointer; } if (validationFlagsExt != null) { SharpVk.Interop.Multivendor.ValidationFlags* extensionPointer = default(SharpVk.Interop.Multivendor.ValidationFlags*); extensionPointer = (SharpVk.Interop.Multivendor.ValidationFlags*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Multivendor.ValidationFlags>()); validationFlagsExt.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkInstanceCreateInfoNextPointer; vkInstanceCreateInfoNextPointer = extensionPointer; } if (validationFeaturesExt != null) { SharpVk.Interop.Multivendor.ValidationFeatures* extensionPointer = default(SharpVk.Interop.Multivendor.ValidationFeatures*); extensionPointer = (SharpVk.Interop.Multivendor.ValidationFeatures*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Multivendor.ValidationFeatures>()); validationFeaturesExt.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkInstanceCreateInfoNextPointer; vkInstanceCreateInfoNextPointer = extensionPointer; } if (debugUtilsMessengerCreateInfoExt != null) { SharpVk.Interop.Multivendor.DebugUtilsMessengerCreateInfo* extensionPointer = default(SharpVk.Interop.Multivendor.DebugUtilsMessengerCreateInfo*); extensionPointer = (SharpVk.Interop.Multivendor.DebugUtilsMessengerCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Multivendor.DebugUtilsMessengerCreateInfo>()); debugUtilsMessengerCreateInfoExt.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkInstanceCreateInfoNextPointer; vkInstanceCreateInfoNextPointer = extensionPointer; } marshalledCreateInfo = (SharpVk.Interop.InstanceCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.InstanceCreateInfo>()); marshalledCreateInfo->SType = StructureType.InstanceCreateInfo; marshalledCreateInfo->Next = vkInstanceCreateInfoNextPointer; if (flags != null) { marshalledCreateInfo->Flags = flags.Value; } else { marshalledCreateInfo->Flags = default(SharpVk.InstanceCreateFlags); } if (applicationInfo != null) { marshalledCreateInfo->ApplicationInfo = (SharpVk.Interop.ApplicationInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.ApplicationInfo>()); applicationInfo.Value.MarshalTo(marshalledCreateInfo->ApplicationInfo); } else { marshalledCreateInfo->ApplicationInfo = default(SharpVk.Interop.ApplicationInfo*); } marshalledCreateInfo->EnabledLayerCount = (uint)(Interop.HeapUtil.GetLength(enabledLayerNames)); marshalledCreateInfo->EnabledLayerNames = Interop.HeapUtil.MarshalTo(enabledLayerNames); marshalledCreateInfo->EnabledExtensionCount = (uint)(Interop.HeapUtil.GetLength(enabledExtensionNames)); marshalledCreateInfo->EnabledExtensionNames = Interop.HeapUtil.MarshalTo(enabledExtensionNames); if (allocator != null) { marshalledAllocator = (SharpVk.Interop.AllocationCallbacks*)(Interop.HeapUtil.Allocate<SharpVk.Interop.AllocationCallbacks>()); allocator.Value.MarshalTo(marshalledAllocator); } else { marshalledAllocator = default(SharpVk.Interop.AllocationCallbacks*); } SharpVk.Interop.VkInstanceCreateDelegate commandDelegate = commandCache.Cache.vkCreateInstance; Result methodResult = commandDelegate(marshalledCreateInfo, marshalledAllocator, &marshalledInstance); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } result = new SharpVk.Instance(commandCache, marshalledInstance); return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Destroy an instance of Vulkan. /// </summary> /// <param name="allocator"> /// An optional AllocationCallbacks instance that controls host memory /// allocation. /// </param> public unsafe void Destroy(SharpVk.AllocationCallbacks? allocator = default(SharpVk.AllocationCallbacks?)) { try { SharpVk.Interop.AllocationCallbacks* marshalledAllocator = default(SharpVk.Interop.AllocationCallbacks*); if (allocator != null) { marshalledAllocator = (SharpVk.Interop.AllocationCallbacks*)(Interop.HeapUtil.Allocate<SharpVk.Interop.AllocationCallbacks>()); allocator.Value.MarshalTo(marshalledAllocator); } else { marshalledAllocator = default(SharpVk.Interop.AllocationCallbacks*); } SharpVk.Interop.VkInstanceDestroyDelegate commandDelegate = commandCache.Cache.vkDestroyInstance; commandDelegate(this.handle, marshalledAllocator); } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Enumerates the physical devices accessible to a Vulkan instance. /// </summary> public unsafe SharpVk.PhysicalDevice[] EnumeratePhysicalDevices() { try { SharpVk.PhysicalDevice[] result = default(SharpVk.PhysicalDevice[]); uint marshalledPhysicalDeviceCount = default(uint); SharpVk.Interop.PhysicalDevice* marshalledPhysicalDevices = default(SharpVk.Interop.PhysicalDevice*); SharpVk.Interop.VkInstanceEnumeratePhysicalDevicesDelegate commandDelegate = commandCache.Cache.vkEnumeratePhysicalDevices; Result methodResult = commandDelegate(this.handle, &marshalledPhysicalDeviceCount, marshalledPhysicalDevices); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } marshalledPhysicalDevices = (SharpVk.Interop.PhysicalDevice*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PhysicalDevice>((uint)(marshalledPhysicalDeviceCount))); commandDelegate(this.handle, &marshalledPhysicalDeviceCount, marshalledPhysicalDevices); if (marshalledPhysicalDevices != null) { var fieldPointer = new SharpVk.PhysicalDevice[(uint)(marshalledPhysicalDeviceCount)]; for(int index = 0; index < (uint)(marshalledPhysicalDeviceCount); index++) { fieldPointer[index] = new SharpVk.PhysicalDevice(this, marshalledPhysicalDevices[index]); } result = fieldPointer; } else { result = null; } return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Return a function pointer for a command. /// </summary> /// <param name="name"> /// </param> public unsafe IntPtr GetProcedureAddress(string name) { try { IntPtr result = default(IntPtr); SharpVk.Interop.VkInstanceGetProcedureAddressDelegate commandDelegate = commandCache.Cache.vkGetInstanceProcAddr; result = commandDelegate(this.handle, Interop.HeapUtil.MarshalTo(name)); return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Returns up to requested number of global extension properties. /// </summary> /// <param name="commandCache"> /// </param> /// <param name="layerName"> /// </param> public static unsafe SharpVk.ExtensionProperties[] EnumerateExtensionProperties(CommandCache commandCache, string layerName) { try { SharpVk.ExtensionProperties[] result = default(SharpVk.ExtensionProperties[]); uint marshalledPropertyCount = default(uint); SharpVk.Interop.ExtensionProperties* marshalledProperties = default(SharpVk.Interop.ExtensionProperties*); SharpVk.Interop.VkInstanceEnumerateExtensionPropertiesDelegate commandDelegate = commandCache.Cache.vkEnumerateInstanceExtensionProperties; Result methodResult = commandDelegate(Interop.HeapUtil.MarshalTo(layerName), &marshalledPropertyCount, marshalledProperties); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } marshalledProperties = (SharpVk.Interop.ExtensionProperties*)(Interop.HeapUtil.Allocate<SharpVk.Interop.ExtensionProperties>((uint)(marshalledPropertyCount))); commandDelegate(Interop.HeapUtil.MarshalTo(layerName), &marshalledPropertyCount, marshalledProperties); if (marshalledProperties != null) { var fieldPointer = new SharpVk.ExtensionProperties[(uint)(marshalledPropertyCount)]; for(int index = 0; index < (uint)(marshalledPropertyCount); index++) { fieldPointer[index] = SharpVk.ExtensionProperties.MarshalFrom(&marshalledProperties[index]); } result = fieldPointer; } else { result = null; } return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Returns up to requested number of global layer properties. /// </summary> /// <param name="commandCache"> /// </param> public static unsafe SharpVk.LayerProperties[] EnumerateLayerProperties(CommandCache commandCache) { try { SharpVk.LayerProperties[] result = default(SharpVk.LayerProperties[]); uint marshalledPropertyCount = default(uint); SharpVk.Interop.LayerProperties* marshalledProperties = default(SharpVk.Interop.LayerProperties*); SharpVk.Interop.VkInstanceEnumerateLayerPropertiesDelegate commandDelegate = commandCache.Cache.vkEnumerateInstanceLayerProperties; Result methodResult = commandDelegate(&marshalledPropertyCount, marshalledProperties); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } marshalledProperties = (SharpVk.Interop.LayerProperties*)(Interop.HeapUtil.Allocate<SharpVk.Interop.LayerProperties>((uint)(marshalledPropertyCount))); commandDelegate(&marshalledPropertyCount, marshalledProperties); if (marshalledProperties != null) { var fieldPointer = new SharpVk.LayerProperties[(uint)(marshalledPropertyCount)]; for(int index = 0; index < (uint)(marshalledPropertyCount); index++) { fieldPointer[index] = SharpVk.LayerProperties.MarshalFrom(&marshalledProperties[index]); } result = fieldPointer; } else { result = null; } return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// /// </summary> /// <param name="commandCache"> /// </param> public static unsafe Version EnumerateVersion(CommandCache commandCache) { try { Version result = default(Version); uint marshalledApiVersion = default(uint); SharpVk.Interop.VkInstanceEnumerateVersionDelegate commandDelegate = commandCache.Cache.vkEnumerateInstanceVersion; Result methodResult = commandDelegate(&marshalledApiVersion); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } result = (Version)(marshalledApiVersion); return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// /// </summary> public unsafe SharpVk.PhysicalDeviceGroupProperties[] EnumeratePhysicalDeviceGroups() { try { SharpVk.PhysicalDeviceGroupProperties[] result = default(SharpVk.PhysicalDeviceGroupProperties[]); uint marshalledPhysicalDeviceGroupCount = default(uint); SharpVk.Interop.PhysicalDeviceGroupProperties* marshalledPhysicalDeviceGroupProperties = default(SharpVk.Interop.PhysicalDeviceGroupProperties*); SharpVk.Interop.VkInstanceEnumeratePhysicalDeviceGroupsDelegate commandDelegate = commandCache.Cache.vkEnumeratePhysicalDeviceGroups; Result methodResult = commandDelegate(this.handle, &marshalledPhysicalDeviceGroupCount, marshalledPhysicalDeviceGroupProperties); if (SharpVkException.IsError(methodResult)) { throw SharpVkException.Create(methodResult); } marshalledPhysicalDeviceGroupProperties = (SharpVk.Interop.PhysicalDeviceGroupProperties*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PhysicalDeviceGroupProperties>((uint)(marshalledPhysicalDeviceGroupCount))); commandDelegate(this.handle, &marshalledPhysicalDeviceGroupCount, marshalledPhysicalDeviceGroupProperties); if (marshalledPhysicalDeviceGroupProperties != null) { var fieldPointer = new SharpVk.PhysicalDeviceGroupProperties[(uint)(marshalledPhysicalDeviceGroupCount)]; for(int index = 0; index < (uint)(marshalledPhysicalDeviceGroupCount); index++) { fieldPointer[index] = SharpVk.PhysicalDeviceGroupProperties.MarshalFrom(&marshalledPhysicalDeviceGroupProperties[index]); } result = fieldPointer; } else { result = null; } return result; } finally { Interop.HeapUtil.FreeAll(); } } /// <summary> /// Destroys the handles and releases any unmanaged resources /// associated with it. /// </summary> public void Dispose() { this.Destroy(); } } }
// 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_LIST_PRIORITY_SGIX symbol. /// </summary> [RequiredByFeature("GL_SGIX_list_priority")] public const int LIST_PRIORITY_SGIX = 0x8182; /// <summary> /// [GL] glGetListParameterfvSGIX: Binding for glGetListParameterfvSGIX. /// </summary> /// <param name="list"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:ListParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:float[]"/>. /// </param> [RequiredByFeature("GL_SGIX_list_priority")] public static void GetListParameterSGIX(uint list, ListParameterName pname, [Out] float[] @params) { unsafe { fixed (float* p_params = @params) { Debug.Assert(Delegates.pglGetListParameterfvSGIX != null, "pglGetListParameterfvSGIX not implemented"); Delegates.pglGetListParameterfvSGIX(list, (int)pname, p_params); LogCommand("glGetListParameterfvSGIX", null, list, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetListParameterivSGIX: Binding for glGetListParameterivSGIX. /// </summary> /// <param name="list"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:ListParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_SGIX_list_priority")] public static void GetListParameterSGIX(uint list, ListParameterName pname, [Out] int[] @params) { unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglGetListParameterivSGIX != null, "pglGetListParameterivSGIX not implemented"); Delegates.pglGetListParameterivSGIX(list, (int)pname, p_params); LogCommand("glGetListParameterivSGIX", null, list, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glListParameterfSGIX: Binding for glListParameterfSGIX. /// </summary> /// <param name="list"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:ListParameterName"/>. /// </param> /// <param name="param"> /// A <see cref="T:float"/>. /// </param> [RequiredByFeature("GL_SGIX_list_priority")] public static void ListParameterSGIX(uint list, ListParameterName pname, float param) { Debug.Assert(Delegates.pglListParameterfSGIX != null, "pglListParameterfSGIX not implemented"); Delegates.pglListParameterfSGIX(list, (int)pname, param); LogCommand("glListParameterfSGIX", null, list, pname, param ); DebugCheckErrors(null); } /// <summary> /// [GL] glListParameterfvSGIX: Binding for glListParameterfvSGIX. /// </summary> /// <param name="list"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:ListParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:float[]"/>. /// </param> [RequiredByFeature("GL_SGIX_list_priority")] public static void ListParameterSGIX(uint list, ListParameterName pname, float[] @params) { unsafe { fixed (float* p_params = @params) { Debug.Assert(Delegates.pglListParameterfvSGIX != null, "pglListParameterfvSGIX not implemented"); Delegates.pglListParameterfvSGIX(list, (int)pname, p_params); LogCommand("glListParameterfvSGIX", null, list, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glListParameteriSGIX: Binding for glListParameteriSGIX. /// </summary> /// <param name="list"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:ListParameterName"/>. /// </param> /// <param name="param"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_SGIX_list_priority")] public static void ListParameterSGIX(uint list, ListParameterName pname, int param) { Debug.Assert(Delegates.pglListParameteriSGIX != null, "pglListParameteriSGIX not implemented"); Delegates.pglListParameteriSGIX(list, (int)pname, param); LogCommand("glListParameteriSGIX", null, list, pname, param ); DebugCheckErrors(null); } /// <summary> /// [GL] glListParameterivSGIX: Binding for glListParameterivSGIX. /// </summary> /// <param name="list"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:ListParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_SGIX_list_priority")] public static void ListParameterSGIX(uint list, ListParameterName pname, int[] @params) { unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglListParameterivSGIX != null, "pglListParameterivSGIX not implemented"); Delegates.pglListParameterivSGIX(list, (int)pname, p_params); LogCommand("glListParameterivSGIX", null, list, pname, @params ); } } DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_SGIX_list_priority")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetListParameterfvSGIX(uint list, int pname, float* @params); [RequiredByFeature("GL_SGIX_list_priority")] [ThreadStatic] internal static glGetListParameterfvSGIX pglGetListParameterfvSGIX; [RequiredByFeature("GL_SGIX_list_priority")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetListParameterivSGIX(uint list, int pname, int* @params); [RequiredByFeature("GL_SGIX_list_priority")] [ThreadStatic] internal static glGetListParameterivSGIX pglGetListParameterivSGIX; [RequiredByFeature("GL_SGIX_list_priority")] [SuppressUnmanagedCodeSecurity] internal delegate void glListParameterfSGIX(uint list, int pname, float param); [RequiredByFeature("GL_SGIX_list_priority")] [ThreadStatic] internal static glListParameterfSGIX pglListParameterfSGIX; [RequiredByFeature("GL_SGIX_list_priority")] [SuppressUnmanagedCodeSecurity] internal delegate void glListParameterfvSGIX(uint list, int pname, float* @params); [RequiredByFeature("GL_SGIX_list_priority")] [ThreadStatic] internal static glListParameterfvSGIX pglListParameterfvSGIX; [RequiredByFeature("GL_SGIX_list_priority")] [SuppressUnmanagedCodeSecurity] internal delegate void glListParameteriSGIX(uint list, int pname, int param); [RequiredByFeature("GL_SGIX_list_priority")] [ThreadStatic] internal static glListParameteriSGIX pglListParameteriSGIX; [RequiredByFeature("GL_SGIX_list_priority")] [SuppressUnmanagedCodeSecurity] internal delegate void glListParameterivSGIX(uint list, int pname, int* @params); [RequiredByFeature("GL_SGIX_list_priority")] [ThreadStatic] internal static glListParameterivSGIX pglListParameterivSGIX; } } }
// ----- // Copyright 2010 Deyan Timnev // This file is part of the Matrix Platform (www.matrixplatform.com). // The Matrix Platform is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. The Matrix Platform is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License along with the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html // ----- using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using Matrix.Common.Core.Serialization; namespace Matrix.Common.Sockets.Common { /// <summary> /// Extends the communicator class with active connection capabilities. /// </summary> public class SocketClientCommunicator : SocketCommunicatorEx { EndPoint _endPoint = null; SocketAsyncEventArgs _asyncConnectArgs = null; /// <summary> /// /// </summary> public override EndPoint EndPoint { get { return _endPoint; } } Timer _autoConnectTimer; bool _autoReconnect = false; /// <summary> /// Is the client trying to auto reconnect. /// </summary> public bool AutoReconnect { get { return _autoReconnect; } set { if (_autoReconnect == value) { return; } _autoReconnect = value; lock (_syncRoot) { if (value == false && _autoConnectTimer != null) {// Release the current timer. _autoConnectTimer.Dispose(); _autoConnectTimer = null; } else if (value && _autoConnectTimer == null) {// Create new timer. _autoConnectTimer = new Timer(AutoConnectTimerCallbackMethod, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } } } } /// <summary> /// Constructor. /// </summary> public SocketClientCommunicator(ISerializer serializer) : base(serializer) { AutoReconnect = false; } /// <summary> /// Constructor. /// </summary> public SocketClientCommunicator(EndPoint endPoint, ISerializer serializer) : base(serializer) { _endPoint = endPoint; AutoReconnect = false; } public override void Dispose() { // Stop the timer, in case it is running. AutoReconnect = false; base.Dispose(); } protected void AutoConnectTimerCallbackMethod(object state) { if (_autoReconnect == false) { lock (_syncRoot) { if (_autoConnectTimer != null) { _autoConnectTimer.Dispose(); _autoConnectTimer = null; } } } if (_endPoint != null && _autoReconnect && IsConnected == false) { ConnectAsync(_endPoint); } } /// <summary> /// Begin asynchronous connect. /// </summary> /// <param name="endPoint"></param> /// <returns></returns> public bool ConnectAsync(EndPoint endPoint) { lock (_syncRoot) { if (_asyncConnectArgs != null) {// Connection in progress. return true; } } System.Net.Sockets.Socket socket = _socket; if (IsConnected) {// Already connected. if (socket != null) { try { if (socket.RemoteEndPoint.Equals(endPoint)) {// Connected to given endPoint. return true; } else {// Connected to some other endPoint ReleaseSocket(true); } } catch (Exception ex) {// socket.RemoteEndPoint can throw. ReleaseSocket(true); #if Matrix_Diagnostics Monitor.OperationError("Failed to start async connect", ex); #endif return false; } } } SocketAsyncEventArgs args; lock(_syncRoot) { if (_asyncConnectArgs != null) {// Connection in progress. return true; } _socket = new System.Net.Sockets.Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket = _socket; _asyncConnectArgs = new SocketAsyncEventArgs(); _asyncConnectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketAsyncEventArgs_Connected); _asyncConnectArgs.RemoteEndPoint = endPoint; _endPoint = endPoint; args = _asyncConnectArgs; } if (socket != null && socket.ConnectAsync(args) == false) { SocketAsyncEventArgs_Connected(this, args); } return true; } void SocketAsyncEventArgs_Connected(object sender, SocketAsyncEventArgs e) { if (e.LastOperation == SocketAsyncOperation.Connect) { if (e.SocketError == SocketError.Success) { #if Matrix_Diagnostics Monitor.ReportImportant("Socket connected."); #endif RaiseConnectedEvent(); AssignAsyncReceiveArgs(false); } else if (e.SocketError == SocketError.IsConnected) {// Already connected. // Connect failed. #if Matrix_Diagnostics Monitor.ReportImportant("Socket already connected."); #endif } else { #if Matrix_Diagnostics Monitor.ReportImportant("Socket connection failed: " + e.SocketError.ToString()); #endif } } else { // Connect failed. #if Matrix_Diagnostics Monitor.ReportImportant("Socket async connect failed."); #endif } lock (_syncRoot) { if (_asyncConnectArgs == e) { _asyncConnectArgs.Dispose(); _asyncConnectArgs = null; } else { #if Matrix_Diagnostics Monitor.Error("SocketAsyncEventArgs mismatch."); #endif e.Dispose(); _asyncConnectArgs = null; } } } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Runtime.Serialization; using System.Security; using Quartz.Collection; using Quartz.Util; namespace Quartz.Impl.Calendar { /// <summary> /// This implementation of the Calendar stores a list of holidays (full days /// that are excluded from scheduling). /// </summary> /// <remarks> /// The implementation DOES take the year into consideration, so if you want to /// exclude July 4th for the next 10 years, you need to add 10 entries to the /// exclude list. /// </remarks> /// <author>Sharada Jambula</author> /// <author>Juergen Donnerstag</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class HolidayCalendar : BaseCalendar { /// <summary> /// Returns a <see cref="ISortedSet&lt;DateTime&gt;" /> of Dates representing the excluded /// days. Only the month, day and year of the returned dates are /// significant. /// </summary> public virtual ISortedSet<DateTime> ExcludedDates { get { return new TreeSet<DateTime>(dates); } } // A sorted set to store the holidays private TreeSet<DateTime> dates = new TreeSet<DateTime>(); /// <summary> /// Initializes a new instance of the <see cref="HolidayCalendar"/> class. /// </summary> public HolidayCalendar() { } /// <summary> /// Initializes a new instance of the <see cref="HolidayCalendar"/> class. /// </summary> /// <param name="baseCalendar">The base calendar.</param> public HolidayCalendar(ICalendar baseCalendar) { CalendarBase = baseCalendar; } /// <summary> /// Serialization constructor. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected HolidayCalendar(SerializationInfo info, StreamingContext context) : base(info, context) { int version; try { version = info.GetInt32("version"); } catch { version = 0; } switch (version) { case 0: object o = info.GetValue("dates", typeof(object)); TreeSet oldTreeset = o as TreeSet; if (oldTreeset != null) { foreach (DateTime dateTime in oldTreeset) { dates.Add(dateTime); } } else { // must be generic treeset dates = (TreeSet<DateTime>) o; } break; case 1: dates = (TreeSet<DateTime>) info.GetValue("dates", typeof(TreeSet<DateTime>)); break; default: throw new NotSupportedException("Unknown serialization version"); } } [SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("version", 1); info.AddValue("dates", dates); } /// <summary> /// Determine whether the given time (in milliseconds) is 'included' by the /// Calendar. /// <para> /// Note that this Calendar is only has full-day precision. /// </para> /// </summary> public override bool IsTimeIncluded(DateTimeOffset timeStampUtc) { if (!base.IsTimeIncluded(timeStampUtc)) { return false; } //apply the timezone timeStampUtc = TimeZoneUtil.ConvertTime(timeStampUtc, this.TimeZone); DateTime lookFor = timeStampUtc.Date; return !(dates.Contains(lookFor)); } /// <summary> /// Determine the next time (in milliseconds) that is 'included' by the /// Calendar after the given time. /// <para> /// Note that this Calendar is only has full-day precision. /// </para> /// </summary> public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc) { // Call base calendar implementation first DateTimeOffset baseTime = base.GetNextIncludedTimeUtc(timeUtc); if ((timeUtc != DateTimeOffset.MinValue) && (baseTime > timeUtc)) { timeUtc = baseTime; } //apply the timezone timeUtc = TimeZoneUtil.ConvertTime(timeUtc, this.TimeZone); // Get timestamp for 00:00:00, with the correct timezone offset DateTimeOffset day = new DateTimeOffset(timeUtc.Date, timeUtc.Offset); while (!IsTimeIncluded(day)) { day = day.AddDays(1); } return day; } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> public override object Clone() { HolidayCalendar clone = (HolidayCalendar) base.Clone(); clone.dates = new TreeSet<DateTime>(dates); return clone; } /// <summary> /// Add the given Date to the list of excluded days. Only the month, day and /// year of the returned dates are significant. /// </summary> public virtual void AddExcludedDate(DateTime excludedDateUtc) { DateTime date = excludedDateUtc.Date; dates.Add(date); } /// <summary> /// Removes the excluded date. /// </summary> /// <param name="dateToRemoveUtc">The date to remove.</param> public virtual void RemoveExcludedDate(DateTime dateToRemoveUtc) { DateTime date = dateToRemoveUtc.Date; dates.Remove(date); } public override int GetHashCode() { int baseHash = 0; if (GetBaseCalendar() != null) { baseHash = GetBaseCalendar().GetHashCode(); } return ExcludedDates.GetHashCode() + 5 * baseHash; } public bool Equals(HolidayCalendar obj) { if (obj == null) { return false; } bool baseEqual = GetBaseCalendar() == null || GetBaseCalendar().Equals(obj.GetBaseCalendar()); return baseEqual && (ExcludedDates.Equals(obj.ExcludedDates)); } public override bool Equals(object obj) { if ((obj == null) || !(obj is HolidayCalendar)) { return false; } return Equals((HolidayCalendar)obj); } } }
using System; using System.Collections.Generic; using System.Text; namespace FlatRedBall.Utilities { #region XML Docs /// <summary> /// A class containing common string maniuplation methods. /// </summary> #endregion public static class StringFunctions { #region Fields static char[] sValidNumericalChars = { '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',' }; #endregion public static bool IsAscii(string stringToCheck) { bool isAscii = true; for (int i = 0; i < stringToCheck.Length; i++) { if (stringToCheck[i] > 255) { isAscii = false; break; } } return isAscii; } public static int CountOf(this string instanceToSearchIn, char characterToSearchFor) { return instanceToSearchIn.CountOf(characterToSearchFor, 0, instanceToSearchIn.Length); } public static int CountOf(this string instanceToSearchIn, char characterToSearchFor, int startIndex, int searchLength) { int count = 0; for (int i = startIndex; i < searchLength; i++) { char characterAtIndex = instanceToSearchIn[i]; if (characterAtIndex == characterToSearchFor) { count++; } } return count; } /// <summary> /// Returns the number of times that the argument whatToFind is found in the calling string. /// </summary> /// <param name="instanceToSearchIn">The string to search within.</param> /// <param name="whatToFind">The string to search for.</param> /// <returns>The number of instances found</returns> public static int CountOf(this string instanceToSearchIn, string whatToFind) { int count = 0; int index = 0; while (true) { int foundIndex = instanceToSearchIn.IndexOf(whatToFind, index); if (foundIndex != -1) { count++; index = foundIndex + 1; } else { break; } } return count; } public static bool Contains(this string[] listToInvestigate, string whatToSearchFor) { for (int i = 0; i < listToInvestigate.Length; i++) { if (listToInvestigate[i] == whatToSearchFor) { return true; } } return false; } #region XML Docs /// <summary> /// Returns the number of non-whitespace characters in the argument stringInQuestion. /// </summary> /// <remarks> /// This method is used internally by the TextManager to determine the number of vertices needed to /// draw a Text object. /// </remarks> /// <param name="stringInQuestion">The string to have its non-witespace counted.</param> /// <returns>The number of non-whitespace characters counted.</returns> #endregion public static int CharacterCountWithoutWhitespace(string stringInQuestion) { int characterCount = 0; for (int i = 0; i < stringInQuestion.Length; i++) { if (stringInQuestion[i] != ' ' && stringInQuestion[i] != '\t' && stringInQuestion[i] != '\n') characterCount++; } return characterCount; } #region XML Docs /// <summary> /// Returns a string of the float with the argument decimalsAfterPoint digits of resolution after the point. /// </summary> /// <param name="floatToConvert">The float to convert.</param> /// <param name="decimalsAfterPoint">The number of decimals after the point. For example, 3.14159 becomes "3.14" if the /// decimalsAfterPoint is 2. This method will not append extra decimals to reach the argument decimalsAfterPoint.</param> /// <returns>The string representation of the argument float.</returns> #endregion public static string FloatToString(float floatToConvert, int decimalsAfterPoint) { if (decimalsAfterPoint == 0) return ((int)floatToConvert).ToString(); else { int lengthAsInt = ((int)floatToConvert).ToString().Length; return floatToConvert.ToString().Substring( 0, System.Math.Min(floatToConvert.ToString().Length, lengthAsInt + 1 + decimalsAfterPoint)); } } #region XML Docs /// <summary> /// Returns the character that can be found after a particular sequence of characters. /// </summary> /// <remarks> /// This will return the first character following a particular sequence of characters. For example, /// GetCharAfter("bcd", "abcdef") would return 'e'. /// </remarks> /// <param name="stringToSearchFor">The string to search for.</param> /// <param name="whereToSearch">The string to search in.</param> /// <returns>Returns the character found or the null character '\0' if the string is not found.</returns> #endregion public static char GetCharAfter(string stringToSearchFor, string whereToSearch) { int indexOf = whereToSearch.IndexOf(stringToSearchFor); if (indexOf != -1) { return whereToSearch[indexOf + stringToSearchFor.Length]; } return '\0'; } public static int GetClosingCharacter(string fullString, int startIndex, char openingCharacter, char closingCharacter) { int numberofParens = 1; for (int i = startIndex; i < fullString.Length; i++) { if (fullString[i] == openingCharacter) { numberofParens++; } if (fullString[i] == closingCharacter) { numberofParens--; } if (numberofParens == 0) { return i; } } return -1; } public static int GetDigitCount(double x) { // Written by Kao Martin 12/6/2008 int count = 1; double diff = x - System.Math.Floor(x); while ((x /= 10.0d) > 1.0d) { count++; } if (diff > 0) { count++; while ((diff *= 10.0d) > 1.0d) { count++; diff -= System.Math.Floor(diff); } } return count; } #region XML Docs /// <summary> /// Returns the float that can be found after a particular sequence of characters. /// </summary> /// <remarks> /// This will return the float following a particular sequence of characters. For example, /// GetCharAfter("height = 6; width = 3; depth = 7;", "width = ") would return 3.0f. /// </remarks> /// <param name="stringToSearchFor">The string to search for.</param> /// <param name="whereToSearch">The string to search in.</param> /// <returns>Returns the float value found or float.NaN if the string is not found.</returns> #endregion public static float GetFloatAfter(string stringToSearchFor, string whereToSearch) { return GetFloatAfter(stringToSearchFor, whereToSearch, 0); } public static float GetFloatAfter(string stringToSearchFor, string whereToSearch, int startIndex) { int startOfNumber = -1; int endOfNumber = -1; int enterAt = -1; string substring = "uninitialized"; try { int indexOf = whereToSearch.IndexOf(stringToSearchFor, startIndex); if (indexOf != -1) { startOfNumber = indexOf + stringToSearchFor.Length; endOfNumber = whereToSearch.IndexOf(' ', startOfNumber); enterAt = whereToSearch.IndexOf('\n', startOfNumber); if (whereToSearch.IndexOf('\r', startOfNumber) < enterAt) enterAt = whereToSearch.IndexOf('\r', startOfNumber); for (int i = startOfNumber; i < endOfNumber; i++) { bool found = false; for (int indexInArray = 0; indexInArray < sValidNumericalChars.Length; indexInArray++) { if (whereToSearch[i] == sValidNumericalChars[indexInArray]) { found = true; break; } } if (!found) { // if we got here, then the character is not valid, so end the string endOfNumber = i; break; } } if (endOfNumber == -1 || (enterAt != -1 && enterAt < endOfNumber)) endOfNumber = enterAt; if (endOfNumber == -1) endOfNumber = whereToSearch.Length; substring = whereToSearch.Substring(startOfNumber, endOfNumber - startOfNumber); // this method is called when reading from a file. // usually, files use the . rather than other numerical formats, so if this fails, just use the regular . format float toReturn = float.Parse(substring); // Let's see if this is using exponential notation, like 5.21029e-007 if (endOfNumber < whereToSearch.Length - 1) { // Is there an "e" there? if (whereToSearch[endOfNumber] == 'e') { int exponent = GetIntAfter("e", whereToSearch, endOfNumber); float multiplyValue = (float)System.Math.Pow(10, exponent); toReturn *= multiplyValue; } } return toReturn; } } catch (System.FormatException) { return float.Parse(substring, System.Globalization.NumberFormatInfo.InvariantInfo); } return float.NaN; } #region XML Docs /// <summary> /// Returns the first integer found after the argument stringToSearchFor in whereToSearch. /// </summary> /// <remarks> /// This method is used to help simplify parsing of text files and data strings. /// If stringToSearchFor is "Y:" and whereToSearch is "X: 30, Y:32", then the value /// of 32 will be returned. /// </remarks> /// <param name="stringToSearchFor">The string pattern to search for.</param> /// <param name="whereToSearch">The string that will be searched.</param> /// <returns>The integer value found after the argument stringToSearchFor.</returns> #endregion public static int GetIntAfter(string stringToSearchFor, string whereToSearch) { return GetIntAfter(stringToSearchFor, whereToSearch, 0); } #region XML Docs /// <summary> /// Returns the first integer found after the argument stringToSearchFor. The search begins /// at the argument startIndex. /// </summary> /// <param name="stringToSearchFor">The string pattern to search for.</param> /// <param name="whereToSearch">The string that will be searched.</param> /// <param name="startIndex">The index to begin searching at. This method /// will ignore any instances of stringToSearchFor which begin at an index smaller /// than the argument startIndex.</param> /// <returns></returns> #endregion public static int GetIntAfter(string stringToSearchFor, string whereToSearch, int startIndex) { int startOfNumber = -1; int endOfNumber = -1; int enterAt = -1; int carriageReturn = -1; string substring = "uninitialized"; try { int indexOf = whereToSearch.IndexOf(stringToSearchFor, startIndex); if (indexOf != -1) { startOfNumber = indexOf + stringToSearchFor.Length; endOfNumber = whereToSearch.IndexOf(' ', startOfNumber); enterAt = whereToSearch.IndexOf('\n', startOfNumber); carriageReturn = whereToSearch.IndexOf('\r', startOfNumber); if ( carriageReturn != -1 && carriageReturn < enterAt) enterAt = whereToSearch.IndexOf('\r', startOfNumber); if (endOfNumber == -1) endOfNumber = whereToSearch.Length; for (int i = startOfNumber; i < endOfNumber; i++) { bool found = false; for (int indexInArray = 0; indexInArray < sValidNumericalChars.Length; indexInArray++) { if (whereToSearch[i] == sValidNumericalChars[indexInArray]) { found = true; break; } } if (!found) { // if we got here, then the character is not valid, so end the string endOfNumber = i; break; } } if (endOfNumber == -1 || (enterAt != -1 && enterAt < endOfNumber)) endOfNumber = enterAt; if (endOfNumber == -1) endOfNumber = whereToSearch.Length; substring = whereToSearch.Substring(startOfNumber, endOfNumber - startOfNumber); // this method is called when reading from a file. // usually, files use the . rather than other numerical formats, so if this fails, just use the regular . format int toReturn = int.Parse(substring); return toReturn; } } catch (System.FormatException) { return int.Parse(substring, System.Globalization.NumberFormatInfo.InvariantInfo); } return 0; } static char[] WhitespaceChars = new char[] { ' ', '\n', '\t', '\r' }; public static string GetWordAfter(string stringToStartAfter, string entireString) { return GetWordAfter(stringToStartAfter, entireString, 0); } public static string GetWordAfter(string stringToStartAfter, string entireString, int indexToStartAt) { return GetWordAfter(stringToStartAfter, entireString, indexToStartAt, StringComparison.Ordinal); } public static string GetWordAfter(string stringToStartAfter, string entireString, int indexToStartAt, StringComparison comparison) { int indexOf = entireString.IndexOf(stringToStartAfter, indexToStartAt, StringComparison.OrdinalIgnoreCase); if (indexOf != -1) { int startOfWord = indexOf + stringToStartAfter.Length; // Let's not count the start of the word if it's a newline while ( entireString[startOfWord] == WhitespaceChars[0] || entireString[startOfWord] == WhitespaceChars[1] || entireString[startOfWord] == WhitespaceChars[2] || entireString[startOfWord] == WhitespaceChars[3]) { startOfWord++; } int endOfWord = entireString.IndexOfAny(WhitespaceChars, startOfWord); if (endOfWord == -1) { endOfWord = entireString.Length; } return entireString.Substring(startOfWord, endOfWord - startOfWord); } else { return null; } } public static string GetWordAfter(string stringToStartAfter, StringBuilder entireString) { return GetWordAfter(stringToStartAfter, entireString, 0); } public static string GetWordAfter(string stringToStartAfter, StringBuilder entireString, int indexToStartAt) { return GetWordAfter(stringToStartAfter, entireString, indexToStartAt, StringComparison.Ordinal); } public static string GetWordAfter(string stringToStartAfter, StringBuilder entireString, int indexToStartAt, StringComparison comparison) { int indexOf = entireString.IndexOf(stringToStartAfter, indexToStartAt, true); if (indexOf != -1) { int startOfWord = indexOf + stringToStartAfter.Length; // Let's not count the start of the word if it's a newline while (entireString[startOfWord] == WhitespaceChars[0] || entireString[startOfWord] == WhitespaceChars[1] || entireString[startOfWord] == WhitespaceChars[2] || entireString[startOfWord] == WhitespaceChars[3]) { startOfWord++; } int endOfWord = entireString.IndexOfAny(WhitespaceChars, startOfWord); if (endOfWord == -1) { endOfWord = entireString.Length; } return entireString.Substring(startOfWord, endOfWord - startOfWord); } else { return null; } } #region XML Docs /// <summary> /// Returns the number of lines in a given string. Newlines '\n' increase the /// line count. /// </summary> /// <param name="stringInQuestion">The string that will have its lines counted.</param> /// <returns>The number of lines in the argument. "Hello" will return a value of 1, "Hello\nthere" will return a value of 2.</returns> #endregion public static int GetLineCount(string stringInQuestion) { if (string.IsNullOrEmpty(stringInQuestion)) { return 0; } int lines = 1; foreach (char character in stringInQuestion) { if (character == '\n') { lines++; } } return lines; } #region XML Docs /// <summary> /// Returns the number found at the end of the argument stringToGetNumberFrom or throws an /// ArgumentException if no number is found. /// </summary> /// <remarks> /// A stringToGetNumberFrom of "sprite41" will result in the value of 41 returned. A /// stringToGetNumberFrom of "sprite" will result in an ArgumentException being thrown. /// </remarks> /// <exception cref="System.ArgumentException">Throws ArgumentException if no number is found at the end of the argument string.</exception> /// <param name="stringToGetNumberFrom">The number found at the end.</param> /// <returns>The integer value found at the end of the stringToGetNumberFrom.</returns> #endregion public static int GetNumberAtEnd(string stringToGetNumberFrom) { int letterChecking = stringToGetNumberFrom.Length; do { letterChecking--; } while (letterChecking > -1 && Char.IsDigit(stringToGetNumberFrom[letterChecking])); if (letterChecking == stringToGetNumberFrom.Length - 1 && !Char.IsDigit(stringToGetNumberFrom[letterChecking])) { throw new ArgumentException("The argument string has no number at the end."); } return System.Convert.ToInt32( stringToGetNumberFrom.Substring(letterChecking + 1, stringToGetNumberFrom.Length - letterChecking - 1)); } public static void GetStartAndEndOfLineContaining(string contents, string whatToSearchFor, out int start, out int end) { int indexOfWhatToSearchFor = contents.IndexOf(whatToSearchFor); start = -1; end = -1; if (indexOfWhatToSearchFor != -1) { start = contents.LastIndexOfAny(new char[] { '\n', '\r' }, indexOfWhatToSearchFor) + 1; end = contents.IndexOfAny(new char[] { '\n', '\r' }, indexOfWhatToSearchFor); } } public static bool HasNumberAtEnd(string stringToGetNumberFrom) { int letterChecking = stringToGetNumberFrom.Length; do { letterChecking--; } while (letterChecking > -1 && Char.IsDigit(stringToGetNumberFrom[letterChecking])); if (letterChecking == stringToGetNumberFrom.Length - 1 && !Char.IsDigit(stringToGetNumberFrom[letterChecking])) { return false; } return true; } #region XML Docs /// <summary> /// Increments the number at the end of a string or adds a number if none exists. /// </summary> /// <remarks> /// This method begins looking at the end of a string for numbers and moves towards the beginning of the string /// until it encounters a character which is not a numerical digit or the beginning of the string. "Sprite123" would return /// "Sprite124", and "MyString" would return "MyString1". /// </remarks> /// <param name="originalString">The string to "increment".</param> /// <returns>Returns a string with the number at the end incremented, or with a number added on the end if none existed before.</returns> #endregion public static string IncrementNumberAtEnd(string originalString) { if(string.IsNullOrEmpty(originalString)) { return "1"; } // first we get the number at the end of the string // start at the end of the string and move backwards until reacing a non-Digit. int letterChecking = originalString.Length; do { letterChecking--; } while (letterChecking > -1 && Char.IsDigit(originalString[letterChecking])); if (letterChecking == originalString.Length - 1 && !Char.IsDigit(originalString[letterChecking])) { // we don't have a number there, so let's add one originalString = originalString + ((int)1).ToString(); return originalString; } string numAtEnd = originalString.Substring(letterChecking + 1, originalString.Length - letterChecking - 1); string baseString = originalString.Remove(letterChecking + 1, originalString.Length - letterChecking - 1); int numAtEndAsInt = System.Convert.ToInt32(numAtEnd); numAtEndAsInt++; return baseString + numAtEndAsInt.ToString(); } #region XML Docs /// <summary> /// Inserts spaces before every capital letter in a camel-case /// string. Ignores the first letter. /// </summary> /// <remarks> /// For example "HelloThereIAmCamelCase" becomes /// "Hello There I Am Camel Case". /// </remarks> /// <param name="originalString">The string in which to insert spaces.</param> /// <returns>The string with spaces inserted.</returns> #endregion public static string InsertSpacesInCamelCaseString(string originalString) { // Normally in reverse loops you go til i > -1, but // we don't want the character at index 0 to be tested. for (int i = originalString.Length - 1; i > 0; i--) { if (char.IsUpper(originalString[i]) && i != 0) { originalString = originalString.Insert(i, " "); } } return originalString; } public static bool IsNumber(string stringToCheck) { double throwaway; return double.TryParse(stringToCheck, out throwaway); } public static string MakeCamelCase(string originalString) { if (string.IsNullOrEmpty(originalString)) { return originalString; } char[] characterArray = originalString.ToCharArray(); for (int i = 0; i < originalString.Length; i++) { if (i == 0 && characterArray[i] >= 'a' && characterArray[i] <= 'z') { characterArray[i] -= (char)32; } if (characterArray[i] == ' ' && i < originalString.Length - 1 && characterArray[i + 1] >= 'a' && characterArray[i + 1] <= 'z') { characterArray[i + 1] -= (char)32; } } return RemoveWhitespace(new string(characterArray)); } public static string MakeStringUnique(string stringToMakeUnique, List<string> stringList) { return MakeStringUnique(stringToMakeUnique, stringList, 1); } public static string MakeStringUnique(string stringToMakeUnique, List<string> stringList, int numberToStartAt) { for (int i = 0; i < stringList.Count; i++) { if (stringToMakeUnique == stringList[i]) { // the name matches an item in the list that isn't the same reference, so increment the number. stringToMakeUnique = IncrementNumberAtEnd(stringToMakeUnique); // Inefficient? Maybe if we have large numbers, but we're just using it to start at #2 // I may revisit this if this causes problems while (GetNumberAtEnd(stringToMakeUnique) < numberToStartAt) { stringToMakeUnique = IncrementNumberAtEnd(stringToMakeUnique); } // restart the loop: i = -1; } } return stringToMakeUnique; } public static void RemoveDuplicates(List<string> strings) { bool ignoreCase = false; RemoveDuplicates(strings, ignoreCase); } public static void RemoveDuplicates(List<string> strings, bool ignoreCase) { Dictionary<string, int> uniqueStore = new Dictionary<string, int>(); List<string> finalList = new List<string>(); foreach (string currValueUncasted in strings) { string currValue; if (ignoreCase) { currValue = currValueUncasted.ToLowerInvariant(); } else { currValue = currValueUncasted; } if (!uniqueStore.ContainsKey(currValue)) { uniqueStore.Add(currValue, 0); finalList.Add(currValueUncasted); } } strings.Clear(); strings.AddRange(finalList); } #region XML Docs /// <summary> /// Removes the number found at the end of the argument originalString and returns the resulting /// string, or returns the original string if no number is found. /// </summary> /// <param name="originalString">The string that will have the number at its end removed.</param> /// <returns>The string after the number has been removed.</returns> #endregion public static string RemoveNumberAtEnd(string originalString) { // start at the end of the string and move backwards until reacing a non-Digit. int letterChecking = originalString.Length; do { letterChecking--; } while (letterChecking > -1 && Char.IsDigit(originalString[letterChecking])); if (letterChecking == originalString.Length - 1 && !Char.IsDigit(originalString[letterChecking])) { // we don't have a number there, so return the original return originalString; } return originalString.Remove(letterChecking + 1, originalString.Length - letterChecking - 1); } #region XML Docs /// <summary> /// Removes all whitespace found in the argument stringToRemoveWhitespaceFrom. /// </summary> /// <param name="stringToRemoveWhitespaceFrom">The string that will have its whitespace removed.</param> /// <returns>The string resulting from removing whitespace from the argument string.</returns> #endregion public static string RemoveWhitespace(string stringToRemoveWhitespaceFrom) { return stringToRemoveWhitespaceFrom.Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", ""); } public static void ReplaceLine(ref string contents, string contentsOfLineToReplace, string whatToReplaceWith) { int startOfLine; int endOfLine; GetStartAndEndOfLineContaining(contents, contentsOfLineToReplace, out startOfLine, out endOfLine); if (startOfLine != -1) { contents = contents.Remove(startOfLine, endOfLine - startOfLine); contents = contents.Insert(startOfLine, whatToReplaceWith); } } } }
using CCExtractorTester.Enums; using System; using System.Configuration; using System.Xml; namespace CCExtractorTester { /// <summary> /// Holds all the configuration settings for the test suite. /// </summary> public class ConfigManager { /// <summary> /// Gets or sets the folder where we'll store the report in (when using the old local method) /// </summary> public string ReportFolder { get; set; } /// <summary> /// Gets or sets the folder where the samples are stored. /// </summary> public string SampleFolder { get; set; } /// <summary> /// Gets or sets the folder that holds the correct results to compare to. /// </summary> public string ResultFolder { get; set; } /// <summary> /// Gets or sets the location of the CCExtractor executable. /// </summary> public string CCExctractorLocation { get; set; } /// <summary> /// Gets or sets which type of comparison should be used. /// </summary> public CompareType Comparer { get; set; } /// <summary> /// Gets or sets if threading should be used. /// </summary> public bool Threading { get; set; } /// <summary> /// Gets or sets if the suite should break when it encounters an error. /// </summary> public bool BreakOnChanges { get; set; } /// <summary> /// Gets or sets if the suite should process the results and create reports, or pass results to the server. /// </summary> public RunType TestType { get; set; } /// <summary> /// Gets or sets the url that should be used to send the progress of the test suite to. /// </summary> public string ReportUrl { get; set; } /// <summary> /// Gets or sets the port that will be used if there's a test involving TCP connections. /// </summary> public int TCPPort { get; set; } /// <summary> /// Gets or sets the port that will be used if there's a test involving UDP connections. /// </summary> public int UDPPort { get; set; } /// <summary> /// Gets or sets the location of the folder to store temporary results in. /// </summary> public string TemporaryFolder { get; set; } /// <summary> /// Gets or sets the time out that will be used to abort a running instance of CCExctractor if necessary. (in seconds). Set by default to 180. /// </summary> public int TimeOut { get; set; } /// <summary> /// Gets or sets the location of the FFMpeg executable that will be used for UDP input tests. /// </summary> public string FFMpegLocation { get; set; } /// <summary> /// Use valgrind while testing. /// </summary> public bool UseValgrind { get; set; } /// <summary> /// Creates a new instance of the ConfigManager. /// </summary> /// <param name="reportFolder">The folder to store reports in.</param> /// <param name="sampleFolder">The folder to store samples in.</param> /// <param name="resultFolder">The folder that holds the correct results.</param> /// <param name="ccextractorLocation">The location of the CCExtractor executable.</param> /// <param name="compare">The comparer to use for reports.</param> /// <param name="useThreading">Use threading?</param> /// <param name="breakErrors">Break when the suite encounters a broken file?</param> private ConfigManager(string reportFolder, string sampleFolder, string resultFolder, string ccextractorLocation, CompareType compare, bool useThreading, bool breakErrors, string ffmpegLocation) { ReportFolder = reportFolder; SampleFolder = sampleFolder; ResultFolder = resultFolder; CCExctractorLocation = ccextractorLocation; Comparer = compare; Threading = useThreading; BreakOnChanges = breakErrors; FFMpegLocation = ffmpegLocation; TimeOut = 180; UseValgrind = false; } /// <summary> /// Creates a ConfigManager instance from the app.config file (if it exists). /// </summary> /// <param name="logger">The logger instance, so errors can be logged.</param> /// <returns>An instance of teh ConfigManager.</returns> public static ConfigManager CreateFromAppSettings(ILogger logger) { Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string reportFolder = "", sampleFolder = "", resultFolder = "", ccextractorLocation = "", ffmpeg = ""; CompareType compare = CompareType.Diffplex; bool useThreading = false, breakErrors = false; foreach (KeyValueConfigurationElement kce in c.AppSettings.Settings) { switch (kce.Key) { case "ReportFolder": reportFolder = kce.Value; break; case "SampleFolder": sampleFolder = kce.Value; break; case "CorrectResultFolder": resultFolder = kce.Value; break; case "CCExtractorLocation": ccextractorLocation = kce.Value; break; case "FFMpegLocation": ffmpeg = kce.Value; break; case "Comparer": try { compare = CompareTypeParser.parseString(kce.Value); } catch (ArgumentOutOfRangeException) { logger.Warn("Could not parse the Comparer value from the config. Will be using the default setting"); } break; case "UseThreading": useThreading = bool.Parse(kce.Value); break; case "BreakOnErrors": breakErrors = bool.Parse(kce.Value); break; default: logger.Warn("Unknown key " + kce.Key + " encountered; ignoring."); break; } } return new ConfigManager(reportFolder,sampleFolder,resultFolder,ccextractorLocation,compare,useThreading,breakErrors, ffmpeg); } /// <summary> /// Creates a ConfigManager instance from given xml settings file. /// </summary> /// <param name="logger">The logger instance, so errors can be logged.</param> /// <param name="xml">The XML document to parse.</param> /// <returns>An instance of teh ConfigManager.</returns> public static ConfigManager CreateFromXML(ILogger logger, XmlDocument xml) { string reportFolder = "", sampleFolder = "", resultFolder = "", ccextractorLocation = "", ffmpeg = ""; CompareType compare = CompareType.Diffplex; bool useThreading = false, breakErrors = false; foreach (XmlNode n in xml.SelectNodes("configuration/appSettings/add")) { string key = n.Attributes["key"].Value; string value = n.Attributes["value"].Value; switch (key) { case "ReportFolder": reportFolder = value; break; case "SampleFolder": sampleFolder = value; break; case "CorrectResultFolder": resultFolder = value; break; case "CCExtractorLocation": ccextractorLocation = value; break; case "FFMpegLocation": ffmpeg = value; break; case "Comparer": try { compare = CompareTypeParser.parseString(value); } catch (ArgumentOutOfRangeException) { logger.Warn("Could not parse the Comparer value from the xml. Will be using the default setting"); } break; case "UseThreading": useThreading = bool.Parse(value); break; case "BreakOnErrors": breakErrors = bool.Parse(value); break; default: logger.Warn("Unknown key " + key + " encountered; ignoring."); break; } } return new ConfigManager(reportFolder, sampleFolder, resultFolder, ccextractorLocation, compare, useThreading, breakErrors, ffmpeg); } /// <summary> /// Checks if the config is correctly initialized. /// </summary> /// <returns>True if the configuration is correct, false otherwise.</returns> public bool IsValidConfig() { bool pass = true; /* Required in any case: sample folder, ccx location, test type, threading, errorbreak Only the first two could be empty or null and need to be checked. */ pass = pass && !String.IsNullOrEmpty(SampleFolder); pass = pass && !String.IsNullOrEmpty(CCExctractorLocation); // Depending on the test type, other parameters are necessary switch (TestType) { case RunType.Report: // We need a report folder, result folder, Comparer set pass = pass && !String.IsNullOrEmpty(ReportFolder); pass = pass && !String.IsNullOrEmpty(ResultFolder); break; case RunType.Server: // We need the report url pass = pass && !String.IsNullOrEmpty(ReportUrl); break; case RunType.Matrix: // We need a report folder pass = pass && !String.IsNullOrEmpty(ReportFolder); break; default: // Invalid type pass = false; break; } return pass; } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Cookie.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Cookie { /// <summary> /// <para>CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieOrigin /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieOrigin", AccessFlags = 49)] public sealed partial class CookieOrigin /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;ILjava/lang/String;Z)V", AccessFlags = 1)] public CookieOrigin(string host, int port, string path, bool secure) /* MethodBuilder.Create */ { } /// <java-name> /// getHost /// </java-name> [Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)] public string GetHost() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPath /// </java-name> [Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)] public string GetPath() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPort /// </java-name> [Dot42.DexImport("getPort", "()I", AccessFlags = 1)] public int GetPort() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "()Z", AccessFlags = 1)] public bool IsSecure() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal CookieOrigin() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getHost /// </java-name> public string Host { [Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetHost(); } } /// <java-name> /// getPath /// </java-name> public string Path { [Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPath(); } } /// <java-name> /// getPort /// </java-name> public int Port { [Dot42.DexImport("getPort", "()I", AccessFlags = 1)] get{ return GetPort(); } } } /// <summary> /// <para>HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/Cookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/Cookie", AccessFlags = 1537)] public partial interface ICookie /* scope: __dot42__ */ { /// <summary> /// <para>Returns the name.</para><para></para> /// </summary> /// <returns> /// <para>String name The name </para> /// </returns> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)] string GetName() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the value.</para><para></para> /// </summary> /// <returns> /// <para>String value The current value. </para> /// </returns> /// <java-name> /// getValue /// </java-name> [Dot42.DexImport("getValue", "()Ljava/lang/String;", AccessFlags = 1025)] string GetValue() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the comment describing the purpose of this cookie, or <code>null</code> if no such comment has been defined.</para><para></para> /// </summary> /// <returns> /// <para>comment </para> /// </returns> /// <java-name> /// getComment /// </java-name> [Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1025)] string GetComment() /* MethodBuilder.Create */ ; /// <summary> /// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para> /// </summary> /// <java-name> /// getCommentURL /// </java-name> [Dot42.DexImport("getCommentURL", "()Ljava/lang/String;", AccessFlags = 1025)] string GetCommentURL() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the expiration Date of the cookie, or <code>null</code> if none exists. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril. </para><para></para> /// </summary> /// <returns> /// <para>Expiration Date, or <code>null</code>. </para> /// </returns> /// <java-name> /// getExpiryDate /// </java-name> [Dot42.DexImport("getExpiryDate", "()Ljava/util/Date;", AccessFlags = 1025)] global::Java.Util.Date GetExpiryDate() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns <code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise.</para><para></para> /// </summary> /// <returns> /// <para><code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise </para> /// </returns> /// <java-name> /// isPersistent /// </java-name> [Dot42.DexImport("isPersistent", "()Z", AccessFlags = 1025)] bool IsPersistent() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns domain attribute of the cookie.</para><para></para> /// </summary> /// <returns> /// <para>the value of the domain attribute </para> /// </returns> /// <java-name> /// getDomain /// </java-name> [Dot42.DexImport("getDomain", "()Ljava/lang/String;", AccessFlags = 1025)] string GetDomain() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the path attribute of the cookie</para><para></para> /// </summary> /// <returns> /// <para>The value of the path attribute. </para> /// </returns> /// <java-name> /// getPath /// </java-name> [Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1025)] string GetPath() /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para> /// </summary> /// <java-name> /// getPorts /// </java-name> [Dot42.DexImport("getPorts", "()[I", AccessFlags = 1025)] int[] GetPorts() /* MethodBuilder.Create */ ; /// <summary> /// <para>Indicates whether this cookie requires a secure connection.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if this cookie should only be sent over secure connections, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)] bool IsSecure() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the version of the cookie specification to which this cookie conforms.</para><para></para> /// </summary> /// <returns> /// <para>the version of the cookie. </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)] int GetVersion() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if this cookie has expired. </para> /// </summary> /// <returns> /// <para><code>true</code> if the cookie has expired. </para> /// </returns> /// <java-name> /// isExpired /// </java-name> [Dot42.DexImport("isExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)] bool IsExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ; } /// <summary> /// <para>This interface represents a <code>SetCookie2</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SetCookie2 /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SetCookie2", AccessFlags = 1537)] public partial interface ISetCookie2 : global::Org.Apache.Http.Cookie.ISetCookie /* scope: __dot42__ */ { /// <summary> /// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para> /// </summary> /// <java-name> /// setCommentURL /// </java-name> [Dot42.DexImport("setCommentURL", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetCommentURL(string commentURL) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para> /// </summary> /// <java-name> /// setPorts /// </java-name> [Dot42.DexImport("setPorts", "([I)V", AccessFlags = 1025)] void SetPorts(int[] ports) /* MethodBuilder.Create */ ; /// <summary> /// <para>Set the Discard attribute.</para><para>Note: <code>Discard</code> attribute overrides <code>Max-age</code>.</para><para><para>isPersistent() </para></para> /// </summary> /// <java-name> /// setDiscard /// </java-name> [Dot42.DexImport("setDiscard", "(Z)V", AccessFlags = 1025)] void SetDiscard(bool discard) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals that a cookie is in some way invalid or illegal in a given context</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/MalformedCookieException /// </java-name> [Dot42.DexImport("org/apache/http/cookie/MalformedCookieException", AccessFlags = 33)] public partial class MalformedCookieException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new MalformedCookieException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public MalformedCookieException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new MalformedCookieException with a specified message string.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public MalformedCookieException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new MalformedCookieException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public MalformedCookieException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/ClientCookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientCookieConstants /* scope: __dot42__ */ { /// <java-name> /// VERSION_ATTR /// </java-name> [Dot42.DexImport("VERSION_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string VERSION_ATTR = "version"; /// <java-name> /// PATH_ATTR /// </java-name> [Dot42.DexImport("PATH_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string PATH_ATTR = "path"; /// <java-name> /// DOMAIN_ATTR /// </java-name> [Dot42.DexImport("DOMAIN_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string DOMAIN_ATTR = "domain"; /// <java-name> /// MAX_AGE_ATTR /// </java-name> [Dot42.DexImport("MAX_AGE_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_AGE_ATTR = "max-age"; /// <java-name> /// SECURE_ATTR /// </java-name> [Dot42.DexImport("SECURE_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string SECURE_ATTR = "secure"; /// <java-name> /// COMMENT_ATTR /// </java-name> [Dot42.DexImport("COMMENT_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string COMMENT_ATTR = "comment"; /// <java-name> /// EXPIRES_ATTR /// </java-name> [Dot42.DexImport("EXPIRES_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string EXPIRES_ATTR = "expires"; /// <java-name> /// PORT_ATTR /// </java-name> [Dot42.DexImport("PORT_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string PORT_ATTR = "port"; /// <java-name> /// COMMENTURL_ATTR /// </java-name> [Dot42.DexImport("COMMENTURL_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string COMMENTURL_ATTR = "commenturl"; /// <java-name> /// DISCARD_ATTR /// </java-name> [Dot42.DexImport("DISCARD_ATTR", "Ljava/lang/String;", AccessFlags = 25)] public const string DISCARD_ATTR = "discard"; } /// <summary> /// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/ClientCookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537)] public partial interface IClientCookie : global::Org.Apache.Http.Cookie.ICookie /* scope: __dot42__ */ { /// <java-name> /// getAttribute /// </java-name> [Dot42.DexImport("getAttribute", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)] string GetAttribute(string name) /* MethodBuilder.Create */ ; /// <java-name> /// containsAttribute /// </java-name> [Dot42.DexImport("containsAttribute", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool ContainsAttribute(string name) /* MethodBuilder.Create */ ; } /// <summary> /// <para>This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the <code>Cookie</code> header such that those with more specific Path attributes precede those with less specific.</para><para>This comparator assumes that Path attributes of two cookies path-match a commmon request-URI. Otherwise, the result of the comparison is undefined. </para><para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookiePathComparator /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookiePathComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" + "okie/Cookie;>;")] public partial class CookiePathComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie> /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CookiePathComparator() /* MethodBuilder.Create */ { } /// <java-name> /// compare /// </java-name> [Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)] public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */ { return default(int); } [Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)] public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } } /// <summary> /// <para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieSpecFactory /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieSpecFactory", AccessFlags = 1537)] public partial interface ICookieSpecFactory /* scope: __dot42__ */ { /// <java-name> /// newInstance /// </java-name> [Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 1025)] global::Org.Apache.Http.Cookie.ICookieSpec NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ; } /// <summary> /// <para>This interface represents a <code>SetCookie</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SetCookie /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SetCookie", AccessFlags = 1537)] public partial interface ISetCookie : global::Org.Apache.Http.Cookie.ICookie /* scope: __dot42__ */ { /// <java-name> /// setValue /// </java-name> [Dot42.DexImport("setValue", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetValue(string value) /* MethodBuilder.Create */ ; /// <summary> /// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.</para><para><para>getComment() </para></para> /// </summary> /// <java-name> /// setComment /// </java-name> [Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetComment(string comment) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets expiration date. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril.</para><para><para>Cookie::getExpiryDate </para></para> /// </summary> /// <java-name> /// setExpiryDate /// </java-name> [Dot42.DexImport("setExpiryDate", "(Ljava/util/Date;)V", AccessFlags = 1025)] void SetExpiryDate(global::Java.Util.Date expiryDate) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the domain attribute.</para><para><para>Cookie::getDomain </para></para> /// </summary> /// <java-name> /// setDomain /// </java-name> [Dot42.DexImport("setDomain", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetDomain(string domain) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the path attribute.</para><para><para>Cookie::getPath </para></para> /// </summary> /// <java-name> /// setPath /// </java-name> [Dot42.DexImport("setPath", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetPath(string path) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the secure attribute of the cookie. </para><para>When <code>true</code> the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.</para><para><para>isSecure() </para></para> /// </summary> /// <java-name> /// setSecure /// </java-name> [Dot42.DexImport("setSecure", "(Z)V", AccessFlags = 1025)] void SetSecure(bool secure) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the version of the cookie specification to which this cookie conforms.</para><para><para>Cookie::getVersion </para></para> /// </summary> /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(I)V", AccessFlags = 1025)] void SetVersion(int version) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Cookie specification registry that can be used to obtain the corresponding cookie specification implementation for a given type of type or version of cookie.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieSpecRegistry /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieSpecRegistry", AccessFlags = 49)] public sealed partial class CookieSpecRegistry /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CookieSpecRegistry() /* MethodBuilder.Create */ { } /// <summary> /// <para>Registers a CookieSpecFactory with the given identifier. If a specification with the given name already exists it will be overridden. This nameis the same one used to retrieve the CookieSpecFactory from getCookieSpec(String).</para><para><para>#getCookieSpec(String) </para></para> /// </summary> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;)V", AccessFlags = 33)] public void Register(string name, global::Org.Apache.Http.Cookie.ICookieSpecFactory factory) /* MethodBuilder.Create */ { } /// <summary> /// <para>Unregisters the CookieSpecFactory with the given ID.</para><para></para> /// </summary> /// <java-name> /// unregister /// </java-name> [Dot42.DexImport("unregister", "(Ljava/lang/String;)V", AccessFlags = 33)] public void Unregister(string id) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the cookie specification with the given ID.</para><para></para> /// </summary> /// <returns> /// <para>cookie specification</para> /// </returns> /// <java-name> /// getCookieSpec /// </java-name> [Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/Co" + "okieSpec;", AccessFlags = 33)] public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Cookie.ICookieSpec); } /// <summary> /// <para>Gets the cookie specification with the given name.</para><para></para> /// </summary> /// <returns> /// <para>cookie specification</para> /// </returns> /// <java-name> /// getCookieSpec /// </java-name> [Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 33)] public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Cookie.ICookieSpec); } /// <summary> /// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para> /// </summary> /// <returns> /// <para>list of registered cookie spec names </para> /// </returns> /// <java-name> /// getSpecNames /// </java-name> [Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] public global::Java.Util.IList<string> GetSpecNames() /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Populates the internal collection of registered cookie specs with the content of the map passed as a parameter.</para><para></para> /// </summary> /// <java-name> /// setItems /// </java-name> [Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;>;)V")] public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Cookie.ICookieSpecFactory> map) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para> /// </summary> /// <returns> /// <para>list of registered cookie spec names </para> /// </returns> /// <java-name> /// getSpecNames /// </java-name> public global::Java.Util.IList<string> SpecNames { [Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] get{ return GetSpecNames(); } } } /// <summary> /// <para>Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.</para><para>Different cookie specifications can provide a specific implementation for this class based on their cookie handling rules.</para><para><para> (Samit Jain)</para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieAttributeHandler /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieAttributeHandler", AccessFlags = 1537)] public partial interface ICookieAttributeHandler /* scope: __dot42__ */ { /// <summary> /// <para>Parse the given cookie attribute value and update the corresponding org.apache.http.cookie.Cookie property.</para><para></para> /// </summary> /// <java-name> /// parse /// </java-name> [Dot42.DexImport("parse", "(Lorg/apache/http/cookie/SetCookie;Ljava/lang/String;)V", AccessFlags = 1025)] void Parse(global::Org.Apache.Http.Cookie.ISetCookie cookie, string value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Peforms cookie validation for the given attribute value.</para><para></para> /// </summary> /// <java-name> /// validate /// </java-name> [Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)] void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the match is successful; <code>false</code> otherwise </para> /// </returns> /// <java-name> /// match /// </java-name> [Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)] bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SM /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ISMConstants /* scope: __dot42__ */ { /// <java-name> /// COOKIE /// </java-name> [Dot42.DexImport("COOKIE", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE = "Cookie"; /// <java-name> /// COOKIE2 /// </java-name> [Dot42.DexImport("COOKIE2", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE2 = "Cookie2"; /// <java-name> /// SET_COOKIE /// </java-name> [Dot42.DexImport("SET_COOKIE", "Ljava/lang/String;", AccessFlags = 25)] public const string SET_COOKIE = "Set-Cookie"; /// <java-name> /// SET_COOKIE2 /// </java-name> [Dot42.DexImport("SET_COOKIE2", "Ljava/lang/String;", AccessFlags = 25)] public const string SET_COOKIE2 = "Set-Cookie2"; } /// <summary> /// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/SM /// </java-name> [Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537)] public partial interface ISM /* scope: __dot42__ */ { } /// <summary> /// <para>Defines the cookie management specification. </para><para>Cookie management specification must define <ul><li><para>rules of parsing "Set-Cookie" header </para></li><li><para>rules of validation of parsed cookies </para></li><li><para>formatting of "Cookie" header </para></li></ul>for a given host, port and path of origin</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieSpec /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieSpec", AccessFlags = 1537)] public partial interface ICookieSpec /* scope: __dot42__ */ { /// <summary> /// <para>Returns version of the state management this cookie specification conforms to.</para><para></para> /// </summary> /// <returns> /// <para>version of the state management specification </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)] int GetVersion() /* MethodBuilder.Create */ ; /// <summary> /// <para>Parse the <code>"Set-Cookie"</code> Header into an array of Cookies.</para><para>This method will not perform the validation of the resultant Cookies</para><para><para>validate</para></para> /// </summary> /// <returns> /// <para>an array of <code>Cookie</code>s parsed from the header </para> /// </returns> /// <java-name> /// parse /// </java-name> [Dot42.DexImport("parse", "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List<Lo" + "rg/apache/http/cookie/Cookie;>;")] global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> Parse(global::Org.Apache.Http.IHeader header, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Validate the cookie according to validation rules defined by the cookie specification.</para><para></para> /// </summary> /// <java-name> /// validate /// </java-name> [Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)] void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Determines if a Cookie matches the target location.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the cookie should be submitted with a request with given attributes, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// match /// </java-name> [Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)] bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ; /// <summary> /// <para>Create <code>"Cookie"</code> headers for an array of Cookies.</para><para></para> /// </summary> /// <returns> /// <para>a Header for the given Cookies. </para> /// </returns> /// <java-name> /// formatCookies /// </java-name> [Dot42.DexImport("formatCookies", "(Ljava/util/List;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;)Ljava/util/List<Lorg/apache/ht" + "tp/Header;>;")] global::Java.Util.IList<global::Org.Apache.Http.IHeader> FormatCookies(global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> cookies) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a request header identifying what version of the state management specification is understood. May be <code>null</code> if the cookie specification does not support <code>Cookie2</code> header. </para> /// </summary> /// <java-name> /// getVersionHeader /// </java-name> [Dot42.DexImport("getVersionHeader", "()Lorg/apache/http/Header;", AccessFlags = 1025)] global::Org.Apache.Http.IHeader GetVersionHeader() /* MethodBuilder.Create */ ; } /// <summary> /// <para>This cookie comparator can be used to compare identity of cookies.</para><para>Cookies are considered identical if their names are equal and their domain attributes match ignoring case. </para><para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/cookie/CookieIdentityComparator /// </java-name> [Dot42.DexImport("org/apache/http/cookie/CookieIdentityComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" + "okie/Cookie;>;")] public partial class CookieIdentityComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie> /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CookieIdentityComparator() /* MethodBuilder.Create */ { } /// <java-name> /// compare /// </java-name> [Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)] public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */ { return default(int); } [Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)] public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } } }
/* * 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.Drawing; using OpenMetaverse; using OpenSim.Region.OptionalModules.Scripting.Minimodule.Object; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { [Serializable] public class TouchEventArgs : EventArgs { public IAvatar Avatar; public Vector3 TouchBiNormal; public Vector3 TouchNormal; public Vector3 TouchPosition; public Vector2 TouchUV; public Vector2 TouchST; public int TouchMaterialIndex; } public delegate void OnTouchDelegate(IObject sender, TouchEventArgs e); public interface IObject : IEntity { #region Events event OnTouchDelegate OnTouch; #endregion /// <summary> /// Returns whether or not this object is still in the world. /// Eg, if you store an IObject reference, however the object /// is deleted before you use it, it will throw a NullReference /// exception. 'Exists' allows you to check the object is still /// in play before utilizing it. /// </summary> /// <example> /// IObject deleteMe = World.Objects[0]; /// /// if (deleteMe.Exists) { /// deleteMe.Say("Hello, I still exist!"); /// } /// /// World.Objects.Remove(deleteMe); /// /// if (!deleteMe.Exists) { /// Host.Console.Info("I was deleted"); /// } /// </example> /// <remarks> /// Objects should be near-guarunteed to exist for any event which /// passes them as an argument. Storing an object for a longer period /// of time however will limit their reliability. /// /// It is a good practice to use Try/Catch blocks handling for /// NullReferenceException, when accessing remote objects. /// </remarks> bool Exists { get; } /// <summary> /// The local region-unique ID for this object. /// </summary> uint LocalID { get; } /// <summary> /// The description assigned to this object. /// </summary> String Description { get; set; } /// <summary> /// Returns the UUID of the Owner of the Object. /// </summary> UUID OwnerId { get; } /// <summary> /// Returns the UUID of the Creator of the Object. /// </summary> UUID CreatorId { get; } /// <summary> /// Returns the root object of a linkset. If this object is the root, it will return itself. /// </summary> IObject Root { get; } /// <summary> /// Returns a collection of objects which are linked to the current object. Does not include the root object. /// </summary> IObject[] Children { get; } /// <summary> /// Returns a list of materials attached to this object. Each may contain unique texture /// and other visual information. For primitive based objects, this correlates with /// Object Faces. For mesh based objects, this correlates with Materials. /// </summary> IObjectMaterial[] Materials { get; } /// <summary> /// The bounding box of the object. Primitive and Mesh objects alike are scaled to fit within these bounds. /// </summary> Vector3 Scale { get; set; } /// <summary> /// The rotation of the object relative to the Scene /// </summary> Quaternion WorldRotation { get; set; } /// <summary> /// The rotation of the object relative to a parent object /// If root, works the same as WorldRotation /// </summary> Quaternion OffsetRotation { get; set; } /// <summary> /// The position of the object relative to a parent object /// If root, works the same as WorldPosition /// </summary> Vector3 OffsetPosition { get; set; } Vector3 SitTarget { get; set; } String SitTargetText { get; set; } String TouchText { get; set; } /// <summary> /// Text to be associated with this object, in the /// Second Life(r) viewer, this is shown above the /// object. /// </summary> String Text { get; set; } bool IsRotationLockedX { get; set; } // SetStatus(!ROTATE_X) bool IsRotationLockedY { get; set; } // SetStatus(!ROTATE_Y) bool IsRotationLockedZ { get; set; } // SetStatus(!ROTATE_Z) bool IsSandboxed { get; set; } // SetStatus(SANDBOX) bool IsImmotile { get; set; } // SetStatus(BLOCK_GRAB) bool IsAlwaysReturned { get; set; } // SetStatus(!DIE_AT_EDGE) bool IsTemporary { get; set; } // TEMP_ON_REZ bool IsFlexible { get; set; } IObjectShape Shape { get; } // TODO: // PrimHole // Repeats, Offsets, Cut/Dimple/ProfileCut // Hollow, Twist, HoleSize, // Taper[A+B], Shear[A+B], Revolutions, // RadiusOffset, Skew PhysicsMaterial PhysicsMaterial { get; set; } IObjectPhysics Physics { get; } IObjectSound Sound { get; } /// <summary> /// Causes the object to speak to its surroundings, /// equivilent to LSL/OSSL llSay /// </summary> /// <param name="msg">The message to send to the user</param> void Say(string msg); /// <summary> /// Causes the object to speak to on a specific channel, /// equivilent to LSL/OSSL llSay /// </summary> /// <param name="msg">The message to send to the user</param> /// <param name="channel">The channel on which to send the message</param> void Say(string msg,int channel); /// <summary> /// Opens a Dialog Panel in the Users Viewer, /// equivilent to LSL/OSSL llDialog /// </summary> /// <param name="avatar">The UUID of the Avatar to which the Dialog should be send</param> /// <param name="message">The Message to display at the top of the Dialog</param> /// <param name="buttons">The Strings that act as label/value of the Bottons in the Dialog</param> /// <param name="chat_channel">The channel on which to send the response</param> void Dialog(UUID avatar, string message, string[] buttons, int chat_channel); //// <value> /// Grants access to the objects inventory /// </value> IObjectInventory Inventory { get; } } public enum PhysicsMaterial { Default, Glass, Metal, Plastic, Wood, Rubber, Stone, Flesh } public enum TextureMapping { Default, Planar } public interface IObjectMaterial { Color Color { get; set; } UUID Texture { get; set; } TextureMapping Mapping { get; set; } // SetPrimParms(PRIM_TEXGEN) bool Bright { get; set; } // SetPrimParms(FULLBRIGHT) double Bloom { get; set; } // SetPrimParms(GLOW) bool Shiny { get; set; } // SetPrimParms(SHINY) bool BumpMap { get; set; } // SetPrimParms(BUMPMAP) [DEPRECATE IN FAVOUR OF UUID?] } }
// 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; namespace Microsoft.Xml { using System; internal partial class ReadContentAsBinaryHelper { // Private enums private enum State { None, InReadContent, InReadElementContent, } // Fields private XmlReader _reader; private State _state; private int _valueOffset; private bool _isEnd; private bool _canReadValueChunk; private char[] _valueChunk; private int _valueChunkLength; private IncrementalReadDecoder _decoder; private Base64Decoder _base64Decoder; private BinHexDecoder _binHexDecoder; // Constants private const int ChunkSize = 256; // Constructor internal ReadContentAsBinaryHelper(XmlReader reader) { _reader = reader; _canReadValueChunk = reader.CanReadValueChunk; if (_canReadValueChunk) { _valueChunk = new char[ChunkSize]; } } // Static methods internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper helper, XmlReader reader) { if (helper == null) { return new ReadContentAsBinaryHelper(reader); } else { helper.Reset(); return helper; } } // Internal methods internal int ReadContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBase64"); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBinHex"); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBase64"); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBinHex"); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal void Finish() { if (_state != State.None) { while (MoveToNextContentNode(true)) ; if (_state == State.InReadElementContent) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(ResXml.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); } } Reset(); } internal void Reset() { _state = State.None; _isEnd = false; _valueOffset = 0; } // Private methods private bool Init() { // make sure we are on a content node if (!MoveToNextContentNode(false)) { return false; } _state = State.InReadContent; _isEnd = false; return true; } private bool InitOnElement() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); bool isEmpty = _reader.IsEmptyElement; // move to content or off the empty element _reader.Read(); if (isEmpty) { return false; } // make sure we are on a content node if (!MoveToNextContentNode(false)) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(ResXml.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off end element _reader.Read(); return false; } _state = State.InReadElementContent; _isEnd = false; return true; } private void InitBase64Decoder() { if (_base64Decoder == null) { _base64Decoder = new Base64Decoder(); } else { _base64Decoder.Reset(); } _decoder = _base64Decoder; } private void InitBinHexDecoder() { if (_binHexDecoder == null) { _binHexDecoder = new BinHexDecoder(); } else { _binHexDecoder.Reset(); } _decoder = _binHexDecoder; } private int ReadContentAsBinary(byte[] buffer, int index, int count) { Debug.Assert(_decoder != null); if (_isEnd) { Reset(); return 0; } _decoder.SetNextOutputBuffer(buffer, index, count); for (; ; ) { // use streaming ReadValueChunk if the reader supports it if (_canReadValueChunk) { for (; ; ) { if (_valueOffset < _valueChunkLength) { int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) { return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk, 0, ChunkSize)) == 0) { break; } _valueOffset = 0; } } else { // read what is reader.Value string value = _reader.Value; int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset); _valueOffset += decodedCharsCount; if (_decoder.IsFull) { return _decoder.DecodedCount; } } _valueOffset = 0; // move to next textual node in the element content; throw on sub elements if (!MoveToNextContentNode(true)) { _isEnd = true; return _decoder.DecodedCount; } } } private int ReadElementContentAsBinary(byte[] buffer, int index, int count) { if (count == 0) { return 0; } // read binary int decoded = ReadContentAsBinary(buffer, index, count); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(ResXml.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); _state = State.None; return 0; } private bool MoveToNextContentNode(bool moveIfOnContentNode) { do { switch (_reader.NodeType) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (_reader.CanResolveEntity) { _reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while (_reader.Read()); return false; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.Leaderboards; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Scoring; namespace osu.Game.Screens.Select.Leaderboards { public class BeatmapLeaderboard : Leaderboard<BeatmapLeaderboardScope, ScoreInfo> { public Action<ScoreInfo> ScoreSelected; [Resolved] private RulesetStore rulesets { get; set; } private BeatmapInfo beatmapInfo; public BeatmapInfo BeatmapInfo { get => beatmapInfo; set { if (beatmapInfo == value) return; beatmapInfo = value; Scores = null; UpdateScores(); } } private bool filterMods; /// <summary> /// Whether to apply the game's currently selected mods as a filter when retrieving scores. /// </summary> public bool FilterMods { get => filterMods; set { if (value == filterMods) return; filterMods = value; UpdateScores(); } } [Resolved] private ScoreManager scoreManager { get; set; } [Resolved] private BeatmapDifficultyCache difficultyCache { get; set; } [Resolved] private IBindable<RulesetInfo> ruleset { get; set; } [Resolved] private IBindable<IReadOnlyList<Mod>> mods { get; set; } [Resolved] private IAPIProvider api { get; set; } [BackgroundDependencyLoader] private void load() { ruleset.ValueChanged += _ => UpdateScores(); mods.ValueChanged += _ => { if (filterMods) UpdateScores(); }; scoreManager.ItemRemoved += scoreStoreChanged; scoreManager.ItemUpdated += scoreStoreChanged; } protected override void Reset() { base.Reset(); TopScore = null; } private void scoreStoreChanged(ScoreInfo score) { if (Scope != BeatmapLeaderboardScope.Local) return; if (BeatmapInfo?.ID != score.BeatmapInfoID) return; RefreshScores(); } protected override bool IsOnlineScope => Scope != BeatmapLeaderboardScope.Local; private CancellationTokenSource loadCancellationSource; protected override APIRequest FetchScores(Action<IEnumerable<ScoreInfo>> scoresCallback) { loadCancellationSource?.Cancel(); loadCancellationSource = new CancellationTokenSource(); var cancellationToken = loadCancellationSource.Token; if (BeatmapInfo == null) { PlaceholderState = PlaceholderState.NoneSelected; return null; } if (Scope == BeatmapLeaderboardScope.Local) { var scores = scoreManager .QueryScores(s => !s.DeletePending && s.BeatmapInfo.ID == BeatmapInfo.ID && s.Ruleset.ID == ruleset.Value.ID); if (filterMods && !mods.Value.Any()) { // we need to filter out all scores that have any mods to get all local nomod scores scores = scores.Where(s => !s.Mods.Any()); } else if (filterMods) { // otherwise find all the scores that have *any* of the currently selected mods (similar to how web applies mod filters) // we're creating and using a string list representation of selected mods so that it can be translated into the DB query itself var selectedMods = mods.Value.Select(m => m.Acronym); scores = scores.Where(s => s.Mods.Any(m => selectedMods.Contains(m.Acronym))); } scoreManager.OrderByTotalScoreAsync(scores.ToArray(), cancellationToken) .ContinueWith(ordered => scoresCallback?.Invoke(ordered.Result), TaskContinuationOptions.OnlyOnRanToCompletion); return null; } if (api?.IsLoggedIn != true) { PlaceholderState = PlaceholderState.NotLoggedIn; return null; } if (BeatmapInfo.OnlineID == null || BeatmapInfo?.Status <= BeatmapOnlineStatus.Pending) { PlaceholderState = PlaceholderState.Unavailable; return null; } if (!api.LocalUser.Value.IsSupporter && (Scope != BeatmapLeaderboardScope.Global || filterMods)) { PlaceholderState = PlaceholderState.NotSupporter; return null; } IReadOnlyList<Mod> requestMods = null; if (filterMods && !mods.Value.Any()) // add nomod for the request requestMods = new Mod[] { new ModNoMod() }; else if (filterMods) requestMods = mods.Value; var req = new GetScoresRequest(BeatmapInfo, ruleset.Value ?? BeatmapInfo.Ruleset, Scope, requestMods); req.Success += r => { scoreManager.OrderByTotalScoreAsync(r.Scores.Select(s => s.CreateScoreInfo(rulesets, BeatmapInfo)).ToArray(), cancellationToken) .ContinueWith(ordered => Schedule(() => { if (cancellationToken.IsCancellationRequested) return; scoresCallback?.Invoke(ordered.Result); TopScore = r.UserScore?.CreateScoreInfo(rulesets, BeatmapInfo); }), TaskContinuationOptions.OnlyOnRanToCompletion); }; return req; } protected override LeaderboardScore CreateDrawableScore(ScoreInfo model, int index) => new LeaderboardScore(model, index, IsOnlineScope) { Action = () => ScoreSelected?.Invoke(model) }; protected override LeaderboardScore CreateDrawableTopScore(ScoreInfo model) => new LeaderboardScore(model, model.Position, false) { Action = () => ScoreSelected?.Invoke(model) }; protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (scoreManager != null) { scoreManager.ItemRemoved -= scoreStoreChanged; scoreManager.ItemUpdated -= scoreStoreChanged; } } } }
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. 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. * */ #endregion using System; using System.Globalization; using Quartz.Spi; namespace Quartz.Impl.Triggers { /// <summary> /// The base abstract class to be extended by all triggers. /// </summary> /// <remarks> /// <para> /// <see cref="ITrigger" />s have a name and group associated with them, which /// should uniquely identify them within a single <see cref="IScheduler" />. /// </para> /// /// <para> /// <see cref="ITrigger" />s are the 'mechanism' by which <see cref="IJob" /> s /// are scheduled. Many <see cref="ITrigger" /> s can point to the same <see cref="IJob" />, /// but a single <see cref="ITrigger" /> can only point to one <see cref="IJob" />. /// </para> /// /// <para> /// Triggers can 'send' parameters/data to <see cref="IJob" />s by placing contents /// into the <see cref="JobDataMap" /> on the <see cref="ITrigger" />. /// </para> /// </remarks> /// <seealso cref="ISimpleTrigger" /> /// <seealso cref="ICronTrigger" /> /// <seealso cref="IDailyTimeIntervalTrigger" /> /// <seealso cref="JobDataMap" /> /// <seealso cref="IJobExecutionContext" /> /// <author>James House</author> /// <author>Sharada Jambula</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public abstract class AbstractTrigger : IOperableTrigger, IEquatable<AbstractTrigger> { private string name = null!; private string group = SchedulerConstants.DefaultGroup; private string jobName = null!; private string jobGroup = SchedulerConstants.DefaultGroup; private JobDataMap jobDataMap = null!; private int misfireInstruction = Quartz.MisfireInstruction.InstructionNotSet; private DateTimeOffset? endTimeUtc; private DateTimeOffset startTimeUtc; [NonSerialized] // we have the key in string fields private TriggerKey? key; /// <summary> /// Get or sets the name of this <see cref="ITrigger" />. /// </summary> /// <exception cref="ArgumentException">If name is null or empty.</exception> public string Name { get => name; set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Trigger name cannot be null or empty."); } name = value; key = null; } } /// <summary> /// Get the group of this <see cref="ITrigger" />. If <see langword="null" />, Scheduler.DefaultGroup will be used. /// </summary> /// <exception cref="ArgumentException"> /// if group is an empty string. /// </exception> public string Group { get => group; set { if (value != null && value.Trim().Length == 0) { throw new ArgumentException("Group name cannot be an empty string."); } if (value == null) { value = SchedulerConstants.DefaultGroup; } group = value; key = null; } } /// <summary> /// Get or set the name of the associated <see cref="IJobDetail" />. /// </summary> /// <exception cref="ArgumentException"> /// if jobName is null or empty. /// </exception> public string JobName { get => jobName; set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Job name cannot be null or empty."); } jobName = value; } } /// <summary> /// Gets or sets the name of the associated <see cref="IJobDetail" />'s /// group. If set with <see langword="null" />, Scheduler.DefaultGroup will be used. /// </summary> /// <exception cref="ArgumentException"> ArgumentException /// if group is an empty string. /// </exception> public string JobGroup { get => jobGroup; set { if (value != null && value.Trim().Length == 0) { throw new ArgumentException("Group name cannot be null or empty."); } if (value == null) { value = SchedulerConstants.DefaultGroup; } jobGroup = value; } } /// <summary> /// Returns the 'full name' of the <see cref="ITrigger" /> in the format /// "group.name". /// </summary> public virtual string FullName => group + "." + name; /// <summary> /// Gets the key. /// </summary> /// <value>The key.</value> public virtual TriggerKey Key { get { if(key == null) { key = new TriggerKey(Name, Group); } return key; } set { Name = value.Name; Group = value.Group; key = value; } } public JobKey JobKey { set { JobName = value.Name; JobGroup = value.Group; } get { if (JobName == null) { // rare condition when trigger is not fully initialized return null!; } return new JobKey(JobName, JobGroup); } } /// <summary> /// Returns the 'full name' of the <see cref="IJob" /> that the <see cref="ITrigger" /> /// points to, in the format "group.name". /// </summary> public virtual string FullJobName => jobGroup + "." + jobName; public TriggerBuilder GetTriggerBuilder() { return TriggerBuilder.Create() .ForJob(JobKey) .ModifiedByCalendar(CalendarName) .UsingJobData(JobDataMap) .WithDescription(Description) .EndAt(EndTimeUtc) .WithIdentity(Key) .WithPriority(Priority) .StartAt(StartTimeUtc) .WithSchedule(GetScheduleBuilder()); } public abstract IScheduleBuilder GetScheduleBuilder(); /// <summary> /// Get or set the description given to the <see cref="ITrigger" /> instance by /// its creator (if any). /// </summary> public virtual string? Description { get; set; } /// <summary> /// Get or set the <see cref="ICalendar" /> with the given name with /// this Trigger. Use <see langword="null" /> when setting to dis-associate a Calendar. /// </summary> public virtual string? CalendarName { get; set; } /// <summary> /// Get or set the <see cref="JobDataMap" /> that is associated with the /// <see cref="ITrigger" />. /// <para> /// Changes made to this map during job execution are not re-persisted, and /// in fact typically result in an illegal state. /// </para> /// </summary> public virtual JobDataMap JobDataMap { get { if (jobDataMap == null) { jobDataMap = new JobDataMap(); } return jobDataMap; } set => jobDataMap = value; } /// <summary> /// Returns the last UTC time at which the <see cref="ITrigger" /> will fire, if /// the Trigger will repeat indefinitely, null will be returned. /// <para> /// Note that the return time *may* be in the past. /// </para> /// </summary> public abstract DateTimeOffset? FinalFireTimeUtc { get; } /// <summary> /// Get or set the instruction the <see cref="IScheduler" /> should be given for /// handling misfire situations for this <see cref="ITrigger" />- the /// concrete <see cref="ITrigger" /> type that you are using will have /// defined a set of additional MISFIRE_INSTRUCTION_XXX /// constants that may be passed to this method. /// <para> /// If not explicitly set, the default value is <see cref="Quartz.MisfireInstruction.InstructionNotSet" />. /// </para> /// </summary> /// <seealso cref="Quartz.MisfireInstruction.InstructionNotSet" /> /// <seealso cref="UpdateAfterMisfire" /> /// <seealso cref="ISimpleTrigger" /> /// <seealso cref="ICronTrigger" /> public virtual int MisfireInstruction { get => misfireInstruction; set { if (!ValidateMisfireInstruction(value)) { throw new ArgumentException("The misfire instruction code is invalid for this type of trigger."); } misfireInstruction = value; } } /// <summary> /// This method should not be used by the Quartz client. /// </summary> /// <remarks> /// Usable by <see cref="IJobStore" /> /// implementations, in order to facilitate 'recognizing' instances of fired /// <see cref="ITrigger" /> s as their jobs complete execution. /// </remarks> public virtual string FireInstanceId { get; set; } = null!; public abstract void SetNextFireTimeUtc(DateTimeOffset? nextFireTime); public abstract void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTime); /// <summary> /// Returns the previous time at which the <see cref="ITrigger" /> fired. /// If the trigger has not yet fired, <see langword="null" /> will be returned. /// </summary> public abstract DateTimeOffset? GetPreviousFireTimeUtc(); /// <summary> /// Gets and sets the date/time on which the trigger must stop firing. This /// defines the final boundary for trigger firings &#x8212; the trigger will /// not fire after to this date and time. If this value is null, no end time /// boundary is assumed, and the trigger can continue indefinitely. /// </summary> public virtual DateTimeOffset? EndTimeUtc { get => endTimeUtc; set { DateTimeOffset sTime = StartTimeUtc; if (value.HasValue && sTime > value.Value) { throw new ArgumentException("End time cannot be before start time"); } endTimeUtc = value; } } /// <summary> /// The time at which the trigger's scheduling should start. May or may not /// be the first actual fire time of the trigger, depending upon the type of /// trigger and the settings of the other properties of the trigger. However /// the first actual first time will not be before this date. /// </summary> /// <remarks> /// Setting a value in the past may cause a new trigger to compute a first /// fire time that is in the past, which may cause an immediate misfire /// of the trigger. /// </remarks> public virtual DateTimeOffset StartTimeUtc { get => startTimeUtc; set { if (EndTimeUtc.HasValue && EndTimeUtc.Value < value) { throw new ArgumentException("End time cannot be before start time"); } if (!HasMillisecondPrecision) { // round off millisecond... startTimeUtc = value.AddMilliseconds(-value.Millisecond); } else { startTimeUtc = value; } } } /// <summary> /// Tells whether this Trigger instance can handle events /// in millisecond precision. /// </summary> public abstract bool HasMillisecondPrecision { get; } /// <summary> /// Create a <see cref="ITrigger" /> with no specified name, group, or <see cref="IJobDetail" />. /// </summary> /// <remarks> /// Note that the <see cref="Name" />, <see cref="Group" /> and /// the <see cref="JobName" /> and <see cref="JobGroup" /> properties /// must be set before the <see cref="ITrigger" /> can be placed into a /// <see cref="IScheduler" />. /// </remarks> protected AbstractTrigger() { // do nothing... } /// <summary> /// Create a <see cref="ITrigger" /> with the given name, and default group. /// </summary> /// <remarks> /// Note that the <see cref="JobName" /> and <see cref="JobGroup" /> /// properties must be set before the <see cref="ITrigger" /> /// can be placed into a <see cref="IScheduler" />. /// </remarks> /// <param name="name">The name.</param> protected AbstractTrigger(string name) : this(name, SchedulerConstants.DefaultGroup) { } /// <summary> /// Create a <see cref="ITrigger" /> with the given name, and group. /// </summary> /// <remarks> /// Note that the <see cref="JobName" /> and <see cref="JobGroup" /> /// properties must be set before the <see cref="ITrigger" /> /// can be placed into a <see cref="IScheduler" />. /// </remarks> /// <param name="name">The name.</param> /// <param name="group">if <see langword="null" />, Scheduler.DefaultGroup will be used.</param> protected AbstractTrigger(string name, string? group) { Name = name; Group = group!; } /// <summary> /// Create a <see cref="ITrigger" /> with the given name, and group. /// </summary> /// <param name="name">The name.</param> /// <param name="group">if <see langword="null" />, Scheduler.DefaultGroup will be used.</param> /// <param name="jobName">Name of the job.</param> /// <param name="jobGroup">The job group.</param> /// <exception cref="ArgumentException"> ArgumentException /// if name is null or empty, or the group is an empty string. /// </exception> protected AbstractTrigger(string name, string group, string jobName, string jobGroup) { Name = name; Group = group; JobName = jobName; JobGroup = jobGroup; } /// <summary> /// The priority of a <see cref="ITrigger" /> acts as a tie breaker such that if /// two <see cref="ITrigger" />s have the same scheduled fire time, then Quartz /// will do its best to give the one with the higher priority first access /// to a worker thread. /// </summary> /// <remarks> /// If not explicitly set, the default value is <i>5</i>. /// </remarks> /// <returns></returns> /// <see cref="TriggerConstants.DefaultPriority" /> public virtual int Priority { get; set; } = TriggerConstants.DefaultPriority; /// <summary> /// This method should not be used by the Quartz client. /// </summary> /// <remarks> /// Called when the <see cref="IScheduler" /> has decided to 'fire' /// the trigger (Execute the associated <see cref="IJob" />), in order to /// give the <see cref="ITrigger" /> a chance to update itself for its next /// triggering (if any). /// </remarks> /// <seealso cref="JobExecutionException" /> public abstract void Triggered(ICalendar? cal); /// <summary> /// This method should not be used by the Quartz client. /// </summary> /// <remarks> /// <para> /// Called by the scheduler at the time a <see cref="ITrigger" /> is first /// added to the scheduler, in order to have the <see cref="ITrigger" /> /// compute its first fire time, based on any associated calendar. /// </para> /// /// <para> /// After this method has been called, <see cref="GetNextFireTimeUtc" /> /// should return a valid answer. /// </para> /// </remarks> /// <returns> /// The first time at which the <see cref="ITrigger" /> will be fired /// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" /> /// will return (until after the first firing of the <see cref="ITrigger" />). /// </returns> public abstract DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar? cal); /// <summary> /// This method should not be used by the Quartz client. /// </summary> /// <remarks> /// Called after the <see cref="IScheduler" /> has executed the /// <see cref="IJobDetail" /> associated with the <see cref="ITrigger" /> /// in order to get the final instruction code from the trigger. /// </remarks> /// <param name="context"> /// is the <see cref="IJobExecutionContext" /> that was used by the /// <see cref="IJob" />'s<see cref="IJob.Execute" /> method.</param> /// <param name="result">is the <see cref="JobExecutionException" /> thrown by the /// <see cref="IJob" />, if any (may be null). /// </param> /// <returns> /// One of the <see cref="SchedulerInstruction"/> members. /// </returns> /// <seealso cref="SchedulerInstruction" /> /// <seealso cref="Triggered" /> public virtual SchedulerInstruction ExecutionComplete(IJobExecutionContext context, JobExecutionException? result) { if (result != null && result.RefireImmediately) { return SchedulerInstruction.ReExecuteJob; } if (result != null && result.UnscheduleFiringTrigger) { return SchedulerInstruction.SetTriggerComplete; } if (result != null && result.UnscheduleAllTriggers) { return SchedulerInstruction.SetAllJobTriggersComplete; } if (!GetMayFireAgain()) { return SchedulerInstruction.DeleteTrigger; } return SchedulerInstruction.NoInstruction; } /// <summary> /// Used by the <see cref="IScheduler" /> to determine whether or not /// it is possible for this <see cref="ITrigger" /> to fire again. /// <para> /// If the returned value is <see langword="false" /> then the <see cref="IScheduler" /> /// may remove the <see cref="ITrigger" /> from the <see cref="IJobStore" />. /// </para> /// </summary> public abstract bool GetMayFireAgain(); /// <summary> /// Returns the next time at which the <see cref="ITrigger" /> is scheduled to fire. If /// the trigger will not fire again, <see langword="null" /> will be returned. Note that /// the time returned can possibly be in the past, if the time that was computed /// for the trigger to next fire has already arrived, but the scheduler has not yet /// been able to fire the trigger (which would likely be due to lack of resources /// e.g. threads). /// </summary> ///<remarks> /// The value returned is not guaranteed to be valid until after the <see cref="ITrigger" /> /// has been added to the scheduler. /// </remarks> /// <returns></returns> public abstract DateTimeOffset? GetNextFireTimeUtc(); /// <summary> /// Returns the next time at which the <see cref="ITrigger" /> will fire, /// after the given time. If the trigger will not fire after the given time, /// <see langword="null" /> will be returned. /// </summary> public abstract DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime); /// <summary> /// Validates the misfire instruction. /// </summary> /// <param name="misfireInstruction">The misfire instruction.</param> /// <returns></returns> protected abstract bool ValidateMisfireInstruction(int misfireInstruction); /// <summary> /// This method should not be used by the Quartz client. /// <para> /// To be implemented by the concrete classes that extend this class. /// </para> /// <para> /// The implementation should update the <see cref="ITrigger" />'s state /// based on the MISFIRE_INSTRUCTION_XXX that was selected when the <see cref="ITrigger" /> /// was created. /// </para> /// </summary> public abstract void UpdateAfterMisfire(ICalendar? cal); /// <summary> /// This method should not be used by the Quartz client. /// <para> /// The implementation should update the <see cref="ITrigger" />'s state /// based on the given new version of the associated <see cref="ICalendar" /> /// (the state should be updated so that it's next fire time is appropriate /// given the Calendar's new settings). /// </para> /// </summary> /// <param name="cal"> </param> /// <param name="misfireThreshold"></param> public abstract void UpdateWithNewCalendar(ICalendar cal, TimeSpan misfireThreshold); /// <summary> /// Validates whether the properties of the <see cref="IJobDetail" /> are /// valid for submission into a <see cref="IScheduler" />. /// </summary> public virtual void Validate() { if (name == null) { throw new SchedulerException("Trigger's name cannot be null"); } if (group == null) { throw new SchedulerException("Trigger's group cannot be null"); } if (jobName == null) { throw new SchedulerException("Trigger's related Job's name cannot be null"); } if (jobGroup == null) { throw new SchedulerException("Trigger's related Job's group cannot be null"); } } /// <summary> /// Gets a value indicating whether this instance has additional properties /// that should be considered when for example saving to database. /// </summary> /// <remarks> /// If trigger implementation has additional properties that need to be saved /// with base properties you need to make your class override this property with value true. /// Returning true will effectively mean that ADOJobStore needs to serialize /// this trigger instance to make sure additional properties are also saved. /// </remarks> /// <value> /// <c>true</c> if this instance has additional properties; otherwise, <c>false</c>. /// </value> public virtual bool HasAdditionalProperties => false; /// <summary> /// Return a simple string representation of this object. /// </summary> public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "Trigger '{0}': triggerClass: '{1} calendar: '{2}' misfireInstruction: {3} nextFireTime: {4}", FullName, GetType().FullName, CalendarName, MisfireInstruction, GetNextFireTimeUtc()); } /// <summary> /// Compare the next fire time of this <see cref="ITrigger" /> to that of /// another by comparing their keys, or in other words, sorts them /// according to the natural (i.e. alphabetical) order of their keys. /// </summary> /// <param name="other"></param> /// <returns></returns> public virtual int CompareTo(ITrigger? other) { if ((other == null || other.Key == null) && Key == null) { return 0; } if (other == null || other.Key == null) { return -1; } if (Key == null) { return 1; } return Key.CompareTo(other.Key); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"></see> to compare with the current <see cref="T:System.Object"></see>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>; otherwise, false. /// </returns> public override bool Equals(object? obj) { return Equals(obj as AbstractTrigger); } /// <summary> /// Trigger equality is based upon the equality of the TriggerKey. /// </summary> /// <param name="trigger"></param> /// <returns>true if the key of this Trigger equals that of the given Trigger</returns> public virtual bool Equals(AbstractTrigger? trigger) { if (trigger?.Key == null || Key == null) { return false; } return Key.Equals(trigger.Key); } /// <summary> /// Serves as a hash function for a particular type. <see cref="M:System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"></see>. /// </returns> public override int GetHashCode() { if (Key == null) { return base.GetHashCode(); } return Key.GetHashCode(); } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public virtual ITrigger Clone() { AbstractTrigger copy; try { copy = (AbstractTrigger)MemberwiseClone(); // Shallow copy the jobDataMap. Note that this means that if a user // modifies a value object in this map from the cloned Trigger // they will also be modifying this Trigger. if (jobDataMap != null) { copy.jobDataMap = (JobDataMap)jobDataMap.Clone(); } } catch (Exception ex) { throw new Exception("Not Cloneable.", ex); } return copy; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Threading.Tasks; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Functions { /// <summary> /// A datetime object represents an instant in time, expressed as a date and time of day. /// /// | Name | Description /// |-------------- |----------------- /// | `.year` | Gets the year of a date object /// | `.month` | Gets the month of a date object /// | `.day` | Gets the day in the month of a date object /// | `.day_of_year` | Gets the day within the year /// | `.hour` | Gets the hour of the date object /// | `.minute` | Gets the minute of the date object /// | `.second` | Gets the second of the date object /// | `.millisecond` | Gets the millisecond of the date object /// /// [:top:](#builtins) /// #### Binary operations /// /// The substract operation `date1 - date2`: Substract `date2` from `date1` and return a timespan internal object (see timespan object below). /// /// Other comparison operators(`==`, `!=`, `&lt;=`, `&gt;=`, `&lt;`, `&gt;`) are also working with date objects. /// /// A `timespan` and also the added to a `datetime` object. /// </summary> /// <seealso cref="Scriban.Runtime.ScriptObject" /> public partial class DateTimeFunctions : ScriptObject, IScriptCustomFunction, IScriptFunctionInfo { private const string FormatKey = "format"; // This is exposed as well as default_format public const string DefaultFormat = "%d %b %Y"; [ScriptMemberIgnore] public static readonly ScriptVariable DateVariable = new ScriptVariableGlobal("date"); // Code from DotLiquid https://github.com/dotliquid/dotliquid/blob/master/src/DotLiquid/Util/StrFTime.cs // Apache License, Version 2.0 private static readonly Dictionary<char, Func<DateTime, CultureInfo, string>> Formats = new Dictionary<char, Func<DateTime, CultureInfo, string>> { { 'a', (dateTime, cultureInfo) => dateTime.ToString("ddd", cultureInfo) }, { 'A', (dateTime, cultureInfo) => dateTime.ToString("dddd", cultureInfo) }, { 'b', (dateTime, cultureInfo) => dateTime.ToString("MMM", cultureInfo) }, { 'B', (dateTime, cultureInfo) => dateTime.ToString("MMMM", cultureInfo) }, { 'c', (dateTime, cultureInfo) => dateTime.ToString("ddd MMM dd HH:mm:ss yyyy", cultureInfo) }, { 'C', (dateTime, cultureInfo) => (dateTime.Year / 100).ToString("D2", cultureInfo) }, { 'd', (dateTime, cultureInfo) => dateTime.ToString("dd", cultureInfo) }, { 'D', (dateTime, cultureInfo) => dateTime.ToString("MM/dd/yy", cultureInfo) }, { 'e', (dateTime, cultureInfo) => dateTime.ToString("%d", cultureInfo).PadLeft(2, ' ') }, { 'F', (dateTime, cultureInfo) => dateTime.ToString("yyyy-MM-dd", cultureInfo) }, { 'h', (dateTime, cultureInfo) => dateTime.ToString("MMM", cultureInfo) }, { 'H', (dateTime, cultureInfo) => dateTime.ToString("HH", cultureInfo) }, { 'I', (dateTime, cultureInfo) => dateTime.ToString("hh", cultureInfo) }, { 'j', (dateTime, cultureInfo) => dateTime.DayOfYear.ToString("D3", cultureInfo) }, { 'k', (dateTime, cultureInfo) => dateTime.ToString("%H", cultureInfo).PadLeft(2, ' ') }, { 'l', (dateTime, cultureInfo) => dateTime.ToString("%h", cultureInfo).PadLeft(2, ' ') }, { 'L', (dateTime, cultureInfo) => dateTime.ToString("FFF", cultureInfo) }, { 'm', (dateTime, cultureInfo) => dateTime.ToString("MM", cultureInfo) }, { 'M', (dateTime, cultureInfo) => dateTime.ToString("mm", cultureInfo) }, { 'n', (dateTime, cultureInfo) => "\n" }, { 'N', (dateTime, cultureInfo) => dateTime.ToString("fffffff00", cultureInfo) }, { 'p', (dateTime, cultureInfo) => dateTime.ToString("tt", cultureInfo) }, { 'P', (dateTime, cultureInfo) => dateTime.ToString("tt", cultureInfo).ToLowerInvariant() }, { 'r', (dateTime, cultureInfo) => dateTime.ToString("hh:mm:ss tt", cultureInfo) }, { 'R', (dateTime, cultureInfo) => dateTime.ToString("HH:mm", cultureInfo) }, { 's', (dateTime, cultureInfo) => ((dateTime.ToUniversalTime().Ticks - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks) / TimeSpan.TicksPerSecond).ToString(cultureInfo) }, { 'S', (dateTime, cultureInfo) => dateTime.ToString("ss", cultureInfo) }, { 't', (dateTime, cultureInfo) => "\t" }, { 'T', (dateTime, cultureInfo) => dateTime.ToString("HH:mm:ss", cultureInfo) }, { 'u', (dateTime, cultureInfo) => ((dateTime.DayOfWeek == DayOfWeek.Sunday) ? 7 : (int) dateTime.DayOfWeek).ToString(cultureInfo) }, { 'U', (dateTime, cultureInfo) => cultureInfo.Calendar.GetWeekOfYear(dateTime, cultureInfo.DateTimeFormat.CalendarWeekRule, DayOfWeek.Sunday).ToString("D2", cultureInfo) }, { 'v', (dateTime, cultureInfo) => string.Format(CultureInfo.InvariantCulture, "{0,2}-{1}-{2:D4}", dateTime.Day, dateTime.ToString("MMM", CultureInfo.InvariantCulture).ToUpper(), dateTime.Year) }, { 'V', (dateTime, cultureInfo) => cultureInfo.Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday).ToString("D2", cultureInfo) }, { 'W', (dateTime, cultureInfo) => cultureInfo.Calendar.GetWeekOfYear(dateTime, cultureInfo.DateTimeFormat.CalendarWeekRule, DayOfWeek.Monday).ToString("D2", cultureInfo) }, { 'w', (dateTime, cultureInfo) => ((int) dateTime.DayOfWeek).ToString(cultureInfo) }, { 'x', (dateTime, cultureInfo) => dateTime.ToString("d", cultureInfo) }, { 'X', (dateTime, cultureInfo) => dateTime.ToString("T", cultureInfo) }, { 'y', (dateTime, cultureInfo) => dateTime.ToString("yy", cultureInfo) }, { 'Y', (dateTime, cultureInfo) => dateTime.ToString("yyyy", cultureInfo) }, { 'Z', (dateTime, cultureInfo) => dateTime.ToString("zzz", cultureInfo) }, { '%', (dateTime, cultureInfo) => "%" } }; /// <summary> /// Initializes a new instance of the <see cref="DateTimeFunctions"/> class. /// </summary> public DateTimeFunctions() { this["default_format"] = DefaultFormat; Format = DefaultFormat; CreateImportFunctions(); } /// <summary> /// Gets or sets the format used to format all dates /// </summary> public string Format { get => GetSafeValue<string>(FormatKey) ?? DefaultFormat; set => SetValue(FormatKey, value, false); } /// <summary> /// Returns a datetime object of the current time, including the hour, minutes, seconds and milliseconds. /// </summary> /// <remarks> /// ```scriban-html /// {{ date.now.year }} /// ``` /// ```html /// 2020 /// ``` /// </remarks> public static DateTime Now() => DateTime.Now; /// <summary> /// Adds the specified number of days to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="days">The days.</param> /// <returns>A new date</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' | date.add_days 1 }} /// ``` /// ```html /// 06 Jan 2016 /// ``` /// </remarks> public static DateTime AddDays(DateTime date, double days) { return date.AddDays(days); } /// <summary> /// Adds the specified number of months to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="months">The months.</param> /// <returns>A new date</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' | date.add_months 1 }} /// ``` /// ```html /// 05 Feb 2016 /// ``` /// </remarks> public static DateTime AddMonths(DateTime date, int months) { return date.AddMonths(months); } /// <summary> /// Adds the specified number of years to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="years">The years.</param> /// <returns>A new date</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' | date.add_years 1 }} /// ``` /// ```html /// 05 Jan 2017 /// ``` /// </remarks> public static DateTime AddYears(DateTime date, int years) { return date.AddYears(years); } /// <summary> /// Adds the specified number of hours to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="hours">The hours.</param> /// <returns>A new date</returns> public static DateTime AddHours(DateTime date, double hours) { return date.AddHours(hours); } /// <summary> /// Adds the specified number of minutes to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="minutes">The minutes.</param> /// <returns>A new date</returns> public static DateTime AddMinutes(DateTime date, double minutes) { return date.AddMinutes(minutes); } /// <summary> /// Adds the specified number of seconds to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="seconds">The seconds.</param> /// <returns>A new date</returns> public static DateTime AddSeconds(DateTime date, double seconds) { return date.AddSeconds(seconds); } /// <summary> /// Adds the specified number of milliseconds to the input date. /// </summary> /// <param name="date">The date.</param> /// <param name="millis">The milliseconds.</param> /// <returns>A new date</returns> public static DateTime AddMilliseconds(DateTime date, double millis) { return date.AddMilliseconds(millis); } /// <summary> /// Parses the specified input string to a date object. /// </summary> /// <param name="context">The template context.</param> /// <param name="text">A text representing a date.</param> /// <returns>A date object</returns> /// <remarks> /// ```scriban-html /// {{ date.parse '2016/01/05' }} /// ``` /// ```html /// 05 Jan 2016 /// ``` /// </remarks> public static DateTime? Parse(TemplateContext context, string text) { if (string.IsNullOrEmpty(text)) { return null; } DateTime result; if (DateTime.TryParse(text, context.CurrentCulture, DateTimeStyles.None, out result)) { return result; } return new DateTime(); } public override IScriptObject Clone(bool deep) { var dateFunctions = (DateTimeFunctions)base.Clone(deep); // This is important to call the CreateImportFunctions as it is instance specific (using DefaultFormat from `date` object) dateFunctions.CreateImportFunctions(); return dateFunctions; } /// <summary> /// Converts a datetime object to a textual representation using the specified format string. /// /// By default, if you are using a date, it will use the format specified by `date.format` which defaults to `date.default_format` (readonly) which default to `%d %b %Y` /// /// You can override the format used for formatting all dates by assigning the a new format: `date.format = '%a %b %e %T %Y';` /// /// You can recover the default format by using `date.format = date.default_format;` /// /// By default, the to_string format is using the **current culture**, but you can switch to an invariant culture by using the modifier `%g` /// /// For example, using `%g %d %b %Y` will output the date using an invariant culture. /// /// If you are using `%g` alone, it will output the date with `date.format` using an invariant culture. /// /// Suppose that `date.now` would return the date `2013-09-12 22:49:27 +0530`, the following table explains the format modifiers: /// /// | Format | Result | Description /// |--------|-------------------|-------------------------------------------- /// | `"%a"` | `"Thu"` | Name of week day in short form of the /// | `"%A"` | `"Thursday"` | Week day in full form of the time /// | `"%b"` | `"Sep"` | Month in short form of the time /// | `"%B"` | `"September"` | Month in full form of the time /// | `"%c"` | | Date and time (%a %b %e %T %Y) /// | `"%C"` | `"20"` | Century of the time /// | `"%d"` | `"12"` | Day of the month of the time /// | `"%D"` | `"09/12/13"` | Date (%m/%d/%y) /// | `"%e"` | `"12"` | Day of the month, blank-padded ( 1..31) /// | `"%F"` | `"2013-09-12"` | ISO 8601 date (%Y-%m-%d) /// | `"%h"` | `"Sep"` | Alias for %b /// | `"%H"` | `"22"` | Hour of the time in 24 hour clock format /// | `"%I"` | `"10"` | Hour of the time in 12 hour clock format /// | `"%j"` | `"255"` | Day of the year (001..366) (3 digits, left padded with zero) /// | `"%k"` | `"22"` | Hour of the time in 24 hour clock format, blank-padded ( 0..23) /// | `"%l"` | `"10"` | Hour of the time in 12 hour clock format, blank-padded ( 0..12) /// | `"%L"` | `"000"` | Millisecond of the time (3 digits, left padded with zero) /// | `"%m"` | `"09"` | Month of the time /// | `"%M"` | `"49"` | Minutes of the time (2 digits, left padded with zero e.g 01 02) /// | `"%n"` | | Newline character (\n) /// | `"%N"` | `"000000000"` | Nanoseconds of the time (9 digits, left padded with zero) /// | `"%p"` | `"PM"` | Gives AM / PM of the time /// | `"%P"` | `"pm"` | Gives am / pm of the time /// | `"%r"` | `"10:49:27 PM"` | Long time in 12 hour clock format (%I:%M:%S %p) /// | `"%R"` | `"22:49"` | Short time in 24 hour clock format (%H:%M) /// | `"%s"` | | Number of seconds since 1970-01-01 00:00:00 +0000 /// | `"%S"` | `"27"` | Seconds of the time /// | `"%t"` | | Tab character (\t) /// | `"%T"` | `"22:49:27"` | Long time in 24 hour clock format (%H:%M:%S) /// | `"%u"` | `"4"` | Day of week of the time (from 1 for Monday to 7 for Sunday) /// | `"%U"` | `"36"` | Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) /// | `"%v"` | `"12-SEP-2013"` | VMS date (%e-%b-%Y) (culture invariant) /// | `"%V"` | `"37"` | Week number of the current year according to ISO 8601 (01..53) /// | `"%W"` | `"36"` | Week number of the current year, starting with the first Monday as the first day of the first week (00..53) /// | `"%w"` | `"4"` | Day of week of the time (from 0 for Sunday to 6 for Saturday) /// | `"%x"` | | Preferred representation for the date alone, no time /// | `"%X"` | | Preferred representation for the time alone, no date /// | `"%y"` | `"13"` | Gives year without century of the time /// | `"%Y"` | `"2013"` | Year of the time /// | `"%Z"` | `"IST"` | Gives Time Zone of the time /// | `"%%"` | `"%"` | Output the character `%` /// /// Note that the format is using a good part of the ruby format ([source](http://apidock.com/ruby/DateTime/strftime)) /// ```scriban-html /// {{ date.parse '2016/01/05' | date.to_string '%d %b %Y' }} /// {{ date.parse '2016/01/05' | date.to_string '%d %B %Y' 'fr-FR' }} /// ``` /// ```html /// 05 Jan 2016 /// 05 janvier 2016 /// ``` /// </summary> /// <param name="datetime">The input datetime to format</param> /// <param name="pattern">The date format pattern.</param> /// <param name="culture">The culture used to format the datetime</param> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public virtual string ToString(DateTime? datetime, string pattern, CultureInfo culture) { if (pattern == null) throw new ArgumentNullException(nameof(pattern)); if (!datetime.HasValue) return null; // If pattern is %g only, use the default date if (pattern == "%g") { pattern = "%g " + Format; } var builder = new StringBuilder(); for (int i = 0; i < pattern.Length; i++) { var c = pattern[i]; if (c == '%' && (i + 1) < pattern.Length) { i++; Func<DateTime, CultureInfo, string> formatter; var format = pattern[i]; // Switch to invariant culture if (format == 'g') { culture = CultureInfo.InvariantCulture; continue; } if (Formats.TryGetValue(format, out formatter)) { builder.Append(formatter.Invoke(datetime.Value, culture)); } else { builder.Append('%'); builder.Append(format); } } else { builder.Append(c); } } return builder.ToString(); } public virtual object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement) { // If we access `date` without any parameter, it calls by default the "parse" function // otherwise it is the 'date' object itself switch (arguments.Count) { case 0: return this; case 1: return Parse(context, context.ObjectToString(arguments[0])); default: throw new ScriptRuntimeException(callerContext.Span, $"Invalid number of parameters `{arguments.Count}` for `date` object/function."); } } public int RequiredParameterCount => 0; public int ParameterCount => 0; public ScriptVarParamKind VarParamKind => ScriptVarParamKind.Direct; public Type ReturnType => typeof(object); private const string Parameter1Name = "text"; public ScriptParameterInfo GetParameterInfo(int index) { return new ScriptParameterInfo(typeof(object), Parameter1Name); } #if !SCRIBAN_NO_ASYNC public ValueTask<object> InvokeAsync(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement) { return new ValueTask<object>(Invoke(context, callerContext, arguments, blockStatement)); } #endif private void CreateImportFunctions() { // This function is very specific, as it is calling a member function of this instance // in order to retrieve the `date.format` this.Import("to_string", new Func<TemplateContext, DateTime?, string, string, string>(ToStringTrampoline)); } private string ToStringTrampoline(TemplateContext context, DateTime? date, string pattern, string culture = null) { var cultureObject = culture != null ? CultureInfo.GetCultureInfo(culture) : null; return ToString(date, pattern, cultureObject ?? context.CurrentCulture); } } }
using System; using Csla; using Csla.Data; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using DalEf; using System.Collections.Generic; namespace BusinessObjects.MDSubjects { [Serializable] public partial class cMDSubjects_Subject_Accounts: CoreBusinessChildClass<cMDSubjects_Subject_Accounts> { public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo<System.Int32> mDSubjects_SubjectIdProperty = RegisterProperty<System.Int32>(p => p.MDSubjects_SubjectId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 MDSubjects_SubjectId { get { return GetProperty(mDSubjects_SubjectIdProperty); } set { SetProperty(mDSubjects_SubjectIdProperty, value); } } private static readonly PropertyInfo<System.Int32> mDSubjects_Enums_BankIdProperty = RegisterProperty<System.Int32>(p => p.MDSubjects_Enums_BankId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 MDSubjects_Enums_BankId { get { return GetProperty(mDSubjects_Enums_BankIdProperty); } set { SetProperty(mDSubjects_Enums_BankIdProperty, value); } } private static readonly PropertyInfo<System.String> accountNumberProperty = RegisterProperty<System.String>(p => p.AccountNumber, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(50, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String AccountNumber { get { return GetProperty(accountNumberProperty); } set { SetProperty(accountNumberProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<System.Int32> mDGeneral_Enums_CurrencyIdProperty = RegisterProperty<System.Int32>(p => p.MDGeneral_Enums_CurrencyId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 MDGeneral_Enums_CurrencyId { get { return GetProperty(mDGeneral_Enums_CurrencyIdProperty); } set { SetProperty(mDGeneral_Enums_CurrencyIdProperty, value); } } private static readonly PropertyInfo<bool> inactiveProperty = RegisterProperty<bool>(p => p.Inactive, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public bool Inactive { get { return GetProperty(inactiveProperty); } set { SetProperty(inactiveProperty, value); } } private static readonly PropertyInfo<System.DateTime?> lastActivityDateProperty = RegisterProperty<System.DateTime?>(p => p.LastActivityDate, string.Empty, (System.DateTime?)null); public System.DateTime? LastActivityDate { get { return GetProperty(lastActivityDateProperty); } set { SetProperty(lastActivityDateProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; public static cMDSubjects_Subject_Accounts NewMDSubjects_Subject_Accounts() { return DataPortal.CreateChild<cMDSubjects_Subject_Accounts>(); } public static cMDSubjects_Subject_Accounts GetcMDSubjects_Subject_Accounts(MDSubjects_Subject_AccountsCol data) { return DataPortal.FetchChild<cMDSubjects_Subject_Accounts>(data); } #region Data Access [RunLocal] protected override void Child_Create() { BusinessRules.CheckRules(); } private void Child_Fetch(MDSubjects_Subject_AccountsCol data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(mDSubjects_SubjectIdProperty, data.MDSubjects_SubjectId); LoadProperty<int>(mDSubjects_Enums_BankIdProperty, data.MDSubjects_Enums_BankId); LoadProperty<string>(accountNumberProperty, data.AccountNumber); LoadProperty<int>(mDGeneral_Enums_CurrencyIdProperty, data.MDGeneral_Enums_CurrencyId); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<DateTime?>(lastActivityDateProperty, data.LastActivityDate); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } private void Child_Insert(MDSubjects_Subject parent) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Subject_AccountsCol(); data.MDSubjects_Subject = parent; data.MDSubjects_Enums_BankId = ReadProperty<int>(mDSubjects_Enums_BankIdProperty); data.AccountNumber = ReadProperty<string>(accountNumberProperty); data.MDGeneral_Enums_CurrencyId = ReadProperty<int>(mDGeneral_Enums_CurrencyIdProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime?>(lastActivityDateProperty); ctx.ObjectContext.AddToMDSubjects_Subject_AccountsCol(data); data.PropertyChanged += (o, e) => { if (e.PropertyName == "Id") { LoadProperty<int>(IdProperty, data.Id); LoadProperty<int>(mDSubjects_SubjectIdProperty, data.MDSubjects_SubjectId); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LastChanged = data.LastChanged; } }; } } private void Child_Update() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Subject_AccountsCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; //data.SubjectId = parent.Id; ctx.ObjectContext.Attach(data); data.MDSubjects_Enums_BankId = ReadProperty<int>(mDSubjects_Enums_BankIdProperty); data.AccountNumber = ReadProperty<string>(accountNumberProperty); data.MDGeneral_Enums_CurrencyId = ReadProperty<int>(mDGeneral_Enums_CurrencyIdProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime?>(lastActivityDateProperty); data.PropertyChanged += (o, e) => { if (e.PropertyName == "LastChanged") LastChanged = data.LastChanged; }; } } private void Child_DeleteSelf() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Subject_AccountsCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; //data.SubjectId = parent.Id; ctx.ObjectContext.Attach(data); ctx.ObjectContext.DeleteObject(data); } } #endregion public void MarkChild() { this.MarkAsChild(); } } [Serializable] public partial class cMDSubjects_Subject_AccountsCol : BusinessListBase<cMDSubjects_Subject_AccountsCol,cMDSubjects_Subject_Accounts> { internal static cMDSubjects_Subject_AccountsCol NewMDSubjects_Subject_AccountsCol() { return DataPortal.CreateChild<cMDSubjects_Subject_AccountsCol>(); } public static cMDSubjects_Subject_AccountsCol GetcMDSubjects_Subject_AccountsCol(IEnumerable<MDSubjects_Subject_AccountsCol> dataSet) { var childList = new cMDSubjects_Subject_AccountsCol(); childList.Fetch(dataSet); return childList; } #region Data Access private void Fetch(IEnumerable<MDSubjects_Subject_AccountsCol> dataSet) { RaiseListChangedEvents = false; foreach (var data in dataSet) this.Add(cMDSubjects_Subject_Accounts.GetcMDSubjects_Subject_Accounts(data)); RaiseListChangedEvents = true; } #endregion //Data Access } }
using System; using System.Collections.Generic; using System.Text; // Copyright (c) 2006, 2007 by Hugh Pyle, inguzaudio.com namespace DSPUtil { public enum DitherType { NONE = 0, TRIANGULAR = 1, SHAPED = 2, SBM = 3 } public class Dither { // F-weighted // These from "Psychoacoustically Optimal Noise Shaping," by Robert A. Wannamaker // (From AES Journal Volume 40, No. 7/8, 1992 July/August) // !!!NOTE: This dither FIR is only good for 44.1kHz sampling rate!!! private static double[] _Wannamaker = { 2.412f, -3.370f, 3.937f, -4.174f, 3.353f, -2.205f, 1.281f, -0.569f, 0.0847f }; // These from the Sony Super Bit Mapping (SBM) private static double[] _SBM = { 1.47933, -1.59032, 1.64436, -1.36613, 9.26704e-1, -5.57931e-1, 2.67859e-1, -1.06726e-1, 2.85161e-2, 1.23066e-3, -6.16555e-3, 3.06700e-3}; private const double _scale8 = 128f; private const double _scale16 = 32768f; private const double _scale24 = 8388608f; private const double _scale32 = 2147483648f; private DitherType _type = DitherType.NONE; private uint _sampleRate; private ushort _bitsPerSample; private double[] _filter; private double _minv; private double _maxv; private double _peak; // Error history array for noise shaping private double[] _EH; private int _HistPos; // Cached random-number generator private Random _random; // Previously tried to cache a block of random numbers. But fail: // with any reasonably small cache the LF behavior is audible pumping // at (samplerate/cachesize). So instead just use the proper rand gen // even though it's a bit slower. /* private const int _cachelen = 4096; private static double[] _randArr; private static double[] _tpdfArr; private static int _randPos; private static int _tpdfPos; */ private bool _clipping = false; public Dither(DitherType type, uint sampleRate, ushort bitsPerSample) { _type = type; _sampleRate = sampleRate; _bitsPerSample = bitsPerSample; _minv = MinValue(_bitsPerSample); _maxv = MaxValue(_bitsPerSample); _filter = FilterArray(type); _EH = new double[2 * _filter.Length]; _HistPos = _filter.Length - 1; // Tweak the random number source _random = new Random(); } static private double[] FilterArray(DitherType type) { switch (type) { case DitherType.SHAPED: return _Wannamaker; case DitherType.SBM: return _SBM; case DitherType.NONE: case DitherType.TRIANGULAR: default: return new double[0]; } } private static double MaxValue(ushort bitsPerSample) { switch (bitsPerSample) { case 8: return _scale8; // -1; case 16: return _scale16; // -1; case 24: return _scale24; // -1; case 32: return _scale32; // -1; default: return Math.Pow(2, bitsPerSample - 1) - 1; } } private static double MinValue(ushort bitsPerSample) { switch (bitsPerSample) { case 8: return -_scale8; case 16: return -_scale16; case 24: return -_scale24; case 32: return -_scale32; default: return -(Math.Pow(2, bitsPerSample - 1)); } } // Random value from -1 to +1 with rectangular PDF private double NextRandom() { return (_random.NextDouble() - 0.5); /* lock (_random) { if (_randArr == null) { _randArr = new double[_cachelen]; for (int j = 0; j < _cachelen; j++) { _randArr[j] = (_random.NextDouble() - 0.5) * 2; } _randPos = 0; } _randPos++; if (_randPos >= _cachelen) { _randPos = 0; } return _randArr[_randPos]; } */ } // Random value from -1 to +1 with triangular PDF private double NextRandom2() { return (_random.NextDouble() + _random.NextDouble() - 1); /* lock (_random) { if (_tpdfArr == null) { _tpdfArr = new double[_cachelen]; for (int j = 0; j < _cachelen; j++) { _tpdfArr[j] = (_random.NextDouble() + _random.NextDouble() - 1) * 2; } _tpdfPos = 0; } _tpdfPos++; if (_tpdfPos >= _cachelen) { _tpdfPos = 0; } return _tpdfArr[_tpdfPos]; } */ } public bool clipping { get { return _clipping; } set { _clipping = value; } } public double dbfsPeak { get { // _peak is from 0 to 1 (unless we clipped, in which case it might be more than 1) return MathUtil.dB(_peak); } } public double processDouble(double samp) { int quantized = process(samp); return (double)quantized / _maxv; } /// <summary> /// Process a ISample (in-place; the original object is returned, with modified data) /// </summary> /// <param name="samp"></param> public ISample process(ISample samp) { for (int c = 0; c < samp.NumChannels; c++) { samp[c] = processDouble(samp[c]); } return samp; } // Dither double-precision float to arbitrary bits-per-sample (up to 32) public int process(double samp) { // peak is absolute, normal range should be 0 thru 1 if (double.IsNaN(samp) || double.IsInfinity(samp)) { samp = 0; } _peak = Math.Max(_peak, Math.Abs(samp)); int output = 0; double noise; double error; try { // Scale the output first, // - we're still working with floats // - max scale is dependent on the target bit-depth (eg. 32768 for 16-bit) // - min scale is +/- 1, any fractional component will be rounded samp *= _maxv; switch (_type) { case DitherType.NONE: output = (int)Math.Round(samp); //, MidpointRounding.AwayFromZero); break; case DitherType.TRIANGULAR: // Triangular dither // Make +/- 1LSB white randomness noise = NextRandom2(); // Add this noise samp += noise; // Round the sample output = (int)Math.Round(samp); //, MidpointRounding.AwayFromZero); break; case DitherType.SHAPED: case DitherType.SBM: // Make +/- 1LSB white randomness noise = NextRandom(); // Add this noise and subtract the previous noise (filtered) samp += noise; for (int x = 0; x < _filter.Length; x++) { samp -= _filter[x] * _EH[_HistPos + x]; } // Round the sample output = (int)Math.Round(samp); //, MidpointRounding.AwayFromZero); break; } if (_filter.Length > 0) { // Find the error of this output sample (before we clip...) error = (double)output - samp; if (_HistPos < 1) _HistPos += _filter.Length; _HistPos--; // Update buffer (both copies) _EH[_HistPos + _filter.Length] = _EH[_HistPos] = error; } } catch (OverflowException) { if (samp > (_maxv-1)) output = (int)(_maxv-1); else output = (int)_minv; } if (output < _minv) { if (!_clipping) { _clipping = true; Trace.WriteLine("CLIPPING-"); } output = (int)_minv; } else if (output > (_maxv-1)) { if (!clipping) { _clipping = true; Trace.WriteLine("CLIPPING+"); } output = (int)(_maxv-1); } return output; } public int process(float samp) { return process((double)samp); } public void reset() { for (int x = 0; x < _filter.Length; x++) { _EH[x] = 0.0; } _HistPos = _filter.Length - 1; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.Forms; using Sensus.UI.UiProperties; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace Sensus.UI.Inputs { public class ItemPickerDialogInput : ItemPickerInput, IVariableDefiningInput { private string _tipText; private List<string> _items; private bool _allowClearSelection; private Picker _picker; private Label _label; private string _definedVariable; /// <summary> /// A short tip that explains how to pick an item from the dialog window. /// </summary> /// <value>The tip text.</value> [EntryStringUiProperty("Tip Text:", true, 10, false)] public string TipText { get { return _tipText; } set { _tipText = value; } } /// <summary> /// These are the items that the user will have to select from. /// </summary> /// <value>The items.</value> [EditableListUiProperty(null, true, 11, true)] public List<string> Items { get { return _items; } // need set method so that binding can set the list via the EditableListUiProperty set { _items = value; } } /// <summary> /// Whether or not to allow the user to clear the current selection. /// </summary> /// <value><c>true</c> to allow clear selection; otherwise, <c>false</c>.</value> [OnOffUiProperty("Allow Clear Selection:", true, 12)] public bool AllowClearSelection { get { return _allowClearSelection; } set { _allowClearSelection = value; } } /// <summary> /// The name of the variable in <see cref="Protocol.VariableValueUiProperty"/> that this input should /// define the value for. For example, if you wanted this input to supply the value for a variable /// named `study-name`, then set this field to `study-name` and the user's selection will be used as /// the value for this variable. /// </summary> /// <value>The defined variable.</value> [EntryStringUiProperty("Define Variable:", true, 13, false)] public string DefinedVariable { get { return _definedVariable; } set { _definedVariable = value?.Trim(); } } public override object Value { get { return _picker == null || _picker.SelectedIndex < 0 ? null : _picker.Items[_picker.SelectedIndex]; } } [JsonIgnore] public override bool Enabled { get { return _picker.IsEnabled; } set { _picker.IsEnabled = value; } } public override string DefaultName { get { return "Picker (Dialog)"; } } public ItemPickerDialogInput() : base() { Construct(null, new List<string>()); } public ItemPickerDialogInput(string labelText, string tipText, List<string> items) : base(labelText) { Construct(tipText, items); } public ItemPickerDialogInput(string labelText, string name, string tipText, List<string> items) : base(labelText, name) { Construct(tipText, items); } private void Construct(string tipText, List<string> items) { _tipText = string.IsNullOrWhiteSpace(tipText) ? "Make selection here." : tipText; _items = items; _allowClearSelection = true; } public override View GetView(int index) { if (_items.Count == 0) { return null; } if (base.GetView(index) == null) { _picker = new Picker { Title = _tipText, HorizontalOptions = LayoutOptions.FillAndExpand // set the style ID on the view so that we can retrieve it when UI testing #if UI_TESTING , StyleId = Name #endif }; if (_allowClearSelection) { _picker.Items.Add("[Clear Selection]"); } foreach (string item in RandomizeItemOrder ? _items.OrderBy(item => Guid.NewGuid()).ToList() : _items) { _picker.Items.Add(item); } if(IncludeOtherOption && !string.IsNullOrWhiteSpace(OtherOptionText)) { _picker.Items.Add(OtherOptionText); } _picker.SelectedIndexChanged += (o, e) => { if (Value == null) { Complete = false; } else if (Value.ToString() == "[Clear Selection]") { _picker.SelectedIndex = -1; } else { Complete = true; } }; _label = CreateLabel(index); base.SetView(new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.Start, Children = { _label, _picker } }); } else { // if the view was already initialized, just update the label since the index might have changed. _label.Text = GetLabelText(index); // if the view is not enabled, there should be no tip text since the user can't do anything with the picker. if (!Enabled) { _picker.Title = ""; } } return base.GetView(index); } public override string ToString() { return base.ToString() + " -- " + (_items.Count + (IncludeOtherOption ? 1 : 0)) + " Items"; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// InvoiceEdit (editable root object).<br/> /// This is a generated <see cref="InvoiceEdit"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="InvoiceLines"/> of type <see cref="InvoiceLineCollection"/> (1:M relation to <see cref="InvoiceLineItem"/>) /// </remarks> [Serializable] public partial class InvoiceEdit : BusinessBase<InvoiceEdit> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="InvoiceId"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id"); /// <summary> /// The invoice internal identification /// </summary> /// <value>The Invoice Id.</value> public Guid InvoiceId { get { return GetProperty(InvoiceIdProperty); } set { SetProperty(InvoiceIdProperty, value); } } /// <summary> /// Maintains metadata about <see cref="InvoiceNumber"/> property. /// </summary> public static readonly PropertyInfo<string> InvoiceNumberProperty = RegisterProperty<string>(p => p.InvoiceNumber, "Invoice Number"); /// <summary> /// The public invoice number /// </summary> /// <value>The Invoice Number.</value> public string InvoiceNumber { get { return GetProperty(InvoiceNumberProperty); } set { SetProperty(InvoiceNumberProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CustomerId"/> property. /// </summary> public static readonly PropertyInfo<string> CustomerIdProperty = RegisterProperty<string>(p => p.CustomerId, "Customer Id"); /// <summary> /// Gets or sets the Customer Id. /// </summary> /// <value>The Customer Id.</value> public string CustomerId { get { return GetProperty(CustomerIdProperty); } set { SetProperty(CustomerIdProperty, value); } } /// <summary> /// Maintains metadata about <see cref="InvoiceDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> InvoiceDateProperty = RegisterProperty<SmartDate>(p => p.InvoiceDate, "Invoice Date"); /// <summary> /// Gets or sets the Invoice Date. /// </summary> /// <value>The Invoice Date.</value> public string InvoiceDate { get { return GetPropertyConvert<SmartDate, string>(InvoiceDateProperty); } set { SetPropertyConvert<SmartDate, string>(InvoiceDateProperty, value); } } /// <summary> /// Maintains metadata about <see cref="TotalAmount"/> property. /// </summary> public static readonly PropertyInfo<decimal> TotalAmountProperty = RegisterProperty<decimal>(p => p.TotalAmount, "Total Amount"); /// <summary> /// Computed invoice total amount /// </summary> /// <value>The Total Amount.</value> public decimal TotalAmount { get { return GetProperty(TotalAmountProperty); } set { SetProperty(TotalAmountProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date"); /// <summary> /// Gets the Create Date. /// </summary> /// <value>The Create Date.</value> public SmartDate CreateDate { get { return GetProperty(CreateDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateUser"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> CreateUserProperty = RegisterProperty<int>(p => p.CreateUser, "Create User"); /// <summary> /// Gets the Create User. /// </summary> /// <value>The Create User.</value> public int CreateUser { get { return GetProperty(CreateUserProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date"); /// <summary> /// Gets the Change Date. /// </summary> /// <value>The Change Date.</value> public SmartDate ChangeDate { get { return GetProperty(ChangeDateProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeUser"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> ChangeUserProperty = RegisterProperty<int>(p => p.ChangeUser, "Change User"); /// <summary> /// Gets the Change User. /// </summary> /// <value>The Change User.</value> public int ChangeUser { get { return GetProperty(ChangeUserProperty); } } /// <summary> /// Maintains metadata about <see cref="RowVersion"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version"); /// <summary> /// Gets the Row Version. /// </summary> /// <value>The Row Version.</value> public byte[] RowVersion { get { return GetProperty(RowVersionProperty); } } /// <summary> /// Maintains metadata about child <see cref="InvoiceLines"/> property. /// </summary> public static readonly PropertyInfo<InvoiceLineCollection> InvoiceLinesProperty = RegisterProperty<InvoiceLineCollection>(p => p.InvoiceLines, "Invoice Lines", RelationshipTypes.Child); /// <summary> /// Gets the Invoice Lines ("parent load" child property). /// </summary> /// <value>The Invoice Lines.</value> public InvoiceLineCollection InvoiceLines { get { return GetProperty(InvoiceLinesProperty); } private set { LoadProperty(InvoiceLinesProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="InvoiceEdit"/> object. /// </summary> /// <returns>A reference to the created <see cref="InvoiceEdit"/> object.</returns> public static InvoiceEdit NewInvoiceEdit() { return DataPortal.Create<InvoiceEdit>(); } /// <summary> /// Factory method. Loads a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param> /// <returns>A reference to the fetched <see cref="InvoiceEdit"/> object.</returns> public static InvoiceEdit GetInvoiceEdit(Guid invoiceId) { return DataPortal.Fetch<InvoiceEdit>(invoiceId); } /// <summary> /// Factory method. Deletes a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param> public static void DeleteInvoiceEdit(Guid invoiceId) { DataPortal.Delete<InvoiceEdit>(invoiceId); } /// <summary> /// Factory method. Asynchronously creates a new <see cref="InvoiceEdit"/> object. /// </summary> /// <param name="callback">The completion callback method.</param> public static void NewInvoiceEdit(EventHandler<DataPortalResult<InvoiceEdit>> callback) { DataPortal.BeginCreate<InvoiceEdit>(callback); } /// <summary> /// Factory method. Asynchronously loads a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback) { DataPortal.BeginFetch<InvoiceEdit>(invoiceId, callback); } /// <summary> /// Factory method. Asynchronously deletes a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param> /// <param name="callback">The completion callback method.</param> public static void DeleteInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback) { DataPortal.BeginDelete<InvoiceEdit>(invoiceId, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="InvoiceEdit"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public InvoiceEdit() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="InvoiceEdit"/> object properties. /// </summary> [RunLocal] protected override void DataPortal_Create() { LoadProperty(InvoiceIdProperty, Guid.NewGuid()); LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now)); LoadProperty(CreateUserProperty, Security.UserInformation.UserId); LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty)); LoadProperty(ChangeUserProperty, ReadProperty(CreateUserProperty)); LoadProperty(InvoiceLinesProperty, DataPortal.CreateChild<InvoiceLineCollection>()); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="InvoiceEdit"/> object from the database, based on given criteria. /// </summary> /// <param name="invoiceId">The Invoice Id.</param> protected void DataPortal_Fetch(Guid invoiceId) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.GetInvoiceEdit", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@InvoiceId", invoiceId).DbType = DbType.Guid; var args = new DataPortalHookArgs(cmd, invoiceId); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); FetchChildren(dr); } } } /// <summary> /// Loads a <see cref="InvoiceEdit"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(InvoiceIdProperty, dr.GetGuid("InvoiceId")); LoadProperty(InvoiceNumberProperty, dr.GetString("InvoiceNumber")); LoadProperty(CustomerIdProperty, dr.GetString("CustomerId")); LoadProperty(InvoiceDateProperty, dr.GetSmartDate("InvoiceDate", true)); LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true)); LoadProperty(CreateUserProperty, dr.GetInt32("CreateUser")); LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true)); LoadProperty(ChangeUserProperty, dr.GetInt32("ChangeUser")); LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void FetchChildren(SafeDataReader dr) { dr.NextResult(); LoadProperty(InvoiceLinesProperty, DataPortal.FetchChild<InvoiceLineCollection>(dr)); } /// <summary> /// Inserts a new <see cref="InvoiceEdit"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { SimpleAuditTrail(); using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.AddInvoiceEdit", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@InvoiceId", ReadProperty(InvoiceIdProperty)).DbType = DbType.Guid; cmd.Parameters.AddWithValue("@InvoiceNumber", ReadProperty(InvoiceNumberProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@CustomerId", ReadProperty(CustomerIdProperty)).DbType = DbType.StringFixedLength; cmd.Parameters.AddWithValue("@InvoiceDate", ReadProperty(InvoiceDateProperty).DBValue).DbType = DbType.Date; cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@CreateUser", ReadProperty(CreateUserProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUser", ReadProperty(ChangeUserProperty)).DbType = DbType.Int32; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="InvoiceEdit"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { SimpleAuditTrail(); using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.UpdateInvoiceEdit", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@InvoiceId", ReadProperty(InvoiceIdProperty)).DbType = DbType.Guid; cmd.Parameters.AddWithValue("@InvoiceNumber", ReadProperty(InvoiceNumberProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@CustomerId", ReadProperty(CustomerIdProperty)).DbType = DbType.StringFixedLength; cmd.Parameters.AddWithValue("@InvoiceDate", ReadProperty(InvoiceDateProperty).DBValue).DbType = DbType.Date; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUser", ReadProperty(ChangeUserProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } private void SimpleAuditTrail() { LoadProperty(ChangeDateProperty, DateTime.Now); LoadProperty(ChangeUserProperty, Security.UserInformation.UserId); if (IsNew) { LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty)); LoadProperty(CreateUserProperty, ReadProperty(ChangeUserProperty)); } } /// <summary> /// Self deletes the <see cref="InvoiceEdit"/> object. /// </summary> protected override void DataPortal_DeleteSelf() { DataPortal_Delete(InvoiceId); } /// <summary> /// Deletes the <see cref="InvoiceEdit"/> object from database. /// </summary> /// <param name="invoiceId">The delete criteria.</param> [Transactional(TransactionalTypes.TransactionScope)] protected void DataPortal_Delete(Guid invoiceId) { // audit the object, just in case soft delete is used on this object SimpleAuditTrail(); using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("dbo.DeleteInvoiceEdit", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@InvoiceId", invoiceId).DbType = DbType.Guid; var args = new DataPortalHookArgs(cmd, invoiceId); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(InvoiceLinesProperty, DataPortal.CreateChild<InvoiceLineCollection>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; /// <summary> /// System.Array.Sort(System.Array) /// </summary> public class ArrayIndexOf1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using default comparer "); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; string[] s2 = new string[]{"Allin", "Jack", "Mary", "Mike", "Peter", "Tom"}; Array.Sort(s1); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using default comparer "); try { int length = TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetInt32(-55); i1[i] = value; i2[i] = value; } Array.Sort(i1); for (int i = 0; i < length - 1; i++) //manually quich sort { for (int j = i + 1; j < length; j++) { if (i2[i] > i2[j]) { int temp = i2[i]; i2[i] = i2[j]; i2[j] = temp; } } } for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using default comparer "); try { int length = TestLibrary.Generator.GetInt16(-55); char[] c1 = new char[length]; char[] c2 = new char[length]; for (int i = 0; i < length; i++) { char value = TestLibrary.Generator.GetChar(-55); c1[i] = value; c2[i] = value; } Array.Sort(c1); for (int i = 0; i < length - 1; i++) //manually quich sort { for (int j = i + 1; j < length; j++) { if (c2[i] > c2[j]) { char temp = c2[i]; c2[i] = c2[j]; c2[j] = temp; } } } for (int i = 0; i < length; i++) { if (c1[i] != c2[i]) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Sort a string array including null reference "); try { string[] s1 = new string[6]{"Jack", "Mary", null, "Peter", "Tom", "Allin"}; string[] s2 = new string[]{null, "Allin", "Jack", "Mary", "Peter", "Tom"}; Array.Sort(s1); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is null "); try { string[] s1 = null; Array.Sort(s1); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The array is not one dimension "); try { int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } }; Array.Sort(i1); TestLibrary.TestFramework.LogError("103", "The RankException is not throw as expected "); retVal = false; } catch (RankException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: One or more elements in array do not implement the IComparable interface "); try { A[] a1 = new A[4] { new A(), new A(), new A(), new A() }; Array.Sort(a1); TestLibrary.TestFramework.LogError("105", "The InvalidOperationException is not throw as expected "); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayIndexOf1 test = new ArrayIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } class A { public A() { } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities.RemoteHost; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TodoComment { public class TodoCommentTests { [Fact] public async Task SingleLineTodoComment_Colon() { var code = @"// [|TODO:test|]"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Space() { var code = @"// [|TODO test|]"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Underscore() { var code = @"// TODO_test"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Number() { var code = @"// TODO1 test"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Quote() { var code = @"// ""TODO test"""; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Middle() { var code = @"// Hello TODO test"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Document() { var code = @"/// [|TODO test|]"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Preprocessor1() { var code = @"#if DEBUG // [|TODO test|]"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Preprocessor2() { var code = @"#if DEBUG /// [|TODO test|]"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_Region() { var code = @"#region // TODO test"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_EndRegion() { var code = @"#endregion // [|TODO test|]"; await TestAsync(code); } [Fact] public async Task SingleLineTodoComment_TrailingSpan() { var code = @"// [|TODO test |]"; await TestAsync(code); } [Fact] public async Task MultilineTodoComment_Singleline() { var code = @"/* [|TODO: hello |]*/"; await TestAsync(code); } [Fact] public async Task MultilineTodoComment_Singleline_Document() { var code = @"/** [|TODO: hello |]*/"; await TestAsync(code); } [Fact] public async Task MultilineTodoComment_Multiline() { var code = @" /* [|TODO: hello |] [|TODO: hello |] [|TODO: hello |] * [|TODO: hello |] [|TODO: hello |]*/"; await TestAsync(code); } [Fact] public async Task MultilineTodoComment_Multiline_DocComment() { var code = @" /** [|TODO: hello |] [|TODO: hello |] [|TODO: hello |] * [|TODO: hello |] [|TODO: hello |]*/"; await TestAsync(code); } [Fact] public async Task SinglelineDocumentComment_Multiline() { var code = @" /// <summary> /// [|TODO : test |] /// </summary> /// [|UNDONE: test2 |]"; await TestAsync(code); } private static async Task TestAsync(string codeWithMarker) { await TestAsync(codeWithMarker, remote: false); await TestAsync(codeWithMarker, remote: true); } private static async Task TestAsync(string codeWithMarker, bool remote) { using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker, openDocuments: false)) { workspace.Options = workspace.Options.WithChangedOption(RemoteHostOptions.RemoteHostTest, remote); var commentTokens = new TodoCommentTokens(); var provider = new TodoCommentIncrementalAnalyzerProvider(commentTokens); var worker = (TodoCommentIncrementalAnalyzer)provider.CreateIncrementalAnalyzer(workspace); var document = workspace.Documents.First(); var documentId = document.Id; var reasons = new InvocationReasons(PredefinedInvocationReasons.DocumentAdded); await worker.AnalyzeSyntaxAsync(workspace.CurrentSolution.GetDocument(documentId), InvocationReasons.Empty, CancellationToken.None); var todoLists = worker.GetItems_TestingOnly(documentId); var expectedLists = document.SelectedSpans; Assert.Equal(todoLists.Length, expectedLists.Count); for (int i = 0; i < todoLists.Length; i++) { var todo = todoLists[i]; var span = expectedLists[i]; var line = document.InitialTextSnapshot.GetLineFromPosition(span.Start); var text = document.InitialTextSnapshot.GetText(span.ToSpan()); Assert.Equal(todo.MappedLine, line.LineNumber); Assert.Equal(todo.MappedColumn, span.Start - line.Start); Assert.Equal(todo.Message, text); } } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using Newtonsoft.Json; namespace XenAPI { [JsonConverter(typeof(vm_operationsConverter))] public enum vm_operations { /// <summary> /// refers to the operation &quot;snapshot&quot; /// </summary> snapshot, /// <summary> /// refers to the operation &quot;clone&quot; /// </summary> clone, /// <summary> /// refers to the operation &quot;copy&quot; /// </summary> copy, /// <summary> /// refers to the operation &quot;create_template&quot; /// </summary> create_template, /// <summary> /// refers to the operation &quot;revert&quot; /// </summary> revert, /// <summary> /// refers to the operation &quot;checkpoint&quot; /// </summary> checkpoint, /// <summary> /// refers to the operation &quot;snapshot_with_quiesce&quot; /// </summary> snapshot_with_quiesce, /// <summary> /// refers to the operation &quot;provision&quot; /// </summary> provision, /// <summary> /// refers to the operation &quot;start&quot; /// </summary> start, /// <summary> /// refers to the operation &quot;start_on&quot; /// </summary> start_on, /// <summary> /// refers to the operation &quot;pause&quot; /// </summary> pause, /// <summary> /// refers to the operation &quot;unpause&quot; /// </summary> unpause, /// <summary> /// refers to the operation &quot;clean_shutdown&quot; /// </summary> clean_shutdown, /// <summary> /// refers to the operation &quot;clean_reboot&quot; /// </summary> clean_reboot, /// <summary> /// refers to the operation &quot;hard_shutdown&quot; /// </summary> hard_shutdown, /// <summary> /// refers to the operation &quot;power_state_reset&quot; /// </summary> power_state_reset, /// <summary> /// refers to the operation &quot;hard_reboot&quot; /// </summary> hard_reboot, /// <summary> /// refers to the operation &quot;suspend&quot; /// </summary> suspend, /// <summary> /// refers to the operation &quot;csvm&quot; /// </summary> csvm, /// <summary> /// refers to the operation &quot;resume&quot; /// </summary> resume, /// <summary> /// refers to the operation &quot;resume_on&quot; /// </summary> resume_on, /// <summary> /// refers to the operation &quot;pool_migrate&quot; /// </summary> pool_migrate, /// <summary> /// refers to the operation &quot;migrate_send&quot; /// </summary> migrate_send, /// <summary> /// refers to the operation &quot;get_boot_record&quot; /// </summary> get_boot_record, /// <summary> /// refers to the operation &quot;send_sysrq&quot; /// </summary> send_sysrq, /// <summary> /// refers to the operation &quot;send_trigger&quot; /// </summary> send_trigger, /// <summary> /// refers to the operation &quot;query_services&quot; /// </summary> query_services, /// <summary> /// refers to the operation &quot;shutdown&quot; /// </summary> shutdown, /// <summary> /// refers to the operation &quot;call_plugin&quot; /// </summary> call_plugin, /// <summary> /// Changing the memory settings /// </summary> changing_memory_live, /// <summary> /// Waiting for the memory settings to change /// </summary> awaiting_memory_live, /// <summary> /// Changing the memory dynamic range /// </summary> changing_dynamic_range, /// <summary> /// Changing the memory static range /// </summary> changing_static_range, /// <summary> /// Changing the memory limits /// </summary> changing_memory_limits, /// <summary> /// Changing the shadow memory for a halted VM. /// </summary> changing_shadow_memory, /// <summary> /// Changing the shadow memory for a running VM. /// </summary> changing_shadow_memory_live, /// <summary> /// Changing VCPU settings for a halted VM. /// </summary> changing_VCPUs, /// <summary> /// Changing VCPU settings for a running VM. /// </summary> changing_VCPUs_live, /// <summary> /// Changing NVRAM for a halted VM. /// </summary> changing_NVRAM, /// <summary> /// /// </summary> assert_operation_valid, /// <summary> /// Add, remove, query or list data sources /// </summary> data_source_op, /// <summary> /// /// </summary> update_allowed_operations, /// <summary> /// Turning this VM into a template /// </summary> make_into_template, /// <summary> /// importing a VM from a network stream /// </summary> import, /// <summary> /// exporting a VM to a network stream /// </summary> export, /// <summary> /// exporting VM metadata to a network stream /// </summary> metadata_export, /// <summary> /// Reverting the VM to a previous snapshotted state /// </summary> reverting, /// <summary> /// refers to the act of uninstalling the VM /// </summary> destroy, unknown } public static class vm_operations_helper { public static string ToString(vm_operations x) { return x.StringOf(); } } public static partial class EnumExt { public static string StringOf(this vm_operations x) { switch (x) { case vm_operations.snapshot: return "snapshot"; case vm_operations.clone: return "clone"; case vm_operations.copy: return "copy"; case vm_operations.create_template: return "create_template"; case vm_operations.revert: return "revert"; case vm_operations.checkpoint: return "checkpoint"; case vm_operations.snapshot_with_quiesce: return "snapshot_with_quiesce"; case vm_operations.provision: return "provision"; case vm_operations.start: return "start"; case vm_operations.start_on: return "start_on"; case vm_operations.pause: return "pause"; case vm_operations.unpause: return "unpause"; case vm_operations.clean_shutdown: return "clean_shutdown"; case vm_operations.clean_reboot: return "clean_reboot"; case vm_operations.hard_shutdown: return "hard_shutdown"; case vm_operations.power_state_reset: return "power_state_reset"; case vm_operations.hard_reboot: return "hard_reboot"; case vm_operations.suspend: return "suspend"; case vm_operations.csvm: return "csvm"; case vm_operations.resume: return "resume"; case vm_operations.resume_on: return "resume_on"; case vm_operations.pool_migrate: return "pool_migrate"; case vm_operations.migrate_send: return "migrate_send"; case vm_operations.get_boot_record: return "get_boot_record"; case vm_operations.send_sysrq: return "send_sysrq"; case vm_operations.send_trigger: return "send_trigger"; case vm_operations.query_services: return "query_services"; case vm_operations.shutdown: return "shutdown"; case vm_operations.call_plugin: return "call_plugin"; case vm_operations.changing_memory_live: return "changing_memory_live"; case vm_operations.awaiting_memory_live: return "awaiting_memory_live"; case vm_operations.changing_dynamic_range: return "changing_dynamic_range"; case vm_operations.changing_static_range: return "changing_static_range"; case vm_operations.changing_memory_limits: return "changing_memory_limits"; case vm_operations.changing_shadow_memory: return "changing_shadow_memory"; case vm_operations.changing_shadow_memory_live: return "changing_shadow_memory_live"; case vm_operations.changing_VCPUs: return "changing_VCPUs"; case vm_operations.changing_VCPUs_live: return "changing_VCPUs_live"; case vm_operations.changing_NVRAM: return "changing_NVRAM"; case vm_operations.assert_operation_valid: return "assert_operation_valid"; case vm_operations.data_source_op: return "data_source_op"; case vm_operations.update_allowed_operations: return "update_allowed_operations"; case vm_operations.make_into_template: return "make_into_template"; case vm_operations.import: return "import"; case vm_operations.export: return "export"; case vm_operations.metadata_export: return "metadata_export"; case vm_operations.reverting: return "reverting"; case vm_operations.destroy: return "destroy"; default: return "unknown"; } } } internal class vm_operationsConverter : XenEnumConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((vm_operations)value).StringOf()); } } }
using Lucene.Net.Support; using System; using System.Diagnostics; using System.IO; namespace Lucene.Net.Util.Packed { /* * 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 DataInput = Lucene.Net.Store.DataInput; /// <summary> /// Space optimized random access capable array of values with a fixed number of /// bits/value. Values are packed contiguously. /// <para/> /// The implementation strives to perform af fast as possible under the /// constraint of contiguous bits, by avoiding expensive operations. This comes /// at the cost of code clarity. /// <para/> /// Technical details: this implementation is a refinement of a non-branching /// version. The non-branching get and set methods meant that 2 or 4 atomics in /// the underlying array were always accessed, even for the cases where only /// 1 or 2 were needed. Even with caching, this had a detrimental effect on /// performance. /// Related to this issue, the old implementation used lookup tables for shifts /// and masks, which also proved to be a bit slower than calculating the shifts /// and masks on the fly. /// See https://issues.apache.org/jira/browse/LUCENE-4062 for details. /// </summary> public class Packed64 : PackedInt32s.MutableImpl { internal const int BLOCK_SIZE = 64; // 32 = int, 64 = long internal const int BLOCK_BITS = 6; // The #bits representing BLOCK_SIZE internal static readonly int MOD_MASK = BLOCK_SIZE - 1; // x % BLOCK_SIZE /// <summary> /// Values are stores contiguously in the blocks array. /// </summary> private readonly long[] blocks; /// <summary> /// A right-aligned mask of width BitsPerValue used by <see cref="Get(int)"/>. /// </summary> private readonly long maskRight; /// <summary> /// Optimization: Saves one lookup in <see cref="Get(int)"/>. /// </summary> private readonly int bpvMinusBlockSize; /// <summary> /// Creates an array with the internal structures adjusted for the given /// limits and initialized to 0. </summary> /// <param name="valueCount"> The number of elements. </param> /// <param name="bitsPerValue"> The number of bits available for any given value. </param> public Packed64(int valueCount, int bitsPerValue) : base(valueCount, bitsPerValue) { PackedInt32s.Format format = PackedInt32s.Format.PACKED; int longCount = format.Int64Count(PackedInt32s.VERSION_CURRENT, valueCount, bitsPerValue); this.blocks = new long[longCount]; // MaskRight = ~0L << (int)((uint)(BLOCK_SIZE - bitsPerValue) >> (BLOCK_SIZE - bitsPerValue)); //original // MaskRight = (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue); //mod /*var a = ~0L << (int)((uint)(BLOCK_SIZE - bitsPerValue) >> (BLOCK_SIZE - bitsPerValue)); //original var b = (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue); //mod Debug.Assert(a == b, "a: " + a, ", b: " + b);*/ maskRight = (long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)); //mod //Debug.Assert((long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)) == (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)); bpvMinusBlockSize = bitsPerValue - BLOCK_SIZE; } /// <summary> /// Creates an array with content retrieved from the given <see cref="DataInput"/>. </summary> /// <param name="in"> A <see cref="DataInput"/>, positioned at the start of Packed64-content. </param> /// <param name="valueCount"> The number of elements. </param> /// <param name="bitsPerValue"> The number of bits available for any given value. </param> /// <exception cref="IOException"> If the values for the backing array could not /// be retrieved. </exception> public Packed64(int packedIntsVersion, DataInput @in, int valueCount, int bitsPerValue) : base(valueCount, bitsPerValue) { PackedInt32s.Format format = PackedInt32s.Format.PACKED; long byteCount = format.ByteCount(packedIntsVersion, valueCount, bitsPerValue); // to know how much to read int longCount = format.Int64Count(PackedInt32s.VERSION_CURRENT, valueCount, bitsPerValue); // to size the array blocks = new long[longCount]; // read as many longs as we can for (int i = 0; i < byteCount / 8; ++i) { blocks[i] = @in.ReadInt64(); } int remaining = (int)(byteCount % 8); if (remaining != 0) { // read the last bytes long lastLong = 0; for (int i = 0; i < remaining; ++i) { lastLong |= (@in.ReadByte() & 0xFFL) << (56 - i * 8); } blocks[blocks.Length - 1] = lastLong; } maskRight = (long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)); bpvMinusBlockSize = bitsPerValue - BLOCK_SIZE; } /// <param name="index"> The position of the value. </param> /// <returns> The value at the given index. </returns> public override long Get(int index) { // The abstract index in a bit stream long majorBitPos = (long)index * m_bitsPerValue; // The index in the backing long-array int elementPos = (int)(((ulong)majorBitPos) >> BLOCK_BITS); //int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS)); // The number of value-bits in the second long long endBits = (majorBitPos & MOD_MASK) + bpvMinusBlockSize; if (endBits <= 0) // Single block { return ((long)((ulong)blocks[elementPos] >> (int)-endBits)) & maskRight; } // Two blocks return ((blocks[elementPos] << (int)endBits) | ((long)((ulong)blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & maskRight; } /*/// <param name="index"> the position of the value. </param> /// <returns> the value at the given index. </returns> public override long Get(int index) { // The abstract index in a bit stream long majorBitPos = (long)index * bitsPerValue; // The index in the backing long-array int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS)); // The number of value-bits in the second long long endBits = (majorBitPos & MOD_MASK) + BpvMinusBlockSize; if (endBits <= 0) // Single block { var mod = (long) ((ulong) (Blocks[elementPos]) >> (int) (-endBits)) & MaskRight; var og = ((long) ((ulong) Blocks[elementPos] >> (int) -endBits)) & MaskRight; Debug.Assert(mod == og); //return (long)((ulong)(Blocks[elementPos]) >> (int)(-endBits)) & MaskRight; return ((long)((ulong)Blocks[elementPos] >> (int)-endBits)) & MaskRight; } // Two blocks var a = (((Blocks[elementPos] << (int)endBits) | (long)(((ulong)(Blocks[elementPos + 1])) >> (int)(BLOCK_SIZE - endBits))) & MaskRight); var b = ((Blocks[elementPos] << (int)endBits) | ((long)((ulong)Blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & MaskRight; Debug.Assert(a == b); //return (((Blocks[elementPos] << (int)endBits) | (long)(((ulong)(Blocks[elementPos + 1])) >> (int)(BLOCK_SIZE - endBits))) & MaskRight); return ((Blocks[elementPos] << (int)endBits) | ((long)((ulong)Blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & MaskRight; }*/ public override int Get(int index, long[] arr, int off, int len) { Debug.Assert(len > 0, "len must be > 0 (got " + len + ")"); Debug.Assert(index >= 0 && index < m_valueCount); len = Math.Min(len, m_valueCount - index); Debug.Assert(off + len <= arr.Length); int originalIndex = index; PackedInt32s.IDecoder decoder = BulkOperation.Of(PackedInt32s.Format.PACKED, m_bitsPerValue); // go to the next block where the value does not span across two blocks int offsetInBlocks = index % decoder.Int64ValueCount; if (offsetInBlocks != 0) { for (int i = offsetInBlocks; i < decoder.Int64ValueCount && len > 0; ++i) { arr[off++] = Get(index++); --len; } if (len == 0) { return index - originalIndex; } } // bulk get Debug.Assert(index % decoder.Int64ValueCount == 0); int blockIndex = (int)((ulong)((long)index * m_bitsPerValue) >> BLOCK_BITS); Debug.Assert((((long)index * m_bitsPerValue) & MOD_MASK) == 0); int iterations = len / decoder.Int64ValueCount; decoder.Decode(blocks, blockIndex, arr, off, iterations); int gotValues = iterations * decoder.Int64ValueCount; index += gotValues; len -= gotValues; Debug.Assert(len >= 0); if (index > originalIndex) { // stay at the block boundary return index - originalIndex; } else { // no progress so far => already at a block boundary but no full block to get Debug.Assert(index == originalIndex); return base.Get(index, arr, off, len); } } public override void Set(int index, long value) { // The abstract index in a contiguous bit stream long majorBitPos = (long)index * m_bitsPerValue; // The index in the backing long-array int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS)); // / BLOCK_SIZE // The number of value-bits in the second long long endBits = (majorBitPos & MOD_MASK) + bpvMinusBlockSize; if (endBits <= 0) // Single block { blocks[elementPos] = blocks[elementPos] & ~(maskRight << (int)-endBits) | (value << (int)-endBits); return; } // Two blocks blocks[elementPos] = blocks[elementPos] & ~((long)((ulong)maskRight >> (int)endBits)) | ((long)((ulong)value >> (int)endBits)); blocks[elementPos + 1] = blocks[elementPos + 1] & ((long)(unchecked((ulong)~0L) >> (int)endBits)) | (value << (int)(BLOCK_SIZE - endBits)); } public override int Set(int index, long[] arr, int off, int len) { Debug.Assert(len > 0, "len must be > 0 (got " + len + ")"); Debug.Assert(index >= 0 && index < m_valueCount); len = Math.Min(len, m_valueCount - index); Debug.Assert(off + len <= arr.Length); int originalIndex = index; PackedInt32s.IEncoder encoder = BulkOperation.Of(PackedInt32s.Format.PACKED, m_bitsPerValue); // go to the next block where the value does not span across two blocks int offsetInBlocks = index % encoder.Int64ValueCount; if (offsetInBlocks != 0) { for (int i = offsetInBlocks; i < encoder.Int64ValueCount && len > 0; ++i) { Set(index++, arr[off++]); --len; } if (len == 0) { return index - originalIndex; } } // bulk set Debug.Assert(index % encoder.Int64ValueCount == 0); int blockIndex = (int)((ulong)((long)index * m_bitsPerValue) >> BLOCK_BITS); Debug.Assert((((long)index * m_bitsPerValue) & MOD_MASK) == 0); int iterations = len / encoder.Int64ValueCount; encoder.Encode(arr, off, blocks, blockIndex, iterations); int setValues = iterations * encoder.Int64ValueCount; index += setValues; len -= setValues; Debug.Assert(len >= 0); if (index > originalIndex) { // stay at the block boundary return index - originalIndex; } else { // no progress so far => already at a block boundary but no full block to get Debug.Assert(index == originalIndex); return base.Set(index, arr, off, len); } } public override string ToString() { return "Packed64(bitsPerValue=" + m_bitsPerValue + ", size=" + Count + ", elements.length=" + blocks.Length + ")"; } public override long RamBytesUsed() { return RamUsageEstimator.AlignObjectSize( RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 3 * RamUsageEstimator.NUM_BYTES_INT32 // bpvMinusBlockSize,valueCount,bitsPerValue + RamUsageEstimator.NUM_BYTES_INT64 // maskRight + RamUsageEstimator.NUM_BYTES_OBJECT_REF) // blocks ref + RamUsageEstimator.SizeOf(blocks); } public override void Fill(int fromIndex, int toIndex, long val) { Debug.Assert(PackedInt32s.BitsRequired(val) <= BitsPerValue); Debug.Assert(fromIndex <= toIndex); // minimum number of values that use an exact number of full blocks int nAlignedValues = 64 / Gcd(64, m_bitsPerValue); int span = toIndex - fromIndex; if (span <= 3 * nAlignedValues) { // there needs be at least 2 * nAlignedValues aligned values for the // block approach to be worth trying base.Fill(fromIndex, toIndex, val); return; } // fill the first values naively until the next block start int fromIndexModNAlignedValues = fromIndex % nAlignedValues; if (fromIndexModNAlignedValues != 0) { for (int i = fromIndexModNAlignedValues; i < nAlignedValues; ++i) { Set(fromIndex++, val); } } Debug.Assert(fromIndex % nAlignedValues == 0); // compute the long[] blocks for nAlignedValues consecutive values and // use them to set as many values as possible without applying any mask // or shift int nAlignedBlocks = (nAlignedValues * m_bitsPerValue) >> 6; long[] nAlignedValuesBlocks; { Packed64 values = new Packed64(nAlignedValues, m_bitsPerValue); for (int i = 0; i < nAlignedValues; ++i) { values.Set(i, val); } nAlignedValuesBlocks = values.blocks; Debug.Assert(nAlignedBlocks <= nAlignedValuesBlocks.Length); } int startBlock = (int)((ulong)((long)fromIndex * m_bitsPerValue) >> 6); int endBlock = (int)((ulong)((long)toIndex * m_bitsPerValue) >> 6); for (int block = startBlock; block < endBlock; ++block) { long blockValue = nAlignedValuesBlocks[block % nAlignedBlocks]; blocks[block] = blockValue; } // fill the gap for (int i = (int)(((long)endBlock << 6) / m_bitsPerValue); i < toIndex; ++i) { Set(i, val); } } private static int Gcd(int a, int b) { if (a < b) { return Gcd(b, a); } else if (b == 0) { return a; } else { return Gcd(b, a % b); } } public override void Clear() { Arrays.Fill(blocks, 0L); } } }
// 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.Globalization; using System.Net.Sockets; using System.Text; #if SYSTEM_NET_PRIMITIVES_DLL namespace System.Net #else namespace System.Net.Internals #endif { // This class is used when subclassing EndPoint, and provides indication // on how to format the memory buffers that the platform uses for network addresses. #if SYSTEM_NET_PRIMITIVES_DLL public #else internal #endif class SocketAddress { internal static readonly int IPv6AddressSize = SocketAddressPal.IPv6AddressSize; internal static readonly int IPv4AddressSize = SocketAddressPal.IPv4AddressSize; internal int InternalSize; internal byte[] Buffer; private const int MinSize = 2; private const int MaxSize = 32; // IrDA requires 32 bytes private const int DataOffset = 2; private bool _changed = true; private int _hash; public AddressFamily Family { get { return SocketAddressPal.GetAddressFamily(Buffer); } } public int Size { get { return InternalSize; } } // Access to unmanaged serialized data. This doesn't // allow access to the first 2 bytes of unmanaged memory // that are supposed to contain the address family which // is readonly. public byte this[int offset] { get { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } return Buffer[offset]; } set { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } if (Buffer[offset] != value) { _changed = true; } Buffer[offset] = value; } } public SocketAddress(AddressFamily family) : this(family, MaxSize) { } public SocketAddress(AddressFamily family, int size) { if (size < MinSize) { throw new ArgumentOutOfRangeException(nameof(size)); } InternalSize = size; Buffer = new byte[(size / IntPtr.Size + 2) * IntPtr.Size]; SocketAddressPal.SetAddressFamily(Buffer, family); } internal SocketAddress(IPAddress ipAddress) : this(ipAddress.AddressFamily, ((ipAddress.AddressFamily == AddressFamily.InterNetwork) ? IPv4AddressSize : IPv6AddressSize)) { // No Port. SocketAddressPal.SetPort(Buffer, 0); if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) { Span<byte> addressBytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; ipAddress.TryWriteBytes(addressBytes, out int bytesWritten); Debug.Assert(bytesWritten == IPAddressParserStatics.IPv6AddressBytes); SocketAddressPal.SetIPv6Address(Buffer, addressBytes, (uint)ipAddress.ScopeId); } else { #pragma warning disable CS0618 // using Obsolete Address API because it's the more efficient option in this case uint address = unchecked((uint)ipAddress.Address); #pragma warning restore CS0618 Debug.Assert(ipAddress.AddressFamily == AddressFamily.InterNetwork); SocketAddressPal.SetIPv4Address(Buffer, address); } } internal SocketAddress(IPAddress ipaddress, int port) : this(ipaddress) { SocketAddressPal.SetPort(Buffer, unchecked((ushort)port)); } internal IPAddress GetIPAddress() { if (Family == AddressFamily.InterNetworkV6) { Debug.Assert(Size >= IPv6AddressSize); Span<byte> address = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; SocketAddressPal.GetIPv6Address(Buffer, address, out scope); return new IPAddress(address, (long)scope); } else if (Family == AddressFamily.InterNetwork) { Debug.Assert(Size >= IPv4AddressSize); long address = (long)SocketAddressPal.GetIPv4Address(Buffer) & 0x0FFFFFFFF; return new IPAddress(address); } else { #if SYSTEM_NET_PRIMITIVES_DLL throw new SocketException(SocketError.AddressFamilyNotSupported); #else throw new SocketException((int)SocketError.AddressFamilyNotSupported); #endif } } internal IPEndPoint GetIPEndPoint() { IPAddress address = GetIPAddress(); int port = (int)SocketAddressPal.GetPort(Buffer); return new IPEndPoint(address, port); } // For ReceiveFrom we need to pin address size, using reserved Buffer space. internal void CopyAddressSizeIntoBuffer() { Buffer[Buffer.Length - IntPtr.Size] = unchecked((byte)(InternalSize)); Buffer[Buffer.Length - IntPtr.Size + 1] = unchecked((byte)(InternalSize >> 8)); Buffer[Buffer.Length - IntPtr.Size + 2] = unchecked((byte)(InternalSize >> 16)); Buffer[Buffer.Length - IntPtr.Size + 3] = unchecked((byte)(InternalSize >> 24)); } // Can be called after the above method did work. internal int GetAddressSizeOffset() { return Buffer.Length - IntPtr.Size; } public override bool Equals(object comparand) { SocketAddress castedComparand = comparand as SocketAddress; if (castedComparand == null || this.Size != castedComparand.Size) { return false; } for (int i = 0; i < this.Size; i++) { if (this[i] != castedComparand[i]) { return false; } } return true; } public override int GetHashCode() { if (_changed) { _changed = false; _hash = 0; int i; int size = Size & ~3; for (i = 0; i < size; i += 4) { _hash ^= (int)Buffer[i] | ((int)Buffer[i + 1] << 8) | ((int)Buffer[i + 2] << 16) | ((int)Buffer[i + 3] << 24); } if ((Size & 3) != 0) { int remnant = 0; int shift = 0; for (; i < Size; ++i) { remnant |= ((int)Buffer[i]) << shift; shift += 8; } _hash ^= remnant; } } return _hash; } public override string ToString() { // Get the address family string. In almost all cases, this should be a cached string // from the enum and won't actually allocate. string familyString = Family.ToString(); // Determine the maximum length needed to format. int maxLength = familyString.Length + // AddressFamily 1 + // : 10 + // Size (max length for a positive Int32) 2 + // :{ (Size - DataOffset) * 4 + // at most ','+3digits per byte 1; // } Span<char> result = maxLength <= 256 ? // arbitrary limit that should be large enough for the vast majority of cases stackalloc char[256] : new char[maxLength]; familyString.AsSpan().CopyTo(result); int length = familyString.Length; result[length++] = ':'; bool formatted = Size.TryFormat(result.Slice(length), out int charsWritten); Debug.Assert(formatted); length += charsWritten; result[length++] = ':'; result[length++] = '{'; byte[] buffer = Buffer; for (int i = DataOffset; i < Size; i++) { if (i > DataOffset) { result[length++] = ','; } formatted = buffer[i].TryFormat(result.Slice(length), out charsWritten); Debug.Assert(formatted); length += charsWritten; } result[length++] = '}'; return result.Slice(0, length).ToString(); } } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERLevel; namespace ParentLoad.Business.ERLevel { /// <summary> /// A03_Continent_Child (editable child object).<br/> /// This is a generated base class of <see cref="A03_Continent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A02_Continent"/> collection. /// </remarks> [Serializable] public partial class A03_Continent_Child : BusinessBase<A03_Continent_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "Continent Child Name"); /// <summary> /// Gets or sets the Continent Child Name. /// </summary> /// <value>The Continent Child Name.</value> public string Continent_Child_Name { get { return GetProperty(Continent_Child_NameProperty); } set { SetProperty(Continent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A03_Continent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="A03_Continent_Child"/> object.</returns> internal static A03_Continent_Child NewA03_Continent_Child() { return DataPortal.CreateChild<A03_Continent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="A03_Continent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="A03_Continent_Child"/> object.</returns> internal static A03_Continent_Child GetA03_Continent_Child(SafeDataReader dr) { A03_Continent_Child obj = new A03_Continent_Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A03_Continent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public A03_Continent_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A03_Continent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A03_Continent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A03_Continent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A02_Continent parent) { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IA03_Continent_ChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.Continent_ID, Continent_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="A03_Continent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A02_Continent parent) { if (!IsDirty) return; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IA03_Continent_ChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.Continent_ID, Continent_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="A03_Continent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A02_Continent parent) { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IA03_Continent_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Continent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* * @author Valentin Simonov / http://va.lent.in/ */ using System; using System.Collections.Generic; using TUIOsharp; using TUIOsharp.DataProcessors; using TUIOsharp.Entities; using UnityEngine; namespace TouchScript.InputSources { /// <summary> /// Processes TUIO 1.1 input. /// </summary> [AddComponentMenu("TouchScript/Input Sources/TUIO Input")] public sealed class TuioInput : InputSource { #region Constants /// <summary> /// Type of TUIO input object. /// </summary> [Flags] public enum InputType { /// <summary> /// Touch/pointer. /// </summary> Cursors = 1 << 0, /// <summary> /// Shape. /// </summary> Blobs = 1 << 1, /// <summary> /// Tagged object. /// </summary> Objects = 1 << 2 } #endregion #region Public properties /// <summary> /// Port to listen to. /// </summary> public int TuioPort { get { return tuioPort; } set { if (tuioPort == value) return; tuioPort = value; connect(); } } /// <summary> /// What input types should the input source listen to. /// </summary> public InputType SupportedInputs { get { return supportedInputs; } set { if (supportedInputs == value) return; supportedInputs = value; updateInputs(); } } /// <summary> /// List of TUIO object ids to tag mappings. /// </summary> public IList<TuioObjectMapping> TuioObjectMappings { get { return tuioObjectMappings; } } /// <summary> /// Tags for new cursors. /// </summary> public Tags CursorTags { get { return cursorTags; } } /// <summary> /// Tags for new blobs. /// </summary> public Tags BlobTags { get { return blobTags; } } /// <summary> /// Tags for new objects. /// </summary> public Tags ObjectTags { get { return objectTags; } } #endregion #region Private variables [SerializeField] private int tuioPort = 3333; [SerializeField] private InputType supportedInputs = InputType.Cursors | InputType.Blobs | InputType.Objects; [SerializeField] private List<TuioObjectMapping> tuioObjectMappings = new List<TuioObjectMapping>(); [SerializeField] private Tags cursorTags = new Tags(new List<string>() {Tags.SOURCE_TUIO, Tags.INPUT_TOUCH}); [SerializeField] private Tags blobTags = new Tags(new List<string>() {Tags.SOURCE_TUIO, Tags.INPUT_TOUCH}); [SerializeField] private Tags objectTags = new Tags(new List<string>() {Tags.SOURCE_TUIO, Tags.INPUT_OBJECT}); private TuioServer server; private CursorProcessor cursorProcessor; private ObjectProcessor objectProcessor; private BlobProcessor blobProcessor; private Dictionary<TuioCursor, ITouch> cursorToInternalId = new Dictionary<TuioCursor, ITouch>(); private Dictionary<TuioBlob, ITouch> blobToInternalId = new Dictionary<TuioBlob, ITouch>(); private Dictionary<TuioObject, ITouch> objectToInternalId = new Dictionary<TuioObject, ITouch>(); private int screenWidth; private int screenHeight; #endregion #region Unity /// <inheritdoc /> protected override void OnEnable() { base.OnEnable(); screenWidth = Screen.width; screenHeight = Screen.height; cursorProcessor = new CursorProcessor(); cursorProcessor.CursorAdded += OnCursorAdded; cursorProcessor.CursorUpdated += OnCursorUpdated; cursorProcessor.CursorRemoved += OnCursorRemoved; blobProcessor = new BlobProcessor(); blobProcessor.BlobAdded += OnBlobAdded; blobProcessor.BlobUpdated += OnBlobUpdated; blobProcessor.BlobRemoved += OnBlobRemoved; objectProcessor = new ObjectProcessor(); objectProcessor.ObjectAdded += OnObjectAdded; objectProcessor.ObjectUpdated += OnObjectUpdated; objectProcessor.ObjectRemoved += OnObjectRemoved; connect(); } /// <inheritdoc /> protected override void Update() { base.Update(); screenWidth = Screen.width; screenHeight = Screen.height; } /// <inheritdoc /> protected override void OnDisable() { disconnect(); base.OnDisable(); } #endregion #region Private functions private void connect() { if (!Application.isPlaying) return; if (server != null) disconnect(); server = new TuioServer(TuioPort); server.Connect(); updateInputs(); } private void disconnect() { if (server != null) { server.RemoveAllDataProcessors(); server.Disconnect(); server = null; } foreach (var i in cursorToInternalId) { cancelTouch(i.Value.Id); } } private void updateInputs() { if (server == null) return; if ((supportedInputs & InputType.Cursors) != 0) server.AddDataProcessor(cursorProcessor); else server.RemoveDataProcessor(cursorProcessor); if ((supportedInputs & InputType.Blobs) != 0) server.AddDataProcessor(blobProcessor); else server.RemoveDataProcessor(blobProcessor); if ((supportedInputs & InputType.Objects) != 0) server.AddDataProcessor(objectProcessor); else server.RemoveDataProcessor(objectProcessor); } private void updateBlobProperties(ITouch touch, TuioBlob blob) { var props = touch.Properties; props["Angle"] = blob.Angle; props["Width"] = blob.Width; props["Height"] = blob.Height; props["Area"] = blob.Area; props["RotationVelocity"] = blob.RotationVelocity; props["RotationAcceleration"] = blob.RotationAcceleration; } private void updateObjectProperties(ITouch touch, TuioObject obj) { var props = touch.Properties; props["Angle"] = obj.Angle; props["ObjectId"] = obj.ClassId; props["RotationVelocity"] = obj.RotationVelocity; props["RotationAcceleration"] = obj.RotationAcceleration; } private string getTagById(int id) { foreach (var tuioObjectMapping in tuioObjectMappings) { if (tuioObjectMapping.Id == id) return tuioObjectMapping.Tag; } return null; } #endregion #region Event handlers private void OnCursorAdded(object sender, TuioCursorEventArgs e) { var entity = e.Cursor; lock (this) { var x = entity.X * screenWidth; var y = (1 - entity.Y) * screenHeight; cursorToInternalId.Add(entity, beginTouch(new Vector2(x, y), new Tags(CursorTags))); } } private void OnCursorUpdated(object sender, TuioCursorEventArgs e) { var entity = e.Cursor; lock (this) { ITouch touch; if (!cursorToInternalId.TryGetValue(entity, out touch)) return; var x = entity.X * screenWidth; var y = (1 - entity.Y) * screenHeight; moveTouch(touch.Id, new Vector2(x, y)); } } private void OnCursorRemoved(object sender, TuioCursorEventArgs e) { var entity = e.Cursor; lock (this) { ITouch touch; if (!cursorToInternalId.TryGetValue(entity, out touch)) return; cursorToInternalId.Remove(entity); endTouch(touch.Id); } } private void OnBlobAdded(object sender, TuioBlobEventArgs e) { var entity = e.Blob; lock (this) { var x = entity.X * screenWidth; var y = (1 - entity.Y) * screenHeight; var touch = beginTouch(new Vector2(x, y), new Tags(BlobTags)); updateBlobProperties(touch, entity); blobToInternalId.Add(entity, touch); } } private void OnBlobUpdated(object sender, TuioBlobEventArgs e) { var entity = e.Blob; lock (this) { ITouch touch; if (!blobToInternalId.TryGetValue(entity, out touch)) return; var x = entity.X * screenWidth; var y = (1 - entity.Y) * screenHeight; moveTouch(touch.Id, new Vector2(x, y)); updateBlobProperties(touch, entity); } } private void OnBlobRemoved(object sender, TuioBlobEventArgs e) { var entity = e.Blob; lock (this) { ITouch touch; if (!blobToInternalId.TryGetValue(entity, out touch)) return; blobToInternalId.Remove(entity); endTouch(touch.Id); } } private void OnObjectAdded(object sender, TuioObjectEventArgs e) { var entity = e.Object; lock (this) { var x = entity.X * screenWidth; var y = (1 - entity.Y) * screenHeight; var touch = beginTouch(new Vector2(x, y), new Tags(ObjectTags)); updateObjectProperties(touch, entity); objectToInternalId.Add(entity, touch); touch.Tags.AddTag(getTagById(entity.ClassId)); } } private void OnObjectUpdated(object sender, TuioObjectEventArgs e) { var entity = e.Object; lock (this) { ITouch touch; if (!objectToInternalId.TryGetValue(entity, out touch)) return; var x = entity.X * screenWidth; var y = (1 - entity.Y) * screenHeight; moveTouch(touch.Id, new Vector2(x, y)); updateObjectProperties(touch, entity); } } private void OnObjectRemoved(object sender, TuioObjectEventArgs e) { var entity = e.Object; lock (this) { ITouch touch; if (!objectToInternalId.TryGetValue(entity, out touch)) return; objectToInternalId.Remove(entity); endTouch(touch.Id); } } #endregion } /// <summary> /// TUIO object id to tag mapping value object. /// </summary> [Serializable] public class TuioObjectMapping { /// <summary> /// TUIO object id. /// </summary> public int Id; /// <summary> /// Tag to attach to this object. /// </summary> public string Tag; } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.APIGateway.Model { /// <summary> /// Represents a HTTP, AWS, or Mock integration. /// </summary> public partial class GetIntegrationResponse : AmazonWebServiceResponse { private List<string> _cacheKeyParameters = new List<string>(); private string _cacheNamespace; private string _credentials; private string _httpMethod; private Dictionary<string, IntegrationResponse> _integrationResponses = new Dictionary<string, IntegrationResponse>(); private Dictionary<string, string> _requestParameters = new Dictionary<string, string>(); private Dictionary<string, string> _requestTemplates = new Dictionary<string, string>(); private IntegrationType _type; private string _uri; /// <summary> /// Gets and sets the property CacheKeyParameters. /// <para> /// Specifies the integration's cache key parameters. /// </para> /// </summary> public List<string> CacheKeyParameters { get { return this._cacheKeyParameters; } set { this._cacheKeyParameters = value; } } // Check to see if CacheKeyParameters property is set internal bool IsSetCacheKeyParameters() { return this._cacheKeyParameters != null && this._cacheKeyParameters.Count > 0; } /// <summary> /// Gets and sets the property CacheNamespace. /// <para> /// Specifies the integration's cache namespace. /// </para> /// </summary> public string CacheNamespace { get { return this._cacheNamespace; } set { this._cacheNamespace = value; } } // Check to see if CacheNamespace property is set internal bool IsSetCacheNamespace() { return this._cacheNamespace != null; } /// <summary> /// Gets and sets the property Credentials. /// <para> /// Specifies the credentials required for the integration, if any. For AWS integrations, /// three options are available. To specify an IAM Role for Amazon API Gateway to assume, /// use the role's Amazon Resource Name (ARN). To require that the caller's identity be /// passed through from the request, specify the string <code>arn:aws:iam::\*:user/\*</code>. /// To use resource-based permissions on supported AWS services, specify null. /// </para> /// </summary> public string Credentials { get { return this._credentials; } set { this._credentials = value; } } // Check to see if Credentials property is set internal bool IsSetCredentials() { return this._credentials != null; } /// <summary> /// Gets and sets the property HttpMethod. /// <para> /// Specifies the integration's HTTP method type. /// </para> /// </summary> public string HttpMethod { get { return this._httpMethod; } set { this._httpMethod = value; } } // Check to see if HttpMethod property is set internal bool IsSetHttpMethod() { return this._httpMethod != null; } /// <summary> /// Gets and sets the property IntegrationResponses. /// <para> /// Specifies the integration's responses. /// </para> /// </summary> public Dictionary<string, IntegrationResponse> IntegrationResponses { get { return this._integrationResponses; } set { this._integrationResponses = value; } } // Check to see if IntegrationResponses property is set internal bool IsSetIntegrationResponses() { return this._integrationResponses != null && this._integrationResponses.Count > 0; } /// <summary> /// Gets and sets the property RequestParameters. /// <para> /// Represents requests parameters that are sent with the backend request. Request parameters /// are represented as a key/value map, with a destination as the key and a source as /// the value. A source must match an existing method request parameter, or a static value. /// Static values must be enclosed with single quotes, and be pre-encoded based on their /// destination in the request. The destination must match the pattern <code>integration.request.{location}.{name}</code>, /// where <code>location</code> is either querystring, path, or header. <code>name</code> /// must be a valid, unique parameter name. /// </para> /// </summary> public Dictionary<string, string> RequestParameters { get { return this._requestParameters; } set { this._requestParameters = value; } } // Check to see if RequestParameters property is set internal bool IsSetRequestParameters() { return this._requestParameters != null && this._requestParameters.Count > 0; } /// <summary> /// Gets and sets the property RequestTemplates. /// <para> /// Specifies the integration's request templates. /// </para> /// </summary> public Dictionary<string, string> RequestTemplates { get { return this._requestTemplates; } set { this._requestTemplates = value; } } // Check to see if RequestTemplates property is set internal bool IsSetRequestTemplates() { return this._requestTemplates != null && this._requestTemplates.Count > 0; } /// <summary> /// Gets and sets the property Type. /// <para> /// Specifies the integration's type. /// </para> /// </summary> public IntegrationType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } /// <summary> /// Gets and sets the property Uri. /// <para> /// Specifies the integration's Uniform Resource Identifier (URI). For HTTP integrations, /// the URI must be a fully formed, encoded HTTP(S) URL according to the <a target="_blank" /// href="https://www.ietf.org/rfc/rfc3986.txt">RFC-3986 specification</a>. For AWS integrations, /// the URI should be of the form <code>arn:aws:apigateway:{region}:{service}:{path|action}/{service_api}</code>. /// <code>Region</code> and <code>service</code> are used to determine the right endpoint. /// For AWS services that use the <code>Action=</code> query string parameter, <code>service_api</code> /// should be a valid action for the desired service. For RESTful AWS service APIs, <code>path</code> /// is used to indicate that the remaining substring in the URI should be treated as the /// path to the resource, including the initial <code>/</code>. /// </para> /// </summary> public string Uri { get { return this._uri; } set { this._uri = value; } } // Check to see if Uri property is set internal bool IsSetUri() { return this._uri != null; } } }
// // IpodTrackInfo.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Banshee.Base; using Banshee.Streaming; using Banshee.Collection; using Banshee.Collection.Database; using Hyena; namespace Banshee.Dap.Ipod { public class IpodTrackInfo : DatabaseTrackInfo { private IPod.Track track; internal IPod.Track IpodTrack { get { return track; } } private int ipod_id; internal int IpodId { get { return ipod_id; } } // Used for podcasts only private string description; public IpodTrackInfo (IPod.Track track) : base () { this.track = track; LoadFromIpodTrack (); CanSaveToDatabase = true; } public IpodTrackInfo (TrackInfo track) { if (track is IpodTrackInfo) { this.track = ((IpodTrackInfo)track).IpodTrack; LoadFromIpodTrack (); } else { AlbumArtist = track.AlbumArtist; AlbumTitle = track.AlbumTitle; ArtistName = track.ArtistName; BitRate = track.BitRate; SampleRate = track.SampleRate; Bpm = track.Bpm; Comment = track.Comment; Composer = track.Composer; Conductor = track.Conductor; Copyright = track.Copyright; DateAdded = track.DateAdded; DiscCount = track.DiscCount; DiscNumber = track.DiscNumber; Duration = track.Duration; FileSize = track.FileSize; Genre = track.Genre; Grouping = track.Grouping; IsCompilation = track.IsCompilation ; LastPlayed = track.LastPlayed; LastSkipped = track.LastSkipped; PlayCount = track.PlayCount; Rating = track.Rating; ReleaseDate = track.ReleaseDate; SkipCount = track.SkipCount; TrackCount = track.TrackCount; TrackNumber = track.TrackNumber; TrackTitle = track.TrackTitle; Year = track.Year; MediaAttributes = track.MediaAttributes; var podcast_info = track.ExternalObject as IPodcastInfo; if (podcast_info != null) { description = podcast_info.Description; ReleaseDate = podcast_info.ReleaseDate; } } CanSaveToDatabase = true; } private void LoadFromIpodTrack () { try { Uri = new SafeUri (track.Uri.LocalPath); } catch { Uri = null; } ExternalId = track.Id; ipod_id = (int)track.Id; AlbumArtist = track.AlbumArtist; AlbumTitle = String.IsNullOrEmpty (track.Album) ? null : track.Album; ArtistName = String.IsNullOrEmpty (track.Artist) ? null : track.Artist; BitRate = track.BitRate; SampleRate = track.SampleRate; Bpm = (int)track.BPM; Comment = track.Comment; Composer = track.Composer; DateAdded = track.DateAdded; DiscCount = track.TotalDiscs; DiscNumber = track.DiscNumber; Duration = track.Duration; FileSize = track.Size; Genre = String.IsNullOrEmpty (track.Genre) ? null : track.Genre; Grouping = track.Grouping; IsCompilation = track.IsCompilation; LastPlayed = track.LastPlayed; PlayCount = track.PlayCount; TrackCount = track.TotalTracks; TrackNumber = track.TrackNumber; TrackTitle = String.IsNullOrEmpty (track.Title) ? null : track.Title; Year = track.Year; description = track.Description; ReleaseDate = track.DateReleased; switch (track.Rating) { case IPod.TrackRating.One: rating = 1; break; case IPod.TrackRating.Two: rating = 2; break; case IPod.TrackRating.Three: rating = 3; break; case IPod.TrackRating.Four: rating = 4; break; case IPod.TrackRating.Five: rating = 5; break; case IPod.TrackRating.Zero: default: rating = 0; break; } if (track.IsProtected) { PlaybackError = StreamPlaybackError.Drm; } MediaAttributes = TrackMediaAttributes.AudioStream; switch (track.Type) { case IPod.MediaType.Audio: MediaAttributes |= TrackMediaAttributes.Music; break; case IPod.MediaType.AudioVideo: case IPod.MediaType.Video: MediaAttributes |= TrackMediaAttributes.VideoStream; break; case IPod.MediaType.MusicVideo: MediaAttributes |= TrackMediaAttributes.Music | TrackMediaAttributes.VideoStream; break; case IPod.MediaType.Movie: MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.Movie; break; case IPod.MediaType.TVShow: MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.TvShow; break; case IPod.MediaType.VideoPodcast: MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.Podcast; break; case IPod.MediaType.Podcast: MediaAttributes |= TrackMediaAttributes.Podcast; // FIXME: persist URL on the track (track.PodcastUrl) break; case IPod.MediaType.Audiobook: MediaAttributes |= TrackMediaAttributes.AudioBook; break; } } public void CommitToIpod (IPod.Device device) { bool update = (track != null); if (!update) { try { track = device.TrackDatabase.CreateTrack (Uri.AbsolutePath); } catch (Exception e) { Log.Exception ("Failed to create iPod track with Uri " + Uri.AbsoluteUri, e); device.TrackDatabase.RemoveTrack (track); return; } } ExternalId = track.Id; //if the track was not in the ipod already, the CreateTrack(uri) //method updates the Uri property with the path of the new file //so we need to save it on Banshee db to be properly synced if (!update) { Uri = new SafeUri (track.Uri); Save (); } track.AlbumArtist = AlbumArtist; track.BitRate = BitRate; track.SampleRate = (ushort)SampleRate; track.BPM = (short)Bpm; track.Comment = Comment; track.Composer = Composer; track.DateAdded = DateAdded; track.TotalDiscs = DiscCount; track.DiscNumber = DiscNumber; track.Duration = Duration; track.Size = (int)FileSize; track.Grouping = Grouping; track.IsCompilation = IsCompilation; track.LastPlayed = LastPlayed; track.PlayCount = PlayCount; track.TotalTracks = TrackCount; track.TrackNumber = TrackNumber; track.Year = Year; track.DateReleased = ReleaseDate; track.Album = AlbumTitle; track.Artist = ArtistName; track.Title = TrackTitle; track.Genre = Genre; switch (Rating) { case 1: track.Rating = IPod.TrackRating.Zero; break; case 2: track.Rating = IPod.TrackRating.Two; break; case 3: track.Rating = IPod.TrackRating.Three; break; case 4: track.Rating = IPod.TrackRating.Four; break; case 5: track.Rating = IPod.TrackRating.Five; break; default: track.Rating = IPod.TrackRating.Zero; break; } if (HasAttribute (TrackMediaAttributes.Podcast)) { track.DateReleased = ReleaseDate; track.Description = description; track.RememberPosition = true; track.NotPlayedMark = track.PlayCount == 0; } if (HasAttribute (TrackMediaAttributes.VideoStream)) { if (HasAttribute (TrackMediaAttributes.Podcast)) { track.Type = IPod.MediaType.VideoPodcast; } else if (HasAttribute (TrackMediaAttributes.Music)) { track.Type = IPod.MediaType.MusicVideo; } else if (HasAttribute (TrackMediaAttributes.Movie)) { track.Type = IPod.MediaType.Movie; } else if (HasAttribute (TrackMediaAttributes.TvShow)) { track.Type = IPod.MediaType.TVShow; } else { track.Type = IPod.MediaType.Video; } } else { if (HasAttribute (TrackMediaAttributes.Podcast)) { track.Type = IPod.MediaType.Podcast; } else if (HasAttribute (TrackMediaAttributes.AudioBook)) { track.Type = IPod.MediaType.Audiobook; } else if (HasAttribute (TrackMediaAttributes.Music)) { track.Type = IPod.MediaType.Audio; } else { track.Type = IPod.MediaType.Audio; } } if (CoverArtSpec.CoverExists (ArtworkId)) { SetIpodCoverArt (device, track, CoverArtSpec.GetPath (ArtworkId)); } } // FIXME: No reason for this to use GdkPixbuf - the file is on disk already in // the artwork cache as a JPEG, so just shove the bytes from disk into the track public static void SetIpodCoverArt (IPod.Device device, IPod.Track track, string path) { try { Gdk.Pixbuf pixbuf = null; foreach (IPod.ArtworkFormat format in device.LookupArtworkFormats (IPod.ArtworkUsage.Cover)) { if (!track.HasCoverArt (format)) { // Lazily load the pixbuf if (pixbuf == null) { pixbuf = new Gdk.Pixbuf (path); } track.SetCoverArt (format, IPod.ArtworkHelpers.ToBytes (format, pixbuf)); } } if (pixbuf != null) { pixbuf.Dispose (); } } catch (Exception e) { Log.Exception (String.Format ("Failed to set cover art on iPod from {0}", path), e); } } } }
// 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.Xml; using System.Xml.Schema; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Security; namespace System.Runtime.Serialization { #if USE_REFEMIT || uapaot public delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); public delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); public sealed class XmlFormatWriterGenerator #else internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); internal sealed class XmlFormatWriterGenerator #endif { private CriticalHelper _helper; public XmlFormatWriterGenerator() { _helper = new CriticalHelper(); } internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { return _helper.GenerateClassWriter(classContract); } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { return _helper.GenerateCollectionWriter(collectionContract); } /// <SecurityNote> /// Review - handles all aspects of IL generation including initializing the DynamicMethod. /// changes to how IL generated could affect how data is serialized and what gets access to data, /// therefore we mark it for review so that changes to generation logic are reviewed. /// </SecurityNote> private class CriticalHelper { #if !USE_REFEMIT && !uapaot private CodeGenerator _ilg; private ArgBuilder _xmlWriterArg; private ArgBuilder _contextArg; private ArgBuilder _dataContractArg; private LocalBuilder _objectLocal; // Used for classes private LocalBuilder _contractNamespacesLocal; private LocalBuilder _memberNamesLocal; private LocalBuilder _childElementNamespacesLocal; private int _typeIndex = 1; private int _childElementIndex = 0; #endif internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return new ReflectionXmlFormatWriter().ReflectionWriteClass; } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { return new ReflectionXmlFormatWriter().ReflectionWriteClass; } #endif else { #if USE_REFEMIT || uapaot throw new InvalidOperationException("Cannot generate class writer"); #else _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + classContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatClassWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(classContract.UnderlyingType); WriteClass(classContract); return (XmlFormatClassWriterDelegate)_ilg.EndMethod(); #endif } } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return new ReflectionXmlFormatWriter().ReflectionWriteCollection; } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { return new ReflectionXmlFormatWriter().ReflectionWriteCollection; } #endif else { #if USE_REFEMIT || uapaot throw new InvalidOperationException("Cannot generate class writer"); #else _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + collectionContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatCollectionWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(collectionContract.UnderlyingType); WriteCollection(collectionContract); return (XmlFormatCollectionWriterDelegate)_ilg.EndMethod(); #endif } } #if !USE_REFEMIT && !uapaot private void InitArgs(Type objType) { _xmlWriterArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(2); _dataContractArg = _ilg.GetArg(3); _objectLocal = _ilg.DeclareLocal(objType, "objSerialized"); ArgBuilder objectArg = _ilg.GetArg(1); _ilg.Load(objectArg); // Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter. // DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (objType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod); } //Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>. else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType); _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments)); _ilg.New(dc.KeyValuePairAdapterConstructorInfo); } else { _ilg.ConvertValue(objectArg.ArgType, objType); } _ilg.Stloc(_objectLocal); } private void InvokeOnSerializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerializing(classContract.BaseContract); if (classContract.OnSerializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerializing); } } private void InvokeOnSerialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerialized(classContract.BaseContract); if (classContract.OnSerialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerialized); } } private void WriteClass(ClassDataContract classContract) { InvokeOnSerializing(classContract); if (classContract.IsISerializable) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteISerializableMethod, _xmlWriterArg, _objectLocal); } else { if (classContract.ContractNamespaces.Length > 1) { _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField); _ilg.Store(_contractNamespacesLocal); } _memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField); _ilg.Store(_memberNamesLocal); for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++) { if (classContract.ChildElementNamespaces[i] != null) { _childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty); _ilg.Store(_childElementNamespacesLocal); } } if (classContract.HasExtensionData) { LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfIExtensibleDataObject); _ilg.LoadMember(XmlFormatGeneratorStatics.ExtensionDataProperty); _ilg.Store(extensionDataLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, -1); WriteMembers(classContract, extensionDataLocal, classContract); } else { WriteMembers(classContract, null, classContract); } } InvokeOnSerialized(classContract); } private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract) { int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns"); if (_contractNamespacesLocal == null) { _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); } else _ilg.LoadArrayElement(_contractNamespacesLocal, _typeIndex - 1); _ilg.Store(namespaceLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classContract.Members.Count); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember member = classContract.Members[i]; Type memberType = member.MemberType; LocalBuilder memberValue = null; if (member.IsGetOnlyCollection) { _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod); } else { _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.ResetIsGetOnlyCollectionMethod); } if (!member.EmitDefaultValue) { memberValue = LoadMemberValue(member); _ilg.IfNotDefaultValue(memberValue); } bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract); if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, null /*arrayItemIndex*/, namespaceLocal, null /*nameLocal*/, i + _childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, namespaceLocal, null /*nameLocal*/, i + _childElementIndex); if (classContract.ChildElementNamespaces[i + _childElementIndex] != null) { _ilg.Load(_xmlWriterArg); _ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex); _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (memberValue == null) memberValue = LoadMemberValue(member); WriteValue(memberValue, writeXsiType); WriteEndElement(); } if (classContract.HasExtensionData) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, memberCount); } if (!member.EmitDefaultValue) { if (member.IsRequired) { _ilg.Else(); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType); } _ilg.EndIf(); } } _typeIndex++; _childElementIndex += classContract.Members.Count; return memberCount; } private LocalBuilder LoadMemberValue(DataMember member) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(member.MemberInfo); LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value"); _ilg.Stloc(memberValue); return memberValue; } private void WriteCollection(CollectionDataContract collectionContract) { LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); _ilg.Store(itemNamespace); LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); if (collectionContract.ChildElementNamespace != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespaceProperty); _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal); if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName, itemNamespace)) { _ilg.For(i, 0, _objectLocal); if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); _ilg.LoadArrayElement(_objectLocal, i); LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue"); _ilg.Stloc(memberValue); WriteValue(memberValue, false /*writeXsiType*/); WriteEndElement(); } _ilg.EndFor(); } } else { MethodInfo incrementCollectionCountMethod = null; switch (collectionContract.Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod; break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType); break; case CollectionKind.GenericDictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } if (incrementCollectionCountMethod != null) { _ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal); } bool isDictionary = false, isGenericDictionary = false; Type enumeratorType = null; Type[] keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { isGenericDictionary = true; keyValueTypes = collectionContract.ItemType.GetGenericArguments(); enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes); } else if (collectionContract.Kind == CollectionKind.Dictionary) { isDictionary = true; keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; enumeratorType = Globals.TypeOfDictionaryEnumerator; } else { enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType; } MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); if (moveNextMethod == null || getCurrentMethod == null) { if (enumeratorType.IsInterface) { if (moveNextMethod == null) moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod; if (getCurrentMethod == null) getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else { Type ienumeratorInterface = Globals.TypeOfIEnumerator; CollectionKind kind = collectionContract.Kind; if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable) { Type[] interfaceTypes = enumeratorType.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType) { ienumeratorInterface = interfaceType; break; } } } if (moveNextMethod == null) moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface); if (getCurrentMethod == null) getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); } } Type elementType = getCurrentMethod.ReturnType; LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue"); LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator"); _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator); _ilg.New(XmlFormatGeneratorStatics.DictionaryEnumeratorCtor); } else if (isGenericDictionary) { Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam }); _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); _ilg.New(dictEnumCtor); } _ilg.Stloc(enumerator); _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); if (incrementCollectionCountMethod == null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); } if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(elementType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); if (isGenericDictionary || isDictionary) { _ilg.Call(_dataContractArg, XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlWriterArg); _ilg.Load(currentValue); _ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.WriteXmlValueMethod); } else { WriteValue(currentValue, false /*writeXsiType*/); } WriteEndElement(); } _ilg.EndForEach(moveNextMethod); } } private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; // load xmlwriter if (type.IsValueType) { _ilg.Load(_xmlWriterArg); } else { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); } // load primitive value if (value != null) { _ilg.Load(value); } else if (memberInfo != null) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(memberInfo); } else { _ilg.LoadArrayElement(_objectLocal, arrayItemIndex); } // load name if (name != null) { _ilg.Load(name); } else { _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); } // load namespace _ilg.Load(ns); // call method to write primitive _ilg.Call(primitiveContract.XmlFormatWriterMethod); return true; } private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string writeArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: writeArrayMethod = "WriteBooleanArray"; break; case TypeCode.DateTime: writeArrayMethod = "WriteDateTimeArray"; break; case TypeCode.Decimal: writeArrayMethod = "WriteDecimalArray"; break; case TypeCode.Int32: writeArrayMethod = "WriteInt32Array"; break; case TypeCode.Int64: writeArrayMethod = "WriteInt64Array"; break; case TypeCode.Single: writeArrayMethod = "WriteSingleArray"; break; case TypeCode.Double: writeArrayMethod = "WriteDoubleArray"; break; default: break; } if (writeArrayMethod != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(value); _ilg.Load(itemName); _ilg.Load(itemNamespace); _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })); return true; } return false; } private void WriteValue(LocalBuilder memberValue, bool writeXsiType) { Type memberType = memberValue.LocalType; bool isNullableOfT = (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.IsValueType && !isNullableOfT) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && !writeXsiType) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType); } else { if (isNullableOfT) { memberValue = UnwrapNullableObject(memberValue);//Leaves !HasValue on stack memberType = memberValue.LocalType; } else { _ilg.Load(memberValue); _ilg.Load(null); _ilg.Ceq(); } _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (isNullableOfT) { _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); } else { _ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue); } } else { if (memberType == Globals.TypeOfObject ||//boxed Nullable<T> memberType == Globals.TypeOfValueType || ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) { _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue"); memberType = memberValue.LocalType; _ilg.Stloc(memberValue); _ilg.If(memberValue, Cmp.EqualTo, null); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); } InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod), memberValue, memberType, writeXsiType); if (memberType == Globals.TypeOfObject) //boxed Nullable<T> _ilg.EndIf(); } _ilg.EndIf(); } } private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType) { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); //In SL GetTypeHandle throws MethodAccessException as its internal and extern. //So as a workaround, call XmlObjectSerializerWriteContext.IsMemberTypeSameAsMemberValue that //does the actual comparison and returns the bool value we care. _ilg.Call(null, XmlFormatGeneratorStatics.IsMemberTypeSameAsMemberValue, memberValue, memberType); _ilg.Load(writeXsiType); _ilg.Load(DataContract.GetId(memberType.TypeHandle)); _ilg.Ldtoken(memberType); _ilg.Call(methodInfo); } private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack { Type memberType = memberValue.LocalType; Label onNull = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); _ilg.Load(memberValue); while (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { Type innerType = memberType.GetGenericArguments()[0]; _ilg.Dup(); _ilg.Call(XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(innerType)); _ilg.Brfalse(onNull); _ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType)); memberType = innerType; } memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); _ilg.Stloc(memberValue); _ilg.Load(false); //isNull _ilg.Br(end); _ilg.MarkLabel(onNull); _ilg.Pop(); _ilg.Call(XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType)); _ilg.Stloc(memberValue); _ilg.Load(true);//isNull _ilg.MarkLabel(end); return memberValue; } private bool NeedsPrefix(Type type, XmlDictionaryString ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex) { bool needsPrefix = NeedsPrefix(type, ns); _ilg.Load(_xmlWriterArg); // prefix if (needsPrefix) _ilg.Load(Globals.ElementPrefix); // localName if (nameLocal == null) _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); else _ilg.Load(nameLocal); // namespace _ilg.Load(namespaceLocal); _ilg.Call(needsPrefix ? XmlFormatGeneratorStatics.WriteStartElementMethod3 : XmlFormatGeneratorStatics.WriteStartElementMethod2); } private void WriteEndElement() { _ilg.Call(_xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod); } private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { // Check for conflict with base type members if (CheckIfConflictingMembersHaveDifferentTypes(member)) return true; // Check for conflict with derived type members string name = member.Name; string ns = classContract.StableName.Namespace; ClassDataContract currentContract = derivedMostClassContract; while (currentContract != null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { List<DataMember> members = currentContract.Members; for (int j = 0; j < members.Count; j++) { if (name == members[j].Name) return CheckIfConflictingMembersHaveDifferentTypes(members[j]); } } currentContract = currentContract.BaseContract; } return false; } private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { if (member.MemberType != member.ConflictingMember.MemberType) return true; member = member.ConflictingMember; } return false; } #endif } } }
/* This file is licensed 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.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Xml; using System; using Org.XmlUnit; using Org.XmlUnit.Diff; using Org.XmlUnit.Util; namespace Org.XmlUnit.Placeholder { /// <summary> /// This class is used to add placeholder feature to XML comparison. /// </summary> /// <remarks> /// <para> /// This class and the whole module are considered experimental /// and any API may change between releases of XMLUnit. /// </para> /// <para> /// Supported scenarios are demonstrated in the unit tests /// (PlaceholderDifferenceEvaluatorTest). /// </para> /// <para> /// Default delimiters for placeholder are ${ and }. To use custom /// delimiters (in regular expression), create instance with the /// PlaceholderDifferenceEvaluator(string /// placeholderOpeningDelimiterRegex, string /// placeholderClosingDelimiterRegex) constructor. /// </para> /// <para> /// since 2.6.0 /// </para> /// </remarks> /* * <p>To use it, just add it with {@link * org.xmlunit.builder.DiffBuilder} like below</p> * * <pre> * Diff diff = DiffBuilder.compare(control).withTest(test).withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build(); * </pre> */ public class PlaceholderDifferenceEvaluator { public static readonly string PLACEHOLDER_DEFAULT_OPENING_DELIMITER_REGEX = Regex.Escape("${"); public static readonly string PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX = Regex.Escape("}"); /// <remarks> /// <para> /// since 2.8.0 /// </para> /// </remarks> public static readonly string PLACEHOLDER_DEFAULT_ARGS_OPENING_DELIMITER_REGEX = Regex.Escape("("); /// <remarks> /// <para> /// since 2.8.0 /// </para> /// </remarks> public static readonly string PLACEHOLDER_DEFAULT_ARGS_CLOSING_DELIMITER_REGEX = Regex.Escape(")"); /// <remarks> /// <para> /// since 2.8.0 /// </para> /// </remarks> public static readonly string PLACEHOLDER_DEFAULT_ARGS_SEPARATOR_REGEX = Regex.Escape(","); private static readonly string PLACEHOLDER_PREFIX_REGEX = Regex.Escape("xmlunit."); // IReadOnlyDictionary is .NET Framework 4.5 private static readonly IDictionary<string, IPlaceholderHandler> KNOWN_HANDLERS; private static readonly string[] NO_ARGS = new string[0]; static PlaceholderDifferenceEvaluator() { var m = new Dictionary<string, IPlaceholderHandler>(); foreach (var h in Load()) { m[h.Keyword] = h; } KNOWN_HANDLERS = m; } private static IEnumerable<IPlaceholderHandler> Load() { return AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => GetLoadableTypes(s)) .Where(t => !t.IsAbstract) .Where(t => t.FindInterfaces((type, n) => type.FullName == (string) n, typeof(IPlaceholderHandler).FullName).Length > 0) .Select(t => Activator.CreateInstance(t)) .Cast<IPlaceholderHandler>(); } private static IEnumerable<Type> GetLoadableTypes(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } } private readonly Regex placeholderRegex; private readonly Regex argsRegex; private readonly Regex argsSplitter; /// <summary> /// Creates a PlaceholderDifferenceEvaluator with default /// delimiters PLACEHOLDER_DEFAULT_OPENING_DELIMITER_REGEX and /// PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX. /// </summary> public PlaceholderDifferenceEvaluator() : this(null, null) { } /// <summary> /// Creates a PlaceholderDifferenceEvaluator with default /// delimiters PLACEHOLDER_DEFAULT_OPENING_DELIMITER_REGEX and /// PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX. /// </summary> /// <param name="placeholderOpeningDelimiterRegex">regular /// expression for the opening delimiter of placeholder, /// defaults to /// PlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_OPENING_DELIMITER_REGEX /// if the parameter is null or blank</param> /// <param name="placeholderClosingDelimiterRegex">regular /// expression for the closing delimiter of placeholder, /// defaults to /// PlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX /// if the parameter is null or blank</param> public PlaceholderDifferenceEvaluator(string placeholderOpeningDelimiterRegex, string placeholderClosingDelimiterRegex) : this(placeholderOpeningDelimiterRegex, placeholderClosingDelimiterRegex, null, null, null) { } /// <summary> /// Creates a PlaceholderDifferenceEvaluator with default /// delimiters PLACEHOLDER_DEFAULT_OPENING_DELIMITER_REGEX and /// PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX. /// </summary> /// <param name="placeholderOpeningDelimiterRegex">regular /// expression for the opening delimiter of placeholder, /// defaults to /// PlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_OPENING_DELIMITER_REGEX /// if the parameter is null or blank</param> /// <param name="placeholderClosingDelimiterRegex">regular /// expression for the closing delimiter of placeholder, /// defaults to /// PlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX /// if the parameter is null or blank</param> /// <param name="placeholderArgsOpeningDelimiterRegex">regular /// expression for the opening delimiter of the placeholder's /// argument list, defaults to /// PlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_ARGS_OPENING_DELIMITER_REGEX /// if the parameter is null or blank</param> /// <param name="placeholderArgsClosingDelimiterRegex">regular /// expression for the closing delimiter of the placeholder's /// argument list, defaults to /// PlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_ARGS_CLOSING_DELIMITER_REGEX /// if the parameter is null or blank</param> /// <param name="placeholderArgsSeparatorRegex">regular /// expression for the delimiter between arguments inside of /// the placeholder's argument list, defaults to /// PlaceholderDifferenceEvaluator#PLACEHOLDER_DEFAULT_ARGS_SEPARATOR_REGEX /// if the parameter is null or blank</param> /// <remarks> /// <para> /// since 2.8.0 /// </para> /// </remarks> public PlaceholderDifferenceEvaluator(string placeholderOpeningDelimiterRegex, string placeholderClosingDelimiterRegex, string placeholderArgsOpeningDelimiterRegex, string placeholderArgsClosingDelimiterRegex, string placeholderArgsSeparatorRegex) { if (placeholderOpeningDelimiterRegex == null || placeholderOpeningDelimiterRegex.Trim().Length == 0) { placeholderOpeningDelimiterRegex = PLACEHOLDER_DEFAULT_OPENING_DELIMITER_REGEX; } if (placeholderClosingDelimiterRegex == null || placeholderClosingDelimiterRegex.Trim().Length == 0) { placeholderClosingDelimiterRegex = PLACEHOLDER_DEFAULT_CLOSING_DELIMITER_REGEX; } if (placeholderArgsOpeningDelimiterRegex == null || placeholderArgsOpeningDelimiterRegex.Trim().Length == 0) { placeholderArgsOpeningDelimiterRegex = PLACEHOLDER_DEFAULT_ARGS_OPENING_DELIMITER_REGEX; } if (placeholderArgsClosingDelimiterRegex == null || placeholderArgsClosingDelimiterRegex.Trim().Length == 0) { placeholderArgsClosingDelimiterRegex = PLACEHOLDER_DEFAULT_ARGS_CLOSING_DELIMITER_REGEX; } if (placeholderArgsSeparatorRegex == null || placeholderArgsSeparatorRegex.Trim().Length == 0) { placeholderArgsSeparatorRegex = PLACEHOLDER_DEFAULT_ARGS_SEPARATOR_REGEX; } placeholderRegex = new Regex("(\\s*" + placeholderOpeningDelimiterRegex + "\\s*" + PLACEHOLDER_PREFIX_REGEX + "(.+)" + "\\s*" + placeholderClosingDelimiterRegex + "\\s*)"); argsRegex = new Regex("((.*)\\s*" + placeholderArgsOpeningDelimiterRegex + "(.+)" + "\\s*" + placeholderArgsClosingDelimiterRegex + "\\s*)"); argsSplitter = new Regex(placeholderArgsSeparatorRegex); } /// <summary> /// DifferenceEvaluator using the configured PlaceholderHandlers. /// </summary> public ComparisonResult Evaluate(Comparison comparison, ComparisonResult outcome) { if (outcome == ComparisonResult.EQUAL) { return outcome; } Comparison.Detail controlDetails = comparison.ControlDetails; XmlNode controlTarget = controlDetails.Target; Comparison.Detail testDetails = comparison.TestDetails; XmlNode testTarget = testDetails.Target; // comparing textual content of elements if (comparison.Type == ComparisonType.TEXT_VALUE) { return EvaluateConsideringPlaceholders((string) controlDetails.Value, (string) testDetails.Value, outcome); // "test document has no text-like child node but control document has" } else if (IsMissingTextNodeDifference(comparison)) { return EvaluateMissingTextNodeConsideringPlaceholders(comparison, outcome); // may be comparing TEXT to CDATA } else if (IsTextCDATAMismatch(comparison)) { return EvaluateConsideringPlaceholders(controlTarget.Value, testTarget.Value, outcome); // comparing textual content of attributes } else if (comparison.Type == ComparisonType.ATTR_VALUE) { return EvaluateConsideringPlaceholders((string) controlDetails.Value, (string) testDetails.Value, outcome); // "test document has no attribute but control document has" } else if (IsMissingAttributeDifference(comparison)) { return EvaluateMissingAttributeConsideringPlaceholders(comparison, outcome); } // default, don't apply any placeholders at all return outcome; } private bool IsMissingTextNodeDifference(Comparison comparison) { return ControlHasOneTextChildAndTestHasNone(comparison) || CantFindControlTextChildInTest(comparison); } private bool ControlHasOneTextChildAndTestHasNone(Comparison comparison) { Comparison.Detail controlDetails = comparison.ControlDetails; XmlNode controlTarget = controlDetails.Target; Comparison.Detail testDetails = comparison.TestDetails; return comparison.Type == ComparisonType.CHILD_NODELIST_LENGTH && 1 == (int) controlDetails.Value && 0 == (int) testDetails.Value && IsTextLikeNode(controlTarget.FirstChild); } private bool CantFindControlTextChildInTest(Comparison comparison) { XmlNode controlTarget = comparison.ControlDetails.Target; return comparison.Type == ComparisonType.CHILD_LOOKUP && controlTarget != null && IsTextLikeNode(controlTarget); } private ComparisonResult EvaluateMissingTextNodeConsideringPlaceholders(Comparison comparison, ComparisonResult outcome) { XmlNode controlTarget = comparison.ControlDetails.Target; string value; if (ControlHasOneTextChildAndTestHasNone(comparison)) { value = controlTarget.FirstChild.Value; } else { value = controlTarget.Value; } return EvaluateConsideringPlaceholders(value, null, outcome); } private bool IsTextCDATAMismatch(Comparison comparison) { return comparison.Type == ComparisonType.NODE_TYPE && IsTextLikeNode(comparison.ControlDetails.Target) && IsTextLikeNode(comparison.TestDetails.Target); } private bool IsTextLikeNode(XmlNode node) { var nodeType = node.NodeType; return nodeType == XmlNodeType.Text || nodeType == XmlNodeType.CDATA; } private bool IsMissingAttributeDifference(Comparison comparison) { return comparison.Type == ComparisonType.ELEMENT_NUM_ATTRIBUTES || (comparison.Type == ComparisonType.ATTR_NAME_LOOKUP && comparison.ControlDetails.Target != null && comparison.ControlDetails.Value != null); } private ComparisonResult EvaluateMissingAttributeConsideringPlaceholders(Comparison comparison, ComparisonResult outcome) { if (comparison.Type == ComparisonType.ELEMENT_NUM_ATTRIBUTES) { return EvaluateAttributeListLengthConsideringPlaceholders(comparison, outcome); } string controlAttrValue = Nodes.GetAttributes(comparison.ControlDetails.Target) [(XmlQualifiedName) comparison.ControlDetails.Value]; return EvaluateConsideringPlaceholders(controlAttrValue, null, outcome); } private ComparisonResult EvaluateAttributeListLengthConsideringPlaceholders(Comparison comparison, ComparisonResult outcome) { var controlAttrs = Nodes.GetAttributes(comparison.ControlDetails.Target); var testAttrs = Nodes.GetAttributes(comparison.TestDetails.Target); int cAttrsMatched = 0; foreach (var cAttr in controlAttrs) { string testValue; if (!testAttrs.TryGetValue(cAttr.Key, out testValue)) { ComparisonResult o = EvaluateConsideringPlaceholders(cAttr.Value, null, outcome); if (o != ComparisonResult.EQUAL) { return outcome; } } else { cAttrsMatched++; } } if (cAttrsMatched != testAttrs.Count) { // there are unmatched test attributes return outcome; } return ComparisonResult.EQUAL; } private ComparisonResult EvaluateConsideringPlaceholders(string controlText, string testText, ComparisonResult outcome) { Match placeholderMatch = placeholderRegex.Match(controlText); if (placeholderMatch.Success) { string content = placeholderMatch.Groups[2].Captures[0].Value.Trim(); Match argsMatch = argsRegex.Match(content); string keyword; string[] args; if (argsMatch.Success) { keyword = argsMatch.Groups[2].Captures[0].Value.Trim(); args = argsSplitter.Split(argsMatch.Groups[3].Captures[0].Value); } else { keyword = content; args = NO_ARGS; } if (IsKnown(keyword)) { if (placeholderMatch.Groups[1].Captures[0].Value.Trim() != controlText.Trim()) { throw new XMLUnitException("The placeholder must exclusively occupy the text node."); } return Evaluate(keyword, testText, args); } } // no placeholder at all or unknown keyword return outcome; } private bool IsKnown(string keyword) { return KNOWN_HANDLERS.ContainsKey(keyword); } private ComparisonResult Evaluate(string keyword, string testText, string[] args) { return KNOWN_HANDLERS[keyword].Evaluate(testText, args); } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Datastore.Query; namespace Datastore.Manipulation { public interface IMovieOriginalData : IBaseEntityOriginalData { string Title { get; } Person Director { get; } IEnumerable<Person> Actors { get; } } public partial class Movie : OGM<Movie, Movie.MovieData, System.String>, IBaseEntity, IMovieOriginalData { #region Initialize static Movie() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadFromNaturalKey RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion #region LoadByTitle RegisterQuery(nameof(LoadByTitle), (query, alias) => query. Where(alias.Title == Parameter.New<string>(Param0))); #endregion AdditionalGeneratedStoredQueries(); } public static Movie LoadByTitle(string title) { return FromQuery(nameof(LoadByTitle), new Parameter(Param0, title)).FirstOrDefault(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, Movie> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.MovieAlias, IWhereQuery> query) { q.MovieAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.Movie.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"Movie => Title : {this.Title?.ToString() ?? "null"}, Uid : {this.Uid}, LastModifiedOn : {this.LastModifiedOn}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new MovieData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class MovieData : Data<System.String> { public MovieData() { } public MovieData(MovieData data) { Title = data.Title; Director = data.Director; Actors = data.Actors; Uid = data.Uid; LastModifiedOn = data.LastModifiedOn; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "Movie"; Director = new EntityCollection<Person>(Wrapper, Members.Director, item => { if (Members.Director.Events.HasRegisteredChangeHandlers) { int loadHack = item.DirectedMovies.Count; } }); Actors = new EntityCollection<Person>(Wrapper, Members.Actors, item => { if (Members.Actors.Events.HasRegisteredChangeHandlers) { int loadHack = item.ActedInMovies.Count; } }); } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("Title", Title); dictionary.Add("Uid", Uid); dictionary.Add("LastModifiedOn", Conversion<System.DateTime, long>.Convert(LastModifiedOn)); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("Title", out value)) Title = (string)value; if (properties.TryGetValue("Uid", out value)) Uid = (string)value; if (properties.TryGetValue("LastModifiedOn", out value)) LastModifiedOn = Conversion<long, System.DateTime>.Convert((long)value); } #endregion #region Members for interface IMovie public string Title { get; set; } public EntityCollection<Person> Director { get; private set; } public EntityCollection<Person> Actors { get; private set; } #endregion #region Members for interface IBaseEntity public string Uid { get; set; } public System.DateTime LastModifiedOn { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IMovie public string Title { get { LazyGet(); return InnerData.Title; } set { if (LazySet(Members.Title, InnerData.Title, value)) InnerData.Title = value; } } public Person Director { get { return ((ILookupHelper<Person>)InnerData.Director).GetItem(null); } set { if (LazySet(Members.Director, ((ILookupHelper<Person>)InnerData.Director).GetItem(null), value)) ((ILookupHelper<Person>)InnerData.Director).SetItem(value, null); } } private void ClearDirector(DateTime? moment) { ((ILookupHelper<Person>)InnerData.Director).ClearLookup(moment); } public EntityCollection<Person> Actors { get { return InnerData.Actors; } } private void ClearActors(DateTime? moment) { ((ILookupHelper<Person>)InnerData.Actors).ClearLookup(moment); } #endregion #region Members for interface IBaseEntity public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } public System.DateTime LastModifiedOn { get { LazyGet(); return InnerData.LastModifiedOn; } set { if (LazySet(Members.LastModifiedOn, InnerData.LastModifiedOn, value)) InnerData.LastModifiedOn = value; } } protected override DateTime GetRowVersion() { return LastModifiedOn; } public override void SetRowVersion(DateTime? value) { LastModifiedOn = value ?? DateTime.MinValue; } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static MovieMembers members = null; public static MovieMembers Members { get { if (members == null) { lock (typeof(Movie)) { if (members == null) members = new MovieMembers(); } } return members; } } public class MovieMembers { internal MovieMembers() { } #region Members for interface IMovie public Property Title { get; } = Blueprint41.UnitTest.DataStore.MockModel.Model.Entities["Movie"].Properties["Title"]; public Property Director { get; } = Blueprint41.UnitTest.DataStore.MockModel.Model.Entities["Movie"].Properties["Director"]; public Property Actors { get; } = Blueprint41.UnitTest.DataStore.MockModel.Model.Entities["Movie"].Properties["Actors"]; #endregion #region Members for interface IBaseEntity public Property Uid { get; } = Blueprint41.UnitTest.DataStore.MockModel.Model.Entities["BaseEntity"].Properties["Uid"]; public Property LastModifiedOn { get; } = Blueprint41.UnitTest.DataStore.MockModel.Model.Entities["BaseEntity"].Properties["LastModifiedOn"]; #endregion } private static MovieFullTextMembers fullTextMembers = null; public static MovieFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(Movie)) { if (fullTextMembers == null) fullTextMembers = new MovieFullTextMembers(); } } return fullTextMembers; } } public class MovieFullTextMembers { internal MovieFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(Movie)) { if (entity == null) entity = Blueprint41.UnitTest.DataStore.MockModel.Model.Entities["Movie"]; } } return entity; } private static MovieEvents events = null; public static MovieEvents Events { get { if (events == null) { lock (typeof(Movie)) { if (events == null) events = new MovieEvents(); } } return events; } } public class MovieEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<Movie, EntityEventArgs> onNew; public event EventHandler<Movie, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<Movie, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<Movie, EntityEventArgs> onDelete; public event EventHandler<Movie, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<Movie, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<Movie, EntityEventArgs> onSave; public event EventHandler<Movie, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<Movie, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnTitle private static bool onTitleIsRegistered = false; private static EventHandler<Movie, PropertyEventArgs> onTitle; public static event EventHandler<Movie, PropertyEventArgs> OnTitle { add { lock (typeof(OnPropertyChange)) { if (!onTitleIsRegistered) { Members.Title.Events.OnChange -= onTitleProxy; Members.Title.Events.OnChange += onTitleProxy; onTitleIsRegistered = true; } onTitle += value; } } remove { lock (typeof(OnPropertyChange)) { onTitle -= value; if (onTitle == null && onTitleIsRegistered) { Members.Title.Events.OnChange -= onTitleProxy; onTitleIsRegistered = false; } } } } private static void onTitleProxy(object sender, PropertyEventArgs args) { EventHandler<Movie, PropertyEventArgs> handler = onTitle; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion #region OnDirector private static bool onDirectorIsRegistered = false; private static EventHandler<Movie, PropertyEventArgs> onDirector; public static event EventHandler<Movie, PropertyEventArgs> OnDirector { add { lock (typeof(OnPropertyChange)) { if (!onDirectorIsRegistered) { Members.Director.Events.OnChange -= onDirectorProxy; Members.Director.Events.OnChange += onDirectorProxy; onDirectorIsRegistered = true; } onDirector += value; } } remove { lock (typeof(OnPropertyChange)) { onDirector -= value; if (onDirector == null && onDirectorIsRegistered) { Members.Director.Events.OnChange -= onDirectorProxy; onDirectorIsRegistered = false; } } } } private static void onDirectorProxy(object sender, PropertyEventArgs args) { EventHandler<Movie, PropertyEventArgs> handler = onDirector; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion #region OnActors private static bool onActorsIsRegistered = false; private static EventHandler<Movie, PropertyEventArgs> onActors; public static event EventHandler<Movie, PropertyEventArgs> OnActors { add { lock (typeof(OnPropertyChange)) { if (!onActorsIsRegistered) { Members.Actors.Events.OnChange -= onActorsProxy; Members.Actors.Events.OnChange += onActorsProxy; onActorsIsRegistered = true; } onActors += value; } } remove { lock (typeof(OnPropertyChange)) { onActors -= value; if (onActors == null && onActorsIsRegistered) { Members.Actors.Events.OnChange -= onActorsProxy; onActorsIsRegistered = false; } } } } private static void onActorsProxy(object sender, PropertyEventArgs args) { EventHandler<Movie, PropertyEventArgs> handler = onActors; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<Movie, PropertyEventArgs> onUid; public static event EventHandler<Movie, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<Movie, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion #region OnLastModifiedOn private static bool onLastModifiedOnIsRegistered = false; private static EventHandler<Movie, PropertyEventArgs> onLastModifiedOn; public static event EventHandler<Movie, PropertyEventArgs> OnLastModifiedOn { add { lock (typeof(OnPropertyChange)) { if (!onLastModifiedOnIsRegistered) { Members.LastModifiedOn.Events.OnChange -= onLastModifiedOnProxy; Members.LastModifiedOn.Events.OnChange += onLastModifiedOnProxy; onLastModifiedOnIsRegistered = true; } onLastModifiedOn += value; } } remove { lock (typeof(OnPropertyChange)) { onLastModifiedOn -= value; if (onLastModifiedOn == null && onLastModifiedOnIsRegistered) { Members.LastModifiedOn.Events.OnChange -= onLastModifiedOnProxy; onLastModifiedOnIsRegistered = false; } } } } private static void onLastModifiedOnProxy(object sender, PropertyEventArgs args) { EventHandler<Movie, PropertyEventArgs> handler = onLastModifiedOn; if ((object)handler != null) handler.Invoke((Movie)sender, args); } #endregion } #endregion } #endregion #region IMovieOriginalData public IMovieOriginalData OriginalVersion { get { return this; } } #region Members for interface IMovie string IMovieOriginalData.Title { get { return OriginalData.Title; } } Person IMovieOriginalData.Director { get { return ((ILookupHelper<Person>)OriginalData.Director).GetOriginalItem(null); } } IEnumerable<Person> IMovieOriginalData.Actors { get { return OriginalData.Actors.OriginalData; } } #endregion #region Members for interface IBaseEntity IBaseEntityOriginalData IBaseEntity.OriginalVersion { get { return this; } } string IBaseEntityOriginalData.Uid { get { return OriginalData.Uid; } } System.DateTime IBaseEntityOriginalData.LastModifiedOn { get { return OriginalData.LastModifiedOn; } } #endregion #endregion } }
/* Software Developer: Fred Ekstrand Copyright (C) 2016 by: Fred Ekstrand 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 SOFTWARE DEVLOPER 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. Except as contained in this notice, the name of the software developer shall not be used in advertising or otherwise to promote the sale, use or other dealings in this "Software" without prior written authorization from the software developer. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace Ekstrand.Encryption.Ciphers { /// <summary> /// Enigma Binary /// </summary> /// <seealso cref="IStreamCipher" /> [Serializable] public class EnigmaBinary : IStreamCipher { #region Variables private EnigmaManager m_EnigmaManager; private bool m_Initialized; private bool m_Encrypt; /// <summary> /// Guard from changing settings while in use. Force user to use reset. /// </summary> protected bool m_SettingsInUse = false; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="EnigmaBinary"/> class. /// </summary> public EnigmaBinary() { m_Initialized = false; m_Encrypt = true; } #endregion #region Methods /// <summary> /// Initialize the cipher. /// </summary> /// <param name="forEncryption">Initialize for encryption if true, for decryption if false.</param> /// <param name="parameters">The key or other data required by the cipher.</param> public void Init(bool forEncryption = true, ICipherParameters parameters = null) { m_Encrypt = forEncryption; m_EnigmaManager = new EnigmaManager(parameters); m_EnigmaManager.Initialize(); m_Initialized = true; } /// <summary> /// encrypt/decrypt a single byte returning the result. /// </summary> /// <param name="input">the byte to be processed.</param> /// <returns> /// the result of processing the input byte. /// </returns> public byte ReturnByte(byte input) { return m_EnigmaManager.ProcessByte(input, m_Encrypt); } /// <summary> /// Process a block of bytes from <c>input</c> putting the result into <c>output</c>. /// </summary> /// <param name="input">The input byte array.</param> /// <param name="inOff">The offset into <c>input</c> where the data to be processed starts.</param> /// <param name="length">The number of bytes to be processed.</param> /// <param name="output">The output buffer the processed bytes go into.</param> /// <param name="outOff">The offset into <c>output</c> the processed data starts at.</param> /// <exception cref="System.InvalidOperationException">You must call Init(...) before processing blocks</exception> /// <exception cref="DataLengthException"> /// Input buffer too short. /// or /// Output buffer too short. /// </exception> public void ProcessBytes(byte[] input, int inOff, int length, byte[] output, int outOff) { if(!m_Initialized) { throw new InvalidOperationException("You must call Init(...) before processing blocks"); } m_SettingsInUse = true; if (inOff + length > input.Length) { throw new DataLengthException("Input buffer too short."); } if(outOff + length > output.Length) { throw new DataLengthException("Output buffer too short."); } for(int i = 0 + inOff; i < input.Length; i++) { output[outOff + i] = m_EnigmaManager.ProcessByte(input[inOff + i], m_Encrypt); } } /// <summary> /// Reset the cipher to the same state as it was after the last init (if there was one). /// </summary> public void Reset() { m_EnigmaManager.Reset(); m_SettingsInUse = false; } /// <summary> /// Returns the current configuration of the EnigmaBinary /// </summary> /// <returns>Return EnigmaBinaryParameters</returns> public EnigmaBinaryParameters ReturnConfiguration() { return m_EnigmaManager.ReturnConfiguration(); } #endregion #region Properties /// <summary> /// Gets the name of the algorithm. /// </summary> /// <value> /// The name of the algorithm. /// </value> public string AlgorithmName { get { return "EnigmaBinary"; } } /// <summary> /// Indicates whether this cipher can handle partial blocks. /// </summary> /// <value> /// <c>true</c> if this instance is partial block okay; otherwise, <c>false</c>. /// </value> public bool IsPartialBlockOkay { get { return false; } } /// <summary> /// Gets the version. /// </summary> /// <value> /// The EnigmaBinary Version /// </value> public string Version { get { return typeof(EnigmaBinary).Assembly.GetName().Version.ToString(); } } /// <summary> /// Gets or sets the entry rotor. /// </summary> /// <value> /// Type of EntryRotor /// </value> public IRotor EntryRotor { get { if(m_EnigmaManager == null) { return null; } return m_EnigmaManager.CipherController.RotorController.EntryRotor; } set { if (value.SubstitutionSet == null || value.SubstitutionSet.Length != 256) { throw new ArgumentException("EntryRotor SubstitutionSet."); } m_EnigmaManager.CipherController.RotorController.EntryRotor = value; } } /// <summary> /// Gets the rotor collection. /// </summary> /// <value> /// Collection of Rotors /// </value> public Collection<IRotor> Rotors { get { if(m_EnigmaManager == null) { return null; } return m_EnigmaManager.CipherController.RotorController.Rotors; } } /// <summary> /// Gets or sets the reflector. /// </summary> /// <value> /// Type of IReflector /// </value> public IRotor Reflector { get { if (m_EnigmaManager == null) { return null; } return m_EnigmaManager.CipherController.RotorController.Reflector; } set { if (value.SubstitutionSet == null || value.SubstitutionSet.Length != 256) { throw new ArgumentException("Reflector SubstitutionSet."); } m_EnigmaManager.CipherController.RotorController.Reflector = value; } } /// <summary> /// Gets or sets the plugboard. /// </summary> /// <value> /// Type of IPlugboard /// </value> public IPlugboard Plugboard { get { if (m_EnigmaManager == null) { return null; } return m_EnigmaManager.CipherController.Plugboard; } set { if (value.TranspositionSet == null) { throw new ArgumentException("Plugboard TranspositionSet."); } m_EnigmaManager.CipherController.Plugboard = value; } } /// <summary> /// Gets the turn collection. /// </summary> /// <value> /// Collection of Turns /// </value> public Collection<ITurn> Turns { get { if (m_EnigmaManager == null) { return null; } return m_EnigmaManager.CipherController.RotorController.Turns; } } /// <summary> /// Gets or sets the rotor controller. /// </summary> /// <value> /// Type of IRotorController /// </value> public IRotorController RotorController { get { if (m_EnigmaManager == null) { return null; } return m_EnigmaManager.CipherController.RotorController; } set { if(m_SettingsInUse) { throw new ArgumentException("RotorController in use. You must Reset before changing objects."); } m_EnigmaManager.CipherController.RotorController = value; } } /// <summary> /// Gets or sets the cipher controller. /// </summary> /// <value> /// The cipher controller. /// </value> public ICipherController CipherController { get { if(m_EnigmaManager == null) { return null; } return m_EnigmaManager.CipherController; } set { if(m_SettingsInUse) { throw new ArgumentException("CipherController in use. You must Reset before changing objects."); } m_EnigmaManager.CipherController = value; } } #endregion } }
/* * CID001a.cs - hr culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "hr.txt". namespace I18N.Other { using System; using System.Globalization; using I18N.Common; public class CID001a : RootCulture { public CID001a() : base(0x001A) {} public CID001a(int culture) : base(culture) {} public override String Name { get { return "hr"; } } public override String ThreeLetterISOLanguageName { get { return "hrv"; } } public override String ThreeLetterWindowsLanguageName { get { return "HRV"; } } public override String TwoLetterISOLanguageName { get { return "hr"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AbbreviatedDayNames = new String[] {"ned", "pon", "uto", "sri", "\u010Det", "pet", "sub"}; dfi.DayNames = new String[] {"nedjelja", "ponedjeljak", "utorak", "srijeda", "\u010Detvrtak", "petak", "subota"}; dfi.AbbreviatedMonthNames = new String[] {"sij", "vel", "o\u017Eu", "tra", "svi", "lip", "srp", "kol", "ruj", "lis", "stu", "pro", ""}; dfi.MonthNames = new String[] {"sije\u010Danj", "velja\u010Da", "o\u017Eujak", "travanj", "svibanj", "lipanj", "srpanj", "kolovoz", "rujan", "listopad", "studeni", "prosinac", ""}; dfi.DateSeparator = "."; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "yyyy. MMMM dd"; dfi.LongTimePattern = "HH:mm:ss z"; dfi.ShortDatePattern = "yyyy.MM.dd"; dfi.ShortTimePattern = "HH:mm"; dfi.FullDateTimePattern = "yyyy. MMMM dd HH:mm:ss z"; dfi.I18NSetDateTimePatterns(new String[] { "d:yyyy.MM.dd", "D:yyyy. MMMM dd", "f:yyyy. MMMM dd HH:mm:ss z", "f:yyyy. MMMM dd HH:mm:ss z", "f:yyyy. MMMM dd HH:mm:ss", "f:yyyy. MMMM dd HH:mm", "F:yyyy. MMMM dd HH:mm:ss", "g:yyyy.MM.dd HH:mm:ss z", "g:yyyy.MM.dd HH:mm:ss z", "g:yyyy.MM.dd HH:mm:ss", "g:yyyy.MM.dd HH:mm", "G:yyyy.MM.dd HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:HH:mm:ss z", "t:HH:mm:ss z", "t:HH:mm:ss", "t:HH:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "."; nfi.NumberGroupSeparator = "."; nfi.PercentGroupSeparator = "."; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "hr": return "hrvatski"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "HR": return "Hrvatska"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 1250; } } public override int EBCDICCodePage { get { return 500; } } public override int MacCodePage { get { return 10082; } } public override int OEMCodePage { get { return 852; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID001a public class CNhr : CID001a { public CNhr() : base() {} }; // class CNhr }; // namespace I18N.Other
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime; using System.Runtime.InteropServices; using System.ServiceModel; namespace System.Collections.Generic { [ComVisible(false)] public abstract class SynchronizedKeyedCollection<K, T> : SynchronizedCollection<T> { private const int defaultThreshold = 0; private IEqualityComparer<K> _comparer; private Dictionary<K, T> _dictionary; private int _keyCount; private int _threshold; protected SynchronizedKeyedCollection() { _comparer = EqualityComparer<K>.Default; _threshold = int.MaxValue; } protected SynchronizedKeyedCollection(object syncRoot) : base(syncRoot) { _comparer = EqualityComparer<K>.Default; _threshold = int.MaxValue; } protected SynchronizedKeyedCollection(object syncRoot, IEqualityComparer<K> comparer) : base(syncRoot) { if (comparer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("comparer")); _comparer = comparer; _threshold = int.MaxValue; } protected SynchronizedKeyedCollection(object syncRoot, IEqualityComparer<K> comparer, int dictionaryCreationThreshold) : base(syncRoot) { if (comparer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("comparer")); if (dictionaryCreationThreshold < -1) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("dictionaryCreationThreshold", dictionaryCreationThreshold, SR.Format(SR.ValueMustBeInRange, -1, int.MaxValue))); else if (dictionaryCreationThreshold == -1) _threshold = int.MaxValue; else _threshold = dictionaryCreationThreshold; _comparer = comparer; } public T this[K key] { get { if (key == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("key")); lock (this.SyncRoot) { if (_dictionary != null) return _dictionary[key]; for (int i = 0; i < this.Items.Count; i++) { T item = this.Items[i]; if (_comparer.Equals(key, this.GetKeyForItem(item))) return item; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new KeyNotFoundException()); } } } protected IDictionary<K, T> Dictionary { get { return _dictionary; } } private void AddKey(K key, T item) { if (_dictionary != null) _dictionary.Add(key, item); else if (_keyCount == _threshold) { this.CreateDictionary(); _dictionary.Add(key, item); } else { if (this.Contains(key)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.CannotAddTwoItemsWithTheSameKeyToSynchronizedKeyedCollection0)); _keyCount++; } } protected void ChangeItemKey(T item, K newKey) { // check if the item exists in the collection if (!this.ContainsItem(item)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.ItemDoesNotExistInSynchronizedKeyedCollection0)); K oldKey = this.GetKeyForItem(item); if (!_comparer.Equals(newKey, oldKey)) { if (newKey != null) this.AddKey(newKey, item); if (oldKey != null) this.RemoveKey(oldKey); } } protected override void ClearItems() { base.ClearItems(); if (_dictionary != null) _dictionary.Clear(); _keyCount = 0; } public bool Contains(K key) { if (key == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("key")); lock (this.SyncRoot) { if (_dictionary != null) return _dictionary.ContainsKey(key); if (key != null) { for (int i = 0; i < Items.Count; i++) { T item = Items[i]; if (_comparer.Equals(key, GetKeyForItem(item))) return true; } } return false; } } private bool ContainsItem(T item) { K key; if ((_dictionary == null) || ((key = GetKeyForItem(item)) == null)) return Items.Contains(item); T itemInDict; if (_dictionary.TryGetValue(key, out itemInDict)) return EqualityComparer<T>.Default.Equals(item, itemInDict); return false; } private void CreateDictionary() { _dictionary = new Dictionary<K, T>(_comparer); foreach (T item in Items) { K key = GetKeyForItem(item); if (key != null) _dictionary.Add(key, item); } } protected abstract K GetKeyForItem(T item); protected override void InsertItem(int index, T item) { K key = this.GetKeyForItem(item); if (key != null) this.AddKey(key, item); base.InsertItem(index, item); } public bool Remove(K key) { if (key == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("key")); lock (this.SyncRoot) { if (_dictionary != null) { if (_dictionary.ContainsKey(key)) return this.Remove(_dictionary[key]); else return false; } else { for (int i = 0; i < Items.Count; i++) { if (_comparer.Equals(key, GetKeyForItem(Items[i]))) { this.RemoveItem(i); return true; } } return false; } } } protected override void RemoveItem(int index) { K key = this.GetKeyForItem(this.Items[index]); if (key != null) this.RemoveKey(key); base.RemoveItem(index); } private void RemoveKey(K key) { if (!(key != null)) { Fx.Assert("key shouldn't be null!"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key"); } if (_dictionary != null) _dictionary.Remove(key); else _keyCount--; } protected override void SetItem(int index, T item) { K newKey = this.GetKeyForItem(item); K oldKey = this.GetKeyForItem(this.Items[index]); if (_comparer.Equals(newKey, oldKey)) { if ((newKey != null) && (_dictionary != null)) _dictionary[newKey] = item; } else { if (newKey != null) this.AddKey(newKey, item); if (oldKey != null) this.RemoveKey(oldKey); } base.SetItem(index, item); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace GameProject { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // game objects. Using inheritance would make this // easier, but inheritance isn't a GDD 1200 topic Burger burger; List<TeddyBear> bears = new List<TeddyBear>(); static List<Projectile> projectiles = new List<Projectile>(); List<Explosion> explosions = new List<Explosion>(); // projectile and explosion sprites. Saved so they don't have to // be loaded every time projectiles or explosions are created static Texture2D frenchFriesSprite; static Texture2D teddyBearProjectileSprite; static Texture2D explosionSpriteStrip; // scoring support int score = 0; string scoreString = GameConstants.SCORE_PREFIX + 0; // health support string healthString = GameConstants.HEALTH_PREFIX + GameConstants.BURGER_INITIAL_HEALTH; bool burgerDead = false; // text display support SpriteFont font; // sound effects SoundEffect burgerDamage; SoundEffect burgerDeath; SoundEffect burgerShot; SoundEffect explosion; SoundEffect teddyBounce; SoundEffect teddyShot; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // set resolution graphics.PreferredBackBufferWidth = GameConstants.WINDOW_WIDTH; graphics.PreferredBackBufferHeight = GameConstants.WINDOW_HEIGHT; IsMouseVisible = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { RandomNumberGenerator.Initialize(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // load audio content // load sprite font // load projectile and explosion sprites // add initial game objects burger = new Burger(Content, "burger", GameConstants.WINDOW_WIDTH / 2,GameConstants.WINDOW_HEIGHT-GameConstants.WINDOW_HEIGHT/8, null); SpawnBear(); // set initial health and score strings } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); // get current mouse state and update burger burger.Update(gameTime, Mouse.GetState()); // update other game objects foreach (TeddyBear bear in bears) { bear.Update(gameTime); } foreach (Projectile projectile in projectiles) { projectile.Update(gameTime); } foreach (Explosion explosion in explosions) { explosion.Update(gameTime); } // check and resolve collisions between teddy bears // check and resolve collisions between burger and teddy bears // check and resolve collisions between burger and projectiles // check and resolve collisions between teddy bears and projectiles // clean out inactive teddy bears and add new ones as necessary // clean out inactive projectiles // clean out finished explosions base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); // draw game objects burger.Draw(spriteBatch); foreach (TeddyBear bear in bears) { bear.Draw(spriteBatch); } foreach (Projectile projectile in projectiles) { projectile.Draw(spriteBatch); } foreach (Explosion explosion in explosions) { explosion.Draw(spriteBatch); } // draw score and health spriteBatch.End(); base.Draw(gameTime); } #region Public methods /// <summary> /// Gets the projectile sprite for the given projectile type /// </summary> /// <param name="type">the projectile type</param> /// <returns>the projectile sprite for the type</returns> public static Texture2D GetProjectileSprite(ProjectileType type) { // replace with code to return correct projectile sprite based on projectile type return frenchFriesSprite; } /// <summary> /// Adds the given projectile to the game /// </summary> /// <param name="projectile">the projectile to add</param> public static void AddProjectile(Projectile projectile) { } #endregion #region Private methods /// <summary> /// Spawns a new teddy bear at a random location /// </summary> private void SpawnBear() { // generate random location int x, y; x = GetRandomLocation(GameConstants.SPAWN_BORDER_SIZE, GameConstants.WINDOW_WIDTH - 2 * GameConstants.SPAWN_BORDER_SIZE); y = GetRandomLocation(GameConstants.SPAWN_BORDER_SIZE, GameConstants.WINDOW_HEIGHT - 2 * GameConstants.SPAWN_BORDER_SIZE); // generate random velocity float speed = GameConstants.MIN_BEAR_SPEED + RandomNumberGenerator.NextFloat(GameConstants.BEAR_SPEED_RANGE); float angle = RandomNumberGenerator.NextFloat(2 * (float)Math.PI); Vector2 velocity = new Vector2(speed * (float)Math.Cos(angle), speed * (float)Math.Sin(angle)); // create new bear TeddyBear newBear = new TeddyBear(Content, "teddybear", x, y, velocity, null, null); // make sure we don't spawn into a collision // add new bear to list bears.Add(newBear); } /// <summary> /// Gets a random location using the given min and range /// </summary> /// <param name="min">the minimum</param> /// <param name="range">the range</param> /// <returns>the random location</returns> private int GetRandomLocation(int min, int range) { return min + RandomNumberGenerator.Next(range); } /// <summary> /// Gets a list of collision rectangles for all the objects in the game world /// </summary> /// <returns>the list of collision rectangles</returns> private List<Rectangle> GetCollisionRectangles() { List<Rectangle> collisionRectangles = new List<Rectangle>(); collisionRectangles.Add(burger.CollisionRectangle); foreach (TeddyBear bear in bears) { collisionRectangles.Add(bear.CollisionRectangle); } foreach (Projectile projectile in projectiles) { collisionRectangles.Add(projectile.CollisionRectangle); } foreach (Explosion explosion in explosions) { collisionRectangles.Add(explosion.CollisionRectangle); } return collisionRectangles; } /// <summary> /// Checks to see if the burger has just been killed /// </summary> private void CheckBurgerKill() { } #endregion } }
using System; using System.Linq; using Xunit; using Shouldly; using System.Collections.Generic; using AutoMapper.QueryableExtensions; namespace AutoMapper.UnitTests.DynamicMapping { public class When_mapping_from_untyped_enum_to_typed_enum : NonValidatingSpecBase { private Destination _result; public class Destination { public ConsoleColor Value { get; set; } } protected override void Because_of() { _result = Mapper.Map<Destination>(new { Value = (Enum) ConsoleColor.DarkGreen }); } [Fact] public void Should_map_ok() { _result.Value.ShouldBe(ConsoleColor.DarkGreen); } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => {}); } public class When_mapping_nested_types : NonValidatingSpecBase { List<ParentTestDto> _destination; public class Test { public int Id { get; set; } public string Name { get; set; } } public class TestDto { public int Id { get; set; } public string Name { get; set; } } public class ParentTestDto { public int Code { get; set; } public string FullName { get; set; } public TestDto Patient { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { }); protected override void Because_of() { var dynamicObject = new { Code = 5, FullName = "John", Patient = new Test { Id = 10, Name = "Roberts" } }; var dynamicList = new List<object> { dynamicObject }; _destination = Mapper.Map<List<ParentTestDto>>(dynamicList); } [Fact] public void Should_map_ok() { var result = _destination.First(); result.Patient.Id.ShouldBe(10); } } public class When_mapping_two_non_configured_types : NonValidatingSpecBase { private Destination _resultWithGenerics; private Destination _resultWithoutGenerics; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { }); [Fact] public void Should_dynamically_map_the_two_types() { _resultWithGenerics = Mapper.Map<Source, Destination>(new Source {Value = 5}); _resultWithoutGenerics = (Destination) Mapper.Map(new Source {Value = 5}, typeof(Source), typeof(Destination)); _resultWithGenerics.Value.ShouldBe(5); _resultWithoutGenerics.Value.ShouldBe(5); } } public class When_mapping_two_non_configured_types_with_resolvers : NonValidatingSpecBase { public class Inner { public string Content { get; set; } } public class Original { public string Text { get; set; } } public class Target { public string Text { get; set; } public Inner Child { get; set; } } public class TargetResolver : IValueResolver<Original, Target, Inner> { public Inner Resolve(Original source, Target dest, Inner destination, ResolutionContext context) { return new Inner { Content = "Hello world from inner!" }; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Original, Target>() .ForMember(t => t.Child, o => o.ResolveUsing<TargetResolver>()); }); [Fact] public void Should_use_resolver() { var tm = Configuration.FindTypeMapFor<Original, Target>(); var original = new Original { Text = "Hello world from original!" }; var mapped = Mapper.Map<Target>(original); mapped.Text.ShouldBe(original.Text); mapped.Child.ShouldNotBeNull(); mapped.Child.Content.ShouldBe("Hello world from inner!"); } } public class When_mapping_two_non_configured_types_with_nesting : NonValidatingSpecBase { private Destination _resultWithGenerics; public class Source { public int Value { get; set; } public ChildSource Child { get; set; } } public class ChildSource { public string Value2 { get; set; } } public class Destination { public int Value { get; set; } public ChildDestination Child { get; set; } } public class ChildDestination { public string Value2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => {}); public When_mapping_two_non_configured_types_with_nesting() { var source = new Source { Value = 5, Child = new ChildSource { Value2 = "foo" } }; _resultWithGenerics = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_dynamically_map_the_two_types() { _resultWithGenerics.Value.ShouldBe(5); } [Fact] public void Should_dynamically_map_the_children() { _resultWithGenerics.Child.Value2.ShouldBe("foo"); } } public class When_mapping_two_non_configured_types_that_do_not_match : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Destination { public int Valuefff { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { }); [Fact] public void Should_ignore_any_members_that_do_not_match() { var destination = Mapper.Map<Source, Destination>(new Source {Value = 5}, opt => opt.ConfigureMap(MemberList.None)); destination.Valuefff.ShouldBe(0); } [Fact] public void Should_not_throw_any_configuration_errors() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.Map<Source, Destination>(new Source { Value = 5 }, opt => opt.ConfigureMap(MemberList.None))); } } public class When_mapping_to_an_existing_destination_object : NonValidatingSpecBase { private Destination _destination; public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Valuefff { get; set; } public int Value2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => {}); public When_mapping_to_an_existing_destination_object() { _destination = new Destination { Valuefff = 7}; Mapper.Map(new Source { Value = 5, Value2 = 3}, _destination, opt => opt.ConfigureMap(MemberList.None)); } [Fact] public void Should_preserve_existing_values() { _destination.Valuefff.ShouldBe(7); } [Fact] public void Should_map_new_values() { _destination.Value2.ShouldBe(3); } } public class When_inline_mapping_with_inline_captured_closure : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(_ => {}); [Fact] public void Should_use_inline_value() { var value = 0; var source = new Source { Value = 10 }; void ConfigOpts(IMappingOperationOptions<Source, Dest> opt) => opt.ConfigureMap().ForMember(d => d.Value, m => m.MapFrom(src => src.Value + value)); var dest = Mapper.Map<Source, Dest>(source, ConfigOpts); dest.Value.ShouldBe(10); value = 10; dest = Mapper.Map<Source, Dest>(source, ConfigOpts); dest.Value.ShouldBe(20); } } public class When_mapping_from_an_anonymous_type_to_an_interface : NonValidatingSpecBase { private IDestination _result; public interface IDestination { int Value { get; set; } } protected override void Because_of() { _result = Mapper.Map<IDestination>(new {Value = 5}); } [Fact] public void Should_allow_dynamic_mapping() { _result.Value.ShouldBe(5); } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { }); } public class When_dynamically_mapping_a_badly_configured_map : NonValidatingSpecBase { public class Source { } public class Dest { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { }); [Fact] public void Should_throw() { typeof(AutoMapperConfigurationException).ShouldBeThrownBy(() => Mapper.Map<Source, Dest>(new Source())); } } public class When_dynamically_mapping_a_badly_configured_map_and_turning_off_validation : NonValidatingSpecBase { public class Source { } public class Dest { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.ValidateInlineMaps = false; }); [Fact] public void Should_not_throw() { Action action = () => Mapper.Map<Source, Dest>(new Source()); action.ShouldNotThrow(); } } public class When_automatically_dynamically_mapping : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => {}); [Fact] public void Should_map() { var source = new Source {Value = 5}; var dest = Mapper.Map<Dest>(source); dest.Value.ShouldBe(5); } } public class When_automatically_dynamically_projecting : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => {}); [Fact] public void Should_map() { var source = new Source {Value = 5}; var items = new[] {source}.AsQueryable(); var dest = items.ProjectTo<Dest>(ConfigProvider).ToArray(); dest.Length.ShouldBe(1); dest[0].Value.ShouldBe(5); } } public class When_mixing_auto_and_manual_map : NonValidatingSpecBase { public class Source { public int Value { get; set; } public Inner Value2 { get; set; } public class Inner { public string Value { get; set; } } } public class Dest { public int Value { get; set; } public Inner Value2 { get; set; } public class Inner { public string Value { get; set; } } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMap<Source, Dest>().ForMember(d => d.Value, opt => opt.MapFrom(src => src.Value + 5))); [Fact] public void Should_map() { var source = new Source { Value = 5, Value2 = new Source.Inner { Value = "asdf" } }; var dest = Mapper.Map<Dest>(source); dest.Value.ShouldBe(source.Value + 5); dest.Value2.Value.ShouldBe(source.Value2.Value); } } public class When_mixing_auto_and_manual_map_with_mismatched_properties : NonValidatingSpecBase { public class Source { public int Value { get; set; } public Inner Value2 { get; set; } public class Inner { public string Value { get; set; } } } public class Dest { public int Value { get; set; } public Inner Value2 { get; set; } public class Inner { public string Valuefff { get; set; } } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMap<Source, Dest>().ForMember(d => d.Value, opt => opt.MapFrom(src => src.Value + 5))); [Fact] public void Should_pass_validation() { Action assert = () => Configuration.AssertConfigurationIsValid(); assert.ShouldNotThrow(); } [Fact] public void Should_not_pass_runtime_validation() { Action assert = () => Mapper.Map<Dest>(new Source { Value = 5, Value2 = new Source.Inner { Value = "asdf"}}); var exception = assert.ShouldThrow<AutoMapperMappingException>(); var inner = exception.InnerException as AutoMapperConfigurationException; inner.ShouldNotBeNull(); inner.Errors.Select(e => e.TypeMap.Types).ShouldContain(tp => tp == new TypePair(typeof(Source.Inner), typeof(Dest.Inner))); } } }
// 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.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using System.Linq; using Xunit; using System.Threading.Tasks; namespace System.Diagnostics.Tests { public class ProcessThreadTests : ProcessTestBase { [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestCommonPriorityAndTimeProperties() { CreateDefaultProcess(); ProcessThreadCollection threadCollection = _process.Threads; Assert.True(threadCollection.Count > 0); ProcessThread thread = threadCollection[0]; try { if (ThreadState.Terminated != thread.ThreadState) { // On OSX, thread id is a 64bit unsigned value. We truncate the ulong to int // due to .NET API surface area. Hence, on overflow id can be negative while // casting the ulong to int. Assert.True(thread.Id >= 0 || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)); Assert.Equal(_process.BasePriority, thread.BasePriority); Assert.True(thread.CurrentPriority >= 0); Assert.True(thread.PrivilegedProcessorTime.TotalSeconds >= 0); Assert.True(thread.UserProcessorTime.TotalSeconds >= 0); Assert.True(thread.TotalProcessorTime.TotalSeconds >= 0); } } catch (Exception e) when (e is Win32Exception || e is InvalidOperationException) { // Win32Exception is thrown when getting threadinfo fails, or // InvalidOperationException if it fails because the thread already exited. } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestThreadCount() { int numOfThreads = 10; CountdownEvent counter = new CountdownEvent(numOfThreads); ManualResetEventSlim mre = new ManualResetEventSlim(); for (int i = 0; i < numOfThreads; i++) { new Thread(() => { counter.Signal(); mre.Wait(); }) { IsBackground = true }.Start(); } counter.Wait(); try { Assert.True(Process.GetCurrentProcess().Threads.Count >= numOfThreads); } finally { mre.Set(); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // OSX throws PNSE from StartTime public void TestStartTimeProperty_OSX() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); ProcessThread thread = threads[0]; Assert.NotNull(thread); Assert.Throws<PlatformNotSupportedException>(() => thread.StartTime); } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // OSX throws PNSE from StartTime [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public async Task TestStartTimeProperty() { TimeSpan allowedWindow = TimeSpan.FromSeconds(1); using (Process p = Process.GetCurrentProcess()) { // Get the process' start time DateTime startTime = p.StartTime.ToUniversalTime(); // Get the process' threads ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); // Get the current time DateTime curTime = DateTime.UtcNow; // Make sure each thread's start time is at least the process' // start time and not beyond the current time. int passed = 0; foreach (ProcessThread t in threads.Cast<ProcessThread>()) { try { Assert.InRange(t.StartTime.ToUniversalTime(), startTime - allowedWindow, curTime + allowedWindow); passed++; } catch (InvalidOperationException) { // The thread may have gone away between our getting its info and attempting to access its StartTime } } Assert.True(passed > 0, "Expected at least one thread to be valid for StartTime"); // Now add a thread, and from that thread, while it's still alive, verify // that there's at least one thread greater than the current time we previously grabbed. await Task.Factory.StartNew(() => { p.Refresh(); try { Assert.Contains(p.Threads.Cast<ProcessThread>(), t => t.StartTime.ToUniversalTime() >= curTime - allowedWindow); } catch (InvalidOperationException) { // A thread may have gone away between our getting its info and attempting to access its StartTime } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestStartAddressProperty() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); IntPtr startAddress = threads[0].StartAddress; // There's nothing we can really validate about StartAddress, other than that we can get its value // without throwing. All values (even zero) are valid on all platforms. } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPriorityLevelProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel); Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } ThreadPriorityLevel originalPriority = thread.PriorityLevel; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } try { thread.PriorityLevel = ThreadPriorityLevel.AboveNormal; Assert.Equal(ThreadPriorityLevel.AboveNormal, thread.PriorityLevel); } finally { thread.PriorityLevel = originalPriority; Assert.Equal(originalPriority, thread.PriorityLevel); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestThreadStateProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (ThreadState.Wait != thread.ThreadState) { Assert.Throws<InvalidOperationException>(() => thread.WaitReason); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void Threads_GetMultipleTimes_ReturnsSameInstance() { CreateDefaultProcess(); Assert.Same(_process.Threads, _process.Threads); } [Fact] public void Threads_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Threads); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Data.Common; using System.Data.SqlClient; using System.Text.Encodings.Web; using System.Text.Unicode; using Benchmarks.Configuration; using Benchmarks.Data; using Benchmarks.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MySql.Data.MySqlClient; using Npgsql; namespace Benchmarks { public class Startup { public Startup(IHostingEnvironment hostingEnv, Scenarios scenarios) { // Set up configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(hostingEnv.ContentRootPath) .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{hostingEnv.EnvironmentName}.json", optional: true) .AddEnvironmentVariables() .AddCommandLine(Program.Args) ; Configuration = builder.Build(); Scenarios = scenarios; } public IConfigurationRoot Configuration { get; set; } public Scenarios Scenarios { get; } public void ConfigureServices(IServiceCollection services) { services.Configure<AppSettings>(Configuration); // We re-register the Scenarios as an instance singleton here to avoid it being created again due to the // registration done in Program.Main services.AddSingleton(Scenarios); // Common DB services services.AddSingleton<IRandom, DefaultRandom>(); services.AddEntityFrameworkSqlServer(); var appSettings = Configuration.Get<AppSettings>(); Console.WriteLine($"Database: {appSettings.Database}"); if (appSettings.Database == DatabaseServer.PostgreSql) { if (Scenarios.Any("Ef")) { services.AddDbContextPool<ApplicationDbContext>(options => options.UseNpgsql(appSettings.ConnectionString)); } if (Scenarios.Any("Raw") || Scenarios.Any("Dapper")) { services.AddSingleton<DbProviderFactory>(NpgsqlFactory.Instance); } } else if (appSettings.Database == DatabaseServer.MySql) { if (Scenarios.Any("Raw") || Scenarios.Any("Dapper")) { services.AddSingleton<DbProviderFactory>(MySqlClientFactory.Instance); } } if (Scenarios.Any("Ef")) { services.AddScoped<EfDb>(); } if (Scenarios.Any("Raw")) { services.AddScoped<RawDb>(); } if (Scenarios.Any("Dapper")) { services.AddScoped<DapperDb>(); } if (Scenarios.Any("Fortunes")) { var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana); settings.AllowCharacter('\u2014'); // allow EM DASH through services.AddWebEncoders((options) => { options.TextEncoderSettings = settings; }); } if (Scenarios.Any("Mvc")) { var mvcBuilder = services .AddMvcCore() .AddControllersAsServices(); if (Scenarios.MvcJson || Scenarios.Any("MvcDbSingle") || Scenarios.Any("MvcDbMulti")) { mvcBuilder.AddJsonFormatters(); } if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes")) { mvcBuilder .AddViews() .AddRazorViewEngine(); } } } public void Configure(IApplicationBuilder app) { if (Scenarios.Plaintext) { app.UsePlainText(); } if (Scenarios.Json) { app.UseJson(); } // Single query endpoints if (Scenarios.DbSingleQueryRaw) { app.UseSingleQueryRaw(); } if (Scenarios.DbSingleQueryDapper) { app.UseSingleQueryDapper(); } if (Scenarios.DbSingleQueryEf) { app.UseSingleQueryEf(); } // Multiple query endpoints if (Scenarios.DbMultiQueryRaw) { app.UseMultipleQueriesRaw(); } if (Scenarios.DbMultiQueryDapper) { app.UseMultipleQueriesDapper(); } if (Scenarios.DbMultiQueryEf) { app.UseMultipleQueriesEf(); } // Multiple update endpoints if (Scenarios.DbMultiUpdateRaw) { app.UseMultipleUpdatesRaw(); } if (Scenarios.DbMultiUpdateDapper) { app.UseMultipleUpdatesDapper(); } if (Scenarios.DbMultiUpdateEf) { app.UseMultipleUpdatesEf(); } // Fortunes endpoints if (Scenarios.DbFortunesRaw) { app.UseFortunesRaw(); } if (Scenarios.DbFortunesDapper) { app.UseFortunesDapper(); } if (Scenarios.DbFortunesEf) { app.UseFortunesEf(); } if (Scenarios.Any("Mvc")) { app.UseMvc(); } if (Scenarios.StaticFiles) { app.UseStaticFiles(); } } } }
using Avalonia.Controls; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Input.UnitTests { public class InputElement_Focus { [Fact] public void Focus_Should_Set_FocusManager_Current() { Button target; using (UnitTestApplication.Start(TestServices.RealFocus)) { var root = new TestRoot { Child = target = new Button() }; target.Focus(); Assert.Same(target, FocusManager.Instance.Current); } } [Fact] public void Focus_Should_Be_Cleared_When_Control_Is_Removed_From_VisualTree() { Button target; using (UnitTestApplication.Start(TestServices.RealFocus)) { var root = new TestRoot { Child = target = new Button() }; target.Focus(); root.Child = null; Assert.Null(FocusManager.Instance.Current); } } [Fact] public void Focus_Pseudoclass_Should_Be_Applied_On_Focus() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var target1 = new Decorator(); var target2 = new Decorator(); var root = new TestRoot { Child = new StackPanel { Children = { target1, target2 } } }; target1.ApplyTemplate(); target2.ApplyTemplate(); FocusManager.Instance?.Focus(target1); Assert.True(target1.IsFocused); Assert.True(target1.Classes.Contains(":focus")); Assert.False(target2.IsFocused); Assert.False(target2.Classes.Contains(":focus")); FocusManager.Instance?.Focus(target2, NavigationMethod.Tab); Assert.False(target1.IsFocused); Assert.False(target1.Classes.Contains(":focus")); Assert.True(target2.IsFocused); Assert.True(target2.Classes.Contains(":focus")); } } [Fact] public void Control_FocusVsisible_Pseudoclass_Should_Be_Applied_On_Tab_And_DirectionalFocus() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var target1 = new Decorator(); var target2 = new Decorator(); var root = new TestRoot { Child = new StackPanel { Children = { target1, target2 } } }; target1.ApplyTemplate(); target2.ApplyTemplate(); FocusManager.Instance?.Focus(target1); Assert.True(target1.IsFocused); Assert.False(target1.Classes.Contains(":focus-visible")); Assert.False(target2.IsFocused); Assert.False(target2.Classes.Contains(":focus-visible")); FocusManager.Instance?.Focus(target2, NavigationMethod.Tab); Assert.False(target1.IsFocused); Assert.False(target1.Classes.Contains(":focus-visible")); Assert.True(target2.IsFocused); Assert.True(target2.Classes.Contains(":focus-visible")); FocusManager.Instance?.Focus(target1, NavigationMethod.Directional); Assert.True(target1.IsFocused); Assert.True(target1.Classes.Contains(":focus-visible")); Assert.False(target2.IsFocused); Assert.False(target2.Classes.Contains(":focus-visible")); } } [Fact] public void Control_FocusWithin_PseudoClass_Should_Be_Applied() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var target1 = new Decorator(); var target2 = new Decorator(); var root = new TestRoot { Child = new StackPanel { Children = { target1, target2 } } }; target1.ApplyTemplate(); target2.ApplyTemplate(); FocusManager.Instance?.Focus(target1); Assert.True(target1.IsFocused); Assert.True(target1.Classes.Contains(":focus-within")); Assert.True(target1.IsKeyboardFocusWithin); Assert.True(root.Child.Classes.Contains(":focus-within")); Assert.True(root.Child.IsKeyboardFocusWithin); Assert.True(root.Classes.Contains(":focus-within")); Assert.True(root.IsKeyboardFocusWithin); } } [Fact] public void Control_FocusWithin_PseudoClass_Should_Be_Applied_and_Removed() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var target1 = new Decorator(); var target2 = new Decorator(); var panel1 = new Panel { Children = { target1 } }; var panel2 = new Panel { Children = { target2 } }; var root = new TestRoot { Child = new StackPanel { Children = { panel1, panel2 } } }; target1.ApplyTemplate(); target2.ApplyTemplate(); FocusManager.Instance?.Focus(target1); Assert.True(target1.IsFocused); Assert.True(target1.Classes.Contains(":focus-within")); Assert.True(target1.IsKeyboardFocusWithin); Assert.True(panel1.Classes.Contains(":focus-within")); Assert.True(panel1.IsKeyboardFocusWithin); Assert.True(root.Child.Classes.Contains(":focus-within")); Assert.True(root.Child.IsKeyboardFocusWithin); Assert.True(root.Classes.Contains(":focus-within")); Assert.True(root.IsKeyboardFocusWithin); FocusManager.Instance?.Focus(target2); Assert.False(target1.IsFocused); Assert.False(target1.Classes.Contains(":focus-within")); Assert.False(target1.IsKeyboardFocusWithin); Assert.False(panel1.Classes.Contains(":focus-within")); Assert.False(panel1.IsKeyboardFocusWithin); Assert.True(root.Child.Classes.Contains(":focus-within")); Assert.True(root.Child.IsKeyboardFocusWithin); Assert.True(root.Classes.Contains(":focus-within")); Assert.True(root.IsKeyboardFocusWithin); Assert.True(target2.IsFocused); Assert.True(target2.Classes.Contains(":focus-within")); Assert.True(target2.IsKeyboardFocusWithin); Assert.True(panel2.Classes.Contains(":focus-within")); Assert.True(panel2.IsKeyboardFocusWithin); } } [Fact] public void Control_FocusWithin_Pseudoclass_Should_Be_Removed_When_Removed_From_Tree() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var target1 = new Decorator(); var target2 = new Decorator(); var root = new TestRoot { Child = new StackPanel { Children = { target1, target2 } } }; target1.ApplyTemplate(); target2.ApplyTemplate(); FocusManager.Instance?.Focus(target1); Assert.True(target1.IsFocused); Assert.True(target1.Classes.Contains(":focus-within")); Assert.True(target1.IsKeyboardFocusWithin); Assert.True(root.Child.Classes.Contains(":focus-within")); Assert.True(root.Child.IsKeyboardFocusWithin); Assert.True(root.Classes.Contains(":focus-within")); Assert.True(root.IsKeyboardFocusWithin); Assert.Equal(KeyboardDevice.Instance.FocusedElement, target1); root.Child = null; Assert.Null(KeyboardDevice.Instance.FocusedElement); Assert.False(target1.IsFocused); Assert.False(target1.Classes.Contains(":focus-within")); Assert.False(target1.IsKeyboardFocusWithin); Assert.False(root.Classes.Contains(":focus-within")); Assert.False(root.IsKeyboardFocusWithin); } } [Fact] public void Control_FocusWithin_Pseudoclass_Should_Be_Removed_Focus_Moves_To_Different_Root() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var target1 = new Decorator(); var target2 = new Decorator(); var root1 = new TestRoot { Child = new StackPanel { Children = { target1, } } }; var root2 = new TestRoot { Child = new StackPanel { Children = { target2, } } }; target1.ApplyTemplate(); target2.ApplyTemplate(); FocusManager.Instance?.Focus(target1); Assert.True(target1.IsFocused); Assert.True(target1.Classes.Contains(":focus-within")); Assert.True(target1.IsKeyboardFocusWithin); Assert.True(root1.Child.Classes.Contains(":focus-within")); Assert.True(root1.Child.IsKeyboardFocusWithin); Assert.True(root1.Classes.Contains(":focus-within")); Assert.True(root1.IsKeyboardFocusWithin); Assert.Equal(KeyboardDevice.Instance.FocusedElement, target1); FocusManager.Instance?.Focus(target2); Assert.False(target1.IsFocused); Assert.False(target1.Classes.Contains(":focus-within")); Assert.False(target1.IsKeyboardFocusWithin); Assert.False(root1.Child.Classes.Contains(":focus-within")); Assert.False(root1.Child.IsKeyboardFocusWithin); Assert.False(root1.Classes.Contains(":focus-within")); Assert.False(root1.IsKeyboardFocusWithin); Assert.True(target2.IsFocused); Assert.True(target2.Classes.Contains(":focus-within")); Assert.True(target2.IsKeyboardFocusWithin); Assert.True(root2.Child.Classes.Contains(":focus-within")); Assert.True(root2.Child.IsKeyboardFocusWithin); Assert.True(root2.Classes.Contains(":focus-within")); Assert.True(root2.IsKeyboardFocusWithin); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Your favorite String class. Native methods ** are implemented in StringNative.cpp ** ** ===========================================================*/ namespace System { using System.Text; using System; using System.Runtime; using System.Runtime.ConstrainedExecution; using System.Globalization; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.Win32; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; // // For Information on these methods, please see COMString.cpp // // The String class represents a static string of characters. Many of // the String methods perform some type of transformation on the current // instance and return the result as a new String. All comparison methods are // implemented as a part of String. As with arrays, character positions // (indices) are zero-based. [Serializable] public sealed partial class String : IComparable, ICloneable, IConvertible, IEnumerable , IComparable<String>, IEnumerable<char>, IEquatable<String> { // //NOTE NOTE NOTE NOTE //These fields map directly onto the fields in an EE StringObject. See object.h for the layout. // [NonSerialized] private int m_stringLength; // For empty strings, this will be '\0' since // strings are both null-terminated and length prefixed [NonSerialized] private char m_firstChar; // The Empty constant holds the empty string value. It is initialized by the EE during startup. // It is treated as intrinsic by the JIT as so the static constructor would never run. // Leaving it uninitialized would confuse debuggers. // //We need to call the String constructor so that the compiler doesn't mark this as a literal. //Marking this as a literal would mean that it doesn't show up as a field which we can access //from native. public static readonly String Empty; internal char FirstChar { get { return m_firstChar; } } // // This is a helper method for the security team. They need to uppercase some strings (guaranteed to be less // than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's) // from the assembly. This provides a workaround for that problem and should NOT be used anywhere else. // internal unsafe static string SmallCharToUpper(string strIn) { Contract.Requires(strIn != null); Contract.EndContractBlock(); // // Get the length and pointers to each of the buffers. Walk the length // of the string and copy the characters from the inBuffer to the outBuffer, // capitalizing it if necessary. We assert that all of our characters are // less than 0x80. // int length = strIn.Length; String strOut = FastAllocateString(length); fixed (char* inBuff = &strIn.m_firstChar, outBuff = &strOut.m_firstChar) { for (int i = 0; i < length; i++) { int c = inBuff[i]; Debug.Assert(c <= 0x7F, "string has to be ASCII"); // uppercase - notice that we need just one compare if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20; outBuff[i] = (char)c; } Debug.Assert(outBuff[length] == '\0', "outBuff[length]=='\0'"); } return strOut; } // Gets the character at a specified position. // // Spec#: Apply the precondition here using a contract assembly. Potential perf issue. [System.Runtime.CompilerServices.IndexerName("Chars")] public extern char this[int index] { [MethodImpl(MethodImplOptions.InternalCall)] get; } // Converts a substring of this string to an array of characters. Copies the // characters of this string beginning at position sourceIndex and ending at // sourceIndex + count - 1 to the character array buffer, beginning // at destinationIndex. // unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); if (sourceIndex < 0) throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index); if (count > Length - sourceIndex) throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount); if (destinationIndex > destination.Length - count || destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount); Contract.EndContractBlock(); // Note: fixed does not like empty arrays if (count > 0) { fixed (char* src = &m_firstChar) fixed (char* dest = destination) wstrcpy(dest + destinationIndex, src + sourceIndex, count); } } // Returns the entire string as an array of characters. unsafe public char[] ToCharArray() { int length = Length; if (length > 0) { char[] chars = new char[length]; fixed (char* src = &m_firstChar) fixed (char* dest = chars) { wstrcpy(dest, src, length); } return chars; } return Array.Empty<char>(); } // Returns a substring of this string as an array of characters. // unsafe public char[] ToCharArray(int startIndex, int length) { // Range check everything. if (startIndex < 0 || startIndex > Length || startIndex > Length - length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); if (length > 0) { char[] chars = new char[length]; fixed (char* src = &m_firstChar) fixed (char* dest = chars) { wstrcpy(dest, src + startIndex, length); } return chars; } return Array.Empty<char>(); } [Pure] public static bool IsNullOrEmpty(String value) { return (value == null || value.Length == 0); } [Pure] public static bool IsNullOrWhiteSpace(String value) { if (value == null) return true; for (int i = 0; i < value.Length; i++) { if (!Char.IsWhiteSpace(value[i])) return false; } return true; } // Gets the length of this string // /// This is a EE implemented function so that the JIT can recognise is specially /// and eliminate checks on character fetchs in a loop like: /// for(int i = 0; i < str.Length; i++) str[i] /// The actually code generated for this will be one instruction and will be inlined. // // Spec#: Add postcondition in a contract assembly. Potential perf problem. public extern int Length { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } // Creates a new string with the characters copied in from ptr. If // ptr is null, a 0-length string (like String.Empty) is returned. // [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe public extern String(char* value); [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe public extern String(char* value, int startIndex, int length); [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe public extern String(sbyte* value); [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe public extern String(sbyte* value, int startIndex, int length); [CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe public extern String(sbyte* value, int startIndex, int length, Encoding enc); unsafe static private String CreateString(sbyte* value, int startIndex, int length, Encoding enc) { if (enc == null) return new String(value, startIndex, length); // default to ANSI if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); if ((value + startIndex) < value) { // overflow check throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR); } byte[] b = new byte[length]; try { Buffer.Memcpy(b, 0, (byte*)value, startIndex, length); } catch (NullReferenceException) { // If we got a NullReferencException. It means the pointer or // the index is out of range throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_PartialWCHAR); } return enc.GetString(b); } // Helper for encodings so they can talk to our buffer directly // stringLength must be the exact size we'll expect unsafe static internal String CreateStringFromEncoding( byte* bytes, int byteLength, Encoding encoding) { Contract.Requires(bytes != null); Contract.Requires(byteLength >= 0); // Get our string length int stringLength = encoding.GetCharCount(bytes, byteLength, null); Debug.Assert(stringLength >= 0, "stringLength >= 0"); // They gave us an empty string if they needed one // 0 bytelength might be possible if there's something in an encoder if (stringLength == 0) return String.Empty; String s = FastAllocateString(stringLength); fixed (char* pTempChars = &s.m_firstChar) { int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null); Debug.Assert(stringLength == doubleCheck, "Expected encoding.GetChars to return same length as encoding.GetCharCount"); } return s; } // This is only intended to be used by char.ToString. // It is necessary to put the code in this class instead of Char, since m_firstChar is a private member. // Making m_firstChar internal would be dangerous since it would make it much easier to break String's immutability. internal static string CreateFromChar(char c) { string result = FastAllocateString(1); result.m_firstChar = c; return result; } unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer, Encoding encoding) { // encoding == Encoding.UTF8 fixed (char* pwzChar = &m_firstChar) { return encoding.GetBytes(pwzChar, m_stringLength, pbNativeBuffer, cbNativeBuffer); } } unsafe internal int ConvertToAnsi(byte* pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar) { Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi"); const uint CP_ACP = 0; int nb; const uint WC_NO_BEST_FIT_CHARS = 0x00000400; uint flgs = (fBestFit ? 0 : WC_NO_BEST_FIT_CHARS); uint DefaultCharUsed = 0; fixed (char* pwzChar = &m_firstChar) { nb = Win32Native.WideCharToMultiByte( CP_ACP, flgs, pwzChar, this.Length, pbNativeBuffer, cbNativeBuffer, IntPtr.Zero, (fThrowOnUnmappableChar ? new IntPtr(&DefaultCharUsed) : IntPtr.Zero)); } if (0 != DefaultCharUsed) { throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char); } pbNativeBuffer[nb] = 0; return nb; } // Normalization Methods // These just wrap calls to Normalization class public bool IsNormalized() { // Default to Form C return IsNormalized(NormalizationForm.FormC); } public bool IsNormalized(NormalizationForm normalizationForm) { if (this.IsFastSort()) { // If its FastSort && one of the 4 main forms, then its already normalized if (normalizationForm == NormalizationForm.FormC || normalizationForm == NormalizationForm.FormKC || normalizationForm == NormalizationForm.FormD || normalizationForm == NormalizationForm.FormKD) return true; } return Normalization.IsNormalized(this, normalizationForm); } public String Normalize() { // Default to Form C return Normalize(NormalizationForm.FormC); } public String Normalize(NormalizationForm normalizationForm) { if (this.IsAscii()) { // If its FastSort && one of the 4 main forms, then its already normalized if (normalizationForm == NormalizationForm.FormC || normalizationForm == NormalizationForm.FormKC || normalizationForm == NormalizationForm.FormD || normalizationForm == NormalizationForm.FormKD) return this; } return Normalization.Normalize(this, normalizationForm); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static String FastAllocateString(int length); // Creates a new string from the characters in a subarray. The new string will // be created from the characters in value between startIndex and // startIndex + length - 1. // [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char[] value, int startIndex, int length); // Creates a new string from the characters in a subarray. The new string will be // created from the characters in value. // [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char[] value); internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount) { Buffer.Memcpy((byte*)dmem, (byte*)smem, charCount * 2); // 2 used everywhere instead of sizeof(char) } private String CtorCharArray(char[] value) { if (value != null && value.Length != 0) { String result = FastAllocateString(value.Length); unsafe { fixed (char* dest = &result.m_firstChar, source = value) { wstrcpy(dest, source, value.Length); } } return result; } else return String.Empty; } private String CtorCharArrayStartLength(char[] value, int startIndex, int length) { if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); if (startIndex > value.Length - length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); if (length > 0) { String result = FastAllocateString(length); unsafe { fixed (char* dest = &result.m_firstChar, source = value) { wstrcpy(dest, source + startIndex, length); } } return result; } else return String.Empty; } private String CtorCharCount(char c, int count) { if (count > 0) { String result = FastAllocateString(count); if (c != 0) { unsafe { fixed (char* dest = &result.m_firstChar) { char* dmem = dest; while (((uint)dmem & 3) != 0 && count > 0) { *dmem++ = c; count--; } uint cc = (uint)((c << 16) | c); if (count >= 4) { count -= 4; do { ((uint*)dmem)[0] = cc; ((uint*)dmem)[1] = cc; dmem += 4; count -= 4; } while (count >= 0); } if ((count & 2) != 0) { ((uint*)dmem)[0] = cc; dmem += 2; } if ((count & 1) != 0) dmem[0] = c; } } } return result; } else if (count == 0) return String.Empty; else throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(count))); } internal static unsafe int wcslen(char* ptr) { char* end = ptr; // First make sure our pointer is aligned on a word boundary int alignment = IntPtr.Size - 1; // If ptr is at an odd address (e.g. 0x5), this loop will simply iterate all the way while (((uint)end & (uint)alignment) != 0) { if (*end == 0) goto FoundZero; end++; } #if !BIT64 // The following code is (somewhat surprisingly!) significantly faster than a naive loop, // at least on x86 and the current jit. // The loop condition below works because if "end[0] & end[1]" is non-zero, that means // neither operand can have been zero. If is zero, we have to look at the operands individually, // but we hope this going to fairly rare. // In general, it would be incorrect to access end[1] if we haven't made sure // end[0] is non-zero. However, we know the ptr has been aligned by the loop above // so end[0] and end[1] must be in the same word (and therefore page), so they're either both accessible, or both not. while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0)) { end += 2; } Debug.Assert(end[0] == 0 || end[1] == 0); if (end[0] != 0) end++; #else // !BIT64 // Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord // 64-bit implementation: process 1 ulong (word) at a time // What we do here is add 0x7fff from each of the // 4 individual chars within the ulong, using MagicMask. // If the char > 0 and < 0x8001, it will have its high bit set. // We then OR with MagicMask, to set all the other bits. // This will result in all bits set (ulong.MaxValue) for any // char that fits the above criteria, and something else otherwise. // Note that for any char > 0x8000, this will be a false // positive and we will fallback to the slow path and // check each char individually. This is OK though, since // we optimize for the common case (ASCII chars, which are < 0x80). // NOTE: We can access a ulong a time since the ptr is aligned, // and therefore we're only accessing the same word/page. (See notes // for the 32-bit version above.) const ulong MagicMask = 0x7fff7fff7fff7fff; while (true) { ulong word = *(ulong*)end; word += MagicMask; // cause high bit to be set if not zero, and <= 0x8000 word |= MagicMask; // set everything besides the high bits if (word == ulong.MaxValue) // 0xffff... { // all of the chars have their bits set (and therefore none can be 0) end += 4; continue; } // at least one of them didn't have their high bit set! // go through each char and check for 0. if (end[0] == 0) goto EndAt0; if (end[1] == 0) goto EndAt1; if (end[2] == 0) goto EndAt2; if (end[3] == 0) goto EndAt3; // if we reached here, it was a false positive-- just continue end += 4; } EndAt3: end++; EndAt2: end++; EndAt1: end++; EndAt0: #endif // !BIT64 FoundZero: Debug.Assert(*end == 0); int count = (int)(end - ptr); return count; } private unsafe String CtorCharPtr(char* ptr) { if (ptr == null) return String.Empty; #if !FEATURE_PAL if (ptr < (char*)64000) throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom); #endif // FEATURE_PAL Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it try { int count = wcslen(ptr); if (count == 0) return String.Empty; String result = FastAllocateString(count); fixed (char* dest = &result.m_firstChar) wstrcpy(dest, ptr, count); return result; } catch (NullReferenceException) { throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR); } } private unsafe String CtorCharPtrStartLength(char* ptr, int startIndex, int length) { if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); } if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); } Contract.EndContractBlock(); Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it char* pFrom = ptr + startIndex; if (pFrom < ptr) { // This means that the pointer operation has had an overflow throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR); } if (length == 0) return String.Empty; String result = FastAllocateString(length); try { fixed (char* dest = &result.m_firstChar) wstrcpy(dest, pFrom, length); return result; } catch (NullReferenceException) { throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char c, int count); // Returns this string. public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return this; } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return this; } // Method required for the ICloneable interface. // There's no point in cloning a string since they're immutable, so we simply return this. public Object Clone() { Contract.Ensures(Contract.Result<Object>() != null); Contract.EndContractBlock(); return this; } unsafe public static String Copy(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); int length = str.Length; String result = FastAllocateString(length); fixed (char* dest = &result.m_firstChar) fixed (char* src = &str.m_firstChar) { wstrcpy(dest, src, length); } return result; } public static String Intern(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.Ensures(Contract.Result<String>().Length == str.Length); Contract.Ensures(str.Equals(Contract.Result<String>())); Contract.EndContractBlock(); return Thread.GetDomain().GetOrInternString(str); } [Pure] public static String IsInterned(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.Ensures(Contract.Result<String>() == null || Contract.Result<String>().Length == str.Length); Contract.EndContractBlock(); return Thread.GetDomain().IsStringInterned(str); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.String; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this, provider); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this, provider); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this, provider); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this, provider); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this, provider); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this, provider); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this, provider); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this, provider); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this, provider); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this, provider); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this, provider); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this, provider); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this, provider); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(this, provider); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } // Is this a string that can be compared quickly (that is it has only characters > 0x80 // and not a - or ' [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern bool IsFastSort(); // Is this a string that only contains characters < 0x80. [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern bool IsAscii(); #if FEATURE_COMINTEROP // Set extra byte for odd-sized strings that came from interop as BSTR. [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void SetTrailByte(byte data); // Try to retrieve the extra byte - returns false if not present. [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern bool TryGetTrailByte(out byte data); #endif public CharEnumerator GetEnumerator() { Contract.Ensures(Contract.Result<CharEnumerator>() != null); Contract.EndContractBlock(); BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead."); return new CharEnumerator(this); } IEnumerator<char> IEnumerable<char>.GetEnumerator() { Contract.Ensures(Contract.Result<IEnumerator<char>>() != null); Contract.EndContractBlock(); BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead."); return new CharEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { Contract.Ensures(Contract.Result<IEnumerator>() != null); Contract.EndContractBlock(); BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead."); return new CharEnumerator(this); } // Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes. internal unsafe static void InternalCopy(String src, IntPtr dest, int len) { if (len == 0) return; fixed (char* charPtr = &src.m_firstChar) { byte* srcPtr = (byte*)charPtr; byte* dstPtr = (byte*)dest; Buffer.Memcpy(dstPtr, srcPtr, len); } } internal ref char GetRawStringData() { return ref m_firstChar; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Diagnostics; using System.Text.RegularExpressions; using System.Xml; using System.Windows.Forms; using JustGestures.Features; namespace JustGestures { class FileOptions { private const string GESTURES = "gestures.jg"; private const string PROGRAMS = "programs.jg"; private const string NETWORK = "network.jg"; private const string TRAINING_SET = "training_set.jg"; private const string FAVICONS = "favicons.jg"; public static void SaveGestures(GesturesCollection gestures) { Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + GESTURES, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, gestures); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); } } public static GesturesCollection LoadGestures() { GesturesCollection gestures = new GesturesCollection(); Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + GESTURES, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); gestures = (GesturesCollection)bFormatter.Deserialize(stream); } catch (Exception ex) { Debug.WriteLine(ex.Message); gestures.Add(MyGesture.GlobalGroup); } finally { if (stream != null) stream.Close(); } return gestures; } public static void SaveLists(List<PrgNamePath> whiteList, List<PrgNamePath> blackList, List<PrgNamePath> finalList) { String[] elements = new string[] { "name", "path", "active" }; XmlWriter writer = null; XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = true; settings.ConformanceLevel = ConformanceLevel.Auto; try { writer = XmlWriter.Create(Config.Default.FilesLocation + PROGRAMS, settings); writer.WriteStartDocument(); writer.WriteStartElement("AutoBehave"); writer.WriteStartElement("WhiteList"); for (int i = 0; i < whiteList.Count; i++) { writer.WriteStartElement("program"); writer.WriteAttributeString(elements[0], whiteList[i].PrgName); writer.WriteElementString(elements[1], whiteList[i].Path); writer.WriteElementString(elements[2], whiteList[i].Active.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("BlackList"); for (int i = 0; i < blackList.Count; i++) { writer.WriteStartElement("program"); writer.WriteAttributeString(elements[0], blackList[i].PrgName); writer.WriteElementString(elements[1], blackList[i].Path); writer.WriteElementString(elements[2], blackList[i].Active.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("FinalList"); for (int i = 0; i < finalList.Count; i++) { writer.WriteStartElement("program"); writer.WriteAttributeString(elements[0], finalList[i].PrgName); writer.WriteElementString(elements[1], finalList[i].Path); writer.WriteElementString(elements[2], finalList[i].Active.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (writer != null) writer.Close(); } } public static void LoadLists(out List<PrgNamePath> whiteList, out List<PrgNamePath> blackList, out List<PrgNamePath> finalList) { XmlDocument document = new XmlDocument(); XmlTextReader reader = null; PrgNamePath prog = new PrgNamePath(); whiteList = new List<PrgNamePath>(); blackList = new List<PrgNamePath>(); finalList = new List<PrgNamePath>(); string reading = null; try { reader = new XmlTextReader(Config.Default.FilesLocation + PROGRAMS); while (reader.Read()) { if (reader.Name == "WhiteList") reading = "WhiteList"; else if (reader.Name == "BlackList") reading = "BlackList"; else if (reader.Name == "FinalList") reading = "FinalList"; else if (reader.Name == "program") prog.PrgName = reader["name"]; else if (reader.Name == "path") prog.Path = reader.ReadString(); else if (reader.Name == "active") { bool result = false; bool.TryParse(reader.ReadString(), out result); prog.Active = result; if (reading == "WhiteList") whiteList.Add(new PrgNamePath(prog.PrgName, prog.Path, prog.Active)); else if (reading == "BlackList") blackList.Add(new PrgNamePath(prog.PrgName, prog.Path, prog.Active)); else if (reading == "FinalList") { string state = prog.Active ? OptionItems.UC_autoBehaviour.STATE_ENABLED : OptionItems.UC_autoBehaviour.STATE_DISABLED; finalList.Add(new PrgNamePath(state, prog.PrgName, prog.Path)); } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (reader != null) reader.Close(); } } public static void SaveNeuralNetwork(NeuralNetwork.Network neuralNetwork) { Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + NETWORK, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); if (neuralNetwork != null) bFormatter.Serialize(stream, neuralNetwork); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); } } public static NeuralNetwork.Network LoadNeuralNetwork() { NeuralNetwork.Network neuralNetwork = null; Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + NETWORK, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); neuralNetwork = (NeuralNetwork.Network)bFormatter.Deserialize(stream); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); } return neuralNetwork; } public static void SaveTrainingSet(Dictionary<string, MyCurve> trainingSet) { Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + TRAINING_SET, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, trainingSet); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); } } public static Dictionary<string, MyCurve> LoadTrainingSet() { Dictionary<string, MyCurve> trainingSet = new Dictionary<string, MyCurve>(); Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + TRAINING_SET, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); trainingSet = (Dictionary<string, MyCurve>)bFormatter.Deserialize(stream); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); } return trainingSet; } public static void SaveFavicons(Dictionary<string, System.Drawing.Bitmap> favicons) { Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + FAVICONS, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, favicons); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); } } public static Dictionary<string, System.Drawing.Bitmap> LoadFavicons() { Dictionary<string, System.Drawing.Bitmap> favicons = new Dictionary<string, System.Drawing.Bitmap>(); Stream stream = null; try { stream = File.Open(Config.Default.FilesLocation + FAVICONS, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); favicons = (Dictionary<string, System.Drawing.Bitmap>)bFormatter.Deserialize(stream); stream.Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); } return favicons; } } }
//----------------------------------------------------------------------- // <copyright file="FrameApi.cs" company="Google"> // // Copyright 2017 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 GoogleARCoreInternal { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using GoogleARCore; using UnityEngine; #if UNITY_IOS && !UNITY_EDITOR using AndroidImport = GoogleARCoreInternal.DllImportNoop; using IOSImport = System.Runtime.InteropServices.DllImportAttribute; #else using AndroidImport = System.Runtime.InteropServices.DllImportAttribute; using IOSImport = GoogleARCoreInternal.DllImportNoop; #endif internal class FrameApi { private NativeSession m_NativeSession; public FrameApi(NativeSession nativeSession) { m_NativeSession = nativeSession; } public void Release(IntPtr frameHandle) { ExternApi.ArFrame_release(frameHandle); } public long GetTimestamp() { long timestamp = 0; ExternApi.ArFrame_getTimestamp( m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref timestamp); return timestamp; } public IntPtr AcquireCamera() { IntPtr cameraHandle = IntPtr.Zero; ExternApi.ArFrame_acquireCamera( m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref cameraHandle); return cameraHandle; } public CameraImageBytes AcquireCameraImageBytes() { IntPtr cameraImageHandle = IntPtr.Zero; ApiArStatus status = ExternApi.ArFrame_acquireCameraImage(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref cameraImageHandle); if (status != ApiArStatus.Success) { Debug.LogWarningFormat("Failed to acquire camera image with status {0}.", status); return new CameraImageBytes(IntPtr.Zero); } return new CameraImageBytes(cameraImageHandle); } public bool TryAcquirePointCloudHandle(out IntPtr pointCloudHandle) { pointCloudHandle = IntPtr.Zero; ApiArStatus status = ExternApi.ArFrame_acquirePointCloud(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref pointCloudHandle); if (status != ApiArStatus.Success) { Debug.LogWarningFormat("Failed to acquire point cloud with status {0}", status); return false; } return true; } public bool AcquireImageMetadata(ref IntPtr imageMetadataHandle) { var status = ExternApi.ArFrame_acquireImageMetadata(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ref imageMetadataHandle); if (status != ApiArStatus.Success) { Debug.LogErrorFormat( "Failed to aquire camera image metadata with status {0}", status); return false; } return true; } public LightEstimate GetLightEstimate() { IntPtr lightEstimateHandle = m_NativeSession.LightEstimateApi.Create(); ExternApi.ArFrame_getLightEstimate( m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, lightEstimateHandle); LightEstimateState state = m_NativeSession.LightEstimateApi.GetState(lightEstimateHandle); Color colorCorrection = m_NativeSession.LightEstimateApi.GetColorCorrection(lightEstimateHandle); m_NativeSession.LightEstimateApi.Destroy(lightEstimateHandle); return new LightEstimate(state, colorCorrection.a, new Color(colorCorrection.r, colorCorrection.g, colorCorrection.b, 1f)); } public void TransformDisplayUvCoords(ref ApiDisplayUvCoords uv) { ApiDisplayUvCoords uvOut = new ApiDisplayUvCoords(); ExternApi.ArFrame_transformDisplayUvCoords( m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ApiDisplayUvCoords.NumFloats, ref uv, ref uvOut); uv = uvOut; } public void TransformCoordinates2d(ref Vector2 uv, DisplayUvCoordinateType inputType, DisplayUvCoordinateType outputType) { Vector2 uvOut = new Vector2(uv.x, uv.y); ExternApi.ArFrame_transformCoordinates2d( m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, inputType.ToApiCoordinates2dType(), 1, ref uv, outputType.ToApiCoordinates2dType(), ref uvOut); uv = uvOut; } public void GetUpdatedTrackables(List<Trackable> trackables) { IntPtr listHandle = m_NativeSession.TrackableListApi.Create(); ExternApi.ArFrame_getUpdatedTrackables( m_NativeSession.SessionHandle, m_NativeSession.FrameHandle, ApiTrackableType.BaseTrackable, listHandle); trackables.Clear(); int count = m_NativeSession.TrackableListApi.GetCount(listHandle); for (int i = 0; i < count; i++) { IntPtr trackableHandle = m_NativeSession.TrackableListApi.AcquireItem(listHandle, i); // TODO:: Remove conditional when b/75291352 is fixed. ApiTrackableType trackableType = m_NativeSession.TrackableApi.GetType(trackableHandle); if ((int)trackableType == 0x41520105) { m_NativeSession.TrackableApi.Release(trackableHandle); continue; } Trackable trackable = m_NativeSession.TrackableFactory(trackableHandle); if (trackable != null) { trackables.Add(trackable); } else { m_NativeSession.TrackableApi.Release(trackableHandle); } } m_NativeSession.TrackableListApi.Destroy(listHandle); } private struct ExternApi { [DllImport(ApiConstants.ARCoreNativeApi)] public static extern void ArFrame_release(IntPtr frame); [DllImport(ApiConstants.ARCoreNativeApi)] public static extern void ArFrame_getTimestamp(IntPtr sessionHandle, IntPtr frame, ref long timestamp); #pragma warning disable 626 [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArFrame_acquireCamera( IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr cameraHandle); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern ApiArStatus ArFrame_acquireCameraImage( IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr imageHandle); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern ApiArStatus ArFrame_acquirePointCloud( IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr pointCloudHandle); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArFrame_transformDisplayUvCoords( IntPtr session, IntPtr frame, int numElements, ref ApiDisplayUvCoords uvsIn, ref ApiDisplayUvCoords uvsOut); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArFrame_transformCoordinates2d( IntPtr session, IntPtr frame, ApiCoordinates2dType inputType, int numVertices, ref Vector2 uvsIn, ApiCoordinates2dType outputType, ref Vector2 uvsOut); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArFrame_getUpdatedTrackables( IntPtr sessionHandle, IntPtr frameHandle, ApiTrackableType filterType, IntPtr outTrackableList); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArFrame_getLightEstimate( IntPtr sessionHandle, IntPtr frameHandle, IntPtr lightEstimateHandle); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern ApiArStatus ArFrame_acquireImageMetadata( IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr outMetadata); #pragma warning restore 626 } } }
// 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.ComponentModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Linq.Expressions.Compiler; using System.Reflection; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Runtime.CompilerServices { public partial class RuntimeOps { /// <summary> /// Quotes the provided expression tree. /// </summary> /// <param name="expression">The expression to quote.</param> /// <param name="hoistedLocals">The hoisted local state provided by the compiler.</param> /// <param name="locals">The actual hoisted local values.</param> /// <returns>The quoted expression.</returns> [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)] public static Expression Quote(Expression expression, object hoistedLocals, object[] locals) { Debug.Assert(hoistedLocals != null && locals != null); var quoter = new ExpressionQuoter((HoistedLocals)hoistedLocals, locals); return quoter.Visit(expression); } /// <summary> /// Combines two runtime variable lists and returns a new list. /// </summary> /// <param name="first">The first list.</param> /// <param name="second">The second list.</param> /// <param name="indexes">The index array indicating which list to get variables from.</param> /// <returns>The merged runtime variables.</returns> [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)] public static IRuntimeVariables MergeRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) { return new MergedRuntimeVariables(first, second, indexes); } // Modifies a quoted Expression instance by changing hoisted variables and // parameters into hoisted local references. The variable's StrongBox is // burned as a constant, and all hoisted variables/parameters are rewritten // as indexing expressions. // // The behavior of Quote is intended to be like C# and VB expression quoting private sealed class ExpressionQuoter : ExpressionVisitor { private readonly HoistedLocals _scope; private readonly object[] _locals; // A stack of variables that are defined in nested scopes. We search // this first when resolving a variable in case a nested scope shadows // one of our variable instances. private readonly Stack<HashSet<ParameterExpression>> _shadowedVars = new Stack<HashSet<ParameterExpression>>(); internal ExpressionQuoter(HoistedLocals scope, object[] locals) { _scope = scope; _locals = locals; } protected internal override Expression VisitLambda<T>(Expression<T> node) { if (node.Parameters.Count > 0) { _shadowedVars.Push(new HashSet<ParameterExpression>(node.Parameters)); } Expression b = Visit(node.Body); if (node.Parameters.Count > 0) { _shadowedVars.Pop(); } if (b == node.Body) { return node; } return Expression.Lambda<T>(b, node.Name, node.TailCall, node.Parameters); } protected internal override Expression VisitBlock(BlockExpression node) { if (node.Variables.Count > 0) { _shadowedVars.Push(new HashSet<ParameterExpression>(node.Variables)); } var b = ExpressionVisitorUtils.VisitBlockExpressions(this, node); if (node.Variables.Count > 0) { _shadowedVars.Pop(); } if (b == null) { return node; } return node.Rewrite(node.Variables, b); } protected override CatchBlock VisitCatchBlock(CatchBlock node) { if (node.Variable != null) { _shadowedVars.Push(new HashSet<ParameterExpression>{ node.Variable }); } Expression b = Visit(node.Body); Expression f = Visit(node.Filter); if (node.Variable != null) { _shadowedVars.Pop(); } if (b == node.Body && f == node.Filter) { return node; } return Expression.MakeCatchBlock(node.Test, node.Variable, b, f); } protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) { int count = node.Variables.Count; var boxes = new List<IStrongBox>(); var vars = new List<ParameterExpression>(); var indexes = new int[count]; for (int i = 0; i < count; i++) { IStrongBox box = GetBox(node.Variables[i]); if (box == null) { indexes[i] = vars.Count; vars.Add(node.Variables[i]); } else { indexes[i] = -1 - boxes.Count; boxes.Add(box); } } // No variables were rewritten. Just return the original node if (boxes.Count == 0) { return node; } var boxesConst = Expression.Constant(new RuntimeVariables(boxes.ToArray()), typeof(IRuntimeVariables)); // All of them were rewritten. Just return the array as a constant if (vars.Count == 0) { return boxesConst; } // Otherwise, we need to return an object that merges them return Expression.Call( RuntimeOps_MergeRuntimeVariables, Expression.RuntimeVariables(new TrueReadOnlyCollection<ParameterExpression>(vars.ToArray())), boxesConst, Expression.Constant(indexes) ); } protected internal override Expression VisitParameter(ParameterExpression node) { IStrongBox box = GetBox(node); if (box == null) { return node; } return Expression.Field(Expression.Constant(box), "Value"); } private IStrongBox GetBox(ParameterExpression variable) { // Skip variables that are shadowed by a nested scope/lambda foreach (HashSet<ParameterExpression> hidden in _shadowedVars) { if (hidden.Contains(variable)) { return null; } } HoistedLocals scope = _scope; object[] locals = _locals; while (true) { int hoistIndex; if (scope.Indexes.TryGetValue(variable, out hoistIndex)) { return (IStrongBox)locals[hoistIndex]; } scope = scope.Parent; if (scope == null) { break; } locals = HoistedLocals.GetParent(locals); } // Unbound variable: an error should've been thrown already // from VariableBinder throw ContractUtils.Unreachable; } } private sealed class RuntimeVariables : IRuntimeVariables { private readonly IStrongBox[] _boxes; internal RuntimeVariables(IStrongBox[] boxes) { _boxes = boxes; } int IRuntimeVariables.Count { get { return _boxes.Length; } } object IRuntimeVariables.this[int index] { get { return _boxes[index].Value; } set { _boxes[index].Value = value; } } } /// <summary> /// Provides a list of variables, supporting read/write of the values /// Exposed via RuntimeVariablesExpression /// </summary> private sealed class MergedRuntimeVariables : IRuntimeVariables { private readonly IRuntimeVariables _first; private readonly IRuntimeVariables _second; // For reach item, the index into the first or second list // Positive values mean the first array, negative means the second private readonly int[] _indexes; internal MergedRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) { _first = first; _second = second; _indexes = indexes; } public int Count { get { return _indexes.Length; } } public object this[int index] { get { index = _indexes[index]; return (index >= 0) ? _first[index] : _second[-1 - index]; } set { index = _indexes[index]; if (index >= 0) { _first[index] = value; } else { _second[-1 - index] = value; } } } } } }
namespace System.Workflow.ComponentModel { using System; using System.Collections; using System.Collections.Generic; [Flags] internal enum ItemListChangeAction { Add = 0x01, Remove = 0x2, Replace = Add | Remove } internal class ItemListChangeEventArgs<T> : EventArgs { private int index = 0; private ICollection<T> addedItems = null; private ICollection<T> removedItems = null; private object owner = null; private ItemListChangeAction action = ItemListChangeAction.Add; public ItemListChangeEventArgs(int index, ICollection<T> removedItems, ICollection<T> addedItems, object owner, ItemListChangeAction action) { this.index = index; this.removedItems = removedItems; this.addedItems = addedItems; this.action = action; this.owner = owner; } public ItemListChangeEventArgs(int index, T removedActivity, T addedActivity, object owner, ItemListChangeAction action) { this.index = index; if ((object)removedActivity != null) { this.removedItems = new List<T>(); ((List<T>)this.removedItems).Add(removedActivity); } if ((object)addedActivity != null) { this.addedItems = new List<T>(); ((List<T>)this.addedItems).Add(addedActivity); } this.action = action; this.owner = owner; } public IList<T> RemovedItems { get { return (this.removedItems != null) ? new List<T>(this.removedItems).AsReadOnly() : new List<T>().AsReadOnly(); } } public IList<T> AddedItems { get { return (this.addedItems != null) ? new List<T>(this.addedItems).AsReadOnly() : new List<T>().AsReadOnly(); } } public object Owner { get { return this.owner; } } public int Index { get { return this.index; } } public ItemListChangeAction Action { get { return this.action; } } } internal delegate void ItemListChangeEventHandler<T>(object sender, ItemListChangeEventArgs<T> e); internal class ItemList<T> : List<T>, IList<T>, IList { internal event ItemListChangeEventHandler<T> ListChanging; private object owner = null; internal ItemList(object owner) { this.owner = owner; } protected object Owner { get { return this.owner; } } bool IsFixedSize { get { return false; } } #region ItemList<T> Members public event ItemListChangeEventHandler<T> ListChanged; #endregion #region IList<T> Members void IList<T>.RemoveAt(int index) { if (index < 0 || index > base.Count) throw new ArgumentOutOfRangeException(); T item = base[index]; FireListChanging(new ItemListChangeEventArgs<T>(index, item, default(T), this.owner, ItemListChangeAction.Remove)); base.RemoveAt(index); FireListChanged(new ItemListChangeEventArgs<T>(index, item, default(T), this.owner, ItemListChangeAction.Remove)); } void IList<T>.Insert(int index, T item) { if (index < 0 || index > base.Count) throw new ArgumentOutOfRangeException(); if ((object)item == null) throw new ArgumentNullException("item"); FireListChanging(new ItemListChangeEventArgs<T>(index, default(T), item, this.owner, ItemListChangeAction.Add)); base.Insert(index, item); FireListChanged(new ItemListChangeEventArgs<T>(index, default(T), item, this.owner, ItemListChangeAction.Add)); } T IList<T>.this[int index] { get { return base[index]; } set { if ((object)value == null) throw new ArgumentNullException("item"); T oldItem = base[index]; FireListChanging(new ItemListChangeEventArgs<T>(index, oldItem, value, this.owner, ItemListChangeAction.Replace)); base[index] = value; FireListChanged(new ItemListChangeEventArgs<T>(index, oldItem, value, this.owner, ItemListChangeAction.Replace)); } } int IList<T>.IndexOf(T item) { return base.IndexOf(item); } #endregion #region ICollection<T> Members bool ICollection<T>.IsReadOnly { get { return false; } } bool ICollection<T>.Contains(T item) { return base.Contains(item); } bool ICollection<T>.Remove(T item) { if (!base.Contains(item)) return false; int index = base.IndexOf(item); if (index >= 0) { FireListChanging(new ItemListChangeEventArgs<T>(index, item, default(T), this.owner, ItemListChangeAction.Remove)); base.Remove(item); FireListChanged(new ItemListChangeEventArgs<T>(index, item, default(T), this.owner, ItemListChangeAction.Remove)); return true; } return false; } void ICollection<T>.Clear() { ICollection<T> children = this.GetRange(0, this.Count); FireListChanging(new ItemListChangeEventArgs<T>(-1, children, null, this.owner, ItemListChangeAction.Remove)); base.Clear(); FireListChanged(new ItemListChangeEventArgs<T>(-1, children, null, this.owner, ItemListChangeAction.Remove)); } void ICollection<T>.Add(T item) { if ((object)item == null) throw new ArgumentNullException("item"); FireListChanging(new ItemListChangeEventArgs<T>(base.Count, default(T), item, this.owner, ItemListChangeAction.Add)); base.Add(item); FireListChanged(new ItemListChangeEventArgs<T>(base.Count, default(T), item, this.owner, ItemListChangeAction.Add)); } int ICollection<T>.Count { get { return base.Count; } } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { base.CopyTo(array, arrayIndex); } #endregion #region IEnumerable<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { return base.GetEnumerator(); } #endregion public new void Add(T item) { ((IList<T>)this).Add(item); } public new void AddRange(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException("collection"); FireListChanging(new ItemListChangeEventArgs<T>(-1, null, new List<T>(collection), this.owner, ItemListChangeAction.Add)); base.AddRange(collection); FireListChanged(new ItemListChangeEventArgs<T>(base.Count, null, new List<T>(collection), this.owner, ItemListChangeAction.Add)); } public new void InsertRange(int index, IEnumerable<T> collection) { if (index < 0 || index > base.Count) throw new ArgumentOutOfRangeException(); if (collection == null) throw new ArgumentNullException("collection"); FireListChanging(new ItemListChangeEventArgs<T>(index, null, new List<T>(collection), this.owner, ItemListChangeAction.Add)); base.InsertRange(index, collection); FireListChanged(new ItemListChangeEventArgs<T>(index, null, new List<T>(collection), this.owner, ItemListChangeAction.Add)); } public new void Clear() { ((IList<T>)this).Clear(); } public new void Insert(int index, T item) { ((IList<T>)this).Insert(index, item); } public new bool Remove(T item) { return ((IList<T>)this).Remove(item); } public new void RemoveAt(int index) { ((IList<T>)this).RemoveAt(index); } public new T this[int index] { get { return ((IList<T>)this)[index]; } set { ((IList<T>)this)[index] = value; } } #region Helper methods protected virtual void FireListChanging(ItemListChangeEventArgs<T> eventArgs) { if (this.ListChanging != null) this.ListChanging(this, eventArgs); } protected virtual void FireListChanged(ItemListChangeEventArgs<T> eventArgs) { if (this.ListChanged != null) this.ListChanged(this, eventArgs); } #endregion #region IList Members int IList.Add(object value) { if (!(value is T)) throw new Exception(SR.GetString(SR.Error_InvalidListItem, this.GetType().GetGenericArguments()[0].FullName)); ((IList<T>)this).Add((T)value); return this.Count - 1; } void IList.Clear() { ((IList<T>)this).Clear(); } bool IList.Contains(object value) { if (!(value is T)) throw new Exception(SR.GetString(SR.Error_InvalidListItem, this.GetType().GetGenericArguments()[0].FullName)); return ((IList<T>)this).Contains((T)value); } int IList.IndexOf(object value) { if (!(value is T)) throw new Exception(SR.GetString(SR.Error_InvalidListItem, this.GetType().GetGenericArguments()[0].FullName)); return ((IList<T>)this).IndexOf((T)value); } void IList.Insert(int index, object value) { if (!(value is T)) throw new Exception(SR.GetString(SR.Error_InvalidListItem, this.GetType().GetGenericArguments()[0].FullName)); ((IList<T>)this).Insert(index, (T)value); } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return ((IList<T>)this).IsReadOnly; } } void IList.Remove(object value) { if (!(value is T)) throw new Exception(SR.GetString(SR.Error_InvalidListItem, this.GetType().GetGenericArguments()[0].FullName)); ((IList<T>)this).Remove((T)value); } object IList.this[int index] { get { return ((IList<T>)this)[index]; } set { if (!(value is T)) throw new Exception(SR.GetString(SR.Error_InvalidListItem, this.GetType().GetGenericArguments()[0].FullName)); ((IList<T>)this)[index] = (T)value; } } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { for (int loop = 0; loop < Count; loop++) array.SetValue(this[loop], loop + index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return base.GetEnumerator(); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Abstractions.TestingHelpers; using NSubstitute; using NUnit.Framework; using TSQLLint.Common; using TSQLLint.Core.Interfaces; using TSQLLint.Infrastructure.Configuration; using TSQLLint.Tests.Helpers; using static System.String; namespace TSQLLint.Tests.UnitTests.ConfigFile { [TestFixture] public class ConfigReaderTests { [Test] public void ConfigReaderInMemoryConfig() { // arrange var fileSystem = new MockFileSystem(); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(Empty); // load config from memory configReader.ListPlugins(); // assert Assert.AreEqual(RuleViolationSeverity.Error, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Error, configReader.GetRuleSeverity("semicolon-termination")); Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("fake-rule")); Assert.IsTrue(configReader.IsConfigLoaded); reporter.Received().Report("Did not find any plugins"); } [Test] public void ConfigReaderEmptyConfigFile() { // arrange var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>()); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); // assert Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("statement-semicolon-termination")); Assert.IsFalse(configReader.IsConfigLoaded); } [Test] public void ConfigReaderConfigFileDoesntExist() { // arrange var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>()); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(TestHelper.GetTestFilePath(@"c:\users\someone\.tsqllintrc")); // assert Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("statement-semicolon-termination")); Assert.IsFalse(configReader.IsConfigLoaded); } [Test] public void ConfigReaderLoadsConfigsFromUserProfile() { // arrange var configFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), @".tsqllintrc"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'rules': { 'select-star': 'warning', 'statement-semicolon-termination': 'warning' } }") } }); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(null); // assert Assert.AreEqual(RuleViolationSeverity.Warning, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Warning, configReader.GetRuleSeverity("statement-semicolon-termination")); Assert.IsTrue(configReader.IsConfigLoaded); } [Test] public void ConfigReaderLoadsConfigsFromLocal() { // arrange var localConfigFile = Path.Combine(TestContext.CurrentContext.TestDirectory, ".tsqllintrc"); var fileSystem = new MockFileSystem( new Dictionary<string, MockFileData> { { // should ignore config files in user profile when local config exists TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"), new MockFileData(@" { 'rules': { 'select-star': 'off', 'statement-semicolon-termination': 'warning' } }") }, { localConfigFile, new MockFileData(@" { 'rules': { 'select-star': 'warning', 'statement-semicolon-termination': 'warning' } }") } }, TestContext.CurrentContext.TestDirectory); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(null); // assert Assert.AreEqual(RuleViolationSeverity.Warning, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Warning, configReader.GetRuleSeverity("statement-semicolon-termination")); Assert.IsTrue(configReader.IsConfigLoaded); } [Test] public void ConfigReaderLoadsConfigsEnvironmentVariable() { // arrange var testConfigFile = TestHelper.GetTestFilePath(@"c:\foo\.tsqllintrc"); var fileSystem = new MockFileSystem( new Dictionary<string, MockFileData> { { // should ignore config files in user profile when local config exists testConfigFile, new MockFileData(@" { 'rules': { 'select-star': 'off', 'statement-semicolon-termination': 'warning' } }") }, { // should ignore config files in user profile when local config exists TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"), new MockFileData(@" { 'rules': { 'select-star': 'error', 'statement-semicolon-termination': 'error' } }") }, }, TestContext.CurrentContext.TestDirectory); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); environmentWrapper.GetEnvironmentVariable("tsqllintrc").Returns(testConfigFile); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(null); // assert Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Warning, configReader.GetRuleSeverity("statement-semicolon-termination")); Assert.IsTrue(configReader.IsConfigLoaded); } [Test] public void ConfigReaderGetRuleSeverity() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'rules': { 'select-star': 'error', 'statement-semicolon-termination': 'warning' } }") } }); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert Assert.AreEqual(RuleViolationSeverity.Error, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Warning, configReader.GetRuleSeverity("statement-semicolon-termination")); Assert.IsTrue(configReader.IsConfigLoaded); } [Test] public void ConfigReaderGetParserFromValidInt() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"); var mockFileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'compatability-level': 120 }") } }); var mockReporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(mockReporter, mockFileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert Assert.IsTrue(configReader.IsConfigLoaded); Assert.AreEqual(120, configReader.CompatabilityLevel); } [Test] public void ConfigReaderGetParserFromValidString() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"); var mockFileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'compatability-level': '130' }") } }); var mockReporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(mockReporter, mockFileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert Assert.IsTrue(configReader.IsConfigLoaded); Assert.AreEqual(130, configReader.CompatabilityLevel); } [Test] public void ConfigReaderGetParserFromInValidInt() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"); var mockFileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'compatability-level': 10 }") } }); var mockReporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(mockReporter, mockFileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert Assert.IsTrue(configReader.IsConfigLoaded); Assert.AreEqual(120, configReader.CompatabilityLevel); } [Test] public void ConfigReaderGetParserFromInValidString() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"); var mockFileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'compatability-level': 'foo' }") } }); var mockReporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(mockReporter, mockFileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert Assert.IsTrue(configReader.IsConfigLoaded); Assert.AreEqual(120, configReader.CompatabilityLevel); } [Test] public void ConfigReaderGetParserNotSet() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"C:\Users\User\.tsqllintrc"); var mockFileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { }") } }); var mockReporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(mockReporter, mockFileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert Assert.IsTrue(configReader.IsConfigLoaded); Assert.AreEqual(120, configReader.CompatabilityLevel); } [Test] public void ConfigReaderNoRulesNoThrow() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"c:\users\someone\.tsqllintrc-missing-rules"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@"{}") } }); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // assert Assert.DoesNotThrow(() => { // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); Assert.IsNotNull(configReader); Assert.IsFalse(configReader.IsConfigLoaded); }); } [Test] public void ConfigReaderReadBadRuleName() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"c:\users\someone\.tsqllintrc"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'rules': { 'select-star': 'error', 'statement-semicolon-termination': 'warning' } }") } }); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); // assert Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("foo"), "Rules that dont have a validator should be set to off"); Assert.IsFalse(configReader.IsConfigLoaded); } [Test] public void ConfigReaderConfigReadBadRuleSeverity() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"c:\users\someone\.tsqllintrc-bad-severity"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@" { 'rules': { 'select-star': 'foo' } }") } }); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert Assert.AreEqual(RuleViolationSeverity.Off, configReader.GetRuleSeverity("select-star"), "Rules that dont have a valid severity should be set to off"); Assert.IsTrue(configReader.IsConfigLoaded); } [Test] public void ConfigReaderConfigReadInvalidJson() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"c:\users\someone\.tsqllintrc-bad-json"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(@"{") } }); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); // assert reporter.Received().Report("Config file is not valid Json."); Assert.IsFalse(configReader.IsConfigLoaded); } [Test] public void ConfigReaderSetupPlugins() { // arrange var configFilePath = TestHelper.GetTestFilePath(@"c:\users\someone\.tsqllintrc"); var pluginPath = TestHelper.GetTestFilePath(@"c:\users\someone\my-plugins\foo.dll"); var plugOnePath = TestHelper.GetTestFilePath(@"c:/users/someone/my-plugins/my-first-plugin.dll"); var plugTwoPath = TestHelper.GetTestFilePath(@"c:/users/someone/my-plugins/my-second-plugin.dll"); var fileContent = $@"{{ ""rules"": {{ ""select-star"": ""error"", ""statement-semicolon-termination"": ""warning"" }}, ""plugins"": {{ ""my-first-plugin"": ""{plugOnePath}"", ""my-second-plugin"": ""{plugTwoPath}"" }} }}"; var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { configFilePath, new MockFileData(fileContent) }, { pluginPath, new MockFileData(Empty) } }); var reporter = Substitute.For<IReporter>(); var environmentWrapper = Substitute.For<IEnvironmentWrapper>(); // act var configReader = new ConfigReader(reporter, fileSystem, environmentWrapper); configReader.LoadConfig(configFilePath); var plugins = configReader.GetPlugins(); configReader.ListPlugins(); // assert Assert.AreEqual(RuleViolationSeverity.Error, configReader.GetRuleSeverity("select-star")); Assert.AreEqual(RuleViolationSeverity.Warning, configReader.GetRuleSeverity("statement-semicolon-termination")); Assert.IsTrue(configReader.IsConfigLoaded); Assert.AreEqual(true, plugins.ContainsKey("my-first-plugin")); Assert.AreEqual(true, plugins.ContainsKey("my-second-plugin")); Assert.AreEqual(TestHelper.GetTestFilePath("c:/users/someone/my-plugins/my-first-plugin.dll"), plugins["my-first-plugin"]); Assert.AreEqual(TestHelper.GetTestFilePath("c:/users/someone/my-plugins/my-second-plugin.dll"), plugins["my-second-plugin"]); reporter.Received().Report("Found the following plugins:"); reporter.Received().Report($@"Plugin Name 'my-first-plugin' loaded from path '{plugOnePath}'"); reporter.Received().Report($@"Plugin Name 'my-second-plugin' loaded from path '{plugTwoPath}'"); } } }
using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Nap.Configuration; using Nap.Exceptions; using Nap.Plugins.Base; using Nap.Proxies; using Nap.Serializers.Base; using System.Net.Http.Headers; namespace Nap { /// <summary> /// An easily configurable request. /// </summary> public partial class NapRequest : INapRequest { private readonly IReadOnlyCollection<IPlugin> _plugins; private readonly INapConfig _config; private readonly string _url; private readonly HttpMethod _method; private readonly Dictionary<string, string> _queryParameters = new Dictionary<string, string>(); private readonly Dictionary<string, string> _headers = new Dictionary<string, string>(); private readonly List<Tuple<Uri, Cookie>> _cookies = new List<Tuple<Uri, Cookie>>(); private readonly Dictionary<EventCode, List<Event>> _events; private string _content; private bool _doNot; /// <summary> /// Initializes a new instance of the <see cref="NapRequest" /> class. /// </summary> /// <param name="plugins">The set of plugins to apply during execution of this request.</param> /// <param name="initialConfiguration">The initial configuration for the request.</param> /// <param name="url">The URL to perform the request against. Can be a full URL or a partial.</param> /// <param name="method">The method to use in the request.</param> internal NapRequest(IReadOnlyCollection<IPlugin> plugins, INapConfig initialConfiguration, string url, HttpMethod method) { // Set up initial configuration parameters. _plugins = plugins; _config = initialConfiguration; _events = new Dictionary<EventCode, List<Event>>(); foreach (var header in _config.Headers) _headers.Add(header.Key, header.Value); foreach (var queryParameter in _config.QueryParameters) _queryParameters.Add(queryParameter.Key, queryParameter.Value); if (_config.Advanced.Proxy.Address != null) Advanced.UseProxy(_config.Advanced.Proxy.Address); if (!string.IsNullOrEmpty(_config.Advanced.Authentication.Username) && !string.IsNullOrEmpty(_config.Advanced.Authentication.Password)) Advanced.Authentication.Basic(_config.Advanced.Authentication.Username, _config.Advanced.Authentication.Password); ClientCreator = _config.Advanced.ClientCreator; _url = url; _method = method; } #region Properties /// <summary> /// Gets the configuration that this request was seeded with. /// </summary> public INapConfig Configuration => _config; /// <summary> /// Gets the collection of plugins that are enabled for this request. /// </summary> public IReadOnlyCollection<IPlugin> Plugins => _plugins; /// <summary> /// Gets the set of cookies that has been configured for this request. /// Required for configuration of the request with a custom <see cref="HttpClient"/>. /// </summary> public IReadOnlyList<Tuple<Uri, Cookie>> Cookies => _cookies; /// <summary> /// Gets the set of headers that have been configured for this request. /// </summary> public IReadOnlyDictionary<string, string> Headers => _headers; /// <summary> /// Gets the set of query parameters that have been configured for this request. /// </summary> public IReadOnlyDictionary<string, string> QueryParamters => _queryParameters; /// <summary> /// Gets the method this request will be sent using. /// </summary> public HttpMethod Method => _method; /// <summary> /// Gets the content of this request, if any. /// </summary> public string Content => _content; /// <summary> /// Gets the URL of the request. /// </summary> public string Url => _url; #endregion #region Include/Fill /// <summary> /// Gets a set of methods to perform some removal of data from the request. /// </summary> public INapRemovableRequestComponent DoNot { get { _doNot = true; return this; } } /// <summary> /// Gets the advanced collection of methods for <see cref="INapRequest"/> configuration. /// </summary> public IAdvancedNapRequestComponent Advanced { get { return this; } } /// <summary> /// Includes the query parameter in the value for the URL. /// </summary> /// <param name="key">The key for the query parameter to include.</param> /// <param name="value">The value of the query parameter to include.</param> /// <returns>The <see cref="INapRequest"/> object.</returns> public INapRequest IncludeQueryParameter(string key, string value) { _queryParameters.Add(key, value); return this; } /// <summary> /// Includes some content in the body, serialized according to <see cref="INapSerializer"/>s. /// </summary> /// <param name="body">The object to serialize into the body.</param> /// <returns>The <see cref="INapRequest"/> object.</returns> public INapRequest IncludeBody(object body) { try { _content = _config.Serializers.AsDictionary()[_config.Serialization].Serialize(body); } catch (Exception ex) { throw new NapSerializationException($"Serialization failed for data:\n {body}", ex); } return this; } /// <summary> /// Includes a header in the request. /// </summary> /// <param name="headerName">Name of the header to include.</param> /// <param name="value">The value of the header to send.</param> /// <returns>The <see cref="INapRequest"/> object.</returns> public INapRequest IncludeHeader(string headerName, string value) { _headers.Add(headerName, value); return this; } /// <summary> /// Includes a cookie in the request. /// </summary> /// <param name="uri">The URL the cookie corresponds to.</param> /// <param name="cookieName">The name of the cookie to include.</param> /// <param name="value">The value of the cookie to include.</param> /// <returns>The <see cref="INapRequest"/> object.</returns> public INapRequest IncludeCookie(string uri, string cookieName, string value) { var asUri = new Uri(uri); _cookies.Add(new Tuple<Uri, Cookie>(asUri, new Cookie(cookieName, value, asUri.AbsolutePath, asUri.Host))); return this; } /// <summary> /// Fills the response object with metadata using special keys, such as "StatusCode". /// If used after <see cref="DoNot"/>, instead removes the fill metadata flag. /// </summary> /// <returns>The <see cref="INapRequest"/> object.</returns> public INapRequest FillMetadata() { _config.FillMetadata = _doNot == false; _doNot = false; return this; } #endregion #region Execution /// <summary> /// Executes the request asynchronously. /// </summary> /// <returns>A task, that when run returns the body content.</returns> public async Task<string> ExecuteAsync() { var napPluginResult = _plugins.Aggregate<IPlugin, string>(null, (current, plugin) => current ?? plugin.Execute<string>(this) as string); if (napPluginResult != null) return napPluginResult; return (await RunRequestAsync()).Body; } /// <summary> /// Executes the request asynchronously. /// </summary> /// <typeparam name="T">The type to deserialize the object to.</typeparam> /// <returns> /// A task, that when run returns the body content deserialized to the object <typeparamref name="T"/>, /// using the serializer matching <see cref="INapConfig.Serializers"/>. /// </returns> public async Task<T> ExecuteAsync<T>() where T : class, new() { var napPluginResult = _plugins.Aggregate<IPlugin, T>(null, (current, plugin) => current ?? plugin.Execute<T>(this) as T); if (napPluginResult != null) return napPluginResult; var response = await RunRequestAsync(); var toReturn = GetSerializer(response.ContentHeaders.ContentType.MediaType).Deserialize<T>(response.Body) ?? new T(); if (_config.FillMetadata) { var property = typeof(T).GetRuntimeProperty("StatusCode"); property?.SetValue(toReturn, Convert.ChangeType(response.StatusCode, property.PropertyType)); HydrateCookieProperties(response, toReturn); HydrateHeaderProperties(response, toReturn); // TODO: Populate items with defaults (headers) } return toReturn; } /// <summary> /// Execute the request and retrieve a pre-built response type. /// The pre-built <see cref="NapResponse"/> contains many commonly utilized properties. /// </summary> /// <returns>A <see cref="Task"/> that when awaited produces a <see cref="NapResponse"/> that equates to the server's response.</returns> public async Task<NapResponse> ExecuteRawAsync() { var napPluginResult = _plugins.Aggregate<IPlugin, NapResponse>(null, (current, plugin) => current ?? plugin.Execute<NapResponse>(this) as NapResponse); if (napPluginResult != null) return napPluginResult; return await RunRequestAsync(); } /// <summary> /// Execute the request and retrieve a pre-built response type. /// The pre-built <see cref="NapResponse"/> contains many commonly utilized properties. /// </summary> /// <returns>A <see cref="NapResponse"/> that equates to the server's response.</returns> public NapResponse ExecuteRaw() { return Task.Run(ExecuteRawAsync).Result; } /// <summary> /// Runs the request using a threadpool thread, and blocks the current thread until completion. /// </summary> /// <returns>The response body content.</returns> public string Execute() { return Task.Run(ExecuteAsync).Result; } /// <summary> /// Runs the request using a threadpool thread, and blocks the current thread until completion. /// </summary> /// <typeparam name="T">The type to deserialize the object to.</typeparam> /// <returns> /// The body content deserialized to the object <typeparamref name="T"/>, /// using the serializer matching <see cref="INapConfig.Serializers"/>. /// </returns> public T Execute<T>() where T : class, new() { return Task.Run(ExecuteAsync<T>).Result; } #endregion #region Helpers /// <summary> /// Runs the request. /// </summary> /// <returns>The content and response.</returns> private async Task<NapResponse> RunRequestAsync(bool skipPreparePlugins = false) { // If plugins have not been run, run those and then run the request. if (!skipPreparePlugins) return await _plugins.Aggregate(this, (request, plugin) => plugin.Prepare(request)).RunRequestAsync(true); var excludedHeaders = new[] { "content-type" }; using (var client = ClientCreator != null ? ClientCreator(this) : CreateClient()) { var content = new StringContent(_content ?? string.Empty); var url = CreateUrl(); var allowedDefaultHeaders = _headers.Where(h => !excludedHeaders.Any(eh => eh.Equals(h.Key, StringComparison.OrdinalIgnoreCase))); foreach (var header in allowedDefaultHeaders) { client.DefaultRequestHeaders.Add(header.Key, header.Value); } var contentType = _headers.FirstOrDefault(kv => kv.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase)); if (contentType.Value != null) { content.Headers.ContentType.MediaType = contentType.Value; } else content.Headers.ContentType.MediaType = _config.Serializers.AsDictionary()[_config.Serialization].ContentType; HttpResponseMessage response = null; if (_method == HttpMethod.Get) response = await client.GetAsync(new Uri(url)); if (_method == HttpMethod.Post) response = await client.PostAsync(new Uri(url), content); if (_method == HttpMethod.Put) response = await client.PutAsync(new Uri(url), content); if (_method == HttpMethod.Delete) response = await client.DeleteAsync(new Uri(url)); if (response == null) return null; var bytes = await response.Content.ReadAsByteArrayAsync(); var encoding = System.Text.Encoding.UTF8; try { encoding = System.Text.Encoding.GetEncoding(response.Content.Headers.ContentEncoding.First()); } catch { } var responseContent = encoding.GetString(bytes, 0, bytes.Length); return _plugins.Aggregate(new NapResponse(this, response, responseContent), (r, plugin) => plugin.Process(r)); } } /// <summary> /// Creates the HttpClient for usage. /// </summary> /// <returns>The newly created and configured <see cref="HttpClient"/>.</returns> private HttpClient CreateClient() { var handler = new HttpClientHandler(); if (_config.Advanced.Proxy?.Address != null) { handler.Proxy = new NapWebProxy(_config.Advanced.Proxy.Address); handler.UseProxy = true; } foreach (var cookie in _cookies) { handler.CookieContainer.Add(cookie.Item1, cookie.Item2); } var client = new HttpClient(handler); return client; } /// <summary> /// Creates the URL from an (optional) <see cref="INapConfig.BaseUrl"/>, URL and query parameters. /// </summary> /// <returns>The fully formed URL.</returns> private string CreateUrl() { var urlTemp = _url; if (!_url.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(_config.BaseUrl)) urlTemp = new Uri(new Uri(_config.BaseUrl), urlTemp).ToString(); if (_queryParameters.Any()) { urlTemp = _url.Contains("?") ? (_url.EndsWith("?", StringComparison.OrdinalIgnoreCase) ? _url : _url + "&") : _url + "?"; urlTemp += string.Join("&", _queryParameters.Select(x => string.Format("{0}={1}", x.Key, WebUtility.UrlEncode(x.Value)))); } return urlTemp; } /// <summary> /// Gets the serializer for a given content type. /// </summary> /// <param name="contentType">Type of the content (eg. application/json).</param> /// <returns>The serializer matching the content type.</returns> private INapSerializer GetSerializer(string contentType) { INapSerializer serializer; var serializers = _config.Serializers.AsDictionary(); if (!serializers.TryGetValue(contentType, out serializer)) { var getSubType = new Func<string, string>(type => type.Substring(type.IndexOf("/"))); var subType = getSubType(contentType); serializer = serializers.FirstOrDefault(f => getSubType(f.Key) == subType).Value; if (serializer == null) throw new NapSerializationException($"No serializer was found for content type {contentType}"); } return serializer; } private static T HydrateHeaderProperties<T>(NapResponse response, T toReturn) where T : class, new() { PropertyInfo property = typeof(T).GetRuntimeProperty("Headers"); // Types of header properties set: // Array-type string // Dictionary-type <string, string> // Specific named string prop // Specific named Convert.ChangeType prop if ((property?.PropertyType?.IsConstructedGenericType ?? false) || (property?.PropertyType?.IsArray ?? false)) { Type headerType; // If the property 'Headers' exists and is generic type, let's find the generic parameter and set it to an array if (property.PropertyType.IsConstructedGenericType) { var isDictionaryType = property.PropertyType.GenericTypeArguments.Count() > 1; headerType = property.PropertyType.GenericTypeArguments.First(); if ((headerType.IsConstructedGenericType && headerType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) || isDictionaryType) { property.SetValue(toReturn, response.Headers.ToDictionary(c => c.Key, c => c.Value)); } else if (headerType == typeof(string)) property.SetValue(toReturn, response.Headers.Select(c => $"{c.Key}: {c.Value}").ToArray()); } else { headerType = property.PropertyType.GetElementType(); if (headerType == typeof(string)) property.SetValue(toReturn, response.Cookies.Select(c => $"{c.Name}: {c.Value}").ToArray()); } } else if (property != null) { // TODO: Log } // Set individual properties foreach (var h in response.Headers) { var p = typeof(T).GetRuntimeProperty(h.Key.Replace("-", string.Empty)); if (p != null) { if (p.PropertyType == typeof(string)) p.SetValue(toReturn, h.Value); else { try { p.SetValue(toReturn, Convert.ChangeType(h.Value, p.PropertyType)); } catch (InvalidCastException e) { // TODO: Log } } } } return toReturn; } private static T HydrateCookieProperties<T>(NapResponse response, T toReturn) where T : class, new() { PropertyInfo property = typeof(T).GetRuntimeProperty("Cookies"); // Types of cookie properties set: // Array-type NapCookie // Array-type Cookie // Dictionary-type <string, string> // Array-type string // Specific named NapCookie prop // Specific named Cookie prop // Specific named string prop // Specific named Convert.ChangeType prop if ((property?.PropertyType?.IsConstructedGenericType ?? false) || (property?.PropertyType?.IsArray ?? false)) { Type cookieType; // If the property 'Cookies' exists and is generic type, let's find the generic parameter and set it to an array if (property.PropertyType.IsConstructedGenericType) { var isDictionaryType = property.PropertyType.GenericTypeArguments.Count() > 1; cookieType = property.PropertyType.GenericTypeArguments.First(); if ((cookieType.IsConstructedGenericType && cookieType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) || isDictionaryType) { property.SetValue(toReturn, response.Cookies.ToDictionary(c => c.Name, c => c.Value)); } else if (cookieType == typeof(NapCookie)) property.SetValue(toReturn, response.Cookies.ToArray()); else if (cookieType == typeof(Cookie)) property.SetValue(toReturn, response.Cookies.Select(c => new Cookie(c.Name, c.Value, c.Metadata.Path, c.Metadata.Domain)).ToArray()); else if (cookieType == typeof(string)) property.SetValue(toReturn, response.Cookies.Select(c => $"{c.Name}: {c.Value}").ToArray()); } else { cookieType = property.PropertyType.GetElementType(); if (cookieType == typeof(NapCookie)) property.SetValue(toReturn, response.Cookies.ToArray()); else if (cookieType == typeof(Cookie)) property.SetValue(toReturn, response.Cookies.Select(c => new Cookie(c.Name, c.Value, c.Metadata.Path, c.Metadata.Domain)).ToArray()); else if (cookieType == typeof(string)) property.SetValue(toReturn, response.Cookies.Select(c => $"{c.Name}: {c.Value}").ToArray()); } } else if (property != null) { // TODO: Log } // Set individual properties foreach (var c in response.Cookies) { var p = typeof(T).GetRuntimeProperty(c.Name.Replace("-", string.Empty)); if (p != null) { if (p.PropertyType == typeof(NapCookie)) p.SetValue(toReturn, c); else if (p.PropertyType == typeof(Cookie)) p.SetValue(toReturn, new Cookie(c.Name, c.Value, c.Metadata.Path, c.Metadata.Domain)); else if (p.PropertyType == typeof(string)) p.SetValue(toReturn, c.Value); else { try { p.SetValue(toReturn, Convert.ChangeType(c.Value, p.PropertyType)); } catch (InvalidCastException e) { // TODO: Log } } } } return toReturn; } private void RunBooleanPluginMethod(Func<IPlugin, bool> pluginMethod, string errorMessage) { try { if (!_plugins.Aggregate(true, (current, plugin) => current && pluginMethod.Invoke(plugin))) throw new NapPluginException(errorMessage); } catch (Exception e) { throw new NapPluginException($"{errorMessage} See inner exception for details.", e); // TODO: Make specific exception } } #endregion /// <summary> /// A child private class to house response and content information. /// </summary> private sealed class InternalResponse { /// <summary> /// Gets or sets the response. /// </summary> public HttpResponseMessage Response { get; set; } /// <summary> /// Gets or sets the content from the response body. /// </summary> public string Content { get; set; } } } /// <summary> /// A class that describes a specific type of object that can be marked 'complete'. /// </summary> /// <typeparam name="T"></typeparam> public class Finalizable<T> { /// <summary> /// Gets the state of the finalizable item - true if the item should not continue down the pipeline, false. /// </summary> public bool IsFinal { get; } /// <summary> /// The item which is being processed by some pipeline. /// </summary> public T Item { get; set; } /// <summary> /// The default constructor for a Finalizable type /// </summary> /// <param name="item"></param> /// <param name="isFinal"></param> public Finalizable(T item, bool isFinal) { Item = item; IsFinal = isFinal; } /// <summary> /// Create a new <see cref="Finalizable{T}"/> type with a status of final marked. /// </summary> /// <param name="item">The item to wrap in a finalizable state.</param> /// <returns>The new item that was created.</returns> public static Finalizable<T> Final(T item) => new Finalizable<T>(item, true); /// <summary> /// Create a new <see cref="Finalizable{T}"/> type with a status of continuing marked. /// </summary> /// <param name="item">The item to wrap in a finalizable state.</param> /// <returns>The new item that was created.</returns> public static Finalizable<T> Continuing(T item) => new Finalizable<T>(item, false); } /// <summary> /// An event that occurs during NapRequest pipline. /// </summary> /// <param name="napRequest">The request that is causing the event.</param> /// <returns>A new modified <see cref="NapRequest"/> to continue.</returns> public delegate INapRequest Event(INapRequest napRequest); /// <summary> /// Event codes for events that can happen to a response. /// </summary> public enum EventCode { /// <summary> /// An event that is executed before a the configuration is applied to the request. /// </summary> BeforeConfigurationApplied = 0x01, /// <summary> /// An event that is executed immediately following configuration application to a request. /// </summary> AfterConfigurationApplied = 0x02, /// <summary> /// An event that is executed immediately before a request is sent off. /// </summary> BeforeRequestExecution = 0x04, /// <summary> /// An event that is executed immediately after a request is sent off (after it returns, successfully or not). /// </summary> AfterRequestExecution = 0x08, /// <summary> /// An event that is executed immediately before respone deserialization is slated to happen. Will not occur if deserialization is not set to occur. /// </summary> BeforeResponseDeserialization = 0x10, /// <summary> /// An event that is executed immediately after response deserialization happens. Will not occur if no deserialization occurred. /// </summary> AfterResponseDeserialization = 0x20, /// <summary> /// An event that is executed immediately prior to a request being serialized by any serializer. /// </summary> BeforeRequestSerialization = 0x40, /// <summary> /// An event that is executed immediately prior to a request being serialized by any serializer. /// </summary> AfterRequestSerialization = 0x80, /// <summary> /// An event that is executed immediately before creating a nap request. /// </summary> CreatingNapRequest = 0x100, /// <summary> /// An event that is executed before authentication is set. /// </summary> SetAuthentication = 0x200, /// <summary> /// A meta-event describing the collection of all events. /// </summary> All = 0x3FF } }
// 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.Configuration.Internal; using System.IO; using System.Runtime.Versioning; namespace System.Configuration { // An instance of the Configuration class represents a single level // in the configuration hierarchy. Its contents can be edited and // saved to disk. // // It is not thread safe for writing. public sealed class Configuration { private readonly MgmtConfigurationRecord _configRecord; private readonly object[] _hostInitConfigurationParams; private readonly Type _typeConfigHost; private Func<string, string> _assemblyStringTransformer; private ContextInformation _evalContext; private ConfigurationLocationCollection _locations; private ConfigurationSectionGroup _rootSectionGroup; private Stack _sectionsStack; private Func<string, string> _typeStringTransformer; internal Configuration(string locationSubPath, Type typeConfigHost, params object[] hostInitConfigurationParams) { _typeConfigHost = typeConfigHost; _hostInitConfigurationParams = hostInitConfigurationParams; IInternalConfigHost configHost = (IInternalConfigHost)TypeUtil.CreateInstance(typeConfigHost); // Wrap the host with the UpdateConfigHost to support SaveAs. UpdateConfigHost updateConfigHost = new UpdateConfigHost(configHost); // Now wrap in ImplicitMachineConfigHost so we can stub in a simple machine.config if needed. IInternalConfigHost implicitMachineConfigHost = new ImplicitMachineConfigHost(updateConfigHost); InternalConfigRoot configRoot = new InternalConfigRoot(this, updateConfigHost); ((IInternalConfigRoot)configRoot).Init(implicitMachineConfigHost, isDesignTime: true); // Set the configuration paths for this Configuration. // // We do this in a separate step so that the WebConfigurationHost // can use this object's _configRoot to get the <sites> section, // which is used in it's MapPath implementation. string configPath, locationConfigPath; implicitMachineConfigHost.InitForConfiguration( ref locationSubPath, out configPath, out locationConfigPath, configRoot, hostInitConfigurationParams); if (!string.IsNullOrEmpty(locationSubPath) && !implicitMachineConfigHost.SupportsLocation) throw ExceptionUtil.UnexpectedError("Configuration::ctor"); if (string.IsNullOrEmpty(locationSubPath) != string.IsNullOrEmpty(locationConfigPath)) throw ExceptionUtil.UnexpectedError("Configuration::ctor"); // Get the configuration record for this config file. _configRecord = (MgmtConfigurationRecord)configRoot.GetConfigRecord(configPath); // Create another MgmtConfigurationRecord for the location that is a child of the above record. // Note that this does not match the resolution hiearchy that is used at runtime. if (!string.IsNullOrEmpty(locationSubPath)) { _configRecord = MgmtConfigurationRecord.Create( configRoot, _configRecord, locationConfigPath, locationSubPath); } // Throw if the config record we created contains global errors. _configRecord.ThrowIfInitErrors(); } public AppSettingsSection AppSettings => (AppSettingsSection)GetSection("appSettings"); public ConnectionStringsSection ConnectionStrings => (ConnectionStringsSection)GetSection("connectionStrings"); public string FilePath => _configRecord.ConfigurationFilePath; public bool HasFile => _configRecord.HasStream; public ConfigurationLocationCollection Locations => _locations ?? (_locations = _configRecord.GetLocationCollection(this)); public ContextInformation EvaluationContext => _evalContext ?? (_evalContext = new ContextInformation(_configRecord)); public ConfigurationSectionGroup RootSectionGroup { get { if (_rootSectionGroup == null) { _rootSectionGroup = new ConfigurationSectionGroup(); _rootSectionGroup.RootAttachToConfigurationRecord(_configRecord); } return _rootSectionGroup; } } public ConfigurationSectionCollection Sections => RootSectionGroup.Sections; public ConfigurationSectionGroupCollection SectionGroups => RootSectionGroup.SectionGroups; // Is the namespace declared in the file or not? // // ie. xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0" // (currently this is the only one we allow) public bool NamespaceDeclared { get { return _configRecord.NamespacePresent; } set { _configRecord.NamespacePresent = value; } } public Func<string, string> TypeStringTransformer { get { return _typeStringTransformer; } set { if (_typeStringTransformer != value) { TypeStringTransformerIsSet = value != null; _typeStringTransformer = value; } } } public Func<string, string> AssemblyStringTransformer { get { return _assemblyStringTransformer; } set { if (_assemblyStringTransformer != value) { AssemblyStringTransformerIsSet = value != null; _assemblyStringTransformer = value; } } } public FrameworkName TargetFramework { get; set; } = null; internal bool TypeStringTransformerIsSet { get; private set; } internal bool AssemblyStringTransformerIsSet { get; private set; } internal Stack SectionsStack => _sectionsStack ?? (_sectionsStack = new Stack()); // Create a new instance of Configuration for the locationSubPath, // with the initialization parameters that were used to create this configuration. internal Configuration OpenLocationConfiguration(string locationSubPath) { return new Configuration(locationSubPath, _typeConfigHost, _hostInitConfigurationParams); } // public methods public ConfigurationSection GetSection(string sectionName) { ConfigurationSection section = (ConfigurationSection)_configRecord.GetSection(sectionName); return section; } public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName) { ConfigurationSectionGroup sectionGroup = _configRecord.GetSectionGroup(sectionGroupName); return sectionGroup; } public void Save() { SaveAsImpl(null, ConfigurationSaveMode.Modified, false); } public void Save(ConfigurationSaveMode saveMode) { SaveAsImpl(null, saveMode, false); } public void Save(ConfigurationSaveMode saveMode, bool forceSaveAll) { SaveAsImpl(null, saveMode, forceSaveAll); } public void SaveAs(string filename) { SaveAs(filename, ConfigurationSaveMode.Modified, false); } public void SaveAs(string filename, ConfigurationSaveMode saveMode) { SaveAs(filename, saveMode, false); } public void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) { if (string.IsNullOrEmpty(filename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(filename)); SaveAsImpl(filename, saveMode, forceSaveAll); } private void SaveAsImpl(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) { filename = string.IsNullOrEmpty(filename) ? null : Path.GetFullPath(filename); if (forceSaveAll) ForceGroupsRecursive(RootSectionGroup); _configRecord.SaveAs(filename, saveMode, forceSaveAll); } // Force all sections and section groups to be instantiated. private void ForceGroupsRecursive(ConfigurationSectionGroup group) { foreach (ConfigurationSection configSection in group.Sections) { // Force the section to be read into the cache _ = group.Sections[configSection.SectionInformation.Name]; } foreach (ConfigurationSectionGroup sectionGroup in group.SectionGroups) ForceGroupsRecursive(group.SectionGroups[sectionGroup.Name]); } } }
/* * 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 { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Affinity; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Log; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Resource; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// This class defines a factory for the main Ignite API. /// <p/> /// Use <see cref="Start()"/> method to start Ignite with default configuration. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public static class Ignition { /** */ private static readonly object SyncRoot = new object(); /** GC warning flag. */ private static int _gcWarn; /** */ private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>(); /** Current DLL name. */ private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); /** Startup info. */ [ThreadStatic] private static Startup _startup; /** Client mode flag. */ [ThreadStatic] private static bool _clientMode; /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Ignition() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } /// <summary> /// Gets or sets a value indicating whether Ignite should be started in client mode. /// Client nodes cannot hold data in caches. /// </summary> public static bool ClientMode { get { return _clientMode; } set { _clientMode = value; } } /// <summary> /// Starts Ignite with default configuration. By default this method will /// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c> /// configuration file. If such file is not found, then all system defaults will be used. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start() { return Start(new IgniteConfiguration()); } /// <summary> /// Starts all grids specified within given Spring XML configuration file. If Ignite with given name /// is already started, then exception is thrown. In this case all instances that may /// have been started so far will be stopped too. /// </summary> /// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be /// absolute or relative to IGNITE_HOME.</param> /// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st /// found instance is returned.</returns> public static IIgnite Start(string springCfgPath) { return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath}); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from first <see cref="IgniteConfigurationSection"/> in the /// application configuration and starts Ignite. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration() { var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var section = cfg.Sections.OfType<IgniteConfigurationSection>().FirstOrDefault(); if (section == null) throw new ConfigurationErrorsException( string.Format("Could not find {0} in current application configuration", typeof(IgniteConfigurationSection).Name)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath"); var fileMap = GetConfigMap(configPath); var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var section = config.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException( string.Format("Could not find {0} with name '{1}' in file '{2}'", typeof(IgniteConfigurationSection).Name, sectionName, configPath)); return Start(section.IgniteConfiguration); } /// <summary> /// Gets the configuration file map. /// </summary> private static ExeConfigurationFileMap GetConfigMap(string fileName) { var fullFileName = Path.GetFullPath(fileName); if (!File.Exists(fullFileName)) throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName); return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName }; } /// <summary> /// Starts Ignite with given configuration. /// </summary> /// <returns>Started Ignite.</returns> public static unsafe IIgnite Start(IgniteConfiguration cfg) { IgniteArgumentCheck.NotNull(cfg, "cfg"); lock (SyncRoot) { // 0. Init logger var log = cfg.Logger ?? new JavaLogger(); log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version); // 1. Check GC settings. CheckServerGc(cfg, log); // 2. Create context. IgniteUtils.LoadDlls(cfg.JvmDllPath, log); var cbs = new UnmanagedCallbacks(log); IgniteManager.CreateJvmContext(cfg, cbs, log); log.Debug("JVM started."); var gridName = cfg.GridName; // 3. Create startup object which will guide us through the rest of the process. _startup = new Startup(cfg, cbs); IUnmanagedTarget interopProc = null; try { // 4. Initiate Ignite start. UU.IgnitionStart(cbs.Context, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null); // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data. var node = _startup.Ignite; interopProc = node.InteropProcessor; var javaLogger = log as JavaLogger; if (javaLogger != null) javaLogger.SetProcessor(interopProc); // 6. On-start callback (notify lifecycle components). node.OnStart(); Nodes[new NodeKey(_startup.Name)] = node; return node; } catch (Exception) { // 1. Perform keys cleanup. string name = _startup.Name; if (name != null) { NodeKey key = new NodeKey(name); if (Nodes.ContainsKey(key)) Nodes.Remove(key); } // 2. Stop Ignite node if it was started. if (interopProc != null) UU.IgnitionStop(interopProc.Context, gridName, true); // 3. Throw error further (use startup error if exists because it is more precise). if (_startup.Error != null) throw _startup.Error; throw; } finally { _startup = null; if (interopProc != null) UU.ProcessorReleaseStart(interopProc); } } } /// <summary> /// Check whether GC is set to server mode. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log">Log.</param> private static void CheckServerGc(IgniteConfiguration cfg, ILogger log) { if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0) log.Warn("GC server mode is not enabled, this could lead to less " + "than optimal performance on multi-core machines (to enable see " + "http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx)."); } /// <summary> /// Prepare callback invoked from Java. /// </summary> /// <param name="inStream">Input stream with data.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> /// <param name="log">Log.</param> internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream, HandleRegistry handleRegistry, ILogger log) { try { BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream); PrepareConfiguration(reader, outStream, log); PrepareLifecycleBeans(reader, outStream, handleRegistry); PrepareAffinityFunctions(reader, outStream); outStream.SynchronizeOutput(); } catch (Exception e) { _startup.Error = e; throw; } } /// <summary> /// Prepare configuration. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Response stream.</param> /// <param name="log">Log.</param> private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log) { // 1. Load assemblies. IgniteConfiguration cfg = _startup.Configuration; LoadAssemblies(cfg.Assemblies); ICollection<string> cfgAssembllies; BinaryConfiguration binaryCfg; BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg); LoadAssemblies(cfgAssembllies); // 2. Create marshaller only after assemblies are loaded. if (cfg.BinaryConfiguration == null) cfg.BinaryConfiguration = binaryCfg; _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration); // 3. Send configuration details to Java cfg.Validate(log); cfg.Write(_startup.Marshaller.StartMarshal(outStream)); } /// <summary> /// Prepare lifecycle beans. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> private static void PrepareLifecycleBeans(IBinaryRawReader reader, IBinaryStream outStream, HandleRegistry handleRegistry) { IList<LifecycleBeanHolder> beans = new List<LifecycleBeanHolder> { new LifecycleBeanHolder(new InternalLifecycleBean()) // add internal bean for events }; // 1. Read beans defined in Java. int cnt = reader.ReadInt(); for (int i = 0; i < cnt; i++) beans.Add(new LifecycleBeanHolder(CreateObject<ILifecycleBean>(reader))); // 2. Append beans defined in local configuration. ICollection<ILifecycleBean> nativeBeans = _startup.Configuration.LifecycleBeans; if (nativeBeans != null) { foreach (ILifecycleBean nativeBean in nativeBeans) beans.Add(new LifecycleBeanHolder(nativeBean)); } // 3. Write bean pointers to Java stream. outStream.WriteInt(beans.Count); foreach (LifecycleBeanHolder bean in beans) outStream.WriteLong(handleRegistry.AllocateCritical(bean)); // 4. Set beans to STARTUP object. _startup.LifecycleBeans = beans; } /// <summary> /// Prepares the affinity functions. /// </summary> private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream) { var cnt = reader.ReadInt(); var writer = reader.Marshaller.StartMarshal(outStream); for (var i = 0; i < cnt; i++) { var objHolder = new ObjectInfoHolder(reader); AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder); } } /// <summary> /// Creates an object and sets the properties. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Resulting object.</returns> private static T CreateObject<T>(IBinaryRawReader reader) { return IgniteUtils.CreateInstance<T>(reader.ReadString(), reader.ReadDictionaryAsGeneric<string, object>()); } /// <summary> /// Kernal start callback. /// </summary> /// <param name="interopProc">Interop processor.</param> /// <param name="stream">Stream.</param> internal static void OnStart(IUnmanagedTarget interopProc, IBinaryStream stream) { try { // 1. Read data and leave critical state ASAP. BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream); // ReSharper disable once PossibleInvalidOperationException var name = reader.ReadString(); // 2. Set ID and name so that Start() method can use them later. _startup.Name = name; if (Nodes.ContainsKey(new NodeKey(name))) throw new IgniteException("Ignite with the same name already started: " + name); _startup.Ignite = new Ignite(_startup.Configuration, _startup.Name, interopProc, _startup.Marshaller, _startup.LifecycleBeans, _startup.Callbacks); } catch (Exception e) { // 5. Preserve exception to throw it later in the "Start" method and throw it further // to abort startup in Java. _startup.Error = e; throw; } } /// <summary> /// Load assemblies. /// </summary> /// <param name="assemblies">Assemblies.</param> private static void LoadAssemblies(IEnumerable<string> assemblies) { if (assemblies != null) { foreach (string s in assemblies) { // 1. Try loading as directory. if (Directory.Exists(s)) { string[] files = Directory.GetFiles(s, "*.dll"); #pragma warning disable 0168 foreach (string dllPath in files) { if (!SelfAssembly(dllPath)) { try { Assembly.LoadFile(dllPath); } catch (BadImageFormatException) { // No-op. } } } #pragma warning restore 0168 continue; } // 2. Try loading using full-name. try { Assembly assembly = Assembly.Load(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 3. Try loading using file path. try { Assembly assembly = Assembly.LoadFrom(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 4. Not found, exception. throw new IgniteException("Failed to load assembly: " + s); } } } /// <summary> /// Whether assembly points to Ignite binary. /// </summary> /// <param name="assembly">Assembly to check..</param> /// <returns><c>True</c> if this is one of GG assemblies.</returns> private static bool SelfAssembly(string assembly) { return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p /> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned.</param> /// <returns> /// An instance of named grid. /// </returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite(string name) { var ignite = TryGetIgnite(name); if (ignite == null) throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name); return ignite; } /// <summary> /// Gets an instance of default no-name grid. Note that /// caller of this method should not assume that it will return the same /// instance every time. /// </summary> /// <returns>An instance of default no-name grid.</returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite() { return GetIgnite(null); } /// <summary> /// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p/> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned. /// </param> /// <returns>An instance of named grid, or null.</returns> public static IIgnite TryGetIgnite(string name) { lock (SyncRoot) { Ignite result; return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result; } } /// <summary> /// Gets an instance of default no-name grid, or <c>null</c> if none found. Note that /// caller of this method should not assume that it will return the same /// instance every time. /// </summary> /// <returns>An instance of default no-name grid, or null.</returns> public static IIgnite TryGetIgnite() { return TryGetIgnite(null); } /// <summary> /// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. If /// grid name is <c>null</c>, then default no-name Ignite will be stopped. /// </summary> /// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.cancel</c>method.</param> /// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c> /// othwerwise (the instance with given <c>name</c> was not found).</returns> public static bool Stop(string name, bool cancel) { lock (SyncRoot) { NodeKey key = new NodeKey(name); Ignite node; if (!Nodes.TryGetValue(key, out node)) return false; node.Stop(cancel); Nodes.Remove(key); GC.Collect(); return true; } } /// <summary> /// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. /// </summary> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.Cancel()</c> method.</param> public static void StopAll(bool cancel) { lock (SyncRoot) { while (Nodes.Count > 0) { var entry = Nodes.First(); entry.Value.Stop(cancel); Nodes.Remove(entry.Key); } } GC.Collect(); } /// <summary> /// Handles the AssemblyResolve event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The <see cref="ResolveEventArgs"/> instance containing the event data.</param> /// <returns>Manually resolved assembly, or null.</returns> private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { return LoadedAssembliesResolver.Instance.GetAssembly(args.Name); } /// <summary> /// Grid key. /// </summary> private class NodeKey { /** */ private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="NodeKey"/> class. /// </summary> /// <param name="name">The name.</param> internal NodeKey(string name) { _name = name; } /** <inheritdoc /> */ public override bool Equals(object obj) { var other = obj as NodeKey; return other != null && Equals(_name, other._name); } /** <inheritdoc /> */ public override int GetHashCode() { return _name == null ? 0 : _name.GetHashCode(); } } /// <summary> /// Value object to pass data between .Net methods during startup bypassing Java. /// </summary> private class Startup { /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs"></param> internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { Configuration = cfg; Callbacks = cbs; } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get; private set; } /// <summary> /// Gets unmanaged callbacks. /// </summary> internal UnmanagedCallbacks Callbacks { get; private set; } /// <summary> /// Lifecycle beans. /// </summary> internal IList<LifecycleBeanHolder> LifecycleBeans { get; set; } /// <summary> /// Node name. /// </summary> internal string Name { get; set; } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get; set; } /// <summary> /// Start error. /// </summary> internal Exception Error { get; set; } /// <summary> /// Gets or sets the ignite. /// </summary> internal Ignite Ignite { get; set; } } /// <summary> /// Internal bean for event notification. /// </summary> private class InternalLifecycleBean : ILifecycleBean { /** */ #pragma warning disable 649 // unused field [InstanceResource] private readonly IIgnite _ignite; /** <inheritdoc /> */ public void OnLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null) ((IgniteProxy) _ignite).Target.BeforeNodeStop(); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Preview.Sync { /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// FetchServiceOptions /// </summary> public class FetchServiceOptions : IOptions<ServiceResource> { /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchServiceOptions /// </summary> /// <param name="pathSid"> The sid </param> public FetchServiceOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// DeleteServiceOptions /// </summary> public class DeleteServiceOptions : IOptions<ServiceResource> { /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteServiceOptions /// </summary> /// <param name="pathSid"> The sid </param> public DeleteServiceOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// CreateServiceOptions /// </summary> public class CreateServiceOptions : IOptions<ServiceResource> { /// <summary> /// The friendly_name /// </summary> public string FriendlyName { get; set; } /// <summary> /// The webhook_url /// </summary> public Uri WebhookUrl { get; set; } /// <summary> /// The reachability_webhooks_enabled /// </summary> public bool? ReachabilityWebhooksEnabled { get; set; } /// <summary> /// The acl_enabled /// </summary> public bool? AclEnabled { get; set; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (WebhookUrl != null) { p.Add(new KeyValuePair<string, string>("WebhookUrl", Serializers.Url(WebhookUrl))); } if (ReachabilityWebhooksEnabled != null) { p.Add(new KeyValuePair<string, string>("ReachabilityWebhooksEnabled", ReachabilityWebhooksEnabled.Value.ToString().ToLower())); } if (AclEnabled != null) { p.Add(new KeyValuePair<string, string>("AclEnabled", AclEnabled.Value.ToString().ToLower())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// ReadServiceOptions /// </summary> public class ReadServiceOptions : ReadOptions<ServiceResource> { /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// UpdateServiceOptions /// </summary> public class UpdateServiceOptions : IOptions<ServiceResource> { /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// The webhook_url /// </summary> public Uri WebhookUrl { get; set; } /// <summary> /// The friendly_name /// </summary> public string FriendlyName { get; set; } /// <summary> /// The reachability_webhooks_enabled /// </summary> public bool? ReachabilityWebhooksEnabled { get; set; } /// <summary> /// The acl_enabled /// </summary> public bool? AclEnabled { get; set; } /// <summary> /// Construct a new UpdateServiceOptions /// </summary> /// <param name="pathSid"> The sid </param> public UpdateServiceOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (WebhookUrl != null) { p.Add(new KeyValuePair<string, string>("WebhookUrl", Serializers.Url(WebhookUrl))); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (ReachabilityWebhooksEnabled != null) { p.Add(new KeyValuePair<string, string>("ReachabilityWebhooksEnabled", ReachabilityWebhooksEnabled.Value.ToString().ToLower())); } if (AclEnabled != null) { p.Add(new KeyValuePair<string, string>("AclEnabled", AclEnabled.Value.ToString().ToLower())); } return p; } } }
using System; using OpenTK; namespace Bearded.Utilities.Math { /// <summary> /// A typesafe representation of a signed angle. /// </summary> public struct Angle : IEquatable<Angle> { private readonly float radians; #region Constructing private Angle(float radians) { this.radians = radians; } /// <summary> /// Initialises an angle from a relative angle value in radians. /// </summary> public static Angle FromRadians(float radians) { return new Angle(radians); } /// <summary> /// Initialises an angle from a relative angle value in degrees. /// </summary> public static Angle FromDegrees(float degrees) { return new Angle(Mathf.DegreesToRadians(degrees)); } /// <summary> /// Initialises an angle as the signed difference between two directional unit vectors in the 2D plane. /// If the vectors are not unit length the result is undefined. /// </summary> public static Angle Between(Vector2 from, Vector2 to) { float perpDot = from.Y * to.X - from.X * to.Y; return Angle.FromRadians(Mathf.Atan2(perpDot, Vector2.Dot(from, to))); } /// <summary> /// Initialises an angle as the signed difference between two directions in the 2D plane. /// The returned value is the smallest possible angle from one direction to the other. /// </summary> public static Angle Between(Direction2 from, Direction2 to) { return to - from; } /// <summary> /// Initialises an angle as the signed difference between two directions in the 2D plane. /// The returned value is the smallest positive angle from one direction to the other. /// </summary> public static Angle BetweenPositive(Direction2 from, Direction2 to) { var a = Angle.Between(from, to); if (a.radians < 0) a += Mathf.TwoPi.Radians(); return a; } /// <summary> /// Initialises an angle as the signed difference between two directions in the 2D plane. /// The returned value is the smallest negative angle from one direction to the other. /// </summary> public static Angle BetweenNegative(Direction2 from, Direction2 to) { var a = Angle.Between(from, to); if (a.radians > 0) a -= Mathf.TwoPi.Radians(); return a; } #endregion #region Static Fields /// <summary> /// The default zero angle. /// </summary> public static readonly Angle Zero = new Angle(0); #endregion #region Properties /// <summary> /// Gets the value of the angle in radians. /// </summary> public float Radians { get { return this.radians; } } /// <summary> /// Gets the value of the angle in degrees. /// </summary> public float Degrees { get { return Mathf.RadiansToDegrees(this.radians); } } /// <summary> /// Gets a 2x2 rotation matrix that rotates vectors by this angle. /// </summary> public Matrix2 Transformation { get { return Matrix2.CreateRotation(this.radians); } } /// <summary> /// Gets the magnitude (absolute value) of the angle in radians. /// </summary> public float MagnitudeInRadians { get { return System.Math.Abs(this.radians); } } /// <summary> /// Gets the magnitude (absolute value) of the angle in degrees. /// </summary> public float MagnitudeInDegrees { get { return System.Math.Abs(this.Degrees); } } #endregion #region Methods #region Arithmetic /// <summary> /// Returns the Sine of the angle. /// </summary> public float Sin() { return Mathf.Sin(this.radians); } /// <summary> /// Returns the Cosine of the angle. /// </summary> public float Cos() { return Mathf.Cos(this.radians); } /// <summary> /// Returns the Tangent of the angle. /// </summary> public float Tan() { return Mathf.Tan(this.radians); } /// <summary> /// Returns the Sign of the angle. /// </summary> public int Sign() { return System.Math.Sign(this.radians); } /// <summary> /// Returns the absolute value of the angle. /// </summary> public Angle Abs() { return new Angle(System.Math.Abs(this.radians)); } /// <summary> /// Returns a new Angle with |value| == 1 radians and the same sign as this angle. /// Returns a new Angle with value 0 if the angle is zero. /// </summary> public Angle Normalized() { return new Angle(System.Math.Sign(this.radians)); } /// <summary> /// Clamps this angle between a minimum and a maximum angle. /// </summary> public Angle Clamped(Angle min, Angle max) { return Angle.Clamp(this, min, max); } #region Statics /// <summary> /// Returns the larger of two angles. /// </summary> public static Angle Max(Angle a1, Angle a2) { return a1 > a2 ? a1 : a2; } /// <summary> /// Returns the smaller of two angles. /// </summary> public static Angle Min(Angle a1, Angle a2) { return a1 < a2 ? a1 : a2; } /// <summary> /// Clamps one angle between a minimum and a maximum angle. /// </summary> public static Angle Clamp(Angle a, Angle min, Angle max) { return a < max ? a > min ? a : min : max; } #endregion #endregion #endregion #region Operators #region Arithmetic /// <summary> /// Adds two angles. /// </summary> public static Angle operator +(Angle angle1, Angle angle2) { return new Angle(angle1.radians + angle2.radians); } /// <summary> /// Substracts an angle from another. /// </summary> public static Angle operator -(Angle angle1, Angle angle2) { return new Angle(angle1.radians - angle2.radians); } /// <summary> /// Inverts an angle. /// </summary> public static Angle operator -(Angle angle) { return new Angle(-angle.radians); } /// <summary> /// Multiplies an angle with a scalar. /// </summary> public static Angle operator *(Angle angle, float scalar) { return new Angle(angle.radians * scalar); } /// <summary> /// Multiplies an angle with a scalar. /// </summary> public static Angle operator *(float scalar, Angle angle) { return new Angle(angle.radians * scalar); } /// <summary> /// Divides an angle by an inverse scalar. /// </summary> public static Angle operator /(Angle angle, float invScalar) { return new Angle(angle.radians / invScalar); } /// <summary> /// Linearly interpolates between two angles. /// </summary> public static Angle Lerp(Angle angle0, Angle angle1, float t) { return angle0 + (angle1 - angle0) * t; } #endregion #region Boolean /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false. /// </returns> public bool Equals(Angle other) { return this.radians == other.radians; } /// <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 obj is Angle && this.Equals((Angle)obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return this.radians.GetHashCode(); } /// <summary> /// Checks two angles for equality. /// </summary> public static bool operator ==(Angle x, Angle y) { return x.Equals(y); } /// <summary> /// Checks two angles for inequality. /// </summary> public static bool operator !=(Angle x, Angle y) { return !(x == y); } /// <summary> /// Checks whether one angle is smaller than another. /// </summary> public static bool operator <(Angle x, Angle y) { return x.radians < y.radians; } /// <summary> /// Checks whether one angle is greater than another. /// </summary> public static bool operator >(Angle x, Angle y) { return x.radians > y.radians; } /// <summary> /// Checks whether one angle is smaller or equal to another. /// </summary> public static bool operator <=(Angle x, Angle y) { return x.radians <= y.radians; } /// <summary> /// Checks whether one angle is greater or equal to another. /// </summary> public static bool operator >=(Angle x, Angle y) { return x.radians >= y.radians; } #endregion #region Casts /// <summary> /// Casts an angle to a direction in the 2D plane. /// This is the same as Direction.Zero + angle. /// </summary> public static explicit operator Direction2(Angle angle) { return Direction2.FromRadians(angle.radians); } #endregion #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace AnimalLookupWebservice.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// XPlat Apps licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if __IOS__ namespace XPlat.Device.Geolocation { using System; using System.Threading.Tasks; using CoreLocation; using global::Foundation; using UIKit; using XPlat.Exceptions; using XPlat.Foundation; /// <summary>Provides access to the current geographic location.</summary> public class Geolocator : IGeolocator { private readonly CLLocationManager locationManager; /// <summary> /// Initializes a new instance of the <see cref="Geolocator"/> class. /// </summary> public Geolocator() { this.locationManager = RetrieveLocationManager(); this.locationManager.AuthorizationChanged += this.LocationManager_OnAuthorizationChanged; this.locationManager.Failed += this.LocationManager_OnFailed; if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0)) { this.locationManager.LocationsUpdated += this.LocationManager_OnLocationsUpdated; } else { this.locationManager.UpdatedLocation += this.LocationManager_OnUpdatedLocation; } } /// <summary>Raised when the location is updated.</summary> public event TypedEventHandler<IGeolocator, PositionChangedEventArgs> PositionChanged; /// <summary>Raised when the ability of the Geolocator to provide updated location changes.</summary> public event TypedEventHandler<IGeolocator, StatusChangedEventArgs> StatusChanged; /// <summary>Gets the last known position recorded by the Geolocator.</summary> public Geoposition LastKnownPosition { get; private set; } /// <summary>Gets or sets the requested minimum time interval between location updates, in milliseconds. If your application requires updates infrequently, set this value so that location services can conserve power by calculating location only when needed.</summary> public uint ReportInterval { get; set; } /// <summary>Gets or sets the distance of movement, in meters, relative to the coordinate from the last PositionChanged event, that is required for the Geolocator to raise a PositionChanged event.</summary> public double MovementThreshold { get; set; } /// <summary>Gets or sets the accuracy level at which the Geolocator provides location updates.</summary> public PositionAccuracy DesiredAccuracy { get; set; } /// <summary>Gets the status that indicates the ability of the Geolocator to provide location updates.</summary> public PositionStatus LocationStatus { get; private set; } /// <summary>Gets or sets the desired accuracy in meters for data returned from the location service.</summary> public uint DesiredAccuracyInMeters { get; set; } /// <summary>Requests permission to access location data.</summary> /// <returns>A GeolocationAccessStatus that indicates if permission to location data has been granted.</returns> /// <exception cref="T:XPlat.Exceptions.AppPermissionInvalidException">Thrown if the NSLocationWhenInUseUsageDescription/NSLocationAlwaysUsageDescription permission is not enabled.</exception> public Task<GeolocationAccessStatus> RequestAccessAsync() { NSDictionary info = NSBundle.MainBundle.InfoDictionary; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { if (info.ContainsKey(new NSString("NSLocationWhenInUseUsageDescription"))) { this.locationManager.RequestWhenInUseAuthorization(); } else if (info.ContainsKey(new NSString("NSLocationAlwaysUsageDescription"))) { this.locationManager.RequestAlwaysAuthorization(); } else { throw new AppPermissionInvalidException( "NSLocationWhenInUseUsageDescription/NSLocationAlwaysUsageDescription", "iOS8+ requires the NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription to enable the Geolocator position changes."); } } this.locationManager.DesiredAccuracy = this.DesiredAccuracyInMeters; this.locationManager.DistanceFilter = this.MovementThreshold; this.locationManager.StartUpdatingLocation(); return Task.FromResult(GeolocationAccessStatus.Allowed); } /// <summary>Starts an asynchronous operation to retrieve the current location of the device.</summary> /// <returns>An asynchronous operation that, upon completion, returns a Geoposition marking the found location.</returns> /// <exception cref="T:XPlat.Exceptions.AppPermissionInvalidException">Thrown if the NSLocationWhenInUseUsageDescription/NSLocationAlwaysUsageDescription permission is not enabled.</exception> public Task<Geoposition> GetGeopositionAsync() { return this.GetGeopositionAsync(TimeSpan.MaxValue, TimeSpan.FromMinutes(1)); } /// <summary> /// Starts an asynchronous operation to retrieve the current location of the device. /// </summary> /// <param name="maximumAge"> /// The maximum acceptable age of cached location data. /// </param> /// <param name="timeout"> /// The timeout. /// </param> /// <returns> /// An asynchronous operation that, upon completion, returns a Geoposition marking the found location. /// </returns> /// <exception cref="T:XPlat.Exceptions.AppPermissionInvalidException">Thrown if the NSLocationWhenInUseUsageDescription/NSLocationAlwaysUsageDescription permission is not enabled.</exception> public async Task<Geoposition> GetGeopositionAsync(TimeSpan maximumAge, TimeSpan timeout) { var tcs = new TaskCompletionSource<Geoposition>(); GeolocationAccessStatus access = await this.RequestAccessAsync(); if (access == GeolocationAccessStatus.Allowed) { if (this.LastKnownPosition == null || (this.LastKnownPosition.Coordinate != null && !(this.LastKnownPosition.Coordinate.Timestamp <= DateTime.UtcNow.Subtract(maximumAge)))) { // Attempts to get the current location based on the event handler of this Geolocator. TypedEventHandler<IGeolocator, PositionChangedEventArgs> positionResponse = null; positionResponse = (s, e) => { tcs.TrySetResult(e.Position); this.PositionChanged -= positionResponse; }; this.PositionChanged += positionResponse; } else { tcs.SetResult(this.LastKnownPosition); } } else { tcs.SetResult(null); } return await tcs.Task; } private static CLLocationManager RetrieveLocationManager() { CLLocationManager manager = null; new NSObject().InvokeOnMainThread(() => manager = new CLLocationManager()); return manager; } private void LocationManager_OnUpdatedLocation(object sender, CLLocationUpdatedEventArgs args) { CLLocation loc = args.NewLocation; var geoposition = new Geoposition(loc); this.LastKnownPosition = geoposition; this.PositionChanged?.Invoke(this, new PositionChangedEventArgs(geoposition)); loc?.Dispose(); } private void LocationManager_OnLocationsUpdated(object sender, CLLocationsUpdatedEventArgs args) { foreach (CLLocation loc in args.Locations) { var geoposition = new Geoposition(loc); this.LastKnownPosition = geoposition; this.PositionChanged?.Invoke(this, new PositionChangedEventArgs(geoposition)); loc?.Dispose(); } } private void LocationManager_OnAuthorizationChanged(object sender, CLAuthorizationChangedEventArgs args) { switch (args.Status) { case CLAuthorizationStatus.NotDetermined: this.LocationStatus = PositionStatus.NotAvailable; break; case CLAuthorizationStatus.Restricted: case CLAuthorizationStatus.Denied: this.LocationStatus = PositionStatus.Disabled; break; case CLAuthorizationStatus.Authorized: case CLAuthorizationStatus.AuthorizedWhenInUse: this.LocationStatus = PositionStatus.Ready; break; } this.StatusChanged?.Invoke(this, new StatusChangedEventArgs(this.LocationStatus)); } private void LocationManager_OnFailed(object sender, NSErrorEventArgs args) { if ((CLError)(int)args.Error.Code != CLError.Network) { return; } this.LocationStatus = PositionStatus.NotAvailable; this.StatusChanged?.Invoke(this, new StatusChangedEventArgs(this.LocationStatus)); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Represents creating a new array and possibly initializing the elements of the new array. /// </summary> [DebuggerTypeProxy(typeof(Expression.NewArrayExpressionProxy))] public class NewArrayExpression : Expression { private readonly ReadOnlyCollection<Expression> _expressions; private readonly Type _type; internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions) { _expressions = expressions; _type = type; } internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions) { if (nodeType == ExpressionType.NewArrayInit) { return new NewArrayInitExpression(type, expressions); } else { return new NewArrayBoundsExpression(type, expressions); } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Gets the bounds of the array if the value of the <see cref="P:NodeType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="P:NodeType"/> property is NewArrayInit. /// </summary> public ReadOnlyCollection<Expression> Expressions { get { return _expressions; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitNewArray(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expressions">The <see cref="Expressions" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public NewArrayExpression Update(IEnumerable<Expression> expressions) { if (expressions == Expressions) { return this; } if (NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(Type.GetElementType(), expressions); } return Expression.NewArrayBounds(Type.GetElementType(), expressions); } } internal sealed class NewArrayInitExpression : NewArrayExpression { internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.NewArrayInit; } } } internal sealed class NewArrayBoundsExpression : NewArrayExpression { internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.NewArrayBounds; } } } public partial class Expression { #region NewArrayInit /// <summary> /// Creates a new array expression of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns> public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers) { return NewArrayInit(type, (IEnumerable<Expression>)initializers); } /// <summary> /// Creates a new array expression of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns> public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(initializers, "initializers"); if (type.Equals(typeof(void))) { throw Error.ArgumentCannotBeOfTypeVoid(); } ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly(); Expression[] newList = null; for (int i = 0, n = initializerList.Count; i < n; i++) { Expression expr = initializerList[i]; RequiresCanRead(expr, "initializers"); if (!TypeUtils.AreReferenceAssignable(type, expr.Type)) { if (!TryQuote(type, ref expr)) { throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type); } if (newList == null) { newList = new Expression[initializerList.Count]; for (int j = 0; j < i; j++) { newList[j] = initializerList[j]; } } } if (newList != null) { newList[i] = expr; } } if (newList != null) { initializerList = new TrueReadOnlyCollection<Expression>(newList); } return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList); } #endregion #region NewArrayBounds /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param> /// <param name="bounds">An array that contains Expression objects to use to populate the Expressions collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds) { return NewArrayBounds(type, (IEnumerable<Expression>)bounds); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param> /// <param name="bounds">An IEnumerable{T} that contains Expression objects to use to populate the Expressions collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(bounds, "bounds"); if (type.Equals(typeof(void))) { throw Error.ArgumentCannotBeOfTypeVoid(); } ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly(); int dimensions = boundsList.Count; if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne(); for (int i = 0; i < dimensions; i++) { Expression expr = boundsList[i]; RequiresCanRead(expr, "bounds"); if (!TypeUtils.IsInteger(expr.Type)) { throw Error.ArgumentMustBeInteger(); } } Type arrayType; if (dimensions == 1) { //To get a vector, need call Type.MakeArrayType(). //Type.MakeArrayType(1) gives a non-vector array, which will cause type check error. arrayType = type.MakeArrayType(); } else { arrayType = type.MakeArrayType(dimensions); } return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, bounds.ToReadOnly()); } #endregion } }
// QuickGraph Library // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // QuickGraph Library HomePage: http://www.mbunit.com // Author: Jonathan de Halleux namespace QuickGraph.Algorithms.Search { using System; using System.Collections; using System.Collections.Specialized; using QuickGraph.Concepts; using QuickGraph.Concepts.Algorithms; using QuickGraph.Concepts.Traversals; using QuickGraph.Concepts.Visitors; using QuickGraph.Collections; /// <summary> /// Performs a breadth-first traversal /// of a directed or undirected graph. /// </summary> /// <remarks> /// <para> /// A breadth-first-search (BFS) traversal visits vertices that are closer to the /// source before visiting vertices that are further away. /// In this context ``distance'' is defined as the number of edges in the /// shortest path from the source vertex. /// </para> /// <para> /// The BFS can be used to compute the shortest /// path from the source to all reachable vertices and the resulting /// shortest-path distances. /// </para> /// <para> /// BFS uses two data structures to to implement the traversal: /// a color marker for each vertex and a queue. /// White vertices are undiscovered while gray vertices are discovered /// but have undiscovered adjacent vertices. Black vertices are discovered /// and are adjacent to only other black or gray vertices. /// </para> /// <para> /// The algorithm proceeds by removing a vertex u from the queue and /// examining each out-edge (u,v). If an adjacent vertex v is not already /// discovered, it is colored gray and placed in the queue. After all of /// the out-edges are examined, vertex u is colored black and the process /// is repeated. Pseudo-code for the BFS algorithm is a listed below. /// </para> /// <code> /// IVertexListGraph g; /// BFS(IVertex s) /// { /// // initialize vertices /// foreach(IVertex u in g.Vertices) /// { /// Colors[u] = White; /// OnInitializeVertex(u); // event /// } /// /// Visit(s); /// } /// /// Visit(IVertex s) /// { /// Colors[s]=GraphColor.Gray; /// OnDiscoverVertex(s); //event /// /// m_Q.Push(s); /// while (m_Q.Count != 0) /// { /// IVertex u = m_Q.Peek(); /// m_Q.Pop(); /// OnExamineVertex(u); // event /// /// foreach(Edge e in g.OutEdges(u)) /// { /// OnExamineEdge(e); // event /// /// GraphColor vColor = Colors[e.Target]; /// if (vColor == GraphColor.White) /// { /// OnTreeEdge(e); // event /// OnDiscoverVertex(v); // event /// Colors[v]=GraphColor.Gray; /// m_Q.Push(v); /// } /// else /// { /// OnNonTreeEdge(e); /// if (vColor == GraphColor.Gray) /// { /// OnGrayTarget(e); // event /// } /// else /// { /// OnBlackTarget(e); //event /// } /// } /// } /// Colors[u]=GraphColor.Black; /// OnFinishVertex(this, uArgs); /// } /// } ///</code> /// <para>This algorithm is directly inspired from the /// BoostGraphLibrary implementation. /// </para> /// </remarks> public class BreadthFirstSearchAlgorithm : IAlgorithm, IPredecessorRecorderAlgorithm, IDistanceRecorderAlgorithm, IVertexColorizerAlgorithm, ITreeEdgeBuilderAlgorithm { private IVertexListGraph m_VisitedGraph; private VertexColorDictionary m_Colors; private VertexBuffer m_Q; /// <summary> /// BreadthFirstSearch searcher constructor /// </summary> /// <param name="g">Graph to visit</param> public BreadthFirstSearchAlgorithm(IVertexListGraph g) { if (g == null) throw new ArgumentNullException("g"); m_VisitedGraph = g; m_Colors = new VertexColorDictionary(); m_Q = new VertexBuffer(); } /// <summary> /// BreadthFirstSearch searcher contructor /// </summary> /// <param name="g">Graph to visit</param> /// <param name="q">Vertex buffer</param> /// <param name="colors">Vertex color map</param> public BreadthFirstSearchAlgorithm( IVertexListGraph g, VertexBuffer q, VertexColorDictionary colors ) { if (g == null) throw new ArgumentNullException("g"); if (q == null) throw new ArgumentNullException("Stack Q is null"); if (colors == null) throw new ArgumentNullException("Colors"); m_VisitedGraph = g; m_Colors = colors; m_Q = q; } /// <summary> /// Visited graph /// </summary> public IVertexListGraph VisitedGraph { get { return m_VisitedGraph; } } Object IAlgorithm.VisitedGraph { get { return this.VisitedGraph; } } /// <summary> /// Gets the <see cref="IVertex"/> to <see cref="GraphColor"/>dictionary /// </summary> /// <value> /// <see cref="IVertex"/> to <see cref="GraphColor"/>dictionary /// </value> public VertexColorDictionary Colors { get { return m_Colors; } } IDictionary IVertexColorizerAlgorithm.Colors { get { return this.Colors; } } #region Events /// <summary> /// Invoked on every vertex before the start of the search /// </summary> public event VertexEventHandler InitializeVertex; /// <summary> /// Raises the <see cref="InitializeVertex"/> event. /// </summary> /// <param name="v">vertex that raised the event</param> protected void OnInitializeVertex(IVertex v) { if (InitializeVertex!=null) InitializeVertex(this, new VertexEventArgs(v)); } /// <summary> /// Invoked in each vertex as it is removed from the queue /// </summary> public event VertexEventHandler ExamineVertex; /// <summary> /// Raises the <see cref="ExamineVertex"/> event. /// </summary> /// <param name="v">vertex that raised the event</param> protected void OnExamineVertex(IVertex v) { if (ExamineVertex!=null) ExamineVertex(this, new VertexEventArgs(v)); } /// <summary> /// Invoked the first time the algorithm encounters vertex u. /// All vertices closer to the source vertex have been discovered, /// and vertices further from the source have not yet been discovered. /// </summary> public event VertexEventHandler DiscoverVertex; /// <summary> /// Raises the <see cref="DiscoverVertex"/> event. /// </summary> /// <param name="v">vertex that raised the event</param> protected void OnDiscoverVertex(IVertex v) { if (DiscoverVertex!=null) DiscoverVertex(this, new VertexEventArgs(v)); } /// <summary> /// Invoked on every out-edge of each vertex immediately after the vertex is removed from the queue. /// </summary> public event EdgeEventHandler ExamineEdge; /// <summary> /// Raises the <see cref="ExamineEdge"/> event. /// </summary> /// <param name="e">edge that raised the event</param> protected void OnExamineEdge(IEdge e) { if (ExamineEdge!=null) ExamineEdge(this, new EdgeEventArgs(e)); } /// <summary> /// Invoked (in addition to ExamineEdge()) if the edge is a tree edge. /// The target vertex of edge e is discovered at this time. /// </summary> public event EdgeEventHandler TreeEdge; /// <summary> /// Raises the <see cref="TreeEdge"/> event. /// </summary> /// <param name="e">edge that raised the event</param> protected void OnTreeEdge(IEdge e) { if (TreeEdge!=null) TreeEdge(this, new EdgeEventArgs(e)); } /// <summary> /// Invoked (in addition to examine_edge()) if the edge is not a tree /// edge. /// </summary> public event EdgeEventHandler NonTreeEdge; /// <summary> /// Raises the <see cref="NonTreeEdge"/> event. /// </summary> /// <param name="e">edge that raised the event</param> protected void OnNonTreeEdge(IEdge e) { if (NonTreeEdge!=null) NonTreeEdge(this, new EdgeEventArgs(e)); } /// <summary> /// Invoked (in addition to non_tree_edge()) if the target vertex is /// colored gray at the time of examination. The color gray indicates /// that the vertex is currently in the queue. /// </summary> public event EdgeEventHandler GrayTarget; /// <summary> /// Raises the <see cref="GrayTarget"/> event. /// </summary> /// <param name="e">edge that raised the event</param> protected void OnGrayTarget(IEdge e) { if (GrayTarget!=null) GrayTarget(this, new EdgeEventArgs(e)); } /// <summary> /// Invoked (in addition to NonTreeEdge()) if the target vertex is /// colored black at the time of examination. The color black indicates /// that the vertex is no longer in the queue. /// </summary> public event EdgeEventHandler BlackTarget; /// <summary> /// Raises the <see cref="BlackTarget"/> event. /// </summary> /// <param name="e">edge that raised the event</param> protected void OnBlackTarget(IEdge e) { if (BlackTarget!=null) BlackTarget(this, new EdgeEventArgs(e)); } /// <summary> /// Invoked after all of the out edges of u have been examined /// and all of the adjacent vertices have been discovered. /// </summary> public event VertexEventHandler FinishVertex; /// <summary> /// Raises the <see cref="FinishVertex"/> event. /// </summary> /// <param name="v">vertex that raised the event</param> protected void OnFinishVertex(IVertex v) { if (FinishVertex!=null) FinishVertex(this, new VertexEventArgs(v)); } #endregion /// <summary> /// Computes the bfs starting at s /// </summary> /// <param name="s">starting vertex</param> /// <exception cref="ArgumentNullException">s is null</exception> /// <remarks> /// This method initializes the color map before appliying the visit. /// </remarks> public void Compute(IVertex s) { if (s == null) throw new ArgumentNullException("Start vertex is null"); // initialize vertex u foreach(IVertex v in VisitedGraph.Vertices) { Colors[v]=GraphColor.White; OnInitializeVertex(v); } Visit(s); } /// <summary> /// Computes the bfs starting at s without initalization. /// </summary> /// <param name="s">starting vertex</param> /// <param name="depth">current depth</param> /// <exception cref="ArgumentNullException">s is null</exception> public void Visit(IVertex s) { if (s == null) throw new ArgumentNullException("Start vertex is null"); Colors[s]=GraphColor.Gray; OnDiscoverVertex(s); m_Q.Push(s); while (m_Q.Count != 0) { IVertex u = (IVertex)m_Q.Peek(); m_Q.Pop(); OnExamineVertex(u); foreach(IEdge e in VisitedGraph.OutEdges(u)) { IVertex v = e.Target; OnExamineEdge(e); GraphColor vColor = Colors[v]; if (vColor == GraphColor.White) { OnTreeEdge(e); Colors[v]=GraphColor.Gray; OnDiscoverVertex(v); m_Q.Push(v); } else { OnNonTreeEdge(e); if (vColor == GraphColor.Gray) { OnGrayTarget(e); } else { OnBlackTarget(e); } } } Colors[u]=GraphColor.Black; OnFinishVertex(u); } } /// <summary> /// /// </summary> /// <param name="vis"></param> public void RegisterVertexColorizerHandlers(IVertexColorizerVisitor vis) { if (vis == null) throw new ArgumentNullException("visitor"); InitializeVertex += new VertexEventHandler(vis.InitializeVertex); DiscoverVertex += new VertexEventHandler(vis.DiscoverVertex); FinishVertex += new VertexEventHandler(vis.FinishVertex); } /// <summary> /// /// </summary> /// <param name="vis"></param> public void RegisterDistanceRecorderHandlers(IDistanceRecorderVisitor vis) { if (vis == null) throw new ArgumentNullException("visitor"); InitializeVertex += new VertexEventHandler(vis.InitializeVertex); DiscoverVertex += new VertexEventHandler(vis.DiscoverVertex); TreeEdge += new EdgeEventHandler(vis.TreeEdge); } /// <summary> /// /// </summary> /// <param name="vis"></param> public void RegisterTreeEdgeBuilderHandlers(ITreeEdgeBuilderVisitor vis) { if (vis == null) throw new ArgumentNullException("visitor"); TreeEdge += new EdgeEventHandler(vis.TreeEdge); } /// <summary> /// Registers the predecessors handler /// </summary> /// <param name="vis"></param> public void RegisterPredecessorRecorderHandlers(IPredecessorRecorderVisitor vis) { if (vis == null) throw new ArgumentNullException("visitor"); TreeEdge += new EdgeEventHandler(vis.TreeEdge); FinishVertex += new VertexEventHandler(vis.FinishVertex); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AngularMaterialDotNet.API.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright 2007 Alp Toker <[email protected]> // 2011 Bertrand Lorentz <[email protected]> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.Threading; using NUnit.Framework; using DBus; using DBus.Protocol; using org.freedesktop.DBus; namespace DBus.Tests { [TestFixture] public class ExportInterfaceTest { ITestOne test; Test test_server; string bus_name = "org.dbussharp.test"; ObjectPath path = new ObjectPath ("/org/dbussharp/test"); int event_a_count = 0; [TestFixtureSetUp] public void Setup () { test_server = new Test (); Bus.Session.Register (path, test_server); Assert.AreEqual (Bus.Session.RequestName (bus_name), RequestNameReply.PrimaryOwner); Assert.AreNotEqual (Bus.Session.RequestName (bus_name), RequestNameReply.PrimaryOwner); test = Bus.Session.GetObject<ITestOne> (bus_name, path); } /// <summary> /// /// </summary> [Test] public void VoidMethods () { test.VoidObject (1); Assert.IsTrue (test_server.void_object_called); test.VoidEnums (TestEnum.Bar, TestEnum.Foo); Assert.IsTrue (test_server.void_enums_called); test.VoidString ("foo"); Assert.IsTrue (test_server.void_enums_called); } /// <summary> /// /// </summary> [Test] public void FireEvent () { test.SomeEvent += HandleSomeEventA; test.FireSomeEvent (); Assert.AreEqual (1, event_a_count); test.SomeEvent -= HandleSomeEventA; test.FireSomeEvent (); Assert.AreEqual (1, event_a_count); } private void HandleSomeEventA (string arg1, object arg2, double arg3, MyTuple mt) { event_a_count++; } /// <summary> /// /// </summary> [Test] public void GetVariant () { Assert.IsInstanceOfType (typeof (byte []), test.GetSomeVariant()); } /// <summary> /// /// </summary> [Test] public void WithOutParameters () { uint n; string istr = "21"; string ostr; test.WithOutParameters (out n, istr, out ostr); Assert.AreEqual (UInt32.Parse (istr), n); Assert.AreEqual ("." + istr + ".", ostr); uint[] a1, a2, a3; test.WithOutParameters2 (out a1, out a2, out a3); Assert.AreEqual (new uint[] { }, a1); Assert.AreEqual (new uint[] { 21, 23, 16 }, a2); Assert.AreEqual (new uint[] { 21, 23 }, a3); } /// <summary> /// /// </summary> [Test] public void GetPresences () { uint[] @contacts = new uint[] { 2 }; IDictionary<uint,SimplePresence> presences; test.GetPresences (contacts, out presences); presences[2] = new SimplePresence { Type = ConnectionPresenceType.Offline, Status = "offline", StatusMessage = "" }; var presence = presences[2]; Assert.AreEqual (ConnectionPresenceType.Offline, presence.Type); Assert.AreEqual ("offline", presence.Status); Assert.AreEqual ("", presence.StatusMessage); } /// <summary> /// /// </summary> [Test] public void ReturnValues () { string str = "abcd"; Assert.AreEqual (str.Length, test.StringLength (str)); } /// <summary> /// /// </summary> [Test] public void ComplexAsVariant () { MyTuple2 cpx = new MyTuple2 (); cpx.A = "a"; cpx.B = "b"; cpx.C = new Dictionary<int,MyTuple> (); cpx.C[3] = new MyTuple("foo", "bar"); object cpxRet = test.ComplexAsVariant (cpx, 12); //MyTuple2 mt2ret = (MyTuple2)Convert.ChangeType (cpxRet, typeof (MyTuple2)); var mt2ret = (DBusStruct<string, string, Dictionary<int, DBusStruct<string, string>>>)cpxRet; Assert.AreEqual (cpx.A, mt2ret.Item1); Assert.AreEqual (cpx.B, mt2ret.Item2); Assert.AreEqual (cpx.C[3].A, mt2ret.Item3[3].Item1); Assert.AreEqual (cpx.C[3].B, mt2ret.Item3[3].Item2); } /// <summary> /// /// </summary> [Test] public void Property () { int i = 99; test.SomeProp = i; Assert.AreEqual (i, test.SomeProp); test.SomeProp = i + 1; Assert.AreEqual (i + 1, test.SomeProp); } /// <summary> /// /// </summary> [Test] public void CatchException () { try { test.ThrowSomeException (); Assert.Fail ("An exception should be thrown before getting here"); } catch (Exception ex) { Assert.IsTrue (ex.Message.Contains ("Some exception")); } } /* Locks up ? /// <summary> /// /// </summary> [Test] public void ObjectArray () { string str = "The best of times"; ITestOne[] objs = test.GetObjectArray (); foreach (ITestOne obj in objs) { Assert.AreEqual (str.Length, obj.StringLength (str)); } }*/ } public delegate void SomeEventHandler (string arg1, object arg2, double arg3, MyTuple mt); [Interface ("org.dbussharp.test")] public interface ITestOne { event SomeEventHandler SomeEvent; void FireSomeEvent (); void VoidObject (object obj); int StringLength (string str); void VoidEnums (TestEnum a, TestEnum b); void VoidString (string str); object GetSomeVariant (); void ThrowSomeException (); void WithOutParameters (out uint n, string str, out string ostr); void WithOutParameters2 (out uint[] a1, out uint[] a2, out uint[] a3); void GetPresences (uint[] @contacts, out IDictionary<uint,SimplePresence> @presence); object ComplexAsVariant (object v, int num); ITestOne[] GetEmptyObjectArray (); ITestOne[] GetObjectArray (); int SomeProp { get; set; } } public class Test : ITestOne { public event SomeEventHandler SomeEvent; public bool void_enums_called = false; public bool void_object_called = false; public bool void_string_called = false; public void VoidObject (object var) { void_object_called = true; } public int StringLength (string str) { return str.Length; } public void VoidEnums (TestEnum a, TestEnum b) { void_enums_called = true; } public virtual void VoidString (string str) { void_string_called = true; } /*void IDemoTwo.Say2 (string str) { Console.WriteLine ("IDemoTwo.Say2: " + str); }*/ public void FireSomeEvent () { MyTuple mt; mt.A = "a"; mt.B = "b"; if (SomeEvent != null) { SomeEvent ("some string", 21, 19.84, mt); } } public object GetSomeVariant () { return new byte[0]; } public void ThrowSomeException () { throw new Exception ("Some exception"); } public void WithOutParameters (out uint n, string str, out string ostr) { n = UInt32.Parse (str); ostr = "." + str + "."; } public void WithOutParameters2 (out uint[] a1, out uint[] a2, out uint[] a3) { a1 = new uint[] { }; a2 = new uint[] { 21, 23, 16 }; a3 = new uint[] { 21, 23 }; } public void GetPresences (uint[] @contacts, out IDictionary<uint,SimplePresence> @presence) { Dictionary<uint,SimplePresence> presences = new Dictionary<uint,SimplePresence>(); presences[2] = new SimplePresence { Type = ConnectionPresenceType.Offline, Status = "offline", StatusMessage = "" }; presence = presences; } public object ComplexAsVariant (object v, int num) { return v; } public ITestOne[] GetEmptyObjectArray () { return new Test[] {}; } public ITestOne[] GetObjectArray () { return new ITestOne[] {this}; } public int SomeProp { get; set; } } public enum TestEnum : byte { Foo, Bar, } public struct MyTuple { public MyTuple (string a, string b) { A = a; B = b; } public string A; public string B; } public struct MyTuple2 { public string A; public string B; public IDictionary<int,MyTuple> C; } public enum ConnectionPresenceType : uint { Unset = 0, Offline = 1, Available = 2, Away = 3, ExtendedAway = 4, Hidden = 5, Busy = 6, Unknown = 7, Error = 8, } public struct SimplePresence { public ConnectionPresenceType Type; public string Status; public string StatusMessage; } }
using YAF.Lucene.Net.Index; using YAF.Lucene.Net.Util; using System; using System.Text; namespace YAF.Lucene.Net.Documents { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Describes the properties of a field. /// </summary> public class FieldType : IIndexableFieldType { // LUCENENET specific: Moved the NumericType enum outside of this class private bool indexed; private bool stored; private bool tokenized = true; private bool storeTermVectors; private bool storeTermVectorOffsets; private bool storeTermVectorPositions; private bool storeTermVectorPayloads; private bool omitNorms; private IndexOptions indexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; private NumericType numericType; private bool frozen; private int numericPrecisionStep = NumericUtils.PRECISION_STEP_DEFAULT; private DocValuesType docValueType; /// <summary> /// Create a new mutable <see cref="FieldType"/> with all of the properties from <paramref name="ref"/> /// </summary> public FieldType(FieldType @ref) { this.indexed = @ref.IsIndexed; this.stored = @ref.IsStored; this.tokenized = @ref.IsTokenized; this.storeTermVectors = @ref.StoreTermVectors; this.storeTermVectorOffsets = @ref.StoreTermVectorOffsets; this.storeTermVectorPositions = @ref.StoreTermVectorPositions; this.storeTermVectorPayloads = @ref.StoreTermVectorPayloads; this.omitNorms = @ref.OmitNorms; this.indexOptions = @ref.IndexOptions; this.docValueType = @ref.DocValueType; this.numericType = @ref.NumericType; // Do not copy frozen! } /// <summary> /// Create a new <see cref="FieldType"/> with default properties. /// </summary> public FieldType() { } private void CheckIfFrozen() { if (frozen) { throw new InvalidOperationException("this FieldType is already frozen and cannot be changed"); } } /// <summary> /// Prevents future changes. Note, it is recommended that this is called once /// the <see cref="FieldType"/>'s properties have been set, to prevent unintentional state /// changes. /// </summary> public virtual void Freeze() { this.frozen = true; } /// <summary> /// Set to <c>true</c> to index (invert) this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool IsIndexed { get { return this.indexed; } set { CheckIfFrozen(); this.indexed = value; } } /// <summary> /// Set to <c>true</c> to store this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool IsStored { get { return this.stored; } set { CheckIfFrozen(); this.stored = value; } } /// <summary> /// Set to <c>true</c> to tokenize this field's contents via the /// configured <see cref="Analysis.Analyzer"/>. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool IsTokenized { get { return this.tokenized; } set { CheckIfFrozen(); this.tokenized = value; } } /// <summary> /// Set to <c>true</c> if this field's indexed form should be also stored /// into term vectors. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectors { get { return this.storeTermVectors; } set { CheckIfFrozen(); this.storeTermVectors = value; } } /// <summary> /// Set to <c>true</c> to also store token character offsets into the term /// vector for this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectorOffsets { get { return this.storeTermVectorOffsets; } set { CheckIfFrozen(); this.storeTermVectorOffsets = value; } } /// <summary> /// Set to <c>true</c> to also store token positions into the term /// vector for this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectorPositions { get { return this.storeTermVectorPositions; } set { CheckIfFrozen(); this.storeTermVectorPositions = value; } } /// <summary> /// Set to <c>true</c> to also store token payloads into the term /// vector for this field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool StoreTermVectorPayloads { get { return this.storeTermVectorPayloads; } set { CheckIfFrozen(); this.storeTermVectorPayloads = value; } } /// <summary> /// Set to <c>true</c> to omit normalization values for the field. The default is <c>false</c>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual bool OmitNorms { get { return this.omitNorms; } set { CheckIfFrozen(); this.omitNorms = value; } } /// <summary> /// Sets the indexing options for the field. /// <para/> /// The default is <see cref="IndexOptions.DOCS_AND_FREQS_AND_POSITIONS"/>. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual IndexOptions IndexOptions { get { return this.indexOptions; } set { CheckIfFrozen(); this.indexOptions = value; } } /// <summary> /// Specifies the field's numeric type, or set to <c>null</c> if the field has no numeric type. /// If non-null then the field's value will be indexed numerically so that /// <see cref="Search.NumericRangeQuery"/> can be used at search time. /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual NumericType NumericType { get { return this.numericType; } set { CheckIfFrozen(); numericType = value; } } /// <summary> /// Sets the numeric precision step for the field. /// <para/> /// This has no effect if <see cref="NumericType"/> returns <see cref="NumericType.NONE"/>. /// <para/> /// The default is <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/>. /// </summary> /// <exception cref="ArgumentException"> if precisionStep is less than 1. </exception> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual int NumericPrecisionStep { get { return numericPrecisionStep; } set { CheckIfFrozen(); if (value < 1) { throw new System.ArgumentException("precisionStep must be >= 1 (got " + value + ")"); } this.numericPrecisionStep = value; } } /// <summary> /// Prints a <see cref="FieldType"/> for human consumption. </summary> public override sealed string ToString() { var result = new StringBuilder(); if (IsStored) { result.Append("stored"); } if (IsIndexed) { if (result.Length > 0) { result.Append(","); } result.Append("indexed"); if (IsTokenized) { result.Append(",tokenized"); } if (StoreTermVectors) { result.Append(",termVector"); } if (StoreTermVectorOffsets) { result.Append(",termVectorOffsets"); } if (StoreTermVectorPositions) { result.Append(",termVectorPosition"); if (StoreTermVectorPayloads) { result.Append(",termVectorPayloads"); } } if (OmitNorms) { result.Append(",omitNorms"); } if (indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) { result.Append(",indexOptions="); // LUCENENET: duplcate what would happen if you print a null indexOptions in Java result.Append(indexOptions != IndexOptions.NONE ? indexOptions.ToString() : string.Empty); } if (numericType != NumericType.NONE) { result.Append(",numericType="); result.Append(numericType); result.Append(",numericPrecisionStep="); result.Append(numericPrecisionStep); } } if (docValueType != DocValuesType.NONE) { if (result.Length > 0) { result.Append(","); } result.Append("docValueType="); result.Append(docValueType); } return result.ToString(); } /// <summary> /// Sets the field's <see cref="DocValuesType"/>, or set to <see cref="DocValuesType.NONE"/> if no <see cref="DocValues"/> should be stored. /// <para/> /// The default is <see cref="DocValuesType.NONE"/> (no <see cref="DocValues"/>). /// </summary> /// <exception cref="InvalidOperationException"> if this <see cref="FieldType"/> is frozen against /// future modifications. </exception> public virtual DocValuesType DocValueType { get { return docValueType; } set { CheckIfFrozen(); docValueType = value; } } } /// <summary> /// Data type of the numeric value /// @since 3.2 /// </summary> public enum NumericType { /// <summary> /// No numeric type will be used. /// <para/> /// NOTE: This is the same as setting to <c>null</c> in Lucene /// </summary> // LUCENENET specific NONE, /// <summary> /// 32-bit integer numeric type /// <para/> /// NOTE: This was INT in Lucene /// </summary> INT32, /// <summary> /// 64-bit long numeric type /// <para/> /// NOTE: This was LONG in Lucene /// </summary> INT64, /// <summary> /// 32-bit float numeric type /// <para/> /// NOTE: This was FLOAT in Lucene /// </summary> SINGLE, /// <summary> /// 64-bit double numeric type </summary> DOUBLE } }
// <copyright file="ComplexTest.TextHandling.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Globalization; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.ComplexTests { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// Complex text handling tests /// </summary> [TestFixture] public class ComplexTextHandlingTest { /// <summary> /// Can parse string to complex with a culture. /// </summary> /// <param name="text">Text to parse.</param> /// <param name="expectedReal">Expected real part.</param> /// <param name="expectedImaginary">Expected imaginary part.</param> /// <param name="cultureName">Culture ID.</param> [TestCase("-1 -2i", -1, -2, "en-US")] //[TestCase("-1 - 2i ", -1, -2, "de-CH")] Windows 8.1 issue, see http://bit.ly/W81deCH public void CanParseStringToComplexWithCulture(string text, double expectedReal, double expectedImaginary, string cultureName) { var parsed = text.ToComplex(new CultureInfo(cultureName)); Assert.AreEqual(expectedReal, parsed.Real); Assert.AreEqual(expectedImaginary, parsed.Imaginary); } /// <summary> /// Can try parse string to complex with invariant. /// </summary> /// <param name="str">String to parse.</param> /// <param name="expectedReal">Expected real part.</param> /// <param name="expectedImaginary">Expected imaginary part.</param> [TestCase("1", 1, 0)] [TestCase("-1", -1, 0)] [TestCase("-i", 0, -1)] [TestCase("i", 0, 1)] [TestCase("2i", 0, 2)] [TestCase("1 + 2i", 1, 2)] [TestCase("1+2i", 1, 2)] [TestCase("1 - 2i", 1, -2)] [TestCase("1-2i", 1, -2)] [TestCase("1,2 ", 1, 2)] [TestCase("1 , 2", 1, 2)] [TestCase("1,2i", 1, 2)] [TestCase("-1, -2i", -1, -2)] [TestCase(" - 1 , - 2 i ", -1, -2)] [TestCase("(+1,2i)", 1, 2)] [TestCase("(-1 , -2)", -1, -2)] [TestCase("(-1 , -2i)", -1, -2)] [TestCase("(+1e1 , -2e-2i)", 10, -0.02)] [TestCase("(-1E1 -2e2i)", -10, -200)] [TestCase("(-1e+1 -2e2i)", -10, -200)] [TestCase("(-1e1 -2e+2i)", -10, -200)] [TestCase("(-1e-1 -2E2i)", -0.1, -200)] [TestCase("(-1e1 -2e-2i)", -10, -0.02)] [TestCase("(-1E+1 -2e+2i)", -10, -200)] [TestCase("(-1e-1,-2e-2i)", -0.1, -0.02)] [TestCase("(+1 +2i)", 1, 2)] [TestCase("(-1E+1 -2e+2i)", -10, -200)] [TestCase("(-1e-1,-2e-2i)", -0.1, -0.02)] public void CanTryParseStringToComplexWithInvariant(string str, double expectedReal, double expectedImaginary) { var invariantCulture = CultureInfo.InvariantCulture; Complex z; var ret = str.TryToComplex(invariantCulture, out z); Assert.IsTrue(ret); Assert.AreEqual(expectedReal, z.Real); Assert.AreEqual(expectedImaginary, z.Imaginary); } /// <summary> /// If missing closing paren parse throws <c>FormatException</c>. /// </summary> [Test] public void IfMissingClosingParenParseThrowsFormatException() { Assert.That(() => "(1,2".ToComplex(), Throws.TypeOf<FormatException>()); } /// <summary> /// Try parse can handle symbols. /// </summary> [Test] public void TryParseCanHandleSymbols() { Complex z; var ni = NumberFormatInfo.CurrentInfo; var separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator; var symbol = ni.NegativeInfinitySymbol + separator + ni.PositiveInfinitySymbol; var ret = symbol.TryToComplex(out z); Assert.IsTrue(ret, "A1"); Assert.AreEqual(double.NegativeInfinity, z.Real, "A2"); Assert.AreEqual(double.PositiveInfinity, z.Imaginary, "A3"); symbol = ni.NaNSymbol + separator + ni.NaNSymbol; ret = symbol.TryToComplex(out z); Assert.IsTrue(ret, "B1"); Assert.AreEqual(double.NaN, z.Real, "B2"); Assert.AreEqual(double.NaN, z.Imaginary, "B3"); symbol = ni.NegativeInfinitySymbol + "+" + ni.PositiveInfinitySymbol + "i"; ret = symbol.TryToComplex(out z); Assert.IsTrue(ret, "C1"); Assert.AreEqual(double.NegativeInfinity, z.Real, "C2"); Assert.AreEqual(double.PositiveInfinity, z.Imaginary, "C3"); symbol = ni.NaNSymbol + "+" + ni.NaNSymbol + "i"; ret = symbol.TryToComplex(out z); Assert.IsTrue(ret, "D1"); Assert.AreEqual(double.NaN, z.Real, "D2"); Assert.AreEqual(double.NaN, z.Imaginary, "D3"); symbol = double.MaxValue.ToString("R") + " " + double.MinValue.ToString("R") + "i"; ret = symbol.TryToComplex(out z); Assert.IsTrue(ret, "E1"); Assert.AreEqual(double.MaxValue, z.Real, "E2"); Assert.AreEqual(double.MinValue, z.Imaginary, "E3"); } #if !PORTABLE /// <summary> /// Try parse can handle symbols with a culture. /// </summary> /// <param name="cultureName">Culture ID.</param> [TestCase("en-US")] [TestCase("tr-TR")] [TestCase("de-DE")] [TestCase("de-CH")] //[TestCase("he-IL")] Mono 4 Issue public void TryParseCanHandleSymbolsWithCulture(string cultureName) { Complex z; var culture = new CultureInfo(cultureName); var ni = culture.NumberFormat; var separator = culture.TextInfo.ListSeparator; var symbol = ni.NegativeInfinitySymbol + separator + ni.PositiveInfinitySymbol; var ret = symbol.TryToComplex(culture, out z); Assert.IsTrue(ret, "A1"); Assert.AreEqual(double.NegativeInfinity, z.Real, "A2"); Assert.AreEqual(double.PositiveInfinity, z.Imaginary, "A3"); symbol = ni.NaNSymbol + separator + ni.NaNSymbol; ret = symbol.TryToComplex(culture, out z); Assert.IsTrue(ret, "B1"); Assert.AreEqual(double.NaN, z.Real, "B2"); Assert.AreEqual(double.NaN, z.Imaginary, "B3"); symbol = ni.NegativeInfinitySymbol + "+" + ni.PositiveInfinitySymbol + "i"; ret = symbol.TryToComplex(culture, out z); Assert.IsTrue(ret, "C1"); Assert.AreEqual(double.NegativeInfinity, z.Real, "C2"); Assert.AreEqual(double.PositiveInfinity, z.Imaginary, "C3"); symbol = ni.NaNSymbol + "+" + ni.NaNSymbol + "i"; ret = symbol.TryToComplex(culture, out z); Assert.IsTrue(ret, "D1"); Assert.AreEqual(double.NaN, z.Real, "D2"); Assert.AreEqual(double.NaN, z.Imaginary, "D3"); symbol = double.MaxValue.ToString("R", culture) + " " + double.MinValue.ToString("R", culture) + "i"; ret = symbol.TryToComplex(culture, out z); Assert.IsTrue(ret, "E1"); Assert.AreEqual(double.MaxValue, z.Real, "E2"); Assert.AreEqual(double.MinValue, z.Imaginary, "E3"); } #endif /// <summary> /// Try parse returns <c>false</c> when given bad value with invariant. /// </summary> /// <param name="str">String to parse.</param> [TestCase("")] [TestCase("+")] [TestCase("1-")] [TestCase("i+")] [TestCase("1/2i")] [TestCase("1i+2i")] [TestCase("i1i")] [TestCase("(1i,2)")] [TestCase("1e+")] [TestCase("1e")] [TestCase("1,")] [TestCase(",1")] [TestCase(null)] [TestCase("()")] [TestCase("( )")] public void TryParseReturnsFalseWhenGivenBadValueWithInvariant(string str) { Complex z; var ret = str.TryToComplex(CultureInfo.InvariantCulture, out z); Assert.IsFalse(ret); Assert.AreEqual(0, z.Real); Assert.AreEqual(0, z.Imaginary); } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // A spin lock is a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop ("spins") // repeatedly checking until the lock becomes available. As the thread remains active performing a non-useful task, // the use of such a lock is a kind of busy waiting and consumes CPU resources without performing real work. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading { /// <summary> /// Provides a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop /// repeatedly checking until the lock becomes available. /// </summary> /// <remarks> /// <para> /// Spin locks can be used for leaf-level locks where the object allocation implied by using a <see /// cref="System.Threading.Monitor"/>, in size or due to garbage collection pressure, is overly /// expensive. Avoiding blocking is another reason that a spin lock can be useful, however if you expect /// any significant amount of blocking, you are probably best not using spin locks due to excessive /// spinning. Spinning can be beneficial when locks are fine grained and large in number (for example, a /// lock per node in a linked list) as well as when lock hold times are always extremely short. In /// general, while holding a spin lock, one should avoid blocking, calling anything that itself may /// block, holding more than one spin lock at once, making dynamically dispatched calls (interface and /// virtuals), making statically dispatched calls into any code one doesn't own, or allocating memory. /// </para> /// <para> /// <see cref="SpinLock"/> should only be used when it's been determined that doing so will improve an /// application's performance. It's also important to note that <see cref="SpinLock"/> is a value type, /// for performance reasons. As such, one must be very careful not to accidentally copy a SpinLock /// instance, as the two instances (the original and the copy) would then be completely independent of /// one another, which would likely lead to erroneous behavior of the application. If a SpinLock instance /// must be passed around, it should be passed by reference rather than by value. /// </para> /// <para> /// Do not store <see cref="SpinLock"/> instances in readonly fields. /// </para> /// <para> /// All members of <see cref="SpinLock"/> are thread-safe and may be used from multiple threads /// concurrently. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(SystemThreading_SpinLockDebugView))] [DebuggerDisplay("IsHeld = {IsHeld}")] public struct SpinLock { // The current ownership state is a single signed int. There are two modes: // // 1) Ownership tracking enabled: the high bit is 0, and the remaining bits // store the managed thread ID of the current owner. When the 31 low bits // are 0, the lock is available. // 2) Performance mode: when the high bit is 1, lock availability is indicated by the low bit. // When the low bit is 1 -- the lock is held; 0 -- the lock is available. // // There are several masks and constants below for convenience. private volatile int _owner; // After how many yields, call Sleep(1) private const int SLEEP_ONE_FREQUENCY = 40; // After how many yields, check the timeout private const int TIMEOUT_CHECK_FREQUENCY = 10; // Thr thread tracking disabled mask private const int LOCK_ID_DISABLE_MASK = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000 // the lock is held by some thread, but we don't know which private const int LOCK_ANONYMOUS_OWNED = 0x1; // 0000 0000 0000 0000 0000 0000 0000 0001 // Waiters mask if the thread tracking is disabled private const int WAITERS_MASK = ~(LOCK_ID_DISABLE_MASK | 1); // 0111 1111 1111 1111 1111 1111 1111 1110 // The Thread tacking is disabled and the lock bit is set, used in Enter fast path to make sure the id is disabled and lock is available private const int ID_DISABLED_AND_ANONYMOUS_OWNED = unchecked((int)0x80000001); // 1000 0000 0000 0000 0000 0000 0000 0001 // If the thread is unowned if: // m_owner zero and the thread tracking is enabled // m_owner & LOCK_ANONYMOUS_OWNED = zero and the thread tracking is disabled private const int LOCK_UNOWNED = 0; // The maximum number of waiters (only used if the thread tracking is disabled) // The actual maximum waiters count is this number divided by two because each waiter increments the waiters count by 2 // The waiters count is calculated by m_owner & WAITERS_MASK 01111....110 private const int MAXIMUM_WAITERS = WAITERS_MASK; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CompareExchange(ref int location, int value, int comparand, ref bool success) { int result = Interlocked.CompareExchange(ref location, value, comparand); success = (result == comparand); return result; } /// <summary> /// Initializes a new instance of the <see cref="System.Threading.SpinLock"/> /// structure with the option to track thread IDs to improve debugging. /// </summary> /// <remarks> /// The default constructor for <see cref="SpinLock"/> tracks thread ownership. /// </remarks> /// <param name="enableThreadOwnerTracking">Whether to capture and use thread IDs for debugging /// purposes.</param> public SpinLock(bool enableThreadOwnerTracking) { _owner = LOCK_UNOWNED; if (!enableThreadOwnerTracking) { _owner |= LOCK_ID_DISABLE_MASK; Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now"); } } /// <summary> /// Initializes a new instance of the <see cref="System.Threading.SpinLock"/> /// structure with the option to track thread IDs to improve debugging. /// </summary> /// <remarks> /// The default constructor for <see cref="SpinLock"/> tracks thread ownership. /// </remarks> /// <summary> /// Acquires the lock in a reliable manner, such that even if an exception occurs within the method /// call, <paramref name="lockTaken"/> can be examined reliably to determine whether the lock was /// acquired. /// </summary> /// <remarks> /// <see cref="SpinLock"/> is a non-reentrant lock, meaning that if a thread holds the lock, it is /// not allowed to enter the lock again. If thread ownership tracking is enabled (whether it's /// enabled is available through <see cref="IsThreadOwnerTrackingEnabled"/>), an exception will be /// thrown when a thread tries to re-enter a lock it already holds. However, if thread ownership /// tracking is disabled, attempting to enter a lock already held will result in deadlock. /// </remarks> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling Enter. /// </exception> public void Enter(ref bool lockTaken) { // Try to keep the code and branching in this method as small as possible in order to inline the method int observedOwner = _owner; if (lockTaken || // invalid parameter (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed ContinueTryEnter(Timeout.Infinite, ref lockTaken); // Then try the slow path if any of the above conditions is met } /// <summary> /// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within /// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the /// lock was acquired. /// </summary> /// <remarks> /// Unlike <see cref="Enter"/>, TryEnter will not block waiting for the lock to be available. If the /// lock is not available when TryEnter is called, it will return immediately without any further /// spinning. /// </remarks> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter. /// </exception> public void TryEnter(ref bool lockTaken) { int observedOwner = _owner; if (((observedOwner & LOCK_ID_DISABLE_MASK) == 0) | lockTaken) { // Thread tracking enabled or invalid arg. Take slow path. ContinueTryEnter(0, ref lockTaken); } else if ((observedOwner & LOCK_ANONYMOUS_OWNED) != 0) { // Lock already held by someone lockTaken = false; } else { // Lock wasn't held; try to acquire it. CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken); } } /// <summary> /// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within /// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the /// lock was acquired. /// </summary> /// <remarks> /// Unlike <see cref="Enter"/>, TryEnter will not block indefinitely waiting for the lock to be /// available. It will block until either the lock is available or until the <paramref /// name="timeout"/> /// has expired. /// </remarks> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="int.MaxValue"/> milliseconds. /// </exception> public void TryEnter(TimeSpan timeout, ref bool lockTaken) { // Validate the timeout long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SpinLock_TryEnter_ArgumentOutOfRange); } // Call reliable enter with the int-based timeout milliseconds TryEnter((int)timeout.TotalMilliseconds, ref lockTaken); } /// <summary> /// Attempts to acquire the lock in a reliable manner, such that even if an exception occurs within /// the method call, <paramref name="lockTaken"/> can be examined reliably to determine whether the /// lock was acquired. /// </summary> /// <remarks> /// Unlike <see cref="Enter"/>, TryEnter will not block indefinitely waiting for the lock to be /// available. It will block until either the lock is available or until the <paramref /// name="millisecondsTimeout"/> has expired. /// </remarks> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param> /// <param name="lockTaken">True if the lock is acquired; otherwise, false. <paramref /// name="lockTaken"/> must be initialized to false prior to calling this method.</param> /// <exception cref="System.Threading.LockRecursionException"> /// Thread ownership tracking is enabled, and the current thread has already acquired this lock. /// </exception> /// <exception cref="System.ArgumentException"> /// The <paramref name="lockTaken"/> argument must be initialized to false prior to calling TryEnter. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is /// a negative number other than -1, which represents an infinite time-out.</exception> public void TryEnter(int millisecondsTimeout, ref bool lockTaken) { int observedOwner = _owner; if (millisecondsTimeout < -1 || // invalid parameter lockTaken || // invalid parameter (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed ContinueTryEnter(millisecondsTimeout, ref lockTaken); // The call the slow pth } /// <summary> /// Try acquire the lock with long path, this is usually called after the first path in Enter and /// TryEnter failed The reason for short path is to make it inline in the run time which improves the /// performance. This method assumed that the parameter are validated in Enter or TryEnter method. /// </summary> /// <param name="millisecondsTimeout">The timeout milliseconds</param> /// <param name="lockTaken">The lockTaken param</param> private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken) { // The fast path doesn't throw any exception, so we have to validate the parameters here if (lockTaken) { lockTaken = false; throw new ArgumentException(SR.SpinLock_TryReliableEnter_ArgumentException); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinLock_TryEnter_ArgumentOutOfRange); } uint startTime = 0; if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout != 0) { startTime = TimeoutHelper.GetTime(); } if (IsThreadOwnerTrackingEnabled) { // Slow path for enabled thread tracking mode ContinueTryEnterWithThreadTracking(millisecondsTimeout, startTime, ref lockTaken); return; } // then thread tracking is disabled // In this case there are three ways to acquire the lock // 1- the first way the thread either tries to get the lock if it's free or updates the waiters, if the turn >= the processors count then go to 3 else go to 2 // 2- In this step the waiter threads spins and tries to acquire the lock, the number of spin iterations and spin count is dependent on the thread turn // the late the thread arrives the more it spins and less frequent it check the lock availability // Also the spins count is increases each iteration // If the spins iterations finished and failed to acquire the lock, go to step 3 // 3- This is the yielding step, there are two ways of yielding Thread.Yield and Sleep(1) // If the timeout is expired in after step 1, we need to decrement the waiters count before returning int observedOwner; int turn = int.MaxValue; // ***Step 1, take the lock or update the waiters // try to acquire the lock directly if possible or update the waiters count observedOwner = _owner; if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) { if (CompareExchange(ref _owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner) { // Acquired lock return; } if (millisecondsTimeout == 0) { // Did not acquire lock in CompareExchange and timeout is 0 so fail fast return; } } else if (millisecondsTimeout == 0) { // Did not acquire lock as owned and timeout is 0 so fail fast return; } else // failed to acquire the lock, then try to update the waiters. If the waiters count reached the maximum, just break the loop to avoid overflow { if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS) { // This can still overflow, but maybe there will never be that many waiters turn = (Interlocked.Add(ref _owner, 2) & WAITERS_MASK) >> 1; } } // lock acquired failed and waiters updated // *** Step 2, Spinning and Yielding var spinner = new SpinWait(); if (turn > Environment.ProcessorCount) { spinner.Count = SpinWait.YieldThreshold; } while (true) { spinner.SpinOnce(SLEEP_ONE_FREQUENCY); observedOwner = _owner; if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) { int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero observedOwner | 1 // don't decrement it. just set the lock bit, it is zero because a previous call of Exit(false) which corrupted the waiters : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit Debug.Assert((newOwner & WAITERS_MASK) >= 0); if (CompareExchange(ref _owner, newOwner, observedOwner, ref lockTaken) == observedOwner) { return; } } if (spinner.Count % TIMEOUT_CHECK_FREQUENCY == 0) { // Check the timeout. if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0) { DecrementWaiters(); return; } } } } /// <summary> /// decrements the waiters, in case of the timeout is expired /// </summary> private void DecrementWaiters() { SpinWait spinner = new SpinWait(); while (true) { int observedOwner = _owner; if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false) if (Interlocked.CompareExchange(ref _owner, observedOwner - 2, observedOwner) == observedOwner) { Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped break; } spinner.SpinOnce(); } } /// <summary> /// ContinueTryEnter for the thread tracking mode enabled /// </summary> private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken) { Debug.Assert(IsThreadOwnerTrackingEnabled); const int LockUnowned = 0; // We are using thread IDs to mark ownership. Snap the thread ID and check for recursion. // We also must or the ID enablement bit, to ensure we propagate when we CAS it in. int newOwner = Environment.CurrentManagedThreadId; if (_owner == newOwner) { // We don't allow lock recursion. throw new LockRecursionException(SR.SpinLock_TryEnter_LockRecursionException); } SpinWait spinner = new SpinWait(); // Loop until the lock has been successfully acquired or, if specified, the timeout expires. while (true) { // We failed to get the lock, either from the fast route or the last iteration // and the timeout hasn't expired; spin once and try again. spinner.SpinOnce(); // Test before trying to CAS, to avoid acquiring the line exclusively unnecessarily. if (_owner == LockUnowned) { if (CompareExchange(ref _owner, newOwner, LockUnowned, ref lockTaken) == LockUnowned) { return; } } // Check the timeout. We only RDTSC if the next spin will yield, to amortize the cost. if (millisecondsTimeout == 0 || (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)) { return; } } } /// <summary> /// Releases the lock. /// </summary> /// <remarks> /// The default overload of <see cref="Exit()"/> provides the same behavior as if calling <see /// cref="Exit(bool)"/> using true as the argument, but Exit() could be slightly faster than Exit(true). /// </remarks> /// <exception cref="SynchronizationLockException"> /// Thread ownership tracking is enabled, and the current thread is not the owner of this lock. /// </exception> public void Exit() { // This is the fast path for the thread tracking is disabled, otherwise go to the slow path if ((_owner & LOCK_ID_DISABLE_MASK) == 0) ExitSlowPath(true); else Interlocked.Decrement(ref _owner); } /// <summary> /// Releases the lock. /// </summary> /// <param name="useMemoryBarrier"> /// A Boolean value that indicates whether a memory fence should be issued in order to immediately /// publish the exit operation to other threads. /// </param> /// <remarks> /// Calling <see cref="Exit(bool)"/> with the <paramref name="useMemoryBarrier"/> argument set to /// true will improve the fairness of the lock at the expense of some performance. The default <see /// cref="Enter"/> /// overload behaves as if specifying true for <paramref name="useMemoryBarrier"/>. /// </remarks> /// <exception cref="SynchronizationLockException"> /// Thread ownership tracking is enabled, and the current thread is not the owner of this lock. /// </exception> public void Exit(bool useMemoryBarrier) { // This is the fast path for the thread tracking is disabled and not to use memory barrier, otherwise go to the slow path // The reason not to add else statement if the usememorybarrier is that it will add more branching in the code and will prevent // method inlining, so this is optimized for useMemoryBarrier=false and Exit() overload optimized for useMemoryBarrier=true. int tmpOwner = _owner; if ((tmpOwner & LOCK_ID_DISABLE_MASK) != 0 & !useMemoryBarrier) { _owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); } else { ExitSlowPath(useMemoryBarrier); } } /// <summary> /// The slow path for exit method if the fast path failed /// </summary> /// <param name="useMemoryBarrier"> /// A Boolean value that indicates whether a memory fence should be issued in order to immediately /// publish the exit operation to other threads /// </param> private void ExitSlowPath(bool useMemoryBarrier) { bool threadTrackingEnabled = (_owner & LOCK_ID_DISABLE_MASK) == 0; if (threadTrackingEnabled && !IsHeldByCurrentThread) { throw new SynchronizationLockException(SR.SpinLock_Exit_SynchronizationLockException); } if (useMemoryBarrier) { if (threadTrackingEnabled) { Interlocked.Exchange(ref _owner, LOCK_UNOWNED); } else { Interlocked.Decrement(ref _owner); } } else { if (threadTrackingEnabled) { _owner = LOCK_UNOWNED; } else { int tmpOwner = _owner; _owner = tmpOwner & (~LOCK_ANONYMOUS_OWNED); } } } /// <summary> /// Gets whether the lock is currently held by any thread. /// </summary> public bool IsHeld { get { if (IsThreadOwnerTrackingEnabled) return _owner != LOCK_UNOWNED; return (_owner & LOCK_ANONYMOUS_OWNED) != LOCK_UNOWNED; } } /// <summary> /// Gets whether the lock is currently held by any thread. /// </summary> /// <summary> /// Gets whether the lock is held by the current thread. /// </summary> /// <remarks> /// If the lock was initialized to track owner threads, this will return whether the lock is acquired /// by the current thread. It is invalid to use this property when the lock was initialized to not /// track thread ownership. /// </remarks> /// <exception cref="System.InvalidOperationException"> /// Thread ownership tracking is disabled. /// </exception> public bool IsHeldByCurrentThread { get { if (!IsThreadOwnerTrackingEnabled) { throw new InvalidOperationException(SR.SpinLock_IsHeldByCurrentThread); } return (_owner & (~LOCK_ID_DISABLE_MASK)) == Environment.CurrentManagedThreadId; } } /// <summary>Gets whether thread ownership tracking is enabled for this instance.</summary> public bool IsThreadOwnerTrackingEnabled => (_owner & LOCK_ID_DISABLE_MASK) == 0; #region Debugger proxy class /// <summary> /// Internal class used by debug type proxy attribute to display the owner thread ID /// </summary> internal class SystemThreading_SpinLockDebugView { // SpinLock object private SpinLock _spinLock; /// <summary> /// SystemThreading_SpinLockDebugView constructor /// </summary> /// <param name="spinLock">The SpinLock to be proxied.</param> public SystemThreading_SpinLockDebugView(SpinLock spinLock) { // Note that this makes a copy of the SpinLock (struct). It doesn't hold a reference to it. _spinLock = spinLock; } /// <summary> /// Checks if the lock is held by the current thread or not /// </summary> public bool? IsHeldByCurrentThread { get { try { return _spinLock.IsHeldByCurrentThread; } catch (InvalidOperationException) { return null; } } } /// <summary> /// Gets the current owner thread, zero if it is released /// </summary> public int? OwnerThreadID { get { if (_spinLock.IsThreadOwnerTrackingEnabled) { return _spinLock._owner; } else { return null; } } } /// <summary> /// Gets whether the lock is currently held by any thread or not. /// </summary> public bool IsHeld => _spinLock.IsHeld; } #endregion } } #pragma warning restore 0420
// Copyright (C) 2014 dot42 // // Original filename: Java.Beans.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Java.Beans { /// <summary> /// <para>A type of PropertyChangeEvent that indicates that an indexed property has changed. </para> /// </summary> /// <java-name> /// java/beans/IndexedPropertyChangeEvent /// </java-name> [Dot42.DexImport("java/beans/IndexedPropertyChangeEvent", AccessFlags = 33)] public partial class IndexedPropertyChangeEvent : global::Java.Beans.PropertyChangeEvent /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new property changed event with an indication of the property index.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;I)V", AccessFlags = 1)] public IndexedPropertyChangeEvent(object source, string propertyName, object oldValue, object newValue, int index) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the index of the property that was changed in this event. </para> /// </summary> /// <java-name> /// getIndex /// </java-name> [Dot42.DexImport("getIndex", "()I", AccessFlags = 1)] public virtual int GetIndex() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal IndexedPropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the index of the property that was changed in this event. </para> /// </summary> /// <java-name> /// getIndex /// </java-name> public int Index { [Dot42.DexImport("getIndex", "()I", AccessFlags = 1)] get{ return GetIndex(); } } } /// <summary> /// <para>Manages a list of listeners to be notified when a property changes. Listeners subscribe to be notified of all property changes, or of changes to a single named property.</para><para>This class is thread safe. No locking is necessary when subscribing or unsubscribing listeners, or when publishing events. Callers should be careful when publishing events because listeners may not be thread safe. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeSupport /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeSupport", AccessFlags = 33)] public partial class PropertyChangeSupport : global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new instance that uses the source bean as source for any event.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;)V", AccessFlags = 1)] public PropertyChangeSupport(object sourceBean) /* MethodBuilder.Create */ { } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, object @object, object object1) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;ILjava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, object @object, object object1) /* MethodBuilder.Create */ { } /// <summary> /// <para>Unsubscribes <c> listener </c> from change notifications for the property named <c> propertyName </c> . If multiple subscriptions exist for <c> listener </c> , it will receive one fewer notifications when the property changes. If the property name or listener is null or not subscribed, this method silently does nothing. </para> /// </summary> /// <java-name> /// removePropertyChangeListener /// </java-name> [Dot42.DexImport("removePropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 33)] public virtual void RemovePropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Subscribes <c> listener </c> to change notifications for the property named <c> propertyName </c> . If the listener is already subscribed, it will receive an additional notification when the property changes. If the property name or listener is null, this method silently does nothing. </para> /// </summary> /// <java-name> /// addPropertyChangeListener /// </java-name> [Dot42.DexImport("addPropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 33)] public virtual void AddPropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the subscribers to be notified when <c> propertyName </c> changes. This includes both listeners subscribed to all property changes and listeners subscribed to the named property only. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> [Dot42.DexImport("getPropertyChangeListeners", "(Ljava/lang/String;)[Ljava/beans/PropertyChangeListener;", AccessFlags = 33)] public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners(string propertyName) /* MethodBuilder.Create */ { return default(global::Java.Beans.IPropertyChangeListener[]); } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;ZZ)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;IZZ)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, bool boolean, bool boolean1) /* MethodBuilder.Create */ { } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;II)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, int int32, int int321) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;III)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, int int321, int int322) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if there are listeners registered to the property with the given name.</para><para></para> /// </summary> /// <returns> /// <para>true if there are listeners registered to that property, false otherwise. </para> /// </returns> /// <java-name> /// hasListeners /// </java-name> [Dot42.DexImport("hasListeners", "(Ljava/lang/String;)Z", AccessFlags = 33)] public virtual bool HasListeners(string propertyName) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Unsubscribes <c> listener </c> from change notifications for all properties. If the listener has multiple subscriptions, it will receive one fewer notification when properties change. If the property name or listener is null or not subscribed, this method silently does nothing. </para> /// </summary> /// <java-name> /// removePropertyChangeListener /// </java-name> [Dot42.DexImport("removePropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 33)] public virtual void RemovePropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Subscribes <c> listener </c> to change notifications for all properties. If the listener is already subscribed, it will receive an additional notification. If the listener is null, this method silently does nothing. </para> /// </summary> /// <java-name> /// addPropertyChangeListener /// </java-name> [Dot42.DexImport("addPropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 33)] public virtual void AddPropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> [Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 33)] public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners() /* MethodBuilder.Create */ { return default(global::Java.Beans.IPropertyChangeListener[]); } /// <summary> /// <para>Publishes a property change event to all listeners of that property. If the event's old and new values are equal (but non-null), no event will be published. </para> /// </summary> /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)] public virtual void FirePropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeSupport() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> public global::Java.Beans.IPropertyChangeListener[] PropertyChangeListeners { [Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 33)] get{ return GetPropertyChangeListeners(); } } } /// <summary> /// <para>A PropertyChangeListener can subscribe with a event source. Whenever that source raises a PropertyChangeEvent this listener will get notified. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeListener /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeListener", AccessFlags = 1537)] public partial interface IPropertyChangeListener : global::Java.Util.IEventListener /* scope: __dot42__ */ { /// <summary> /// <para>The source bean calls this method when an event is raised.</para><para></para> /// </summary> /// <java-name> /// propertyChange /// </java-name> [Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1025)] void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ ; } /// <summary> /// <para>An event that indicates that a constraint or a boundary of a property has changed. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeEvent /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeEvent", AccessFlags = 33)] public partial class PropertyChangeEvent : global::Java.Util.EventObject /* scope: __dot42__ */ { /// <summary> /// <para>The constructor used to create a new <c> PropertyChangeEvent </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public PropertyChangeEvent(object source, string propertyName, object oldValue, object newValue) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para> /// </summary> /// <returns> /// <para>the name of the property that has changed, or null. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPropertyName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the propagationId object.</para><para><para>getPropagationId() </para></para> /// </summary> /// <java-name> /// setPropagationId /// </java-name> [Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void SetPropagationId(object propagationId) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para> /// </summary> /// <returns> /// <para>the propagationId object. </para> /// </returns> /// <java-name> /// getPropagationId /// </java-name> [Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetPropagationId() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getOldValue /// </java-name> [Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetOldValue() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getNewValue /// </java-name> [Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetNewValue() /* MethodBuilder.Create */ { return default(object); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para> /// </summary> /// <returns> /// <para>the name of the property that has changed, or null. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> public string PropertyName { [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPropertyName(); } } /// <summary> /// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para> /// </summary> /// <returns> /// <para>the propagationId object. </para> /// </returns> /// <java-name> /// getPropagationId /// </java-name> public object PropagationId { [Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetPropagationId(); } [Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)] set{ SetPropagationId(value); } } /// <summary> /// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getOldValue /// </java-name> public object OldValue { [Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetOldValue(); } } /// <summary> /// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getNewValue /// </java-name> public object NewValue { [Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetNewValue(); } } } /// <summary> /// <para>The implementation of this listener proxy just delegates the received events to its listener. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeListenerProxy /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeListenerProxy", AccessFlags = 33)] public partial class PropertyChangeListenerProxy : global::Java.Util.EventListenerProxy, global::Java.Beans.IPropertyChangeListener /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new listener proxy that associates a listener with a property name.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public PropertyChangeListenerProxy(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name of the property associated with this listener proxy.</para><para></para> /// </summary> /// <returns> /// <para>the name of the associated property. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPropertyName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>The source bean calls this method when an event is raised.</para><para></para> /// </summary> /// <java-name> /// propertyChange /// </java-name> [Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)] public virtual void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeListenerProxy() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name of the property associated with this listener proxy.</para><para></para> /// </summary> /// <returns> /// <para>the name of the associated property. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> public string PropertyName { [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPropertyName(); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Preview.Wireless; namespace Twilio.Tests.Rest.Preview.Wireless { [TestFixture] public class RatePlanTest : TwilioTest { [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Preview, "/wireless/RatePlans", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RatePlanResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"first_page_url\": \"https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0\",\"key\": \"rate_plans\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0\"},\"rate_plans\": []}" )); var response = RatePlanResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"first_page_url\": \"https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0\",\"key\": \"rate_plans\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://preview.twilio.com/wireless/RatePlans?PageSize=50&Page=0\"},\"rate_plans\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"unique_name\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"pooled\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"friendly_name\": \"friendly_name\",\"messaging_enabled\": true,\"voice_enabled\": true,\"national_roaming_enabled\": true,\"international_roaming\": [\"data\",\"messaging\",\"voice\"],\"sid\": \"WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}" )); var response = RatePlanResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Preview, "/wireless/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RatePlanResource.Fetch("WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"unique_name\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"pooled\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"friendly_name\": \"friendly_name\",\"messaging_enabled\": true,\"voice_enabled\": true,\"national_roaming_enabled\": true,\"international_roaming\": [\"data\",\"messaging\",\"voice\"],\"sid\": \"WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RatePlanResource.Fetch("WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Preview, "/wireless/RatePlans", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RatePlanResource.Create(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"unique_name\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"pooled\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"friendly_name\": \"friendly_name\",\"messaging_enabled\": true,\"voice_enabled\": true,\"national_roaming_enabled\": true,\"international_roaming\": [\"data\",\"messaging\",\"voice\"],\"sid\": \"WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RatePlanResource.Create(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Preview, "/wireless/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RatePlanResource.Update("WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"unique_name\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"pooled\",\"date_created\": \"2015-07-30T20:00:00Z\",\"date_updated\": \"2015-07-30T20:00:00Z\",\"friendly_name\": \"friendly_name\",\"messaging_enabled\": true,\"voice_enabled\": true,\"national_roaming_enabled\": true,\"international_roaming\": [\"data\",\"messaging\",\"voice\"],\"sid\": \"WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://preview.twilio.com/wireless/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RatePlanResource.Update("WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Preview, "/wireless/RatePlans/WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RatePlanResource.Delete("WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = RatePlanResource.Delete("WPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } } }
/* * 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.Reflection; using System.Text; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Assets; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Agent.TextureSender { public class J2KDecoderModule : IRegionModule, IJ2KDecoder { #region IRegionModule Members private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Cached Decoded Layers /// </summary> private readonly Dictionary<UUID, OpenJPEG.J2KLayerInfo[]> m_cacheddecode = new Dictionary<UUID, OpenJPEG.J2KLayerInfo[]>(); private bool OpenJpegFail = false; private readonly string CacheFolder = Util.dataDir() + "/j2kDecodeCache"; private readonly J2KDecodeFileCache fCache; /// <summary> /// List of client methods to notify of results of decode /// </summary> private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>(); public J2KDecoderModule() { fCache = new J2KDecodeFileCache(CacheFolder); } public void Initialise(Scene scene, IConfigSource source) { scene.RegisterModuleInterface<IJ2KDecoder>(this); } public void PostInitialise() { } public void Close() { } public string Name { get { return "J2KDecoderModule"; } } public bool IsSharedModule { get { return true; } } #endregion #region IJ2KDecoder Members public void decode(UUID AssetId, byte[] assetData, DecodedCallback decodedReturn) { // Dummy for if decoding fails. OpenJPEG.J2KLayerInfo[] result = new OpenJPEG.J2KLayerInfo[0]; // Check if it's cached bool cached = false; lock (m_cacheddecode) { if (m_cacheddecode.ContainsKey(AssetId)) { cached = true; result = m_cacheddecode[AssetId]; } } // If it's cached, return the cached results if (cached) { decodedReturn(AssetId, result); } else { // not cached, so we need to decode it // Add to notify list and start decoding. // Next request for this asset while it's decoding will only be added to the notify list // once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated bool decode = false; lock (m_notifyList) { if (m_notifyList.ContainsKey(AssetId)) { m_notifyList[AssetId].Add(decodedReturn); } else { List<DecodedCallback> notifylist = new List<DecodedCallback>(); notifylist.Add(decodedReturn); m_notifyList.Add(AssetId, notifylist); decode = true; } } // Do Decode! if (decode) { doJ2kDecode(AssetId, assetData); } } } /// <summary> /// Provides a synchronous decode so that caller can be assured that this executes before the next line /// </summary> /// <param name="AssetId"></param> /// <param name="j2kdata"></param> public void syncdecode(UUID AssetId, byte[] j2kdata) { doJ2kDecode(AssetId, j2kdata); } #endregion /// <summary> /// Decode Jpeg2000 Asset Data /// </summary> /// <param name="AssetId">UUID of Asset</param> /// <param name="j2kdata">Byte Array Asset Data </param> private void doJ2kDecode(UUID AssetId, byte[] j2kdata) { int DecodeTime = 0; DecodeTime = Environment.TickCount; OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[0]; // Dummy result for if it fails. Informs that there's only full quality if (!OpenJpegFail) { if (!fCache.TryLoadCacheForAsset(AssetId, out layers)) { try { AssetTexture texture = new AssetTexture(AssetId, j2kdata); if (texture.DecodeLayerBoundaries()) { bool sane = true; // Sanity check all of the layers for (int i = 0; i < texture.LayerInfo.Length; i++) { if (texture.LayerInfo[i].End > texture.AssetData.Length) { sane = false; break; } } if (sane) { layers = texture.LayerInfo; fCache.SaveFileCacheForAsset(AssetId, layers); // Write out decode time m_log.InfoFormat("[J2KDecoderModule]: {0} Decode Time: {1}", Environment.TickCount - DecodeTime, AssetId); } else { m_log.WarnFormat( "[J2KDecoderModule]: JPEG2000 texture decoding succeeded, but sanity check failed for {0}", AssetId); } } else { /* Random rnd = new Random(); // scramble ends for test for (int i = 0; i < texture.LayerInfo.Length; i++) { texture.LayerInfo[i].End = rnd.Next(999999); } */ // Try to do some heuristics error correction! Yeah. bool sane2Heuristics = true; if (texture.Image == null) sane2Heuristics = false; if (texture.LayerInfo == null) sane2Heuristics = false; if (sane2Heuristics) { if (texture.LayerInfo.Length == 0) sane2Heuristics = false; } if (sane2Heuristics) { // Last layer start is less then the end of the file and last layer start is greater then 0 if (texture.LayerInfo[texture.LayerInfo.Length - 1].Start < texture.AssetData.Length && texture.LayerInfo[texture.LayerInfo.Length - 1].Start > 0) { } else { sane2Heuristics = false; } } if (sane2Heuristics) { int start = 0; // try to fix it by using consistant data in the start field for (int i = 0; i < texture.LayerInfo.Length; i++) { if (i == 0) start = 0; if (i == texture.LayerInfo.Length - 1) texture.LayerInfo[i].End = texture.AssetData.Length; else texture.LayerInfo[i].End = texture.LayerInfo[i + 1].Start - 1; // in this case, the end of the next packet is less then the start of the last packet // after we've attempted to fix it which means the start of the last packet is borked // there's no recovery from this if (texture.LayerInfo[i].End < start) { sane2Heuristics = false; break; } if (texture.LayerInfo[i].End < 0 || texture.LayerInfo[i].End > texture.AssetData.Length) { sane2Heuristics = false; break; } if (texture.LayerInfo[i].Start < 0 || texture.LayerInfo[i].Start > texture.AssetData.Length) { sane2Heuristics = false; break; } start = texture.LayerInfo[i].Start; } } if (sane2Heuristics) { layers = texture.LayerInfo; fCache.SaveFileCacheForAsset(AssetId, layers); // Write out decode time m_log.InfoFormat("[J2KDecoderModule]: HEURISTICS SUCCEEDED {0} Decode Time: {1}", Environment.TickCount - DecodeTime, AssetId); } else { m_log.WarnFormat("[J2KDecoderModule]: JPEG2000 texture decoding failed for {0}. Is this a texture? is it J2K?", AssetId); } } texture = null; // dereference and dispose of ManagedImage } catch (DllNotFoundException) { m_log.Error( "[J2KDecoderModule]: OpenJpeg is not installed properly. Decoding disabled! This will slow down texture performance! Often times this is because of an old version of GLIBC. You must have version 2.4 or above!"); OpenJpegFail = true; } catch (Exception ex) { m_log.WarnFormat( "[J2KDecoderModule]: JPEG2000 texture decoding threw an exception for {0}, {1}", AssetId, ex); } } } // Cache Decoded layers lock (m_cacheddecode) { if (!m_cacheddecode.ContainsKey(AssetId)) m_cacheddecode.Add(AssetId, layers); } // Notify Interested Parties lock (m_notifyList) { if (m_notifyList.ContainsKey(AssetId)) { foreach (DecodedCallback d in m_notifyList[AssetId]) { if (d != null) d.DynamicInvoke(AssetId, layers); } m_notifyList.Remove(AssetId); } } } } public class J2KDecodeFileCache { private readonly string m_cacheDecodeFolder; private bool enabled = true; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Creates a new instance of a file cache /// </summary> /// <param name="pFolder">base folder for the cache. Will be created if it doesn't exist</param> public J2KDecodeFileCache(string pFolder) { m_cacheDecodeFolder = pFolder; if (!Directory.Exists(pFolder)) { Createj2KCacheFolder(pFolder); } } /// <summary> /// Save Layers to Disk Cache /// </summary> /// <param name="AssetId">Asset to Save the layers. Used int he file name by default</param> /// <param name="Layers">The Layer Data from OpenJpeg</param> /// <returns></returns> public bool SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers) { if (Layers.Length > 0 && enabled) { FileStream fsCache = new FileStream(String.Format("{0}/{1}", m_cacheDecodeFolder, FileNameFromAssetId(AssetId)), FileMode.Create); StreamWriter fsSWCache = new StreamWriter(fsCache); StringBuilder stringResult = new StringBuilder(); string strEnd = "\n"; for (int i = 0; i < Layers.Length; i++) { if (i == (Layers.Length - 1)) strEnd = ""; stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); } fsSWCache.Write(stringResult.ToString()); fsSWCache.Close(); fsSWCache.Dispose(); fsCache.Dispose(); return true; } return false; } /// <summary> /// Loads the Layer data from the disk cache /// Returns true if load succeeded /// </summary> /// <param name="AssetId">AssetId that we're checking the cache for</param> /// <param name="Layers">out layers to save to</param> /// <returns>true if load succeeded</returns> public bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers) { string filename = String.Format("{0}/{1}", m_cacheDecodeFolder, FileNameFromAssetId(AssetId)); Layers = new OpenJPEG.J2KLayerInfo[0]; if (!File.Exists(filename)) return false; if (!enabled) { return false; } string readResult = string.Empty; try { FileStream fsCachefile = new FileStream(filename, FileMode.Open); StreamReader sr = new StreamReader(fsCachefile); readResult = sr.ReadToEnd(); sr.Close(); sr.Dispose(); fsCachefile.Dispose(); } catch (IOException ioe) { if (ioe is PathTooLongException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. Path is too long."); } else if (ioe is DirectoryNotFoundException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. Cache Directory does not exist!"); enabled = false; } else { m_log.Error( "[J2KDecodeCache]: Cache Read failed. IO Exception."); } return false; } catch (UnauthorizedAccessException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. UnauthorizedAccessException Exception. Do you have the proper permissions on this file?"); return false; } catch (ArgumentException ae) { if (ae is ArgumentNullException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. No Filename provided"); } else { m_log.Error( "[J2KDecodeCache]: Cache Read failed. Filname was invalid"); } return false; } catch (NotSupportedException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed, not supported. Cache disabled!"); enabled = false; return false; } catch (Exception e) { m_log.ErrorFormat( "[J2KDecodeCache]: Cache Read failed, unknown exception. Error: {0}", e.ToString()); return false; } string[] lines = readResult.Split('\n'); if (lines.Length <= 0) return false; Layers = new OpenJPEG.J2KLayerInfo[lines.Length]; for (int i = 0; i < lines.Length; i++) { string[] elements = lines[i].Split('|'); if (elements.Length == 3) { int element1, element2; try { element1 = Convert.ToInt32(elements[0]); element2 = Convert.ToInt32(elements[1]); } catch (FormatException) { m_log.WarnFormat("[J2KDecodeCache]: Cache Read failed with ErrorConvert for {0}", AssetId); Layers = new OpenJPEG.J2KLayerInfo[0]; return false; } Layers[i] = new OpenJPEG.J2KLayerInfo(); Layers[i].Start = element1; Layers[i].End = element2; } else { // reading failed m_log.WarnFormat("[J2KDecodeCache]: Cache Read failed for {0}", AssetId); Layers = new OpenJPEG.J2KLayerInfo[0]; return false; } } return true; } /// <summary> /// Routine which converts assetid to file name /// </summary> /// <param name="AssetId">asset id of the image</param> /// <returns>string filename</returns> public string FileNameFromAssetId(UUID AssetId) { return String.Format("j2kCache_{0}.cache", AssetId); } /// <summary> /// Creates the Cache Folder /// </summary> /// <param name="pFolder">Folder to Create</param> public void Createj2KCacheFolder(string pFolder) { try { Directory.CreateDirectory(pFolder); } catch (IOException ioe) { if (ioe is PathTooLongException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because the path to the cache folder is too long. Cache disabled!"); } else if (ioe is DirectoryNotFoundException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because the supplied base of the directory folder does not exist. Cache disabled!"); } else { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an IO Exception. Cache disabled!"); } enabled = false; } catch (UnauthorizedAccessException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an UnauthorizedAccessException Exception. Cache disabled!"); enabled = false; } catch (ArgumentException ae) { if (ae is ArgumentNullException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because the folder provided is invalid! Cache disabled!"); } else { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because no cache folder was provided! Cache disabled!"); } enabled = false; } catch (NotSupportedException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because it's not supported. Cache disabled!"); enabled = false; } catch (Exception e) { m_log.ErrorFormat( "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an unknown exception. Cache disabled! Error: {0}", e.ToString()); enabled = false; } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ namespace Multiverse.Tools.WorldEditor { partial class AddParticleFXDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.particleEffectComboBox = new System.Windows.Forms.ComboBox(); this.particleEffectComboBoxLabel = new System.Windows.Forms.Label(); this.velocityScaleTextBox = new System.Windows.Forms.TextBox(); this.positionScaleTextBox = new System.Windows.Forms.TextBox(); this.velocityScaleLabel = new System.Windows.Forms.Label(); this.positionScaleLabel = new System.Windows.Forms.Label(); this.okbutton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.helpButton = new System.Windows.Forms.Button(); this.attachmentPointLabel = new System.Windows.Forms.Label(); this.attachmentPointComboBox = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // particleEffectComboBox // this.particleEffectComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.particleEffectComboBox.FormattingEnabled = true; this.particleEffectComboBox.Location = new System.Drawing.Point(129, 13); this.particleEffectComboBox.Name = "particleEffectComboBox"; this.particleEffectComboBox.Size = new System.Drawing.Size(182, 21); this.particleEffectComboBox.TabIndex = 1; // // particleEffectComboBoxLabel // this.particleEffectComboBoxLabel.AutoSize = true; this.particleEffectComboBoxLabel.Location = new System.Drawing.Point(12, 16); this.particleEffectComboBoxLabel.Name = "particleEffectComboBoxLabel"; this.particleEffectComboBoxLabel.Size = new System.Drawing.Size(76, 13); this.particleEffectComboBoxLabel.TabIndex = 0; this.particleEffectComboBoxLabel.Text = "Particle Effect:"; // // velocityScaleTextBox // this.velocityScaleTextBox.Location = new System.Drawing.Point(129, 41); this.velocityScaleTextBox.Name = "velocityScaleTextBox"; this.velocityScaleTextBox.Size = new System.Drawing.Size(182, 20); this.velocityScaleTextBox.TabIndex = 3; this.velocityScaleTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floatVerifyevent); // // positionScaleTextBox // this.positionScaleTextBox.Location = new System.Drawing.Point(129, 67); this.positionScaleTextBox.Name = "positionScaleTextBox"; this.positionScaleTextBox.Size = new System.Drawing.Size(182, 20); this.positionScaleTextBox.TabIndex = 5; this.positionScaleTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floatVerifyevent); // // velocityScaleLabel // this.velocityScaleLabel.AutoSize = true; this.velocityScaleLabel.Location = new System.Drawing.Point(12, 44); this.velocityScaleLabel.Name = "velocityScaleLabel"; this.velocityScaleLabel.Size = new System.Drawing.Size(77, 13); this.velocityScaleLabel.TabIndex = 2; this.velocityScaleLabel.Text = "Velocity Scale:"; // // positionScaleLabel // this.positionScaleLabel.AutoSize = true; this.positionScaleLabel.Location = new System.Drawing.Point(12, 70); this.positionScaleLabel.Name = "positionScaleLabel"; this.positionScaleLabel.Size = new System.Drawing.Size(75, 13); this.positionScaleLabel.TabIndex = 4; this.positionScaleLabel.Text = "Particle Scale:"; // // okbutton // this.okbutton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okbutton.Location = new System.Drawing.Point(13, 129); this.okbutton.Name = "okbutton"; this.okbutton.Size = new System.Drawing.Size(75, 23); this.okbutton.TabIndex = 8; this.okbutton.Text = "Add"; this.okbutton.UseVisualStyleBackColor = true; // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(234, 129); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 10; this.cancelButton.Text = "&Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // helpButton // this.helpButton.Location = new System.Drawing.Point(153, 129); this.helpButton.Name = "helpButton"; this.helpButton.Size = new System.Drawing.Size(75, 23); this.helpButton.TabIndex = 9; this.helpButton.Tag = "Particle_Effect"; this.helpButton.Text = "Help"; this.helpButton.UseVisualStyleBackColor = true; this.helpButton.Click += new System.EventHandler(this.helpButton_clicked); // // attachmentPointLabel // this.attachmentPointLabel.AutoSize = true; this.attachmentPointLabel.Location = new System.Drawing.Point(12, 96); this.attachmentPointLabel.Name = "attachmentPointLabel"; this.attachmentPointLabel.Size = new System.Drawing.Size(91, 13); this.attachmentPointLabel.TabIndex = 6; this.attachmentPointLabel.Text = "Attachment Point:"; this.attachmentPointLabel.Visible = false; // // attachmentPointComboBox // this.attachmentPointComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.attachmentPointComboBox.FormattingEnabled = true; this.attachmentPointComboBox.Location = new System.Drawing.Point(129, 93); this.attachmentPointComboBox.Name = "attachmentPointComboBox"; this.attachmentPointComboBox.Size = new System.Drawing.Size(182, 21); this.attachmentPointComboBox.TabIndex = 7; this.attachmentPointComboBox.Visible = false; // // AddParticleFXDialog // this.AcceptButton = this.okbutton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(327, 164); this.Controls.Add(this.attachmentPointComboBox); this.Controls.Add(this.attachmentPointLabel); this.Controls.Add(this.helpButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okbutton); this.Controls.Add(this.positionScaleLabel); this.Controls.Add(this.velocityScaleLabel); this.Controls.Add(this.positionScaleTextBox); this.Controls.Add(this.velocityScaleTextBox); this.Controls.Add(this.particleEffectComboBoxLabel); this.Controls.Add(this.particleEffectComboBox); this.Name = "AddParticleFXDialog"; this.ShowInTaskbar = false; this.Text = "Add Particle Effects"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox particleEffectComboBox; private System.Windows.Forms.Label particleEffectComboBoxLabel; private System.Windows.Forms.TextBox velocityScaleTextBox; private System.Windows.Forms.TextBox positionScaleTextBox; private System.Windows.Forms.Label velocityScaleLabel; private System.Windows.Forms.Label positionScaleLabel; private System.Windows.Forms.Button okbutton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button helpButton; private System.Windows.Forms.Label attachmentPointLabel; private System.Windows.Forms.ComboBox attachmentPointComboBox; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // /*============================================================================= ** ** ** ** Purpose: Base class for representing Events ** ** =============================================================================*/ namespace System.Security.AccessControl { internal class EventWaitHandleSecurity { } internal enum EventWaitHandleRights { } } namespace System.Threading { using System; using System.Threading; using System.Runtime.CompilerServices; using System.IO; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.AccessControl; [ComVisibleAttribute(true)] public class EventWaitHandle : WaitHandle { private const uint AccessRights = (uint)Win32Native.MAXIMUM_ALLOWED | Win32Native.SYNCHRONIZE | Win32Native.EVENT_MODIFY_STATE; public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState, mode, null) { } public EventWaitHandle(bool initialState, EventResetMode mode, string name) { if (name != null) { #if PLATFORM_UNIX throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); #else if (System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } #endif } uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0; switch (mode) { case EventResetMode.ManualReset: eventFlags |= Win32Native.CREATE_EVENT_MANUAL_RESET; break; case EventResetMode.AutoReset: break; default: throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name)); }; SafeWaitHandle _handle = Win32Native.CreateEventEx(null, name, eventFlags, AccessRights); if (_handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); _handle.SetHandleAsInvalid(); if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); } SetHandleInternal(_handle); } public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew) : this(initialState, mode, name, out createdNew, null) { } internal unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity) { if (name != null) { #if PLATFORM_UNIX throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); #else if (System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } #endif } Win32Native.SECURITY_ATTRIBUTES secAttrs = null; uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0; switch (mode) { case EventResetMode.ManualReset: eventFlags |= Win32Native.CREATE_EVENT_MANUAL_RESET; break; case EventResetMode.AutoReset: break; default: throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name)); }; SafeWaitHandle _handle = Win32Native.CreateEventEx(secAttrs, name, eventFlags, AccessRights); int errorCode = Marshal.GetLastWin32Error(); if (_handle.IsInvalid) { _handle.SetHandleAsInvalid(); if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); } createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS; SetHandleInternal(_handle); } private EventWaitHandle(SafeWaitHandle handle) { SetHandleInternal(handle); } public static EventWaitHandle OpenExisting(string name) { return OpenExisting(name, (EventWaitHandleRights)0); } internal static EventWaitHandle OpenExisting(string name, EventWaitHandleRights rights) { EventWaitHandle result; switch (OpenExistingWorker(name, rights, out result)) { case OpenExistingResult.NameNotFound: throw new WaitHandleCannotBeOpenedException(); case OpenExistingResult.NameInvalid: throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); case OpenExistingResult.PathNotFound: throw Win32Marshal.GetExceptionForWin32Error(Win32Native.ERROR_PATH_NOT_FOUND, ""); default: return result; } } public static bool TryOpenExisting(string name, out EventWaitHandle result) { return OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success; } private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result) { #if PLATFORM_UNIX throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); #else if (name == null) { throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); } if (null != name && System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } result = null; SafeWaitHandle myHandle = Win32Native.OpenEvent(AccessRights, false, name); if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; //this is for passed through Win32Native Errors throw Win32Marshal.GetExceptionForWin32Error(errorCode, ""); } result = new EventWaitHandle(myHandle); return OpenExistingResult.Success; #endif } public bool Reset() { bool res = Win32Native.ResetEvent(safeWaitHandle); if (!res) throw Win32Marshal.GetExceptionForLastWin32Error(); return res; } public bool Set() { bool res = Win32Native.SetEvent(safeWaitHandle); if (!res) throw Win32Marshal.GetExceptionForLastWin32Error(); return res; } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Linq; using System.Reflection; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace Aurora.Modules.Chat { /// <summary> /// This dialog module has support for mute lists /// </summary> public class AuroraDialogModule : INonSharedRegionModule, IDialogModule { protected bool m_enabled = true; protected IMuteListModule m_muteListModule; protected IScene m_scene; public bool IsSharedModule { get { return false; } } #region IDialogModule Members public void SendAlertToUser(IClientAPI client, string message) { SendAlertToUser(client, message, false); } public void SendAlertToUser(IClientAPI client, string message, bool modal) { client.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(UUID agentID, string message) { SendAlertToUser(agentID, message, false); } public void SendAlertToUser(UUID agentID, string message, bool modal) { IScenePresence sp = m_scene.GetScenePresence(agentID); if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(string firstName, string lastName, string message, bool modal) { IScenePresence presence = m_scene.SceneGraph.GetScenePresence(firstName, lastName); if (presence != null && !presence.IsChildAgent) presence.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendGeneralAlert(string message) { m_scene.ForEachScenePresence(delegate(IScenePresence presence) { if (!presence.IsChildAgent) presence.ControllingClient.SendAlertMessage(message); }); } public void SendDialogToUser( UUID avatarID, string objectName, UUID objectID, UUID ownerID, string message, UUID textureID, int ch, string[] buttonlabels) { UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerID); string ownerFirstName, ownerLastName; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } //If the user is muted, we do NOT send them dialog boxes if (m_muteListModule != null) { bool cached = false; //Unneeded #if (!ISWIN) foreach (MuteList mute in m_muteListModule.GetMutes(avatarID, out cached)) { if (mute.MuteID == ownerID) { return; } } #else if (m_muteListModule.GetMutes(avatarID, out cached).Any(mute => mute.MuteID == ownerID)) { return; } #endif } IScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendDialog(objectName, objectID, ownerID, ownerFirstName, ownerLastName, message, textureID, ch, buttonlabels); } public void SendUrlToUser( UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { IScenePresence sp = m_scene.GetScenePresence(avatarID); //If the user is muted, do NOT send them URL boxes if (m_muteListModule != null) { bool cached = false; //Unneeded #if (!ISWIN) foreach (MuteList mute in m_muteListModule.GetMutes(avatarID, out cached)) { if (mute.MuteID == ownerID) { return; } } #else if (m_muteListModule.GetMutes(avatarID, out cached).Any(mute => mute.MuteID == ownerID)) { return; } #endif } if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); } public void SendTextBoxToUser(UUID avatarID, string message, int chatChannel, string name, UUID objectID, UUID ownerID) { IScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null && !sp.IsChildAgent) { UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerID); string ownerFirstName, ownerLastName; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; } else { if (name != "") { ownerFirstName = name; ownerLastName = ""; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } } //If the user is muted, do not send the text box if (m_muteListModule != null) { bool cached = false; //Unneeded #if (!ISWIN) foreach (MuteList mute in m_muteListModule.GetMutes(avatarID, out cached)) { if (mute.MuteID == ownerID) { return; } } #else if (m_muteListModule.GetMutes(avatarID, out cached).Any(mute => mute.MuteID == ownerID)) { return; } #endif } sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName, objectID); } } public void SendNotificationToUsersInRegion( UUID fromAvatarID, string fromAvatarName, string message) { m_scene.ForEachScenePresence(delegate(IScenePresence presence) { if (!presence.IsChildAgent) presence.ControllingClient.SendBlueBoxMessage(fromAvatarID, fromAvatarName, message); }); } #endregion #region INonSharedRegionModule Members public void Initialise(IConfigSource source) { IConfig m_config = source.Configs["Dialog"]; if (null == m_config) { m_enabled = false; return; } if (m_config.GetString("DialogModule", "DialogModule") != "AuroraDialogModule") { m_enabled = false; } } public void AddRegion(IScene scene) { if (!m_enabled) return; m_scene = scene; m_scene.RegisterModuleInterface<IDialogModule>(this); m_scene.EventManager.OnPermissionError += SendAlertToUser; if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand( "alert", "alert [first] [last] [message]", "Send an alert to a user", HandleAlertConsoleCommand); MainConsole.Instance.Commands.AddCommand( "alert general", "alert general [message]", "Send an alert to everyone", HandleAlertConsoleCommand); } } public void RemoveRegion(IScene scene) { } public void RegionLoaded(IScene scene) { m_muteListModule = m_scene.RequestModuleInterface<IMuteListModule>(); } public Type ReplaceableInterface { get { return null; } } public void Close() { } public string Name { get { return "Dialog Module"; } } #endregion public void PostInitialise() { } /// <summary> /// Handle an alert command from the console. /// </summary> /// <param name = "module"></param> /// <param name = "cmdparams"></param> public void HandleAlertConsoleCommand(string[] cmdparams) { if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene == null) return; if (cmdparams[1] == "general") { string message = Util.CombineParams(cmdparams, 2); MainConsole.Instance.InfoFormat( "[DIALOG]: Sending general alert in region {0} with message {1}", m_scene.RegionInfo.RegionName, message); SendGeneralAlert(message); } else { string firstName = cmdparams[1]; string lastName = cmdparams[2]; string message = Util.CombineParams(cmdparams, 3); MainConsole.Instance.InfoFormat( "[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}", m_scene.RegionInfo.RegionName, firstName, lastName, message); SendAlertToUser(firstName, lastName, message, false); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Llvm.NET.DebugInfo; using Llvm.NET.Types; using Llvm.NET.Values; namespace Llvm.NET { /// <summary>LLVM Bit code module</summary> /// <remarks> /// A module is the basic unit for containing code in LLVM. Modules are an in memory /// representation of the LLVM bit-code. /// </remarks> public sealed class NativeModule : IDisposable , IExtensiblePropertyContainer { internal NativeModule( LLVMModuleRef handle ) { ModuleHandle = handle; DIBuilder_ = new Lazy<DebugInfoBuilder>( ( ) => new DebugInfoBuilder( this ) ); Context.AddModule( this ); } /// <summary>Creates an unnamed module without debug information</summary> public NativeModule( ) : this( string.Empty, null ) { } /// <summary>Creates a new module with the specified id in a new context</summary> /// <param name="moduleId">Module's ID</param> public NativeModule( string moduleId ) : this( moduleId, null ) { } /// <summary>Creates an named module in a given context</summary> /// <param name="moduleId">Module's ID</param> /// <param name="context">Context for the module</param> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Reliability", "CA2000:Dispose objects before losing scope" )] public NativeModule( string moduleId, Context context ) { if( moduleId == null ) moduleId = string.Empty; if( context == null ) { context = new Context( ); OwnsContext = true; } ModuleHandle = NativeMethods.ModuleCreateWithNameInContext( moduleId, context.ContextHandle ); if( ModuleHandle.Pointer == IntPtr.Zero ) throw new InternalCodeGeneratorException( "Could not create module in context" ); DIBuilder_ = new Lazy<DebugInfoBuilder>( ( ) => new DebugInfoBuilder( this ) ); Context.AddModule( this ); } /// <summary>Creates a named module with a root <see cref="DICompileUnit"/> to contain debugging information</summary> /// <param name="moduleId">Module name</param> /// <param name="language">Language to store in the debugging information</param> /// <param name="srcFilePath">path of source file to set for the compilation unit</param> /// <param name="producer">Name of the application producing this module</param> /// <param name="optimized">Flag to indicate if the module is optimized</param> /// <param name="flags">Additional flags</param> /// <param name="runtimeVersion">Runtime version if any (use 0 if the runtime version has no meaning)</param> public NativeModule( string moduleId , SourceLanguage language , string srcFilePath , string producer , bool optimized = false , string flags = "" , uint runtimeVersion = 0 ) : this( moduleId , null , language , srcFilePath , producer , optimized , flags , runtimeVersion ) { } /// <summary>Creates a named module with a root <see cref="DICompileUnit"/> to contain debugging information</summary> /// <param name="moduleId">Module name</param> /// <param name="context">Context for the module</param> /// <param name="language">Language to store in the debugging information</param> /// <param name="srcFilePath">path of source file to set for the compilation unit</param> /// <param name="producer">Name of the application producing this module</param> /// <param name="optimized">Flag to indicate if the module is optimized</param> /// <param name="compilationFlags">Additional flags</param> /// <param name="runtimeVersion">Runtime version if any (use 0 if the runtime version has no meaning)</param> public NativeModule( string moduleId , Context context , SourceLanguage language , string srcFilePath , string producer , bool optimized = false , string compilationFlags = "" , uint runtimeVersion = 0 ) : this( moduleId, context ) { DICompileUnit = DIBuilder.CreateCompileUnit( language , srcFilePath , producer , optimized , compilationFlags , runtimeVersion ); } #region IDisposable Pattern public void Dispose( ) { Dispose( true ); GC.SuppressFinalize( this ); } ~NativeModule( ) { Dispose( false ); } void Dispose( bool disposing ) { // if not already disposed, dispose the module // Do this only on dispose. The containing context // will clean up the module when it is disposed or // finalized. Since finalization order isn't // deterministic it is possible that the module is // finalized after the context has already run its // finalizer, which would cause an access violation // in the native LLVM layer. if( disposing && ModuleHandle.Pointer != IntPtr.Zero ) { // if this module created the context then just dispose // the context as that will clean up the module as well. if( OwnsContext ) Context.Dispose( ); else NativeMethods.DisposeModule( ModuleHandle ); ModuleHandle = default( LLVMModuleRef ); } } #endregion /// <summary>Name of the Debug Version information module flag</summary> public const string DebugVersionValue = "Debug Info Version"; /// <summary>Name of the Dwarf Version module flag</summary> public const string DwarfVersionValue = "Dwarf Version"; /// <summary>Version of the Debug information Metadata</summary> public const UInt32 DebugMetadataVersion = 3; /* DEBUG_METADATA_VERSION (for LLVM v3.7.0) */ /// <summary><see cref="Context"/> this module belongs to</summary> public Context Context { get { if( ModuleHandle.Pointer == IntPtr.Zero ) return null; return Context.GetContextFor( ModuleHandle ); } } /// <summary><see cref="DebugInfoBuilder"/> to create debug information for this module</summary> public DebugInfoBuilder DIBuilder => DIBuilder_.Value; /// <summary>Debug Compile unit for this module</summary> public DICompileUnit DICompileUnit { get; internal set; } /// <summary>Data layout string</summary> /// <remarks> /// Note the data layout string doesn't do what seems obvious. /// That is, it doesn't force the target back-end to generate code /// or types with a particular layout. Rather, the layout string has /// to match the implicit layout of the target. The layout string /// provides hints to the optimization passes about the target at /// the expense of making the bit code and front-end a bit target /// dependent. /// </remarks> public string DataLayoutString { get { return Layout?.ToString( ) ?? string.Empty; } set { Layout = DataLayout.Parse( Context, value ); } } /// <summary>Target data layout for this module</summary> /// <remarks>The layout is produced by parsing the <see cref="DataLayoutString"/> /// therefore this property changes anytime the <see cref="DataLayoutString"/> is /// set. Furthermore, setting this property will change the value of <see cref="DataLayoutString"/>. /// In other words, Layout and <see cref="DataLayoutString"/> are two different views /// of the same information and setting either one updates the other. /// </remarks> public DataLayout Layout { get { return Layout_; } set { if( Layout_ != null ) Layout_.Dispose( ); Layout_ = value; NativeMethods.SetDataLayout( ModuleHandle, value?.ToString( ) ?? string.Empty ); } } private DataLayout Layout_; /// <summary>Target Triple describing the target, ABI and OS</summary> public string TargetTriple { get { var ptr = NativeMethods.GetTarget( ModuleHandle ); return NativeMethods.NormalizeLineEndings( ptr ); } set { NativeMethods.SetTarget( ModuleHandle, value ); } } /// <summary>Globals contained by this module</summary> public IEnumerable<Value> Globals { get { var current = NativeMethods.GetFirstGlobal( ModuleHandle ); while( current.Pointer != IntPtr.Zero ) { yield return Value.FromHandle( current ); current = NativeMethods.GetNextGlobal( current ); } } } /// <summary>Enumerable collection of functions contained in this module</summary> public IEnumerable<Function> Functions { get { var current = NativeMethods.GetFirstFunction( ModuleHandle ); while( current.Pointer != IntPtr.Zero ) { yield return Value.FromHandle<Function>( current ); current = NativeMethods.GetNextFunction( current ); } } } // TODO: Add enumerator for GlobalAlias(s) // TODO: Add enumerator for Comdat(s) // TODO: Add enumerator for NamedMDNode(s) /// <summary>Name of the module</summary> public string Name { get { var ptr = NativeMethods.GetModuleName( ModuleHandle ); return NativeMethods.NormalizeLineEndings( ptr ); } } /// <summary>Link another bit-code module into the current module</summary> /// <param name="otherModule">Module to merge into this one</param> /// <param name="linkMode">Linker mode to use when merging</param> public void Link( NativeModule otherModule, LinkerMode linkMode ) { if( otherModule == null ) throw new ArgumentNullException( nameof( otherModule ) ); IntPtr errMsgPtr; if( 0 != NativeMethods.LinkModules( ModuleHandle, otherModule.ModuleHandle, ( LLVMLinkerMode )linkMode, out errMsgPtr ).Value ) { var errMsg = NativeMethods.MarshalMsg( errMsgPtr ); throw new InternalCodeGeneratorException( errMsg ); } } /// <summary>Verifies a bit-code module</summary> /// <param name="errmsg">Error messages describing any issues found in the bit-code</param> /// <returns>true if the verification succeeded and false if not.</returns> public bool Verify( out string errmsg ) { errmsg = null; IntPtr msgPtr; LLVMBool result = NativeMethods.VerifyModule( ModuleHandle, LLVMVerifierFailureAction.LLVMReturnStatusAction, out msgPtr ); if( result.Succeeded ) return true; errmsg = NativeMethods.MarshalMsg( msgPtr ); return false; } /// <summary>Gets a function by name from this module</summary> /// <param name="name">Name of the function to get</param> /// <returns>The function or null if not found</returns> public Function GetFunction( string name ) { var funcRef = NativeMethods.GetNamedFunction( ModuleHandle, name ); if( funcRef.Pointer == IntPtr.Zero ) return null; return Value.FromHandle<Function>( funcRef ); } /// <summary>Add a function with the specified signature to the module</summary> /// <param name="name">Name of the function to add</param> /// <param name="signature">Signature of the function</param> /// <returns><see cref="Function"/>matching the specified signature and name</returns> /// <remarks> /// If a matching function already exists it is returned, and therefore the returned /// <see cref="Function"/> may have a body and additional attributes. If a function of /// the same name exists with a different signature an exception is thrown as LLVM does /// not perform any function overloading. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public Function AddFunction( string name, IFunctionType signature ) { return Value.FromHandle<Function>( NativeMethods.GetOrInsertFunction( ModuleHandle, name, signature.GetTypeRef( ) ) ); } /// <summary>Writes a bit-code module to a file</summary> /// <param name="path">Path to write the bit-code into</param> /// <remarks> /// This is a blind write. (e.g. no verification is performed) /// So if an invalid module is saved it might not work with any /// later stage processing tools. /// </remarks> public void WriteToFile( string path ) { var err = NativeMethods.WriteBitcodeToFile( ModuleHandle, path ); if( err < 0 ) throw new IOException( ); } /// <summary>Writes this module as LLVM IR source to a file</summary> /// <param name="path">File to write the LLVM IR source to</param> /// <param name="errMsg">Error messages encountered, if any</param> /// <returns><see langword="true"/> if successful or <see langword="false"/> if not</returns> public bool WriteToTextFile( string path, out string errMsg ) { errMsg = string.Empty; IntPtr msg; if( NativeMethods.PrintModuleToFile( ModuleHandle, path, out msg ) ) return true; errMsg = NativeMethods.MarshalMsg( msg ); return false; } /// <summary>Creates a string representation of the module</summary> /// <returns>LLVM textual representation of the module</returns> /// <remarks> /// This is intentionally NOT an override of ToString() as that is /// used by debuggers to show the value of a type and this can take /// an extremely long time (up to many seconds depending on complexity /// of the module) which is bad for the debugger. /// </remarks> public string AsString( ) { return NativeMethods.MarshalMsg( NativeMethods.PrintModuleToString( ModuleHandle ) ); } /// <summary>Add an alias to the module</summary> /// <param name="aliasee">Value being aliased</param> /// <param name="aliasName">Name of the alias</param> /// <returns><see cref="GlobalAlias"/> for the alias</returns> public GlobalAlias AddAlias( Value aliasee, string aliasName ) { if( aliasee == null ) throw new ArgumentNullException( nameof( aliasee ) ); var handle = NativeMethods.AddAlias( ModuleHandle, aliasee.NativeType.GetTypeRef( ), aliasee.ValueHandle, aliasName ); return Value.FromHandle<GlobalAlias>( handle ); } /// <summary>Get an alias by name</summary> /// <param name="name">name of the alias to get</param> /// <returns>Alias matching <paramref name="name"/> or null if no such alias exists</returns> public GlobalAlias GetAlias( string name ) { var handle = NativeMethods.GetGlobalAlias( ModuleHandle, name ); return Value.FromHandle<GlobalAlias>( handle ); } /// <summary>Adds a global to this module</summary> /// <param name="typeRef">Type of the global's value</param> /// <param name="name">Name of the global</param> /// <returns>The new <see cref="GlobalVariable"/></returns> /// <openissues> /// - What does LLVM do if creating a second Global with the same name (return null, throw, crash??,...) /// </openissues> public GlobalVariable AddGlobal( ITypeRef typeRef, string name ) { var handle = NativeMethods.AddGlobal( ModuleHandle, typeRef.GetTypeRef( ), name ); return Value.FromHandle<GlobalVariable>( handle ); } /// <summary>Adds a global to this module</summary> /// <param name="typeRef">Type of the global's value</param> /// <param name="isConst">Flag to indicate if this global is a constant</param> /// <param name="linkage">Linkage type for this global</param> /// <param name="constVal">Initial value for the global</param> /// <returns>New global variable</returns> public GlobalVariable AddGlobal( ITypeRef typeRef, bool isConst, Linkage linkage, Constant constVal ) { return AddGlobal( typeRef, isConst, linkage, constVal, string.Empty ); } /// <summary>Adds a global to this module</summary> /// <param name="typeRef">Type of the global's value</param> /// <param name="isConst">Flag to indicate if this global is a constant</param> /// <param name="linkage">Linkage type for this global</param> /// <param name="constVal">Initial value for the global</param> /// <param name="name">Name of the variable</param> /// <returns>New global variable</returns> public GlobalVariable AddGlobal( ITypeRef typeRef, bool isConst, Linkage linkage, Constant constVal, string name ) { var retVal = AddGlobal( typeRef, name ); retVal.IsConstant = isConst; retVal.Linkage = linkage; retVal.Initializer = constVal; return retVal; } /// <summary>Retrieves a <see cref="ITypeRef"/> by name from the module</summary> /// <param name="name">Name of the type</param> /// <returns>The type or null if no type with the specified name exists in the module</returns> public ITypeRef GetTypeByName( string name ) { var hType = NativeMethods.GetTypeByName( ModuleHandle, name ); return hType.Pointer == IntPtr.Zero ? null : TypeRef.FromHandle( hType ); } /// <summary>Retrieves a named global from the module</summary> /// <param name="name"></param> /// <returns></returns> public GlobalVariable GetNamedGlobal( string name ) { var hGlobal = NativeMethods.GetNamedGlobal( ModuleHandle, name ); if( hGlobal.Pointer == IntPtr.Zero ) return null; return Value.FromHandle<GlobalVariable>( hGlobal ); } /// <summary>Adds a module flag to the module</summary> /// <param name="behavior">Module flag behavior for this flag</param> /// <param name="name">Name of the flag</param> /// <param name="value">Value of the flag</param> public void AddModuleFlag( ModuleFlagBehavior behavior, string name, UInt32 value ) { // AddModuleFlag comes from custom LLVMDebug-C API NativeMethods.AddModuleFlag( ModuleHandle, ( LLVMModFlagBehavior )behavior, name, value ); } /// <summary>Adds operand value to named metadata</summary> /// <param name="name">Name of the metadata</param> /// <param name="value">operand value</param> public void AddNamedMetadataOperand( string name, LlvmMetadata value ) { NativeMethods.AddNamedMetadataOperand2( ModuleHandle, name, value?.MetadataHandle ?? LLVMMetadataRef.Zero ); } /// <summary>Adds an llvm.ident metadata string to the module</summary> /// <param name="version">version information to place in the llvm.ident metadata</param> public void AddVersionIdentMetadata( string version ) { var elements = new LLVMMetadataRef[ ] { NativeMethods.MDString2( Context.ContextHandle, version, ( uint )( version?.Length ?? 0 ) ) }; var hNode = NativeMethods.MDNode2( Context.ContextHandle, out elements[ 0 ], 1 ); NativeMethods.AddNamedMetadataOperand2( ModuleHandle, "llvm.ident", hNode ); } /// <summary>Creates a Function definition with Debug information</summary> /// <param name="scope">Containing scope for the function</param> /// <param name="name">Name of the function in source language form</param> /// <param name="linkageName">Mangled linker visible name of the function (may be same as <paramref name="name"/> if mangling not required by source language</param> /// <param name="file">File containing the function definition</param> /// <param name="line">Line number of the function definition</param> /// <param name="signature">LLVM Function type for the signature of the function</param> /// <param name="isLocalToUnit">Flag to indicate if this function is local to the compilation unit</param> /// <param name="isDefinition">Flag to indicate if this is a definition</param> /// <param name="scopeLine">First line of the function's outermost scope, this may not be the same as the first line of the function definition due to source formatting</param> /// <param name="debugFlags">Additional flags describing this function</param> /// <param name="isOptimized">Flag to indicate if this function is optimized</param> /// <param name="tParam"></param> /// <param name="decl"></param> /// <returns>Function described by the arguments</returns> public Function CreateFunction( DIScope scope , string name , string linkageName , DIFile file , uint line , DebugFunctionType signature , bool isLocalToUnit , bool isDefinition , uint scopeLine , DebugInfoFlags debugFlags , bool isOptimized , MDNode tParam = null , MDNode decl = null ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( string.IsNullOrWhiteSpace( name ) ) throw new ArgumentException( "Name cannot be null, empty or whitespace", nameof( name ) ); if( signature == null ) throw new ArgumentNullException( nameof( signature ) ); var func = AddFunction( linkageName ?? name, signature ); var diSignature = signature.DIType; Debug.Assert( diSignature != null ); var diFunc = DIBuilder.CreateFunction( scope: scope , name: name , mangledName: linkageName , file: file , line: line , signatureType: diSignature , isLocalToUnit: isLocalToUnit , isDefinition: isDefinition , scopeLine: scopeLine , debugFlags: debugFlags , isOptimized: isOptimized , function: func , typeParameter: tParam , declaration: decl ); Debug.Assert( diFunc.Describes( func ) ); func.DISubProgram = diFunc; return func; } public Function CreateFunction( string name , bool isVarArg , IDebugType<ITypeRef, DIType> returnType , params IDebugType<ITypeRef, DIType>[] argumentTypes ) { IFunctionType signature = Context.CreateFunctionType( DIBuilder, isVarArg, returnType, argumentTypes ); return AddFunction( name, signature ); } /// <inheritdoc/> bool IExtensiblePropertyContainer.TryGetExtendedPropertyValue<T>( string id, out T value ) { return PropertyBag.TryGetExtendedPropertyValue( id, out value ); } /// <inheritdoc/> void IExtensiblePropertyContainer.AddExtendedPropertyValue( string id, object value ) { PropertyBag.AddExtendedPropertyValue( id, value ); } internal static NativeModule FromHandle( LLVMModuleRef nativeHandle ) { var context = Context.GetContextFor( nativeHandle ); return context.GetModuleFor( nativeHandle ); } /// <summary>Load a bit-code module from a given file</summary> /// <param name="path">path of the file to load</param> /// <param name="context">Context to use for creating the module</param> /// <returns>Loaded <see cref="NativeModule"/></returns> public static NativeModule LoadFrom( string path, Context context ) { if( string.IsNullOrWhiteSpace( path ) ) throw new ArgumentException( "path cannot be null or an empty string", nameof( path ) ); if( context == null ) throw new ArgumentNullException( nameof( context ) ); if( !File.Exists( path ) ) throw new FileNotFoundException( "Specified bit-code file does not exist", path ); using( var buffer = new MemoryBuffer( path ) ) { LLVMModuleRef modRef; IntPtr errMsgPtr; if( NativeMethods.ParseBitcodeInContext( context.ContextHandle, buffer.BufferHandle, out modRef, out errMsgPtr ).Failed ) { var errMsg = NativeMethods.MarshalMsg( errMsgPtr ); throw new InternalCodeGeneratorException( errMsg ); } return context.GetModuleFor( modRef ); } } internal LLVMModuleRef ModuleHandle { get; private set; } private readonly ExtensiblePropertyContainer PropertyBag = new ExtensiblePropertyContainer( ); private readonly Lazy<DebugInfoBuilder> DIBuilder_; private readonly bool OwnsContext; } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Insights { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// TenantEventsOperations operations. /// </summary> internal partial class TenantEventsOperations : Microsoft.Rest.IServiceOperations<InsightsClient>, ITenantEventsOperations { /// <summary> /// Initializes a new instance of the TenantEventsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal TenantEventsOperations(InsightsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the InsightsClient /// </summary> public InsightsClient Client { get; private set; } /// <summary> /// get the Activity Logs for the Tenant. Everything that is applicable to the /// API to get the Activity Log for the subscription is applicable to this API /// (the parameters, $filter, etc.). One thing to point out here is that this /// API does *not* retrieve the logs at the individual subscription of the /// tenant but only surfaces the logs that were generated at the tenant level. /// The **$filter** is very restricted and allows only the following patterns. /// - List events for a resource group: $filter=eventTimestamp ge '&lt;Start /// Time&gt;' and eventTimestamp le '&lt;End Time&gt;' and eventChannels eq /// 'Admin, Operation' and resourceGroupName eq '&lt;ResourceGroupName&gt;'. - /// List events for resource: $filter=eventTimestamp ge '&lt;Start Time&gt;' /// and eventTimestamp le '&lt;End Time&gt;' and eventChannels eq 'Admin, /// Operation' and resourceUri eq '&lt;ResourceURI&gt;'. - List events for a /// subscription: $filter=eventTimestamp ge '&lt;Start Time&gt;' and /// eventTimestamp le '&lt;End Time&gt;' and eventChannels eq 'Admin, /// Operation'. - List evetns for a resource provider: $filter=eventTimestamp /// ge '&lt;Start Time&gt;' and eventTimestamp le '&lt;End Time&gt;' and /// eventChannels eq 'Admin, Operation' and resourceProvider eq /// '&lt;ResourceProviderName&gt;'. - List events for a correlation Id: /// api-version=2014-04-01&amp;$filter=eventTimestamp ge /// '2014-07-16T04:36:37.6407898Z' and eventTimestamp le /// '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and /// correlationId eq '&lt;CorrelationID&gt;'. No other syntax is allowed. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// Used to fetch events with only the given properties. The filter is a comma /// separated list of property names to be returned. Possible values are: /// authorization, channels, claims, correlationId, description, eventDataId, /// eventName, eventTimestamp, httpRequest, level, operationId, operationName, /// properties, resourceGroupName, resourceProviderName, resourceId, status, /// submissionTimestamp, subStatus, subscriptionId /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>> ListWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery<EventData> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<EventData>), string select = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { string apiVersion = "2015-04-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("select", select); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/microsoft.insights/eventtypes/management/values").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<EventData>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// get the Activity Logs for the Tenant. Everything that is applicable to the /// API to get the Activity Log for the subscription is applicable to this API /// (the parameters, $filter, etc.). One thing to point out here is that this /// API does *not* retrieve the logs at the individual subscription of the /// tenant but only surfaces the logs that were generated at the tenant level. /// The **$filter** is very restricted and allows only the following patterns. /// - List events for a resource group: $filter=eventTimestamp ge '&lt;Start /// Time&gt;' and eventTimestamp le '&lt;End Time&gt;' and eventChannels eq /// 'Admin, Operation' and resourceGroupName eq '&lt;ResourceGroupName&gt;'. - /// List events for resource: $filter=eventTimestamp ge '&lt;Start Time&gt;' /// and eventTimestamp le '&lt;End Time&gt;' and eventChannels eq 'Admin, /// Operation' and resourceUri eq '&lt;ResourceURI&gt;'. - List events for a /// subscription: $filter=eventTimestamp ge '&lt;Start Time&gt;' and /// eventTimestamp le '&lt;End Time&gt;' and eventChannels eq 'Admin, /// Operation'. - List evetns for a resource provider: $filter=eventTimestamp /// ge '&lt;Start Time&gt;' and eventTimestamp le '&lt;End Time&gt;' and /// eventChannels eq 'Admin, Operation' and resourceProvider eq /// '&lt;ResourceProviderName&gt;'. - List events for a correlation Id: /// api-version=2014-04-01&amp;$filter=eventTimestamp ge /// '2014-07-16T04:36:37.6407898Z' and eventTimestamp le /// '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and /// correlationId eq '&lt;CorrelationID&gt;'. No other syntax is allowed. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<EventData>>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<EventData>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // ContentDescriptionObject.cs: Provides a representation of an ASF Content // Description object which can be read from and written to disk. // // Author: // Brian Nickel ([email protected]) // // Copyright (C) 2006-2007 Brian Nickel // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; namespace TagLib.Asf { /// <summary> /// This class extends <see cref="Object" /> to provide a /// representation of an ASF Content Description object which can be /// read from and written to disk. /// </summary> public class ContentDescriptionObject : Object { #region Private Fields /// <summary> /// Contains the media title. /// </summary> private string title = string.Empty; /// <summary> /// Contains the author/performer. /// </summary> private string author = string.Empty; /// <summary> /// Contains the copyright information. /// </summary> private string copyright = string.Empty; /// <summary> /// Contains the description of the media. /// </summary> private string description = string.Empty; /// <summary> /// Contains the rating of the media. /// </summary> private string rating = string.Empty; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="ContentDescriptionObject" /> by reading the /// contents from a specified position in a specified file. /// </summary> /// <param name="file"> /// A <see cref="Asf.File" /> object containing the file from /// which the contents of the new instance are to be read. /// </param> /// <param name="position"> /// A <see cref="long" /> value specify at what position to /// read the object. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="position" /> is less than zero or greater /// than the size of the file. /// </exception> /// <exception cref="CorruptFileException"> /// The object read from disk does not have the correct GUID /// or smaller than the minimum size. /// </exception> public ContentDescriptionObject (Asf.File file, long position) : base (file, position) { if (Guid != Asf.Guid.AsfContentDescriptionObject) throw new CorruptFileException ( "Object GUID incorrect."); if (OriginalSize < 34) throw new CorruptFileException ( "Object size too small."); ushort title_length = file.ReadWord (); ushort author_length = file.ReadWord (); ushort copyright_length = file.ReadWord (); ushort description_length = file.ReadWord (); ushort rating_length = file.ReadWord (); title = file.ReadUnicode (title_length); author = file.ReadUnicode (author_length); copyright = file.ReadUnicode (copyright_length); description = file.ReadUnicode (description_length); rating = file.ReadUnicode (rating_length); } /// <summary> /// Constructs and initializes a new instance of <see /// cref="ContentDescriptionObject" /> with no contents. /// </summary> public ContentDescriptionObject () : base (Asf.Guid.AsfContentDescriptionObject) { } #endregion #region Public Region /// <summary> /// Gets and sets the title of the media described by the /// current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing the title of /// the media or <see langword="null" /> if it is not set. /// </value> public string Title { get {return title.Length == 0 ? null : title;} set { title = string.IsNullOrEmpty (value) ? string.Empty : value; } } /// <summary> /// Gets and sets the author or performer of the media /// described by the current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing the author of /// the media or <see langword="null" /> if it is not set. /// </value> public string Author { get {return author.Length == 0 ? null : author;} set { author = string.IsNullOrEmpty (value) ? string.Empty : value; } } /// <summary> /// Gets and sets the copyright information for the media /// described by the current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing the copyright /// information for the media or <see langword="null" /> if /// it is not set. /// </value> public string Copyright { get {return copyright.Length == 0 ? null : copyright;} set { copyright = string.IsNullOrEmpty (value) ? string.Empty : value; } } /// <summary> /// Gets and sets the description of the media described by /// the current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing a description /// of the media or <see langword="null" /> if it is not set. /// </value> public string Description { get { return description.Length == 0 ? null : description; } set { description = string.IsNullOrEmpty (value) ? string.Empty : value; } } /// <summary> /// Gets and sets the rating of the media described by the /// current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing a rating of the /// media or <see langword="null" /> if it is not set. /// </value> public string Rating { get {return rating.Length == 0 ? null : rating;} set { rating = string.IsNullOrEmpty (value) ? string.Empty : value; } } /// <summary> /// Gets whether or not the current instance is empty. /// </summary> /// <value> /// <see langword="true" /> if all the values are cleared. /// Otherwise <see langword="false" />. /// </value> public bool IsEmpty { get { return title.Length == 0 && author.Length == 0 && copyright.Length == 0 && description.Length == 0 && rating.Length == 0; } } #endregion #region Public Region /// <summary> /// Renders the current instance as a raw ASF object. /// </summary> /// <returns> /// A <see cref="ByteVector" /> object containing the /// rendered version of the current instance. /// </returns> public override ByteVector Render () { ByteVector title_bytes = RenderUnicode (title); ByteVector author_bytes = RenderUnicode (author); ByteVector copyright_bytes = RenderUnicode (copyright); ByteVector description_bytes = RenderUnicode (description); ByteVector rating_bytes = RenderUnicode (rating); ByteVector output = RenderWord ((ushort) title_bytes.Count); output.Add (RenderWord ((ushort) author_bytes.Count)); output.Add (RenderWord ((ushort) copyright_bytes.Count)); output.Add (RenderWord ((ushort) description_bytes.Count)); output.Add (RenderWord ((ushort) rating_bytes.Count)); output.Add (title_bytes); output.Add (author_bytes); output.Add (copyright_bytes); output.Add (description_bytes); output.Add (rating_bytes); return Render (output); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Parse.Abstractions.Internal; using Parse.Abstractions.Platform.Objects; using Parse.Infrastructure; using Parse.Platform.Objects; namespace Parse.Tests { [TestClass] public class ObjectTests { [ParseClassName(nameof(SubClass))] class SubClass : ParseObject { } [ParseClassName(nameof(UnregisteredSubClass))] class UnregisteredSubClass : ParseObject { } ParseClient Client { get; } = new ParseClient(new ServerConnectionData { Test = true }); [TestCleanup] public void TearDown() => (Client.Services as ServiceHub).Reset(); [TestMethod] public void TestParseObjectConstructor() { ParseObject obj = new ParseObject("Corgi"); Assert.AreEqual("Corgi", obj.ClassName); Assert.IsNull(obj.CreatedAt); Assert.IsTrue(obj.IsDataAvailable); Assert.IsTrue(obj.IsDirty); } [TestMethod] public void TestParseObjectCreate() { ParseObject obj = Client.CreateObject("Corgi"); Assert.AreEqual("Corgi", obj.ClassName); Assert.IsNull(obj.CreatedAt); Assert.IsTrue(obj.IsDataAvailable); Assert.IsTrue(obj.IsDirty); ParseObject obj2 = Client.CreateObjectWithoutData("Corgi", "waGiManPutr4Pet1r"); Assert.AreEqual("Corgi", obj2.ClassName); Assert.AreEqual("waGiManPutr4Pet1r", obj2.ObjectId); Assert.IsNull(obj2.CreatedAt); Assert.IsFalse(obj2.IsDataAvailable); Assert.IsFalse(obj2.IsDirty); } [TestMethod] public void TestParseObjectCreateWithGeneric() { Client.AddValidClass<SubClass>(); ParseObject obj = Client.CreateObject<SubClass>(); Assert.AreEqual(nameof(SubClass), obj.ClassName); Assert.IsNull(obj.CreatedAt); Assert.IsTrue(obj.IsDataAvailable); Assert.IsTrue(obj.IsDirty); ParseObject obj2 = Client.CreateObjectWithoutData<SubClass>("waGiManPutr4Pet1r"); Assert.AreEqual(nameof(SubClass), obj2.ClassName); Assert.AreEqual("waGiManPutr4Pet1r", obj2.ObjectId); Assert.IsNull(obj2.CreatedAt); Assert.IsFalse(obj2.IsDataAvailable); Assert.IsFalse(obj2.IsDirty); } [TestMethod] public void TestParseObjectCreateWithGenericFailWithoutSubclass() => Assert.ThrowsException<InvalidCastException>(() => Client.CreateObject<SubClass>()); [TestMethod] public void TestFromState() { IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = new DateTime { }, ServerData = new Dictionary<string, object> { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; ParseObject obj = Client.GenerateObjectFromState<ParseObject>(state, "Omitted"); Assert.AreEqual("waGiManPutr4Pet1r", obj.ObjectId); Assert.AreEqual("Pagi", obj.ClassName); Assert.IsNotNull(obj.CreatedAt); Assert.IsNull(obj.UpdatedAt); Assert.AreEqual("kevin", obj["username"]); Assert.AreEqual("se551onT0k3n", obj["sessionToken"]); } [TestMethod] public void TestRegisterSubclass() { Assert.ThrowsException<InvalidCastException>(() => Client.CreateObject<SubClass>()); try { Client.AddValidClass<SubClass>(); Client.CreateObject<SubClass>(); Client.ClassController.RemoveClass(typeof(UnregisteredSubClass)); Client.CreateObject<SubClass>(); } catch { Assert.Fail(); } Client.ClassController.RemoveClass(typeof(SubClass)); Assert.ThrowsException<InvalidCastException>(() => Client.CreateObject<SubClass>()); } [TestMethod] public void TestRevert() { ParseObject obj = Client.CreateObject("Corgi"); obj["gogo"] = true; Assert.IsTrue(obj.IsDirty); Assert.AreEqual(1, obj.CurrentOperations.Count); Assert.IsTrue(obj.ContainsKey("gogo")); obj.Revert(); Assert.IsTrue(obj.IsDirty); Assert.AreEqual(0, obj.CurrentOperations.Count); Assert.IsFalse(obj.ContainsKey("gogo")); } [TestMethod] public void TestDeepTraversal() { ParseObject obj = Client.CreateObject("Corgi"); IDictionary<string, object> someDict = new Dictionary<string, object> { ["someList"] = new List<object> { } }; obj[nameof(obj)] = Client.CreateObject("Pug"); obj["obj2"] = Client.CreateObject("Pug"); obj["list"] = new List<object>(); obj["dict"] = someDict; obj["someBool"] = true; obj["someInt"] = 23; IEnumerable<object> traverseResult = Client.TraverseObjectDeep(obj, true, true); Assert.AreEqual(8, traverseResult.Count()); // Don't traverse beyond the root (since root is ParseObject). traverseResult = Client.TraverseObjectDeep(obj, false, true); Assert.AreEqual(1, traverseResult.Count()); traverseResult = Client.TraverseObjectDeep(someDict, false, true); Assert.AreEqual(2, traverseResult.Count()); // Should ignore root. traverseResult = Client.TraverseObjectDeep(obj, true, false); Assert.AreEqual(7, traverseResult.Count()); } [TestMethod] public void TestRemove() { ParseObject obj = Client.CreateObject("Corgi"); obj["gogo"] = true; Assert.IsTrue(obj.ContainsKey("gogo")); obj.Remove("gogo"); Assert.IsFalse(obj.ContainsKey("gogo")); IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = new DateTime { }, ServerData = new Dictionary<string, object> { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; obj = Client.GenerateObjectFromState<ParseObject>(state, "Corgi"); Assert.IsTrue(obj.ContainsKey("username")); Assert.IsTrue(obj.ContainsKey("sessionToken")); obj.Remove("username"); Assert.IsFalse(obj.ContainsKey("username")); Assert.IsTrue(obj.ContainsKey("sessionToken")); } [TestMethod] public void TestIndexGetterSetter() { ParseObject obj = Client.CreateObject("Corgi"); obj["gogo"] = true; obj["list"] = new List<string>(); obj["dict"] = new Dictionary<string, object>(); obj["fakeACL"] = new ParseACL(); obj[nameof(obj)] = new ParseObject("Corgi"); Assert.IsTrue(obj.ContainsKey("gogo")); Assert.IsInstanceOfType(obj["gogo"], typeof(bool)); Assert.IsTrue(obj.ContainsKey("list")); Assert.IsInstanceOfType(obj["list"], typeof(IList<string>)); Assert.IsTrue(obj.ContainsKey("dict")); Assert.IsInstanceOfType(obj["dict"], typeof(IDictionary<string, object>)); Assert.IsTrue(obj.ContainsKey("fakeACL")); Assert.IsInstanceOfType(obj["fakeACL"], typeof(ParseACL)); Assert.IsTrue(obj.ContainsKey(nameof(obj))); Assert.IsInstanceOfType(obj[nameof(obj)], typeof(ParseObject)); Assert.ThrowsException<KeyNotFoundException>(() => { object gogo = obj["missingItem"]; }); } [TestMethod] public void TestPropertiesGetterSetter() { DateTime now = new DateTime { }; IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = now, ServerData = new Dictionary<string, object> { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; ParseObject obj = Client.GenerateObjectFromState<ParseObject>(state, "Omitted"); Assert.AreEqual("Pagi", obj.ClassName); Assert.AreEqual(now, obj.CreatedAt); Assert.IsNull(obj.UpdatedAt); Assert.AreEqual("waGiManPutr4Pet1r", obj.ObjectId); Assert.AreEqual(2, obj.Keys.Count()); Assert.IsFalse(obj.IsNew); Assert.IsNull(obj.ACL); } [TestMethod] public void TestAddToList() { ParseObject obj = new ParseObject("Corgi").Bind(Client); obj.AddToList("emptyList", "gogo"); obj["existingList"] = new List<string>() { "rich" }; Assert.IsTrue(obj.ContainsKey("emptyList")); Assert.AreEqual(1, obj.Get<List<object>>("emptyList").Count); obj.AddToList("existingList", "gogo"); Assert.IsTrue(obj.ContainsKey("existingList")); Assert.AreEqual(2, obj.Get<List<object>>("existingList").Count); obj.AddToList("existingList", 1); Assert.AreEqual(3, obj.Get<List<object>>("existingList").Count); obj.AddRangeToList("newRange", new List<string>() { "anti", "mage" }); Assert.AreEqual(2, obj.Get<List<object>>("newRange").Count); } [TestMethod] public void TestAddUniqueToList() { ParseObject obj = new ParseObject("Corgi").Bind(Client); obj.AddUniqueToList("emptyList", "gogo"); obj["existingList"] = new List<string>() { "gogo" }; Assert.IsTrue(obj.ContainsKey("emptyList")); Assert.AreEqual(1, obj.Get<List<object>>("emptyList").Count); obj.AddUniqueToList("existingList", "gogo"); Assert.IsTrue(obj.ContainsKey("existingList")); Assert.AreEqual(1, obj.Get<List<object>>("existingList").Count); obj.AddUniqueToList("existingList", 1); Assert.AreEqual(2, obj.Get<List<object>>("existingList").Count); obj.AddRangeUniqueToList("newRange", new List<string>() { "anti", "anti" }); Assert.AreEqual(1, obj.Get<List<object>>("newRange").Count); } [TestMethod] public void TestRemoveAllFromList() { ParseObject obj = new ParseObject("Corgi", Client) { ["existingList"] = new List<string> { "gogo", "Queen of Pain" } }; obj.RemoveAllFromList("existingList", new List<string>() { "gogo", "missingItem" }); Assert.AreEqual(1, obj.Get<List<object>>("existingList").Count); } [TestMethod] public void TestGetRelation() { // TODO (hallucinogen): do this } [TestMethod] public void TestTryGetValue() { IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = new DateTime { }, ServerData = new Dictionary<string, object>() { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; ParseObject obj = Client.GenerateObjectFromState<ParseObject>(state, "Omitted"); obj.TryGetValue("username", out string res); Assert.AreEqual("kevin", res); obj.TryGetValue("username", out ParseObject resObj); Assert.IsNull(resObj); obj.TryGetValue("missingItem", out res); Assert.IsNull(res); } [TestMethod] public void TestGet() { IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = new DateTime { }, ServerData = new Dictionary<string, object>() { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; ParseObject obj = Client.GenerateObjectFromState<ParseObject>(state, "Omitted"); Assert.AreEqual("kevin", obj.Get<string>("username")); Assert.ThrowsException<InvalidCastException>(() => obj.Get<ParseObject>("username")); Assert.ThrowsException<KeyNotFoundException>(() => obj.Get<string>("missingItem")); } #warning Some tests are not implemented. [TestMethod] public void TestIsDataAvailable() { // TODO (hallucinogen): do this } [TestMethod] public void TestHasSameId() { // TODO (hallucinogen): do this } [TestMethod] public void TestKeys() { IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = new DateTime { }, ServerData = new Dictionary<string, object>() { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; ParseObject obj = Client.GenerateObjectFromState<ParseObject>(state, "Omitted"); Assert.AreEqual(2, obj.Keys.Count); obj["additional"] = true; Assert.AreEqual(3, obj.Keys.Count); obj.Remove("username"); Assert.AreEqual(2, obj.Keys.Count); } [TestMethod] public void TestAdd() { IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = new DateTime { }, ServerData = new Dictionary<string, object>() { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; ParseObject obj = Client.GenerateObjectFromState<ParseObject>(state, "Omitted"); Assert.ThrowsException<ArgumentException>(() => obj.Add("username", "kevin")); obj.Add("zeus", "bewithyou"); Assert.AreEqual("bewithyou", obj["zeus"]); } [TestMethod] public void TestEnumerator() { IObjectState state = new MutableObjectState { ObjectId = "waGiManPutr4Pet1r", ClassName = "Pagi", CreatedAt = new DateTime { }, ServerData = new Dictionary<string, object>() { ["username"] = "kevin", ["sessionToken"] = "se551onT0k3n" } }; ParseObject obj = Client.GenerateObjectFromState<ParseObject>(state, "Omitted"); int count = 0; foreach (KeyValuePair<string, object> key in obj) { count++; } Assert.AreEqual(2, count); obj["newDirtyItem"] = "newItem"; count = 0; foreach (KeyValuePair<string, object> key in obj) { count++; } Assert.AreEqual(3, count); } [TestMethod] public void TestGetQuery() { Client.AddValidClass<SubClass>(); ParseQuery<ParseObject> query = Client.GetQuery(nameof(UnregisteredSubClass)); Assert.AreEqual(nameof(UnregisteredSubClass), query.GetClassName()); Assert.ThrowsException<ArgumentException>(() => Client.GetQuery(nameof(SubClass))); Client.ClassController.RemoveClass(typeof(SubClass)); } #warning These tests are incomplete. [TestMethod] public void TestPropertyChanged() { // TODO (hallucinogen): do this } [TestMethod] [AsyncStateMachine(typeof(ObjectTests))] public Task TestSave() => // TODO (hallucinogen): do this Task.FromResult(0); [TestMethod] [AsyncStateMachine(typeof(ObjectTests))] public Task TestSaveAll() => // TODO (hallucinogen): do this Task.FromResult(0); [TestMethod] [AsyncStateMachine(typeof(ObjectTests))] public Task TestDelete() => // TODO (hallucinogen): do this Task.FromResult(0); [TestMethod] [AsyncStateMachine(typeof(ObjectTests))] public Task TestDeleteAll() => // TODO (hallucinogen): do this Task.FromResult(0); [TestMethod] [AsyncStateMachine(typeof(ObjectTests))] public Task TestFetch() => // TODO (hallucinogen): do this Task.FromResult(0); [TestMethod] [AsyncStateMachine(typeof(ObjectTests))] public Task TestFetchAll() => // TODO (hallucinogen): do this Task.FromResult(0); } }
#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.Storages.Algo File: ISecurityMarketDataDrive.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Storages { using System; using Ecng.Common; using Ecng.Reflection; using StockSharp.Algo.Storages.Csv; using StockSharp.BusinessEntities; using StockSharp.Localization; using StockSharp.Messages; /// <summary> /// The interface, describing the storage for instrument. /// </summary> public interface ISecurityMarketDataDrive { /// <summary> /// Instrument identifier. /// </summary> SecurityId SecurityId { get; } /// <summary> /// To get the storage of tick trades for the specified instrument. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns>The storage of tick trades.</returns> IMarketDataStorage<ExecutionMessage> GetTickStorage(IMarketDataSerializer<ExecutionMessage> serializer); /// <summary> /// To get the storage of order books for the specified instrument. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns>The order books storage.</returns> IMarketDataStorage<QuoteChangeMessage> GetQuoteStorage(IMarketDataSerializer<QuoteChangeMessage> serializer); /// <summary> /// To get the storage of orders log for the specified instrument. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns>The storage of orders log.</returns> IMarketDataStorage<ExecutionMessage> GetOrderLogStorage(IMarketDataSerializer<ExecutionMessage> serializer); /// <summary> /// To get the storage of level1 data. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns>The storage of level1 data.</returns> IMarketDataStorage<Level1ChangeMessage> GetLevel1Storage(IMarketDataSerializer<Level1ChangeMessage> serializer); /// <summary> /// To get the storage of position changes data. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns>The storage of position changes data.</returns> IMarketDataStorage<PositionChangeMessage> GetPositionMessageStorage(IMarketDataSerializer<PositionChangeMessage> serializer); /// <summary> /// To get the candles storage for the specified instrument. /// </summary> /// <param name="candleType">The candle type.</param> /// <param name="arg">Candle arg.</param> /// <param name="serializer">The serializer.</param> /// <returns>The candles storage.</returns> IMarketDataStorage<CandleMessage> GetCandleStorage(Type candleType, object arg, IMarketDataSerializer<CandleMessage> serializer); /// <summary> /// To get the transactions storage for the specified instrument. /// </summary> /// <param name="serializer">The serializer.</param> /// <returns>The transactions storage.</returns> IMarketDataStorage<ExecutionMessage> GetTransactionStorage(IMarketDataSerializer<ExecutionMessage> serializer); /// <summary> /// To get the market-data storage. /// </summary> /// <param name="dataType">Market data type.</param> /// <param name="arg">The parameter associated with the <paramref name="dataType" /> type. For example, <see cref="CandleMessage.Arg"/>.</param> /// <param name="serializer">The serializer.</param> /// <returns>Market-data storage.</returns> IMarketDataStorage GetStorage(Type dataType, object arg, IMarketDataSerializer serializer); ///// <summary> ///// To get available candles types with parameters for the instrument. ///// </summary> ///// <param name="serializer">The serializer.</param> ///// <returns>Available candles types with parameters.</returns> //IEnumerable<Tuple<Type, object[]>> GetCandleTypes(IMarketDataSerializer<CandleMessage> serializer); } /// <summary> /// The storage for the instrument. /// </summary> public class SecurityMarketDataDrive : ISecurityMarketDataDrive { /// <summary> /// Initializes a new instance of the <see cref="SecurityMarketDataDrive"/>. /// </summary> /// <param name="drive">The storage (database, file etc.).</param> /// <param name="security">Security.</param> public SecurityMarketDataDrive(IMarketDataDrive drive, Security security) { Drive = drive ?? throw new ArgumentNullException(nameof(drive)); Security = security ?? throw new ArgumentNullException(nameof(security)); SecurityId = security.ToSecurityId(); } /// <summary> /// The storage (database, file etc.). /// </summary> public IMarketDataDrive Drive { get; } /// <summary> /// Security. /// </summary> public Security Security { get; } private static StorageFormats ToFormat(IMarketDataSerializer serializer) { if (serializer == null) throw new ArgumentNullException(nameof(serializer)); return serializer.GetType().GetGenericType(typeof(CsvMarketDataSerializer<>)) != null ? StorageFormats.Csv : StorageFormats.Binary; } private IMarketDataStorageDrive GetStorageDrive<TMessage>(IMarketDataSerializer<TMessage> serializer, object arg = null) where TMessage : Message { return GetStorageDrive(serializer, typeof(TMessage), arg); } private IMarketDataStorageDrive GetStorageDrive(IMarketDataSerializer serializer, Type messageType, object arg = null) { return Drive.GetStorageDrive(SecurityId, DataType.Create(messageType, arg), ToFormat(serializer)); } /// <inheritdoc /> public SecurityId SecurityId { get; } private IExchangeInfoProvider _exchangeInfoProvider = new InMemoryExchangeInfoProvider(); /// <summary> /// Exchanges and trading boards provider. /// </summary> public IExchangeInfoProvider ExchangeInfoProvider { get => _exchangeInfoProvider; set => _exchangeInfoProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <inheritdoc /> public IMarketDataStorage<ExecutionMessage> GetTickStorage(IMarketDataSerializer<ExecutionMessage> serializer) { return new TradeStorage(SecurityId, GetStorageDrive(serializer, ExecutionTypes.Tick), serializer); } /// <inheritdoc /> public IMarketDataStorage<QuoteChangeMessage> GetQuoteStorage(IMarketDataSerializer<QuoteChangeMessage> serializer) { return new MarketDepthStorage(SecurityId, GetStorageDrive(serializer), serializer); } /// <inheritdoc /> public IMarketDataStorage<ExecutionMessage> GetOrderLogStorage(IMarketDataSerializer<ExecutionMessage> serializer) { return new OrderLogStorage(SecurityId, GetStorageDrive(serializer, ExecutionTypes.OrderLog), serializer); } /// <inheritdoc /> public IMarketDataStorage<Level1ChangeMessage> GetLevel1Storage(IMarketDataSerializer<Level1ChangeMessage> serializer) { return new Level1Storage(SecurityId, GetStorageDrive(serializer), serializer); } /// <inheritdoc /> public IMarketDataStorage<PositionChangeMessage> GetPositionMessageStorage(IMarketDataSerializer<PositionChangeMessage> serializer) { return new PositionChangeStorage(SecurityId, GetStorageDrive(serializer), serializer); } /// <inheritdoc /> public IMarketDataStorage<CandleMessage> GetCandleStorage(Type candleType, object arg, IMarketDataSerializer<CandleMessage> serializer) { if (candleType == null) throw new ArgumentNullException(nameof(candleType)); if (!candleType.IsCandleMessage()) throw new ArgumentOutOfRangeException(nameof(candleType), candleType, LocalizedStrings.WrongCandleType); return typeof(CandleStorage<>).Make(candleType).CreateInstance<IMarketDataStorage<CandleMessage>>(SecurityId, arg, GetStorageDrive(serializer, candleType, arg), serializer); } /// <inheritdoc /> public IMarketDataStorage<ExecutionMessage> GetTransactionStorage(IMarketDataSerializer<ExecutionMessage> serializer) { return new TransactionStorage(SecurityId, GetStorageDrive(serializer, ExecutionTypes.Transaction), serializer); } /// <inheritdoc /> public IMarketDataStorage GetStorage(Type dataType, object arg, IMarketDataSerializer serializer) { if (dataType == null) throw new ArgumentNullException(nameof(dataType)); if (!dataType.IsSubclassOf(typeof(Message))) dataType = dataType.ToMessageType(ref arg); if (dataType == typeof(ExecutionMessage)) { switch ((ExecutionTypes)arg) { case ExecutionTypes.Tick: return GetTickStorage((IMarketDataSerializer<ExecutionMessage>)serializer); case ExecutionTypes.Transaction: return GetTransactionStorage((IMarketDataSerializer<ExecutionMessage>)serializer); case ExecutionTypes.OrderLog: return GetTransactionStorage((IMarketDataSerializer<ExecutionMessage>)serializer); default: throw new ArgumentOutOfRangeException(nameof(arg), arg, LocalizedStrings.Str1219); } } else if (dataType == typeof(Level1ChangeMessage)) return GetLevel1Storage((IMarketDataSerializer<Level1ChangeMessage>)serializer); else if (dataType == typeof(QuoteChangeMessage)) return GetQuoteStorage((IMarketDataSerializer<QuoteChangeMessage>)serializer); else if (dataType.IsCandleMessage()) return GetCandleStorage(dataType, arg, (IMarketDataSerializer<CandleMessage>)serializer); else throw new ArgumentOutOfRangeException(nameof(dataType), dataType, LocalizedStrings.Str1018); } ///// <summary> ///// To get available candles types with parameters for the instrument. ///// </summary> ///// <param name="serializer">The serializer.</param> ///// <returns>Available candles types with parameters.</returns> //public IEnumerable<Tuple<Type, object[]>> GetCandleTypes(IMarketDataSerializer<CandleMessage> serializer) //{ // return Drive.GetCandleTypes(Security.ToSecurityId(), ToFormat(serializer)); //} } }
// *********************************************************************** // Copyright (c) 2011 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. // *********************************************************************** #if !SILVERLIGHT using System; using System.Reflection; using System.Globalization; using NUnit.Common; using NUnit.Options; using NUnit.Framework; namespace NUnitLite.Tests { using System.Collections.Generic; [TestFixture] public class CommandLineTests { #region General Tests [Test] public void NoInputFiles() { var options = new NUnitLiteOptions(); Assert.True(options.Validate()); Assert.AreEqual(0, options.InputFiles.Count); } [TestCase("ShowHelp", "help|h")] [TestCase("ShowVersion", "version|V")] [TestCase("StopOnError", "stoponerror")] [TestCase("WaitBeforeExit", "wait")] #if !PORTABLE [TestCase("NoHeader", "noheader|noh")] [TestCase("Full", "full")] #if !SILVERLIGHT && !NETCF [TestCase("TeamCity", "teamcity")] #endif #endif public void CanRecognizeBooleanOptions(string propertyName, string pattern) { Console.WriteLine("Testing " + propertyName); string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName); NUnitLiteOptions options; foreach (string option in prototypes) { if (option.Length == 1) { options = new NUnitLiteOptions("-" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option); } else { options = new NUnitLiteOptions("--" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option); } options = new NUnitLiteOptions("/" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option); } } [TestCase("WhereClause", "where", new string[] { "cat==Fast" }, new string[0])] [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" }, new string[] { "JUNK" })] #if !PORTABLE [TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])] [TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])] [TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })] #endif public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string option in prototypes) { foreach (string value in goodValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } foreach (string value in badValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue); } } } [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })] #if !PORTABLE [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })] #endif public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues) { PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string canonicalValue in canonicalValues) { string lowercaseValue = canonicalValue.ToLower(CultureInfo.InvariantCulture); string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } } [TestCase("DefaultTimeout", "timeout")] [TestCase("RandomSeed", "seed")] #if PARALLEL [TestCase("NumberOfTestWorkers", "workers")] #endif public void CanRecognizeIntOptions(string propertyName, string pattern) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(int), property.PropertyType); foreach (string option in prototypes) { var options = new NUnitLiteOptions("--" + option + ":42"); Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":text"); } } // [TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))] // public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType) // { // string[] prototypes = pattern.Split('|'); // PropertyInfo property = GetPropertyInfo(propertyName); // Assert.IsNotNull(property, "Property {0} not found", propertyName); // Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName); // Assert.AreEqual(enumType, property.PropertyType); // foreach (string option in prototypes) // { // foreach (string name in Enum.GetNames(enumType)) // { // { // ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name); // Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name); // } // } // } // } [TestCase("--where")] [TestCase("--timeout")] #if !PORTABLE [TestCase("--output")] [TestCase("--err")] [TestCase("--work")] [TestCase("--trace")] #endif public void MissingValuesAreReported(string option) { var options = new NUnitLiteOptions(option + "="); Assert.False(options.Validate(), "Missing value should not be valid"); Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]); } [Test] public void AssemblyName() { var options = new NUnitLiteOptions("nunit.tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count); Assert.AreEqual("nunit.tests.dll", options.InputFiles[0]); } // [Test] // public void FixtureNamePlusAssemblyIsValid() // { // var options = new NUnitLiteOptions( "-fixture:NUnit.Tests.AllTests", "nunit.tests.dll" ); // Assert.AreEqual("nunit.tests.dll", options.Parameters[0]); // Assert.AreEqual("NUnit.Tests.AllTests", options.fixture); // Assert.IsTrue(options.Validate()); // } [Test] public void AssemblyAloneIsValid() { var options = new NUnitLiteOptions("nunit.tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid"); } [Test] public void InvalidOption() { var options = new NUnitLiteOptions("-asembly:nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -asembly:nunit.tests.dll", options.ErrorMessages[0]); } // [Test] // public void NoFixtureNameProvided() // { // ConsoleOptions options = new ConsoleOptions( "-fixture:", "nunit.tests.dll" ); // Assert.IsFalse(options.Validate()); // } [Test] public void InvalidCommandLineParms() { var options = new NUnitLiteOptions("-garbage:TestFixture", "-assembly:Tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]); Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]); } #endregion #region Timeout Option [Test] public void TimeoutIsMinusOneIfNoOptionIsProvided() { var options = new NUnitLiteOptions("tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } [Test] public void TimeoutThrowsExceptionIfOptionHasNoValue() { Assert.Throws<OptionException>(() => new NUnitLiteOptions("tests.dll", "-timeout")); } [Test] public void TimeoutParsesIntValueCorrectly() { var options = new NUnitLiteOptions("tests.dll", "-timeout:5000"); Assert.True(options.Validate()); Assert.AreEqual(5000, options.DefaultTimeout); } [Test] public void TimeoutCausesErrorIfValueIsNotInteger() { var options = new NUnitLiteOptions("tests.dll", "-timeout:abc"); Assert.False(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } #endregion #region EngineResult Option [Test] public void FileNameWithoutResultOptionLooksLikeParameter() { var options = new NUnitLiteOptions("tests.dll", "results.xml"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); Assert.AreEqual(2, options.InputFiles.Count); } #if !PORTABLE [Test] public void ResultOptionWithFilePath() { var options = new NUnitLiteOptions("tests.dll", "-result:results.xml"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); Assert.Null(spec.Transform); } [Test] public void ResultOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("tests.dll", "-result:results.xml;format=nunit2"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit2", spec.Format); Assert.Null(spec.Transform); } [Test] public void ResultOptionWithFilePathAndTransform() { var options = new NUnitLiteOptions("tests.dll", "-result:results.xml;transform=transform.xslt"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("user", spec.Format); Assert.AreEqual("transform.xslt", spec.Transform); } [Test] public void ResultOptionWithoutFileNameIsInvalid() { var options = new NUnitLiteOptions("tests.dll", "-result:"); Assert.False(options.Validate(), "Should not be valid"); Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected"); } [Test] public void ResultOptionMayBeRepeated() { var options = new NUnitLiteOptions("tests.dll", "-result:results.xml", "-result:nunit2results.xml;format=nunit2", "-result:myresult.xml;transform=mytransform.xslt"); Assert.True(options.Validate(), "Should be valid"); var specs = options.ResultOutputSpecifications; Assert.AreEqual(3, specs.Count); var spec1 = specs[0]; Assert.AreEqual("results.xml", spec1.OutputPath); Assert.AreEqual("nunit3", spec1.Format); Assert.Null(spec1.Transform); var spec2 = specs[1]; Assert.AreEqual("nunit2results.xml", spec2.OutputPath); Assert.AreEqual("nunit2", spec2.Format); Assert.Null(spec2.Transform); var spec3 = specs[2]; Assert.AreEqual("myresult.xml", spec3.OutputPath); Assert.AreEqual("user", spec3.Format); Assert.AreEqual("mytransform.xslt", spec3.Transform); } [Test] public void DefaultResultSpecification() { var options = new NUnitLiteOptions("test.dll"); Assert.AreEqual(1, options.ResultOutputSpecifications.Count); var spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("TestResult.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); Assert.Null(spec.Transform); } [Test] public void NoResultSuppressesDefaultResultSpecification() { var options = new NUnitLiteOptions("test.dll", "-noresult"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test] public void NoResultSuppressesAllResultSpecifications() { var options = new NUnitLiteOptions("test.dll", "-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } #endif #endregion #region Explore Option #if !PORTABLE [Test] public void ExploreOptionWithoutPath() { var options = new NUnitLiteOptions("tests.dll", "-explore"); Assert.True(options.Validate()); Assert.True(options.Explore); } [Test] public void ExploreOptionWithFilePath() { var options = new NUnitLiteOptions("tests.dll", "-explore:results.xml"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); Assert.Null(spec.Transform); } [Test] public void ExploreOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("tests.dll", "-explore:results.xml;format=cases"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("cases", spec.Format); Assert.Null(spec.Transform); } [Test] public void ExploreOptionWithFilePathAndTransform() { var options = new NUnitLiteOptions("tests.dll", "-explore:results.xml;transform=myreport.xslt"); Assert.True(options.Validate()); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("user", spec.Format); Assert.AreEqual("myreport.xslt", spec.Transform); } [Test] public void ExploreOptionWithFilePathUsingEqualSign() { var options = new NUnitLiteOptions("tests.dll", "-explore=C:/nunit/tests/bin/Debug/console-test.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set"); Assert.AreEqual("tests.dll", options.InputFiles[0]); Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath); } #if !SILVERLIGHT && !NETCF [TestCase(true, null, true)] [TestCase(false, null, false)] [TestCase(true, false, true)] [TestCase(false, false, false)] [TestCase(true, true, true)] [TestCase(false, true, true)] public void ShouldSetTeamCityFlagAccordingToArgsAndDefauls(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity) { // Given List<string> args = new List<string> { "tests.dll" }; if (hasTeamcityInCmd) { args.Add("--teamcity"); } CommandLineOptions options; if (defaultTeamcity.HasValue) { options = new NUnitLiteOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray()); } else { options = new NUnitLiteOptions(args.ToArray()); } // When var actualTeamCity = options.TeamCity; // Then Assert.AreEqual(actualTeamCity, expectedTeamCity); } #endif #endif #endregion #region Helper Methods //private static FieldInfo GetFieldInfo(string fieldName) //{ // FieldInfo field = typeof(NUnitLiteOptions).GetField(fieldName); // Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName); // return field; //} private static PropertyInfo GetPropertyInfo(string propertyName) { PropertyInfo property = typeof(NUnitLiteOptions).GetProperty(propertyName); Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName); return property; } #endregion internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider { public DefaultOptionsProviderStub(bool teamCity) { TeamCity = teamCity; } public bool TeamCity { get; private set; } } } } #endif
/* * 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.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// DataManager will manage the subscriptions for both the DataFeeds and the SubscriptionManager /// </summary> public class DataManager : IAlgorithmSubscriptionManager, IDataFeedSubscriptionManager, IDataManager { private readonly IAlgorithmSettings _algorithmSettings; private readonly IDataFeed _dataFeed; private readonly MarketHoursDatabase _marketHoursDatabase; private readonly ITimeKeeper _timeKeeper; private readonly bool _liveMode; private readonly IRegisteredSecurityDataTypesProvider _registeredTypesProvider; private readonly IDataPermissionManager _dataPermissionManager; /// There is no ConcurrentHashSet collection in .NET, /// so we use ConcurrentDictionary with byte value to minimize memory usage private readonly ConcurrentDictionary<SubscriptionDataConfig, SubscriptionDataConfig> _subscriptionManagerSubscriptions = new ConcurrentDictionary<SubscriptionDataConfig, SubscriptionDataConfig>(); /// <summary> /// Event fired when a new subscription is added /// </summary> public event EventHandler<Subscription> SubscriptionAdded; /// <summary> /// Event fired when an existing subscription is removed /// </summary> public event EventHandler<Subscription> SubscriptionRemoved; /// <summary> /// Creates a new instance of the DataManager /// </summary> public DataManager( IDataFeed dataFeed, UniverseSelection universeSelection, IAlgorithm algorithm, ITimeKeeper timeKeeper, MarketHoursDatabase marketHoursDatabase, bool liveMode, IRegisteredSecurityDataTypesProvider registeredTypesProvider, IDataPermissionManager dataPermissionManager) { _dataFeed = dataFeed; UniverseSelection = universeSelection; UniverseSelection.SetDataManager(this); _algorithmSettings = algorithm.Settings; AvailableDataTypes = SubscriptionManager.DefaultDataTypes(); _timeKeeper = timeKeeper; _marketHoursDatabase = marketHoursDatabase; _liveMode = liveMode; _registeredTypesProvider = registeredTypesProvider; _dataPermissionManager = dataPermissionManager; // wire ourselves up to receive notifications when universes are added/removed algorithm.UniverseManager.CollectionChanged += (sender, args) => { switch (args.Action) { case NotifyCollectionChangedAction.Add: foreach (var universe in args.NewItems.OfType<Universe>()) { var config = universe.Configuration; var start = algorithm.UtcTime; var end = algorithm.LiveMode ? Time.EndOfTime : algorithm.EndDate.ConvertToUtc(algorithm.TimeZone); Security security; if (!algorithm.Securities.TryGetValue(config.Symbol, out security)) { // create a canonical security object if it doesn't exist security = new Security( _marketHoursDatabase.GetExchangeHours(config), config, algorithm.Portfolio.CashBook[algorithm.AccountCurrency], SymbolProperties.GetDefault(algorithm.AccountCurrency), algorithm.Portfolio.CashBook, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); } AddSubscription( new SubscriptionRequest(true, universe, security, config, start, end)); } break; case NotifyCollectionChangedAction.Remove: foreach (var universe in args.OldItems.OfType<Universe>()) { // removing the subscription will be handled by the SubscriptionSynchronizer // in the next loop as well as executing a UniverseSelection one last time. if (!universe.DisposeRequested) { universe.Dispose(); } } break; default: throw new NotImplementedException("The specified action is not implemented: " + args.Action); } }; } #region IDataFeedSubscriptionManager /// <summary> /// Gets the data feed subscription collection /// </summary> public SubscriptionCollection DataFeedSubscriptions { get; } = new SubscriptionCollection(); /// <summary> /// Will remove all current <see cref="Subscription"/> /// </summary> public void RemoveAllSubscriptions() { // remove each subscription from our collection foreach (var subscription in DataFeedSubscriptions) { try { RemoveSubscription(subscription.Configuration); } catch (Exception err) { Log.Error(err, "DataManager.RemoveAllSubscriptions():" + $"Error removing: {subscription.Configuration}"); } } } /// <summary> /// Adds a new <see cref="Subscription"/> to provide data for the specified security. /// </summary> /// <param name="request">Defines the <see cref="SubscriptionRequest"/> to be added</param> /// <returns>True if the subscription was created and added successfully, false otherwise</returns> public bool AddSubscription(SubscriptionRequest request) { // guarantee the configuration is present in our config collection // this is related to GH issue 3877: where we added a configuration which we also removed _subscriptionManagerSubscriptions.TryAdd(request.Configuration, request.Configuration); Subscription subscription; if (DataFeedSubscriptions.TryGetValue(request.Configuration, out subscription)) { // duplicate subscription request subscription.AddSubscriptionRequest(request); // only result true if the existing subscription is internal, we actually added something from the users perspective return subscription.Configuration.IsInternalFeed; } // before adding the configuration to the data feed let's assert it's valid _dataPermissionManager.AssertConfiguration(request.Configuration, request.StartTimeLocal, request.EndTimeLocal); subscription = _dataFeed.CreateSubscription(request); if (subscription == null) { Log.Trace($"DataManager.AddSubscription(): Unable to add subscription for: {request.Configuration}"); // subscription will be null when there's no tradeable dates for the security between the requested times, so // don't even try to load the data return false; } if (_liveMode) { OnSubscriptionAdded(subscription); Log.Trace($"DataManager.AddSubscription(): Added {request.Configuration}." + $" Start: {request.StartTimeUtc}. End: {request.EndTimeUtc}"); } else if(Log.DebuggingEnabled) { // for performance lets not create the message string if debugging is not enabled // this can be executed many times and its in the algorithm thread Log.Debug($"DataManager.AddSubscription(): Added {request.Configuration}." + $" Start: {request.StartTimeUtc}. End: {request.EndTimeUtc}"); } return DataFeedSubscriptions.TryAdd(subscription); } /// <summary> /// Removes the <see cref="Subscription"/>, if it exists /// </summary> /// <param name="configuration">The <see cref="SubscriptionDataConfig"/> of the subscription to remove</param> /// <param name="universe">Universe requesting to remove <see cref="Subscription"/>. /// Default value, null, will remove all universes</param> /// <returns>True if the subscription was successfully removed, false otherwise</returns> public bool RemoveSubscription(SubscriptionDataConfig configuration, Universe universe = null) { // remove the subscription from our collection, if it exists Subscription subscription; if (DataFeedSubscriptions.TryGetValue(configuration, out subscription)) { // we remove the subscription when there are no other requests left if (subscription.RemoveSubscriptionRequest(universe)) { if (!DataFeedSubscriptions.TryRemove(configuration, out subscription)) { Log.Error($"DataManager.RemoveSubscription(): Unable to remove {configuration}"); return false; } _dataFeed.RemoveSubscription(subscription); if (_liveMode) { OnSubscriptionRemoved(subscription); } subscription.Dispose(); RemoveSubscriptionDataConfig(subscription); if (_liveMode) { Log.Trace($"DataManager.RemoveSubscription(): Removed {configuration}"); } else if(Log.DebuggingEnabled) { // for performance lets not create the message string if debugging is not enabled // this can be executed many times and its in the algorithm thread Log.Debug($"DataManager.RemoveSubscription(): Removed {configuration}"); } return true; } } else if (universe != null) { // a universe requested removal of a subscription which wasn't present anymore, this can happen when a subscription ends // it will get removed from the data feed subscription list, but the configuration will remain until the universe removes it // why? the effect I found is that the fill models are using these subscriptions to determine which data they could use SubscriptionDataConfig config; _subscriptionManagerSubscriptions.TryRemove(configuration, out config); } return false; } /// <summary> /// Event invocator for the <see cref="SubscriptionAdded"/> event /// </summary> /// <param name="subscription">The added subscription</param> private void OnSubscriptionAdded(Subscription subscription) { SubscriptionAdded?.Invoke(this, subscription); } /// <summary> /// Event invocator for the <see cref="SubscriptionRemoved"/> event /// </summary> /// <param name="subscription">The removed subscription</param> private void OnSubscriptionRemoved(Subscription subscription) { SubscriptionRemoved?.Invoke(this, subscription); } #endregion #region IAlgorithmSubscriptionManager /// <summary> /// Gets all the current data config subscriptions that are being processed for the SubscriptionManager /// </summary> public IEnumerable<SubscriptionDataConfig> SubscriptionManagerSubscriptions => _subscriptionManagerSubscriptions.Select(x => x.Key); /// <summary> /// Gets existing or adds new <see cref="SubscriptionDataConfig" /> /// </summary> /// <returns>Returns the SubscriptionDataConfig instance used</returns> public SubscriptionDataConfig SubscriptionManagerGetOrAdd(SubscriptionDataConfig newConfig) { var config = _subscriptionManagerSubscriptions.GetOrAdd(newConfig, newConfig); // if the reference is not the same, means it was already there and we did not add anything new if (!ReferenceEquals(config, newConfig)) { // for performance lets not create the message string if debugging is not enabled // this can be executed many times and its in the algorithm thread if (Log.DebuggingEnabled) { Log.Debug("DataManager.SubscriptionManagerGetOrAdd(): subscription already added: " + config); } } else { // for performance, only count if we are above the limit if (SubscriptionManagerCount() > _algorithmSettings.DataSubscriptionLimit) { // count data subscriptions by symbol, ignoring multiple data types. // this limit was added due to the limits IB places on number of subscriptions var uniqueCount = SubscriptionManagerSubscriptions .Where(x => !x.Symbol.IsCanonical()) .DistinctBy(x => x.Symbol.Value) .Count(); if (uniqueCount > _algorithmSettings.DataSubscriptionLimit) { throw new Exception( $"The maximum number of concurrent market data subscriptions was exceeded ({_algorithmSettings.DataSubscriptionLimit})." + "Please reduce the number of symbols requested or increase the limit using Settings.DataSubscriptionLimit."); } } // add the time zone to our time keeper _timeKeeper.AddTimeZone(newConfig.ExchangeTimeZone); } return config; } /// <summary> /// Will try to remove a <see cref="SubscriptionDataConfig"/> and update the corresponding /// consumers accordingly /// </summary> /// <param name="subscription">The <see cref="Subscription"/> owning the configuration to remove</param> private void RemoveSubscriptionDataConfig(Subscription subscription) { // the subscription could of ended but might still be part of the universe if (subscription.RemovedFromUniverse.Value) { SubscriptionDataConfig config; _subscriptionManagerSubscriptions.TryRemove(subscription.Configuration, out config); } } /// <summary> /// Returns the amount of data config subscriptions processed for the SubscriptionManager /// </summary> public int SubscriptionManagerCount() { return _subscriptionManagerSubscriptions.Skip(0).Count(); } #region ISubscriptionDataConfigService /// <summary> /// The different <see cref="TickType" /> each <see cref="SecurityType" /> supports /// </summary> public Dictionary<SecurityType, List<TickType>> AvailableDataTypes { get; } /// <summary> /// Creates and adds a list of <see cref="SubscriptionDataConfig" /> for a given symbol and configuration. /// Can optionally pass in desired subscription data type to use. /// If the config already existed will return existing instance instead /// </summary> public SubscriptionDataConfig Add( Type dataType, Symbol symbol, Resolution? resolution = null, bool fillForward = true, bool extendedMarketHours = false, bool isFilteredSubscription = true, bool isInternalFeed = false, bool isCustomData = false, DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted ) { return Add(symbol, resolution, fillForward, extendedMarketHours, isFilteredSubscription, isInternalFeed, isCustomData, new List<Tuple<Type, TickType>> { new Tuple<Type, TickType>(dataType, LeanData.GetCommonTickTypeForCommonDataTypes(dataType, symbol.SecurityType))}, dataNormalizationMode) .First(); } /// <summary> /// Creates and adds a list of <see cref="SubscriptionDataConfig" /> for a given symbol and configuration. /// Can optionally pass in desired subscription data types to use. /// If the config already existed will return existing instance instead /// </summary> public List<SubscriptionDataConfig> Add( Symbol symbol, Resolution? resolution = null, bool fillForward = true, bool extendedMarketHours = false, bool isFilteredSubscription = true, bool isInternalFeed = false, bool isCustomData = false, List<Tuple<Type, TickType>> subscriptionDataTypes = null, DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted ) { var dataTypes = subscriptionDataTypes ?? LookupSubscriptionConfigDataTypes(symbol.SecurityType, resolution ?? Resolution.Minute, symbol.IsCanonical()); if (!dataTypes.Any()) { throw new ArgumentNullException(nameof(dataTypes), "At least one type needed to create new subscriptions"); } var resolutionWasProvided = resolution.HasValue; foreach (var typeTuple in dataTypes) { var baseInstance = typeTuple.Item1.GetBaseDataInstance(); baseInstance.Symbol = symbol; if (!resolutionWasProvided) { var defaultResolution = baseInstance.DefaultResolution(); if (resolution.HasValue && resolution != defaultResolution) { // we are here because there are multiple 'dataTypes'. // if we get different default resolutions lets throw, this shouldn't happen throw new InvalidOperationException( $"Different data types ({string.Join(",", dataTypes.Select(tuple => tuple.Item1))})" + $" provided different default resolutions {defaultResolution} and {resolution}, this is an unexpected invalid operation."); } resolution = defaultResolution; } else { // only assert resolution in backtesting, live can use other data source // for example daily data for options if (!_liveMode) { var supportedResolutions = baseInstance.SupportedResolutions(); if (supportedResolutions.Contains(resolution.Value)) { continue; } throw new ArgumentException($"Sorry {resolution.ToStringInvariant()} is not a supported resolution for {typeTuple.Item1.Name}" + $" and SecurityType.{symbol.SecurityType.ToStringInvariant()}." + $" Please change your AddData to use one of the supported resolutions ({string.Join(",", supportedResolutions)})."); } } } var marketHoursDbEntry = _marketHoursDatabase.GetEntry(symbol, dataTypes.Select(tuple => tuple.Item1)); var exchangeHours = marketHoursDbEntry.ExchangeHours; if (symbol.ID.SecurityType.IsOption() || symbol.ID.SecurityType == SecurityType.Future || symbol.ID.SecurityType == SecurityType.Index) { dataNormalizationMode = DataNormalizationMode.Raw; } if (marketHoursDbEntry.DataTimeZone == null) { throw new ArgumentNullException(nameof(marketHoursDbEntry.DataTimeZone), "DataTimeZone is a required parameter for new subscriptions. Set to the time zone the raw data is time stamped in."); } if (exchangeHours.TimeZone == null) { throw new ArgumentNullException(nameof(exchangeHours.TimeZone), "ExchangeTimeZone is a required parameter for new subscriptions. Set to the time zone the security exchange resides in."); } var result = (from subscriptionDataType in dataTypes let dataType = subscriptionDataType.Item1 let tickType = subscriptionDataType.Item2 select new SubscriptionDataConfig( dataType, symbol, resolution.Value, marketHoursDbEntry.DataTimeZone, exchangeHours.TimeZone, fillForward, extendedMarketHours, // if the subscription data types were not provided and the tick type is OpenInterest we make it internal subscriptionDataTypes == null && tickType == TickType.OpenInterest || isInternalFeed, isCustomData, isFilteredSubscription: isFilteredSubscription, tickType: tickType, dataNormalizationMode: dataNormalizationMode)).ToList(); for (int i = 0; i < result.Count; i++) { result[i] = SubscriptionManagerGetOrAdd(result[i]); // track all registered data types _registeredTypesProvider.RegisterType(result[i].Type); } return result; } /// <summary> /// Get the data feed types for a given <see cref="SecurityType" /> <see cref="Resolution" /> /// </summary> /// <param name="symbolSecurityType">The <see cref="SecurityType" /> used to determine the types</param> /// <param name="resolution">The resolution of the data requested</param> /// <param name="isCanonical">Indicates whether the security is Canonical (future and options)</param> /// <returns>Types that should be added to the <see cref="SubscriptionDataConfig" /></returns> public List<Tuple<Type, TickType>> LookupSubscriptionConfigDataTypes( SecurityType symbolSecurityType, Resolution resolution, bool isCanonical ) { if (isCanonical) { return new List<Tuple<Type, TickType>> { new Tuple<Type, TickType>(typeof(ZipEntryName), TickType.Quote) }; } IEnumerable<TickType> availableDataType = AvailableDataTypes[symbolSecurityType]; // Equities will only look for trades in case of low resolutions. if (symbolSecurityType == SecurityType.Equity && (resolution == Resolution.Daily || resolution == Resolution.Hour)) { // we filter out quote tick type availableDataType = availableDataType.Where(t => t != TickType.Quote); } return availableDataType .Select(tickType => new Tuple<Type, TickType>(LeanData.GetDataType(resolution, tickType), tickType)).ToList(); } /// <summary> /// Gets a list of all registered <see cref="SubscriptionDataConfig"/> for a given <see cref="Symbol"/> /// </summary> /// <remarks>Will not return internal subscriptions by default</remarks> public List<SubscriptionDataConfig> GetSubscriptionDataConfigs(Symbol symbol, bool includeInternalConfigs = false) { return SubscriptionManagerSubscriptions.Where(x => x.Symbol == symbol && (includeInternalConfigs || !x.IsInternalFeed)).ToList(); } #endregion #endregion #region IDataManager /// <summary> /// Get the universe selection instance /// </summary> public UniverseSelection UniverseSelection { get; } #endregion } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Data; using GeoAPI.Geometries; namespace DotSpatial.Data { /// <summary> /// A layer contains a list of features of a specific type that matches the geometry type. /// While this supports IRenderable, this merely forwards the drawing instructions to /// each of its members, but does not allow the control of any default layer properties here. /// Calling FeatureDataSource.Open will create a number of layers of the appropriate /// specific type and also create a specific layer type that is derived from this class /// that does expose default "layer" properties, as well as the symbology elements. /// </summary> public interface IFeatureSet : IDataSet, IAttributeSource { /// <summary> /// Occurs when a new feature is added to the list. /// </summary> event EventHandler<FeatureEventArgs> FeatureAdded; /// <summary> /// Occurs when a feature is removed from the list. /// </summary> event EventHandler<FeatureEventArgs> FeatureRemoved; /// <summary> /// Occurs when the vertices are invalidated, encouraging a re-draw. /// </summary> event EventHandler VerticesInvalidated; #region Properties /// <summary> /// Gets or sets a value indicating whether or not the attributes have all been loaded into the data table. /// </summary> bool AttributesPopulated { get; set; } /// <summary> /// Gets or sets the coordinate type across the entire featureset. /// </summary> CoordinateType CoordinateType { get; set; } /// <summary> /// Gets or sets the DataTable associated with this specific feature. /// </summary> IDataTable DataTable { get; set; } /// <summary> /// Gets or sets an optional GeometryFactory that can be set to control how the geometries on features are /// created. if this is not specified, the default GeometryFactory is used. /// </summary> IGeometryFactory FeatureGeometryFactory { get; set; } /// <summary> /// Gets the feature lookup Table itself. /// </summary> Dictionary<IDataRow, IFeature> FeatureLookup { get; } /// <summary> /// Gets or sets the list of all the features that are included in this layer. /// </summary> IFeatureList Features { get; set; } /// <summary> /// Gets or sets an enumeration indicating the type of feature represented in this dataset, if any. /// </summary> FeatureType FeatureType { get; set; } /// <summary> /// Gets or sets a value indicating whether the ShapeIndices and Vertex values are used, /// and features are created on demand. If set to false the list of Features is used directly. /// </summary> bool IndexMode { get; set; } /// <summary> /// Gets or sets the M coordinates. /// </summary> double[] M { get; set; } /// <summary> /// Gets or sets the shape indices. These specifically allow the user to make sense of the Vertices array. These are /// fast acting sealed classes and are not meant to be overridden or support clever /// new implementations. /// </summary> List<ShapeRange> ShapeIndices { get; set; } /// <summary> /// Gets or sets an array of Vertex structures with X and Y coordinates /// </summary> double[] Vertex { get; set; } /// <summary> /// Gets a value indicating whether or not the InvalidateVertices has been called /// more recently than the cached vertex array has been built. /// </summary> bool VerticesAreValid { get; } /// <summary> /// Gets or sets the Z coordinates. /// </summary> double[] Z { get; set; } #endregion #region Methods /// <summary> /// Generates a new feature, adds it to the features and returns the value. /// </summary> /// <param name="geometry">The geometry that is used to create the feature.</param> /// <returns>The feature that was added to this featureset</returns> IFeature AddFeature(IGeometry geometry); /// <summary> /// Adds the FID values as a field called FID, but only if the FID field does not already exist. /// </summary> void AddFid(); /// <summary> /// If this featureset is in index mode, this will append the vertices and shapeindex of the shape. Otherwise, this will add a /// new feature based on this shape. If the attributes of the shape are not null, this will attempt to append a new datarow. /// It is up to the developer to ensure that the object array of attributes matches the this featureset. If the Attributes of /// this feature are loaded, this will add the attributes in ram only. Otherwise, this will attempt to insert the attributes as a /// new record using the "AddRow" method. The schema of the object array should match this featureset's column schema. /// </summary> /// <param name="shape">The shape to add to this featureset.</param> void AddShape(Shape shape); /// <summary> /// Adds any type of list or array of shapes. If this featureset is not in index moded, /// it will add the features to the featurelist and suspend events for faster copying. /// </summary> /// <param name="shapes">An enumerable collection of shapes.</param> void AddShapes(IEnumerable<Shape> shapes); /// <summary> /// Copies all the features to a new featureset. /// </summary> /// <param name="withAttributes">Indicates whether the features attributes should be copied. If this is true, /// and the attributes are not loaded, a FillAttributes call will be made.</param> /// <returns>A featureset with the copied features.</returns> IFeatureSet CopyFeatures(bool withAttributes); /// <summary> /// Retrieves a subset using exclusively the features matching the specified values. Attributes are always copied. /// </summary> /// <param name="indices">An integer list of indices to copy into the new FeatureSet</param> /// <returns>A FeatureSet with the new items.</returns> IFeatureSet CopySubset(List<int> indices); /// <summary> /// Retrieves a subset using exclusively the features matching the specified values. Attributes are only copied if withAttributes is true. /// </summary> /// <param name="indices">An integer list of indices to copy into the new FeatureSet.</param> /// <param name="withAttributes">Indicates whether the features attributes should be copied.</param> /// <returns>A FeatureSet with the new items.</returns> IFeatureSet CopySubset(List<int> indices, bool withAttributes); /// <summary> /// Copies the subset of specified features to create a new featureset that is restricted to /// just the members specified. Attributes are always copied. /// </summary> /// <param name="filterExpression">The string expression to that specifies the features that should be copied. /// An empty expression copies all features.</param> /// <returns>A FeatureSet that has members that only match the specified members.</returns> IFeatureSet CopySubset(string filterExpression); /// <summary> /// Copies the subset of specified features to create a new featureset that is restricted to /// just the members specified. /// </summary> /// <param name="filterExpression">The string expression to that specifies the features that should be copied. /// An empty expression copies all features.</param> /// <param name="withAttributes">Indicates whether the features attributes should be copied.</param> /// <returns>A FeatureSet that has members that only match the specified members.</returns> IFeatureSet CopySubset(string filterExpression, bool withAttributes); /// <summary> /// Copies only the names and types of the attribute fields, without copying any of the attributes or features. /// </summary> /// <param name="source">The source featureSet to obtain the schema from.</param> void CopyTableSchema(IFeatureSet source); /// <summary> /// Copies the Table schema (column names/data types) /// from a DatatTable, but doesn't copy any values. /// </summary> /// <param name="sourceTable">The Table to obtain schema from.</param> void CopyTableSchema(IDataTable sourceTable); /// <summary> /// Exports current shapefile as a zip archive in memory /// </summary> /// <returns>Shapefile components.</returns> ShapefilePackage ExportShapefilePackage(); /// <summary> /// Given a datarow, this will return the associated feature. This FeatureSet uses an internal dictionary, so that even /// if the items are re-ordered or have new members inserted, this lookup will still work. /// </summary> /// <param name="row">The DataRow for which to obtaind the feature</param> /// <returns>The feature to obtain that is associated with the specified data row.</returns> IFeature FeatureFromRow(IDataRow row); /// <summary> /// Instructs the shapefile to read all the attributes from the file. /// This may also be a cue to read values from a database. /// </summary> void FillAttributes(); /// <summary> /// Instructs the shapefile to read all the attributes from the file. /// This may also be a cue to read values from a database. /// </summary> /// <param name="progressHandler">A ProgressHandler to show the progress.</param> void FillAttributes(IProgressHandler progressHandler); /// <summary> /// Gets the specified feature by constructing it from the vertices, rather /// than requiring that all the features be created. (which takes up a lot of memory). /// </summary> /// <param name="index">The integer index</param> /// <returns>The specified feature.</returns> IFeature GetFeature(int index); /// <summary> /// Gets a shape at the specified shape index. If the featureset is in IndexMode, this returns a copy of the shape. /// If not, it will create a new shape based on the specified feature. /// </summary> /// <param name="index">The zero based integer index of the shape.</param> /// <param name="getAttributes">If getAttributes is true, then this also try to get attributes for that shape. /// If attributes are loaded, then it will use the existing datarow. Otherwise, it will read the attributes /// from the file. (This second option is not recommended for large repeats. In such a case, the attributes /// can be set manually from a larger bulk query of the data source.)</param> /// <returns>The Shape object</returns> Shape GetShape(int index, bool getAttributes); /// <summary> /// This forces the vertex initialization so that Vertices, ShapeIndices, and the /// ShapeIndex property on each feature will no longer be null. /// </summary> void InitializeVertices(); /// <summary> /// Switches a boolean so that the next time that the vertices are requested, /// they must be re-calculated from the feature coordinates. /// </summary> /// <remarks>This only affects reading values from the Vertices cache</remarks> void InvalidateVertices(); /// <summary> /// For attributes that are small enough to be loaded into a data table, this will join attributes from a foreign table. This method /// won't create new rows in this table, so only matching members are brought in, but no rows are removed either, so not all rows will receive data. /// </summary> /// <param name="table">Foreign data table.</param> /// <param name="localJoinField">The field name to join on in this table.</param> /// <param name="dataTableJoinField">The field in the foreign table.</param> /// <returns> /// A modified featureset with the changes. /// </returns> IFeatureSet Join(DataTable table, string localJoinField, string dataTableJoinField); /// <summary> /// For attributes that are small enough to be loaded into a data table, this will join attributes from a foreign table (from an excel file). This method /// won't create new rows in this table, so only matching members are brought in, but no rows are removed either, so not all rows will receive data. /// </summary> /// <param name="xlsFilePath">The complete path of the file to join</param> /// <param name="localJoinField">The field name to join on in this table</param> /// <param name="xlsJoinField">The field in the foreign table.</param> /// <returns> /// A modified featureset with the changes. /// </returns> IFeatureSet Join(string xlsFilePath, string localJoinField, string xlsJoinField); /// <summary> /// Attempts to remove the specified shape. /// </summary> /// <param name="index"> /// The integer index of the shape to remove. /// </param> /// <returns> /// Boolean, true if the remove was successful. /// </returns> bool RemoveShapeAt(int index); /// <summary> /// Attempts to remove a range of shapes by index. This is optimized to /// work better for large numbers. For one or two, using RemoveShapeAt might /// be faster. /// </summary> /// <param name="indices"> /// The enumerable set of indices to remove. /// </param> void RemoveShapesAt(IEnumerable<int> indices); /// <summary> /// Saves the information in the Layers provided by this datasource onto its existing file location /// </summary> void Save(); /// <summary> /// Saves a datasource to the file. /// </summary> /// <param name="fileName">The string fileName location to save to</param> /// <param name="overwrite">Boolean, if this is true then it will overwrite a file of the existing name.</param> void SaveAs(string fileName, bool overwrite); /// <summary> /// returns only the features that have envelopes that /// intersect with the specified envelope. /// </summary> /// <param name="region">The specified region to test for intersect with</param> /// <returns>A List of the IFeature elements that are contained in this region</returns> List<IFeature> Select(Extent region); /// <summary> /// returns only the features that have envelopes that /// intersect with the specified envelope. /// </summary> /// <param name="region">The specified region to test for intersect with</param> /// <param name="selectedRegion">This returns the geographic extents for the entire selected area.</param> /// <returns>A List of the IFeature elements that are contained in this region</returns> List<IFeature> Select(Extent region, out Extent selectedRegion); /// <summary> /// The string filter expression to use in order to return the desired features. /// </summary> /// <param name="filterExpression">The features to return.</param> /// <returns>The list of desired features.</returns> List<IFeature> SelectByAttribute(string filterExpression); /// <summary> /// This version is more tightly integrated to the DataTable and returns the row indices, rather /// than attempting to link the results to features themselves, which may not even exist. /// </summary> /// <param name="filterExpression">The filter expression</param> /// <returns>The list of indices</returns> List<int> SelectIndexByAttribute(string filterExpression); /// <summary> /// Skips the features themselves and uses the shapeindicies instead. /// </summary> /// <param name="region">The region to select members from</param> /// <returns>A list of integer valued shape indices that are selected.</returns> List<int> SelectIndices(Extent region); /// <summary> /// After changing coordinates, this will force the re-calculation of envelopes on a feature /// level as well as on the featureset level. /// </summary> void UpdateExtent(); #endregion } }