context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace OLEDB.Test.ModuleCore { //////////////////////////////////////////////////////////////// // CTestBase // //////////////////////////////////////////////////////////////// public abstract class CTestBase : IComparable { //Defines public const int TEST_FAIL = (int)tagVARIATION_STATUS.eVariationStatusFailed; public const int TEST_PASS = (int)tagVARIATION_STATUS.eVariationStatusPassed; public const int TEST_SKIPPED = (int)tagVARIATION_STATUS.eVariationStatusNotRun; public const int TEST_NOTFOUND = (int)tagVARIATION_STATUS.eVariationStatusNonExistent; public const int TEST_UNKNOWN = (int)tagVARIATION_STATUS.eVariationStatusUnknown; public const int TEST_TIMEOUT = (int)tagVARIATION_STATUS.eVariationStatusTimedOut; public const int TEST_WARNING = (int)tagVARIATION_STATUS.eVariationStatusConformanceWarning; public const int TEST_EXCEPTION = (int)tagVARIATION_STATUS.eVariationStatusException; public const int TEST_ABORTED = (int)tagVARIATION_STATUS.eVariationStatusAborted; //Data private CTestBase _parent; private List<object> _children; private CAttrBase _attribute; //Constructor public CTestBase(string desc) : this(null, desc) { } //Constructor public CTestBase(string name, string desc) { //Now set the passed in names. if (name != null) this.Name = name; if (this.Name == null) this.Name = "No Name Provided"; if (desc != null) this.Desc = desc; } //Accessors public virtual CAttrBase Attribute { get { if (_attribute == null) _attribute = CreateAttribute(); return _attribute; } set { _attribute = value; } } protected abstract CAttrBase CreateAttribute(); //Note: These are just a mere convenience to access the attribute values //for this particular object. Also note that for non-attribute based //scenarios (dynamic), the attribute class will be created just to hold //the values public object Param { get { return Attribute.Param; } set { Attribute.Param = value; } } public object[] Params { get { return Attribute.Params; } set { Attribute.Params = value; } } public int id { get { return Attribute.id; } set { Attribute.id = value; } } public int Pri { get { return Attribute.Pri; } set { Attribute.Pri = value; } } public int Priority //Alias for Pri { get { return Attribute.Pri; } set { Attribute.Pri = value; } } public string Name { get { return Attribute.Name; } set { Attribute.Name = value; } } public string Desc { get { return Attribute.Desc; } set { Attribute.Desc = value; } } public bool Implemented { get { return Attribute.Implemented; } set { Attribute.Implemented = value; } } public bool Skipped { get { return Attribute.Skipped; } set { Attribute.Skipped = value; } } public bool Error { get { return Attribute.Error; } set { Attribute.Error = value; } } public SecurityFlags Security { get { return Attribute.Security; } set { Attribute.Security = value; } } public bool Inheritance { get { return Attribute.Inheritance; } set { Attribute.Inheritance = value; } } public string FilterCriteria { get { return Attribute.FilterCriteria; } set { Attribute.FilterCriteria = value; } } public string Language { get { return Attribute.Language; } set { Attribute.Language = value; } } public string[] Languages { get { return Attribute.Languages; } set { Attribute.Languages = value; } } public string Xml { get { return Attribute.Xml; } set { Attribute.Xml = value; } } protected CTestBase Parent { get { return _parent; } set { _parent = value; } } public string Filter { get { return Attribute.Filter; } set { Attribute.Filter = value; } } public List<object> Children { get { //Deferred Creation of the children. if (_children == null) _children = new List<object>(); return _children; } set { _children = value; } } protected virtual void UpdateAttributes() { } protected virtual void DetermineChildren() { //Override this method if this node has children } protected void AddChild(CTestBase child) { //Setup the parent child.Parent = this; //Inheritance of attributes child.Attribute.Parent = this.Attribute; //Adjust the Id (if not set) if (child.id <= 0) child.id = Children.Count + 1; //Only add implemented items //Note: we still increment id counts, to save the 'spot' once they are implemented if (child.Implemented || CModInfo.IncludeNotImplemented) { //Determine any children of this node (before adding it) //Note: We don't call 'determinechildren' from within the (test case) constructor //since none of the attributes/properties are setup until now. So as soon as we //setup that information then we call determinechildren which when implemented //for dynamic tests can now look at those properties (otherwise they wouldn't be setup //until after the constructor returns). child.DetermineChildren(); //Add it to our list... Children.Add(child); } } public virtual void AddChildren() { } //ITestCase implementation public string GetName() { return Name; } public string GetDescription() { return Desc; } public virtual int Init(object o) { //Note: This version is the only override-able Init, since the other one //automatically handles the exception you might throw from this function //Note: If you override this function, (as with most overrides) make sure you call the base. return TEST_PASS; } public int Init() { try { //Skipped if (this.Skipped || !this.Implemented) return TEST_SKIPPED; return Init(Param); } catch (Exception e) { return HandleException(e); } } public virtual int Terminate(object o) { //Note: This version is the only override-able Terminate, since the other one //automatically handles the exception you might throw from this function //Note: If you override this function, (as with most overrides) make sure you call the base. return TEST_PASS; } public bool Terminate() { bool bResult = false; try { //Skipped if (this.Skipped || !this.Implemented) return true; if (Terminate(Param) == TEST_PASS) bResult = true; } catch (Exception e) { Console.WriteLine(e); HandleException(e); } try { //Clear any previous existing info (in the static class). if (this is CTestModule) { //Note: We actually have to clear these "statics" since they are not cleaned up //until the process exits. Which means that if you run again, in an apartment model //thread it will try to release these when setting them which is not allowed to //call a method on an object created in another apartment CModInfo.Dispose(); } } catch (Exception e) { HandleException(e); } //This is also a good point to hint to the GC to free up any unused memory //at the end of each TestCase and the end of each module. GC.Collect(); GC.WaitForPendingFinalizers(); return bResult; } public virtual tagVARIATION_STATUS Execute() { return tagVARIATION_STATUS.eVariationStatusPassed; } public int CompareTo(object o) { return this.id.CompareTo(((CTestBase)o).id); } public static int HandleException(Exception e) { //TargetInvocationException is almost always the outer //since we call the variation through late binding if (e.InnerException != null) e = e.InnerException; int eResult = TEST_FAIL; object actual = e.GetType(); object expected = null; string message = e.Message; tagERRORLEVEL eErrorLevel = tagERRORLEVEL.HR_FAIL; if (e is CTestException) { CTestException eTest = (CTestException)e; //Setup more meaningful info actual = eTest.Actual; expected = eTest.Expected; eResult = eTest.Result; switch (eResult) { case TEST_PASS: case TEST_SKIPPED: return eResult; //were done case TEST_WARNING: eErrorLevel = tagERRORLEVEL.HR_WARNING; break; }; } //Note: We don't use Exception.ToString as the details for the log since that also includes //the message text (again). Normally this isn't a problem but if you throw a good message //(multiple lines) it show up twice and is confusing. So we will strictly use the //StackTrace as the details and roll our own message (which also include inner exception //messages). Exception inner = e.InnerException; CError.Log(actual, expected, e.Source, message, e.StackTrace, eErrorLevel); while (inner != null) { CError.WriteLine("\n INNER EXCEPTION :"); CError.Log(actual, expected, inner.Source, inner.Message, inner.StackTrace, eErrorLevel); inner = inner.InnerException; } return eResult; } } }
using UnityEngine; using System.Collections; using UnityEngine.Events; namespace RootMotion.Dynamics { /// <summary> /// The base abstract class for all Puppet Behaviours. /// </summary> public abstract class BehaviourBase : MonoBehaviour { /// <summary> /// Gets the PuppetMaster associated with this behaviour. Returns null while the behaviour is not initiated by the PuppetMaster. /// </summary> public PuppetMaster puppetMaster { get; private set; } public delegate void BehaviourDelegate(); public delegate void HitDelegate(MuscleHit hit); public delegate void CollisionDelegate(MuscleCollision collision); public abstract void OnReactivate(); public BehaviourDelegate OnPreActivate; public BehaviourDelegate OnPreInitiate; public BehaviourDelegate OnPreFixedUpdate; public BehaviourDelegate OnPreUpdate; public BehaviourDelegate OnPreLateUpdate; public BehaviourDelegate OnPreDisable; public BehaviourDelegate OnPreFixTransforms; public BehaviourDelegate OnPreRead; public BehaviourDelegate OnPreWrite; public HitDelegate OnPreMuscleHit; public CollisionDelegate OnPreMuscleCollision; public CollisionDelegate OnPreMuscleCollisionExit; public virtual void Resurrect() {} public virtual void Freeze() {} public virtual void Unfreeze() {} public virtual void KillStart() {} public virtual void KillEnd() {} protected virtual void OnActivate() {} protected virtual void OnDeactivate() {} protected virtual void OnInitiate() {} protected virtual void OnFixedUpdate() {} protected virtual void OnUpdate() {} protected virtual void OnLateUpdate() {} protected virtual void OnDisableBehaviour() {} protected virtual void OnDrawGizmosBehaviour() {} protected virtual void OnFixTransformsBehaviour() {} protected virtual void OnReadBehaviour() {} protected virtual void OnWriteBehaviour() {} protected virtual void OnMuscleHitBehaviour(MuscleHit hit) {} protected virtual void OnMuscleCollisionBehaviour(MuscleCollision collision) {} protected virtual void OnMuscleCollisionExitBehaviour(MuscleCollision collision) {} public BehaviourDelegate OnPostActivate; public BehaviourDelegate OnPostInitiate; public BehaviourDelegate OnPostFixedUpdate; public BehaviourDelegate OnPostUpdate; public BehaviourDelegate OnPostLateUpdate; public BehaviourDelegate OnPostDisable; public BehaviourDelegate OnPostDrawGizmos; public BehaviourDelegate OnPostFixTransforms; public BehaviourDelegate OnPostRead; public BehaviourDelegate OnPostWrite; public HitDelegate OnPostMuscleHit; public CollisionDelegate OnPostMuscleCollision; public CollisionDelegate OnPostMuscleCollisionExit; [HideInInspector] public bool deactivated; public bool forceActive { get; protected set; } private bool initiated = false; public void Initiate(PuppetMaster puppetMaster) { this.puppetMaster = puppetMaster; initiated = true; if (OnPreInitiate != null) OnPreInitiate(); OnInitiate(); if (OnPostInitiate != null) OnPostInitiate(); } public void Activate() { if (!initiated) { Debug.LogError("Trying to activate a puppet behaviour that has not initiated yet.", transform); return; } foreach (BehaviourBase b in puppetMaster.behaviours) { if (b != this && b.enabled) { b.enabled = false; b.OnDeactivate(); } } this.enabled = true; if (OnPreActivate != null) OnPreActivate(); OnActivate(); if (OnPostActivate != null) OnPostActivate(); } public void OnFixTransforms() { if (!initiated) return; if (!enabled) return; if (OnPreFixTransforms != null) OnPreFixTransforms(); OnFixTransformsBehaviour(); if (OnPostFixTransforms != null) OnPostFixTransforms(); } public void OnRead() { if (!initiated) return; if (!enabled) return; if (OnPreRead != null) OnPreRead(); OnReadBehaviour(); if (OnPostRead != null) OnPostRead(); } public void OnWrite() { if (!initiated) return; if (!enabled) return; if (OnPreWrite != null) OnPreWrite(); OnWriteBehaviour(); if (OnPostWrite != null) OnPostWrite(); } public void OnMuscleHit(MuscleHit hit) { if (!initiated) return; if (OnPreMuscleHit != null) OnPreMuscleHit(hit); OnMuscleHitBehaviour(hit); if (OnPostMuscleHit != null) OnPostMuscleHit(hit); } public void OnMuscleCollision(MuscleCollision collision) { if (!initiated) return; if (OnPreMuscleCollision != null) OnPreMuscleCollision(collision); OnMuscleCollisionBehaviour(collision); if (OnPostMuscleCollision != null) OnPostMuscleCollision(collision); } public void OnMuscleCollisionExit(MuscleCollision collision) { if (!initiated) return; if (OnPreMuscleCollisionExit != null) OnPreMuscleCollisionExit(collision); OnMuscleCollisionExitBehaviour(collision); if (OnPostMuscleCollisionExit != null) OnPostMuscleCollisionExit(collision); } void OnDisable() { if (!initiated) return; if (OnPreDisable != null) OnPreDisable(); OnDisableBehaviour(); if (OnPostDisable != null) OnPostDisable(); } void FixedUpdate() { if (!initiated) return; if (OnPreFixedUpdate != null && enabled) OnPreFixedUpdate(); OnFixedUpdate(); if (OnPostFixedUpdate != null && enabled) OnPostFixedUpdate(); } void Update() { if (!initiated) return; if (OnPreUpdate != null && enabled) OnPreUpdate(); OnUpdate(); if (OnPostUpdate != null && enabled) OnPostUpdate(); } void LateUpdate() { if (!initiated) return; if (OnPreLateUpdate != null && enabled) OnPreLateUpdate(); OnLateUpdate(); if (OnPostLateUpdate != null && enabled) OnPostLateUpdate(); } protected virtual void OnDrawGizmos() { if (!initiated) return; OnDrawGizmosBehaviour(); if (OnPostDrawGizmos != null) OnPostDrawGizmos(); } /// <summary> /// Defines actions taken on certain events defined by the Puppet Behaviours. /// </summary> [System.Serializable] public struct PuppetEvent { [TooltipAttribute("Another Puppet Behaviour to switch to on this event. This must be the exact Type of the the Behaviour, careful with spelling.")] /// <summary> /// Another Puppet Behaviour to switch to on this event. This must be the exact Type of the the Behaviour, careful with spelling. /// </summary> public string switchToBehaviour; [TooltipAttribute("Animations to cross-fade to on this event. This is separate from the UnityEvent below because UnityEvents can't handle calls with more than one parameter such as Animator.CrossFade.")] /// <summary> /// Animations to cross-fade to on this event. This is separate from the UnityEvent below because UnityEvents can't handle calls with more than one parameter such as Animator.CrossFade. /// </summary> public AnimatorEvent[] animations; [TooltipAttribute("The UnityEvent to invoke on this event.")] /// <summary> /// The UnityEvent to invoke on this event. /// </summary> public UnityEvent unityEvent; public bool switchBehaviour { get { return switchToBehaviour != string.Empty && switchToBehaviour != empty; } } private const string empty = ""; public void Trigger(PuppetMaster puppetMaster, bool switchBehaviourEnabled = true) { unityEvent.Invoke(); foreach (AnimatorEvent animatorEvent in animations) animatorEvent.Activate(puppetMaster.targetAnimator, puppetMaster.targetAnimation); if (switchBehaviour) { bool found = false; foreach (BehaviourBase behaviour in puppetMaster.behaviours) { //if (behaviour != null && behaviour.GetType() == System.Type.GetType(switchToBehaviour)) { if (behaviour != null && behaviour.GetType().ToString() == "RootMotion.Dynamics." + switchToBehaviour) { found = true; behaviour.Activate(); break; } } if (!found) { Debug.LogWarning("No Puppet Behaviour of type '" + switchToBehaviour + "' was found. Can not switch to the behaviour, please check the spelling (also for empty spaces)."); } } } } /// <summary> /// Cross-fades to an animation state. UnityEvent can not be used for cross-fading, it requires multiple parameters. /// </summary> [System.Serializable] public class AnimatorEvent { /// <summary> /// The name of the animation state /// </summary> public string animationState; /// <summary> /// The crossfading time /// </summary> public float crossfadeTime = 0.3f; /// <summary> /// The layer of the animation state (if using Legacy, the animation state will be forced to this layer) /// </summary> public int layer; /// <summary> /// Should the animation always start from 0 normalized time? /// </summary> public bool resetNormalizedTime; private const string empty = ""; // Activate the animation public void Activate(Animator animator, Animation animation) { if (animator != null) Activate(animator); if (animation != null) Activate(animation); } // Activate a Mecanim animation private void Activate(Animator animator) { if (animationState == empty) return; if (resetNormalizedTime) { if (crossfadeTime > 0f) animator.CrossFadeInFixedTime(animationState, crossfadeTime, layer, 0f); else animator.Play(animationState, layer, 0f); } else { if (crossfadeTime > 0f) { animator.CrossFadeInFixedTime(animationState, crossfadeTime, layer); } else animator.Play(animationState, layer); } } // Activate a Legacy animation private void Activate(Animation animation) { if (animationState == empty) return; if (resetNormalizedTime) animation[animationState].normalizedTime = 0f; animation[animationState].layer = layer; animation.CrossFade(animationState, crossfadeTime); } } protected void RotateTargetToRootMuscle() { Vector3 hipsForward = Quaternion.Inverse(puppetMaster.muscles[0].target.rotation) * puppetMaster.targetRoot.forward; Vector3 forward = puppetMaster.muscles[0].rigidbody.rotation * hipsForward; forward.y = 0f; puppetMaster.targetRoot.rotation = Quaternion.LookRotation(forward); } protected void TranslateTargetToRootMuscle(float maintainY) { puppetMaster.muscles[0].target.position = new Vector3( puppetMaster.muscles[0].transform.position.x, Mathf.Lerp(puppetMaster.muscles[0].transform.position.y, puppetMaster.muscles[0].target.position.y, maintainY), puppetMaster.muscles[0].transform.position.z); } protected void RemoveMusclesOfGroup(Muscle.Group group) { while (MusclesContainsGroup(group)) { for (int i = 0; i < puppetMaster.muscles.Length; i++) { if (puppetMaster.muscles[i].props.group == group) { puppetMaster.RemoveMuscleRecursive(puppetMaster.muscles[i].joint, true); break; } } } } protected void GroundTarget(LayerMask layers) { Ray ray = new Ray(puppetMaster.targetRoot.position + puppetMaster.targetRoot.up, -puppetMaster.targetRoot.up); RaycastHit hit; if (Physics.Raycast(ray, out hit, 4f, layers)) { puppetMaster.targetRoot.position = hit.point; } } protected bool MusclesContainsGroup(Muscle.Group group) { foreach (Muscle m in puppetMaster.muscles) { if (m.props.group == group) return true; } return false; } } }
// Copyright 2006-2008 Splicer Project - http://www.codeplex.com/splicer/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using Splicer.Properties; namespace Splicer.Timeline { public sealed class VirtualClipCollection : IVirtualClipCollection { private readonly List<VirtualClip> _clips = new List<VirtualClip>(); #region IVirtualClipCollection Members public IVirtualClip this[int index] { get { return _clips[index]; } } public int Count { get { return _clips.Count; } } public IEnumerator<IVirtualClip> GetEnumerator() { return new List<IVirtualClip>(_clips.ToArray()).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) _clips).GetEnumerator(); } #endregion public void AddVirtualClip(IClip clip) { AdjustForNewclip(clip); AddClip(clip); } private void AdjustForNewclip(IClip clip) { double newClipStart = clip.Offset; double newClipEnd = clip.Duration + clip.Offset; foreach (VirtualClip virtualClip in _clips.ToArray()) { double curClipStart = virtualClip.Offset; double curClipEnd = virtualClip.Duration + virtualClip.Offset; if ((curClipStart >= newClipStart) && (curClipEnd <= newClipEnd)) { // scenario 1, full occlusion, remove the clip _clips.Remove(virtualClip); } else if ((curClipStart < newClipStart) && (curClipEnd > newClipEnd)) { // scenario 2, split the clip in two double frontDelta = newClipStart - curClipStart; double endDelta = curClipEnd - newClipEnd; // reduce duration of part of clip that falls over front virtualClip.Duration = frontDelta; // add a new clip for the part of the clip falls over the end of the new clip AddClip(newClipEnd, endDelta, (newClipEnd - curClipStart) + virtualClip.MediaStart, virtualClip.SourceClip); } else if ((newClipStart <= curClipStart) && (newClipEnd < curClipEnd) && (newClipEnd > curClipStart)) { // scenario 3, trim front of clip double delta = newClipEnd - curClipStart; virtualClip.Duration -= delta; virtualClip.MediaStart += delta; virtualClip.Offset += delta; } else if ((newClipStart > curClipStart) && (newClipStart < curClipEnd) && (newClipEnd >= curClipEnd)) { // scenario 4, trim end of clip double delta = curClipEnd - newClipStart; virtualClip.Duration -= delta; } } } private void AddClip(IClip clip) { AddClip(clip.Offset, clip.Duration, clip.MediaStart, clip); } private void AddClip(double offset, double duration, double mediaStart, IClip clip) { _clips.Add(new VirtualClip(offset, duration, mediaStart, clip)); _clips.Sort(); } public override string ToString() { var builder = new StringBuilder(); foreach (VirtualClip clip in _clips) { if (builder.Length > 0) builder.Append(Environment.NewLine); builder.Append(clip.ToString()); } return builder.ToString(); } } public class VirtualClip : IVirtualClip, IComparable<IVirtualClip>, IComparable { private readonly IClip _sourceClip; private double _offset; public VirtualClip(double offset, double duration, double mediaStart, IClip sourceClip) { _offset = offset; Duration = duration; MediaStart = mediaStart; _sourceClip = sourceClip; } #region IComparable Members public int CompareTo(object obj) { return CompareTo(obj as VirtualClip); } #endregion #region IComparable<IVirtualClip> Members public int CompareTo(IVirtualClip other) { if (other == null) return -1; return _offset.CompareTo(other.Offset); } #endregion #region IVirtualClip Members public double Offset { get { return _offset; } set { _offset = value; } } public double Duration { get; set; } public double MediaStart { get; set; } public IClip SourceClip { get { return _sourceClip; } } public string Name { get { return _sourceClip.Name; } } #endregion public override bool Equals(Object obj) { if (!(obj is IVirtualClip)) return false; return (CompareTo(obj) == 0); } public override int GetHashCode() { return (int) _offset; } public static bool operator ==(VirtualClip r1, VirtualClip r2) { return r1.Equals(r2); } public static bool operator !=(VirtualClip r1, VirtualClip r2) { return !(r1 == r2); } public static bool operator <(VirtualClip r1, VirtualClip r2) { return (r1.CompareTo(r2) < 0); } public static bool operator >(VirtualClip r1, VirtualClip r2) { return (r1.CompareTo(r2) > 0); } public override string ToString() { return string.Format(CultureInfo.CurrentUICulture, Resources.VirtualClipToStringTemplate, Offset, Offset + Duration, SourceClip.File.FileName, MediaStart); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace BinaryTree { public class BinaryTree<TData> : ICollection<TData>, IEnumerable<TData>, IEnumerable, ITree<TData> { private BinaryTree<TData> leftSubtree; private BinaryTree<TData> rightSubtree; /// <summary> /// Gets the number of children at this level, which can be at most two. /// /// </summary> public int Count { get { int num = 0; if (this.leftSubtree != null) ++num; if (this.rightSubtree != null) ++num; return num; } } /// <summary> /// Gets or sets the data of this tree. /// /// </summary> /// /// <value> /// The data. /// /// </value> public TData Data { get; set; } /// <summary> /// Gets the degree. /// /// </summary> public int Degree { get { return this.Count; } } /// <summary> /// Gets the height. /// /// </summary> public virtual int Height { get { if (this.Degree == 0) return 0; else return 1 + this.FindMaximumChildHeight(); } } /// <summary> /// Gets whether both sides are occupied, i.e. the left and right positions are filled. /// /// </summary> /// /// <value> /// <c>true</c> if this instance is full; otherwise, <c>false</c>. /// /// </value> public bool IsComplete { get { if (this.leftSubtree != null) return this.rightSubtree != null; else return false; } } /// <summary> /// Gets a value indicating whether this tree is empty. /// /// </summary> /// /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// /// </value> public bool IsEmpty { get { return this.Count == 0; } } /// <summary> /// Gets whether this is a leaf node, i.e. it doesn't have children nodes. /// /// </summary> /// /// <value> /// <c>true</c> if this instance is leaf node; otherwise, <c>false</c>. /// /// </value> public virtual bool IsLeafNode { get { return this.Degree == 0; } } /// <summary> /// Returns <c>false</c>; this tree is never read-only. /// /// </summary> /// /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// /// </value> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets or sets the left subtree. /// /// </summary> /// /// <value> /// The left subtree. /// </value> public virtual BinaryTree<TData> Left { get { return this.leftSubtree; } set { if (this.leftSubtree != null) this.RemoveLeft(); if (value != null) { if (value.Parent != null) value.Parent.Remove(value); value.Parent = this; } this.leftSubtree = value; } } /// <summary> /// Gets the parent of the current node. /// /// </summary> /// /// <value> /// The parent of the current node. /// </value> public BinaryTree<TData> Parent { get; set; } /// <summary> /// Gets or sets the right subtree. /// /// </summary> /// /// <value> /// The right subtree. /// </value> public virtual BinaryTree<TData> Right { get { return this.rightSubtree; } set { if (this.rightSubtree != null) this.RemoveRight(); if (value != null) { if (value.Parent != null) value.Parent.Remove(value); value.Parent = this; } this.rightSubtree = value; } } /// <summary> /// Gets the root of the binary tree. /// /// </summary> public BinaryTree<TData> Root { get { for (BinaryTree<TData> parent = this.Parent; parent != null; parent = parent.Parent) { if (parent.Parent == null) return parent; } return this; } } ITree<TData> ITree<TData>.Parent { get { return (ITree<TData>)this.Parent; } } /// <summary> /// Gets the BinaryTree at the specified index. /// /// </summary> public BinaryTree<TData> this[int index] { get { return this.GetChild(index); } } public BinaryTree(TData data, TData left, TData right) : this(data, new BinaryTree<TData>(left, (BinaryTree<TData>)null, (BinaryTree<TData>)null), new BinaryTree<TData>(right, (BinaryTree<TData>)null, (BinaryTree<TData>)null)) { } public BinaryTree(TData data, BinaryTree<TData> left = null, BinaryTree<TData> right = null) { this.leftSubtree = left; if (left != null) left.Parent = this; this.rightSubtree = right; if (right != null) right.Parent = this; this.Data = data; } /// <summary> /// Adds the given item to this tree. /// /// </summary> /// <param name="item">The item to add.</param> public virtual void Add(TData item) { this.AddItem(new BinaryTree<TData>(item, (BinaryTree<TData>)null, (BinaryTree<TData>)null)); } public void Add(BinaryTree<TData> subtree) { this.AddItem(subtree); } public virtual void BreadthFirstTraversal(IVisitor<TData> visitor) { Queue<BinaryTree<TData>> queue = new Queue<BinaryTree<TData>>(); queue.Enqueue(this); while (queue.Count > 0 && !visitor.HasCompleted) { BinaryTree<TData> binaryTree = queue.Dequeue(); visitor.Visit(binaryTree.Data); for (int index = 0; index < binaryTree.Degree; ++index) { BinaryTree<TData> child = binaryTree.GetChild(index); if (child != null) queue.Enqueue(child); } } } /// <summary> /// Clears this tree of its content. /// /// </summary> public virtual void Clear() { if (this.leftSubtree != null) { this.leftSubtree.Parent = (BinaryTree<TData>)null; this.leftSubtree = (BinaryTree<TData>)null; } if (this.rightSubtree == null) return; this.rightSubtree.Parent = (BinaryTree<TData>)null; this.rightSubtree = (BinaryTree<TData>)null; } /// <summary> /// Returns whether the given item is contained in this collection. /// /// </summary> /// <param name="item">The item.</param> /// <returns> /// <c>true</c> if is contained in this collection; otherwise, <c>false</c>. /// /// </returns> public bool Contains(TData item) { return Enumerable.Contains<TData>((IEnumerable<TData>)this, item); } /// <summary> /// Copies the tree to the given array. /// /// </summary> /// <param name="array">The array.</param><param name="arrayIndex">Index of the array.</param> public void CopyTo(TData[] array, int arrayIndex) { foreach (TData data in this) { if (arrayIndex >= array.Length) throw new ArgumentException("ArrayIndex should not exceed array.Length", "array"); array[arrayIndex++] = data; } } /// <summary> /// Performs a depth first traversal on this tree with the specified visitor. /// /// </summary> /// <param name="visitor">The ordered visitor.</param><exception cref="T:System.ArgumentNullException"><paramref name="visitor"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception> public virtual void DepthFirstTraversal(IVisitor<TData> visitor) { if (visitor.HasCompleted) return; IBeforAfterVisitor<TData> prePostVisitor = visitor as IBeforAfterVisitor<TData>; if (prePostVisitor != null) prePostVisitor.BeforVisit(this.Data); if (this.leftSubtree != null) this.leftSubtree.DepthFirstTraversal(visitor); visitor.Visit(this.Data); if (this.rightSubtree != null) this.rightSubtree.DepthFirstTraversal(visitor); if (prePostVisitor == null) return; prePostVisitor.AfterVisit(this.Data); } /// <summary> /// Seeks the tree node containing the given data. /// /// </summary> /// <param name="value">The value.</param> /// <returns/> public BinaryTree<TData> Find(TData value) { Queue<BinaryTree<TData>> queue = new Queue<BinaryTree<TData>>(); queue.Enqueue(this.Root); while (queue.Count > 0) { BinaryTree<TData> binaryTree = queue.Dequeue(); if (EqualityComparer<TData>.Default.Equals(binaryTree.Data, value)) return binaryTree; for (int index = 0; index < binaryTree.Degree; ++index) { BinaryTree<TData> child = binaryTree.GetChild(index); if (child != null) queue.Enqueue(child); } } return (BinaryTree<TData>)null; } /// <summary> /// Finds the node with the specified condition. If a node is not found matching /// the specified condition, null is returned. /// /// </summary> /// <param name="condition">The condition to test.</param> /// <returns> /// The first node that matches the condition supplied. If a node is not found, null is returned. /// </returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="condition"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception> public BinaryTree<TData> FindNode(Predicate<TData> condition) { if (condition(this.Data)) return this; if (this.leftSubtree != null) { BinaryTree<TData> node = this.leftSubtree.FindNode(condition); if (node != null) return node; } if (this.rightSubtree != null) { BinaryTree<TData> node = this.rightSubtree.FindNode(condition); if (node != null) return node; } return (BinaryTree<TData>)null; } /// <summary> /// Gets the left (index zero) or right (index one) subtree. /// /// </summary> /// <param name="index">The index of the child in question.</param> /// <returns> /// The child at the specified index. /// </returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/>There are at most two children at each level of a binary tree, the index can hence only be zero or one.</exception> public BinaryTree<TData> GetChild(int index) { switch (index) { case 0: return this.leftSubtree; case 1: return this.rightSubtree; default: throw new ArgumentOutOfRangeException("index"); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// /// </summary> /// /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// /// </returns> public IEnumerator<TData> GetEnumerator() { Stack<BinaryTree<TData>> stack = new Stack<BinaryTree<TData>>(); stack.Push(this); while (stack.Count > 0) { BinaryTree<TData> tree = stack.Pop(); yield return tree.Data; if (tree.leftSubtree != null) stack.Push(tree.leftSubtree); if (tree.rightSubtree != null) stack.Push(tree.rightSubtree); } } /// <summary> /// Removes the specified item from the tree. /// /// </summary> /// <param name="item">The item to remove.</param> /// <returns/> public virtual bool Remove(TData item) { if (this.leftSubtree != null && this.leftSubtree.Data.Equals((object)item)) { this.RemoveLeft(); return true; } else { if (this.rightSubtree == null || !this.rightSubtree.Data.Equals((object)item)) return false; this.RemoveRight(); return true; } } /// <summary> /// Removes the specified child. /// /// </summary> /// <param name="child">The child.</param> /// <returns> /// Returns whether the child was found (and removed) from this tree. /// </returns> public virtual bool Remove(BinaryTree<TData> child) { if (this.leftSubtree != null && this.leftSubtree == child) { this.RemoveLeft(); return true; } else { if (this.rightSubtree == null || this.rightSubtree != child) return false; this.RemoveRight(); return true; } } /// <summary> /// Removes the left child. /// /// </summary> public virtual void RemoveLeft() { if (this.leftSubtree == null) return; this.leftSubtree.Parent = (BinaryTree<TData>)null; this.leftSubtree = (BinaryTree<TData>)null; } /// <summary> /// Removes the left child. /// /// </summary> public virtual void RemoveRight() { if (this.rightSubtree == null) return; this.rightSubtree.Parent = (BinaryTree<TData>)null; this.rightSubtree = (BinaryTree<TData>)null; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents this instance. /// /// </summary> /// /// <returns> /// A <see cref="T:System.String"/> that represents this instance. /// /// </returns> public override string ToString() { string str = (string)null; switch (this.Count) { case 0: str = "No children"; break; case 1: str = this.Left == null ? "One right child." : "One left child."; break; case 2: str = "Is full (two children)."; break; } return string.Format("{0}; {1}", (object)this.Data, (object)str); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)this.GetEnumerator(); } void ITree<TData>.Add(ITree<TData> child) { this.AddItem((BinaryTree<TData>)child); } ITree<TData> ITree<TData>.FindNode(Predicate<TData> condition) { return (ITree<TData>)this.FindNode(condition); } ITree<TData> ITree<TData>.GetChild(int index) { return (ITree<TData>)this.GetChild(index); } bool ITree<TData>.Remove(ITree<TData> child) { return this.Remove((BinaryTree<TData>)child); } /// <summary> /// Finds the maximum height between the child nodes. /// /// </summary> /// /// <returns> /// The maximum height of the tree between all paths from this node and all leaf nodes. /// </returns> protected virtual int FindMaximumChildHeight() { int num1 = this.leftSubtree != null ? this.leftSubtree.Height : 0; int num2 = this.rightSubtree != null ? this.rightSubtree.Height : 0; if (num1 <= num2) return num2; else return num1; } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// /// </summary> /// <param name="subtree">The sub tree.</param> private void AddItem(BinaryTree<TData> subtree) { if (this.leftSubtree == null) { if (subtree.Parent != null) subtree.Parent.Remove(subtree); this.leftSubtree = subtree; subtree.Parent = this; } else { if (this.rightSubtree != null) throw new InvalidOperationException("This binary tree is full."); if (subtree.Parent != null) subtree.Parent.Remove(subtree); this.rightSubtree = subtree; subtree.Parent = this; } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Microsoft.PowerShell; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// The information about a parameter set and its parameters for a cmdlet /// </summary> /// public class CommandParameterSetInfo { #region ctor /// <summary> /// Constructs the parameter set information using the specified parameter name, /// and type metadata. /// </summary> /// /// <param name="name"> /// The formal name of the parameter. /// </param> /// /// <param name="isDefaultParameterSet"> /// True if the parameter set is the default parameter set, or false otherwise. /// </param> /// /// <param name="parameterSetFlag"> /// The bit that specifies the parameter set in the type metadata. /// </param> /// /// <param name="parameterMetadata"> /// The type metadata about the cmdlet. /// </param> /// /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="parameterMetadata"/> is null. /// </exception> /// internal CommandParameterSetInfo( string name, bool isDefaultParameterSet, uint parameterSetFlag, MergedCommandParameterMetadata parameterMetadata) { IsDefault = true; Name = String.Empty; if (String.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException("parameterMetadata"); } this.Name = name; this.IsDefault = isDefaultParameterSet; Initialize(parameterMetadata, parameterSetFlag); } #endregion ctor #region public members /// <summary> /// Gets the name of the parameter set /// </summary> public string Name { get; private set; } /// <summary> /// Gets whether the parameter set is the default parameter set. /// </summary> public bool IsDefault { get; private set; } /// <summary> /// Gets the parameter information for the parameters in this parameter set. /// </summary> public ReadOnlyCollection<CommandParameterInfo> Parameters { get; private set; } /// <summary> /// Gets the synopsis for the cmdlet as a string /// </summary> public override string ToString() { return ToString(false); } /// <summary> /// /// </summary> /// <param name="isCapabilityWorkflow"> /// This boolean is used to suppress common workflow parameters (or) display /// them separately towards the end /// </param> /// <returns></returns> internal string ToString(bool isCapabilityWorkflow) { Text.StringBuilder result = new Text.StringBuilder(); GenerateParametersInDisplayOrder(isCapabilityWorkflow, parameter => AppendFormatCommandParameterInfo(parameter, ref result), delegate (string str) { if (result.Length > 0) { result.Append(" "); } result.Append("["); result.Append(str); result.Append("]"); }); return result.ToString(); } /// <summary> /// GenerateParameters parameters in display order /// ie., Positional followed by /// Named Mandatory (in alpha numeric) followed by /// Named (in alpha numeric). /// /// Callers use <paramref name="parameterAction"/> and /// <paramref name="commonParameterAction"/> to handle /// syntax generation etc. /// </summary> /// <param name="isCapabilityWorkflow"> /// This boolean is used to suppress common workflow parameters (or) display /// them separately towards the end /// </param> /// <param name="parameterAction"></param> /// <param name="commonParameterAction"></param> /// <returns></returns> internal void GenerateParametersInDisplayOrder(bool isCapabilityWorkflow, Action<CommandParameterInfo> parameterAction, Action<string> commonParameterAction) { // First figure out the positions List<CommandParameterInfo> sortedPositionalParameters = new List<CommandParameterInfo>(); List<CommandParameterInfo> namedMandatoryParameters = new List<CommandParameterInfo>(); List<CommandParameterInfo> namedParameters = new List<CommandParameterInfo>(); foreach (CommandParameterInfo parameter in Parameters) { if (parameter.Position == int.MinValue) { // The parameter is a named parameter if (parameter.IsMandatory) { namedMandatoryParameters.Add(parameter); } else { namedParameters.Add(parameter); } } else { // The parameter is positional so add it at the correct // index (note we have to pad the list if the position is // higher than the list count since we don't have any requirements // that positional parameters start at zero and are consecutive. if (parameter.Position >= sortedPositionalParameters.Count) { for (int fillerIndex = sortedPositionalParameters.Count; fillerIndex <= parameter.Position; ++fillerIndex) { sortedPositionalParameters.Add(null); } } sortedPositionalParameters[parameter.Position] = parameter; } } // Now convert the sorted positional parameters into a string List<CommandParameterInfo> commonWorkflowParameter = new List<CommandParameterInfo>(); foreach (CommandParameterInfo parameter in sortedPositionalParameters) { if (parameter == null) { continue; } if (!Internal.CommonParameters.CommonWorkflowParameters.Contains(parameter.Name, StringComparer.OrdinalIgnoreCase) || !isCapabilityWorkflow) { parameterAction(parameter); } else { commonWorkflowParameter.Add(parameter); } } // Now convert the named mandatory parameters into a string foreach (CommandParameterInfo parameter in namedMandatoryParameters) { if (parameter == null) { continue; } parameterAction(parameter); } List<CommandParameterInfo> commonParameters = new List<CommandParameterInfo>(); // Now convert the named parameters into a string foreach (CommandParameterInfo parameter in namedParameters) { if (parameter == null) { continue; } // Hold off common parameters bool isCommon = Cmdlet.CommonParameters.Contains(parameter.Name, StringComparer.OrdinalIgnoreCase); if (!isCommon) { if (!Internal.CommonParameters.CommonWorkflowParameters.Contains(parameter.Name, StringComparer.OrdinalIgnoreCase) || !isCapabilityWorkflow) { parameterAction(parameter); } else { commonWorkflowParameter.Add(parameter); } } else { commonParameters.Add(parameter); } } if (commonWorkflowParameter.Count == Internal.CommonParameters.CommonWorkflowParameters.Length) { commonParameterAction(HelpDisplayStrings.CommonWorkflowParameters); } else { foreach (CommandParameterInfo parameter in commonWorkflowParameter) { parameterAction(parameter); } } // If all common parameters are present, group them together if (commonParameters.Count == Cmdlet.CommonParameters.Count) { commonParameterAction(HelpDisplayStrings.CommonParameters); } // Else, convert to string as before else { foreach (CommandParameterInfo parameter in commonParameters) { parameterAction(parameter); } } } #endregion public members #region private members private static void AppendFormatCommandParameterInfo(CommandParameterInfo parameter, ref Text.StringBuilder result) { if (result.Length > 0) { // Add a space between parameters result.Append(" "); } if (parameter.ParameterType == typeof(SwitchParameter)) { result.AppendFormat(CultureInfo.InvariantCulture, parameter.IsMandatory ? "-{0}" : "[-{0}]", parameter.Name); } else { string parameterTypeString = GetParameterTypeString(parameter.ParameterType, parameter.Attributes); if (parameter.IsMandatory) { result.AppendFormat(CultureInfo.InvariantCulture, parameter.Position != int.MinValue ? "[-{0}] <{1}>" : "-{0} <{1}>", parameter.Name, parameterTypeString); } else { result.AppendFormat(CultureInfo.InvariantCulture, parameter.Position != int.MinValue ? "[[-{0}] <{1}>]" : "[-{0} <{1}>]", parameter.Name, parameterTypeString); } } } internal static string GetParameterTypeString(Type type, IEnumerable<Attribute> attributes) { string parameterTypeString; PSTypeNameAttribute typeName; if (attributes != null && (typeName = attributes.OfType<PSTypeNameAttribute>().FirstOrDefault()) != null) { // If we have a PSTypeName specified on the class, we assume it has a more useful type than the actual // parameter type. This is a reasonable assumption, the parameter binder does honor this attribute. // // This typename might be long, e.g.: // Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Process // System.Management.ManagementObject#root\cimv2\Win32_Process // To shorten this, we will drop the namespaces, both on the .Net side and the CIM/WMI side: // CimInstance#Win32_Process // If our regex doesn't match, we'll just use the full name. var match = Regex.Match(typeName.PSTypeName, "(.*\\.)?(?<NetTypeName>.*)#(.*[/\\\\])?(?<CimClassName>.*)"); if (match.Success) { parameterTypeString = match.Groups["NetTypeName"].Value + "#" + match.Groups["CimClassName"].Value; } else { parameterTypeString = typeName.PSTypeName; // Drop the namespace from the typename, if any. var lastDotIndex = parameterTypeString.LastIndexOfAny(Utils.Separators.Dot); if (lastDotIndex != -1 && lastDotIndex + 1 < parameterTypeString.Length) { parameterTypeString = parameterTypeString.Substring(lastDotIndex + 1); } } // If the type is really an array, but the typename didn't include [], then add it. if (type.IsArray && (parameterTypeString.IndexOf("[]", StringComparison.OrdinalIgnoreCase) == -1)) { var t = type; while (t.IsArray) { parameterTypeString += "[]"; t = t.GetElementType(); } } } else { Type parameterType = Nullable.GetUnderlyingType(type) ?? type; parameterTypeString = ToStringCodeMethods.Type(parameterType, true); } return parameterTypeString; } private void Initialize(MergedCommandParameterMetadata parameterMetadata, uint parameterSetFlag) { Diagnostics.Assert( parameterMetadata != null, "The parameterMetadata should never be null"); Collection<CommandParameterInfo> processedParameters = new Collection<CommandParameterInfo>(); // Get the parameters in the parameter set Collection<MergedCompiledCommandParameter> compiledParameters = parameterMetadata.GetParametersInParameterSet(parameterSetFlag); foreach (MergedCompiledCommandParameter parameter in compiledParameters) { if (parameter != null) { processedParameters.Add( new CommandParameterInfo(parameter.Parameter, parameterSetFlag)); } } Parameters = new ReadOnlyCollection<CommandParameterInfo>(processedParameters); } #endregion private members } // class CommandParameterSetInfo } // namespace System.Management.Automation
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// RouteFilterRulesOperations operations. /// </summary> public partial interface IRouteFilterRulesOperations { /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// The 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.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<RouteFilterRule>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<RouteFilterRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<RouteFilterRule>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// The 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.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<RouteFilterRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<RouteFilterRule>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using SqlKata.Compilers; using SqlKata.Extensions; using SqlKata.Tests.Infrastructure; using System; using System.Collections.Generic; using Xunit; namespace SqlKata.Tests { public class SelectTests : TestSupport { [Fact] public void BasicSelect() { var q = new Query().From("users").Select("id", "name"); var c = Compile(q); Assert.Equal("SELECT [id], [name] FROM [users]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT `id`, `name` FROM `users`", c[EngineCodes.MySql]); Assert.Equal("SELECT \"id\", \"name\" FROM \"users\"", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT \"ID\", \"NAME\" FROM \"USERS\"", c[EngineCodes.Firebird]); Assert.Equal("SELECT \"id\", \"name\" FROM \"users\"", c[EngineCodes.Oracle]); } [Fact] public void BasicSelectEnumerable() { var q = new Query().From("users").Select(new List<string>() { "id", "name" }); var c = Compile(q); Assert.Equal("SELECT [id], [name] FROM [users]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT `id`, `name` FROM `users`", c[EngineCodes.MySql]); Assert.Equal("SELECT \"id\", \"name\" FROM \"users\"", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT \"ID\", \"NAME\" FROM \"USERS\"", c[EngineCodes.Firebird]); Assert.Equal("SELECT \"id\", \"name\" FROM \"users\"", c[EngineCodes.Oracle]); } [Fact] public void BasicSelectWhereBindingIsEmptyOrNull() { var q = new Query() .From("users") .Select("id", "name") .Where("author", "") .OrWhere("author", null); var c = Compile(q); Assert.Equal("SELECT [id], [name] FROM [users] WHERE [author] = '' OR [author] IS NULL", c[EngineCodes.SqlServer]); Assert.Equal("SELECT `id`, `name` FROM `users` WHERE `author` = '' OR `author` IS NULL", c[EngineCodes.MySql]); Assert.Equal("SELECT \"id\", \"name\" FROM \"users\" WHERE \"author\" = '' OR \"author\" IS NULL", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT \"ID\", \"NAME\" FROM \"USERS\" WHERE \"AUTHOR\" = '' OR \"AUTHOR\" IS NULL", c[EngineCodes.Firebird]); } [Fact] public void BasicSelectWithAlias() { var q = new Query().From("users as u").Select("id", "name"); var c = Compile(q); Assert.Equal("SELECT [id], [name] FROM [users] AS [u]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT `id`, `name` FROM `users` AS `u`", c[EngineCodes.MySql]); Assert.Equal("SELECT \"id\", \"name\" FROM \"users\" AS \"u\"", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT \"ID\", \"NAME\" FROM \"USERS\" AS \"U\"", c[EngineCodes.Firebird]); } [Fact] public void ExpandedSelect() { var q = new Query().From("users").Select("users.{id,name, age}"); var c = Compile(q); Assert.Equal("SELECT [users].[id], [users].[name], [users].[age] FROM [users]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT `users`.`id`, `users`.`name`, `users`.`age` FROM `users`", c[EngineCodes.MySql]); } [Fact] public void ExpandedSelectWithSchema() { var q = new Query().From("users").Select("dbo.users.{id,name, age}"); var c = Compile(q); Assert.Equal("SELECT [dbo].[users].[id], [dbo].[users].[name], [dbo].[users].[age] FROM [users]", c[EngineCodes.SqlServer]); } [Fact] public void NestedEmptyWhereAtFirstCondition() { var query = new Query("table") .Where(q => new Query()) .Where("id", 1); var c = Compile(query); Assert.Equal("SELECT * FROM [table] WHERE [id] = 1", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"TABLE\" WHERE \"ID\" = 1", c[EngineCodes.Firebird]); } [Fact] public void WhereTrue() { var query = new Query("Table").WhereTrue("IsActive"); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE [IsActive] = cast(1 as bit)", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM `Table` WHERE `IsActive` = true", c[EngineCodes.MySql]); Assert.Equal("SELECT * FROM \"Table\" WHERE \"IsActive\" = true", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT * FROM \"TABLE\" WHERE \"ISACTIVE\" = 1", c[EngineCodes.Firebird]); } [Fact] public void WhereFalse() { var query = new Query("Table").WhereFalse("IsActive"); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE [IsActive] = cast(0 as bit)", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM `Table` WHERE `IsActive` = false", c[EngineCodes.MySql]); Assert.Equal("SELECT * FROM \"Table\" WHERE \"IsActive\" = false", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT * FROM \"TABLE\" WHERE \"ISACTIVE\" = 0", c[EngineCodes.Firebird]); } [Fact] public void OrWhereFalse() { var query = new Query("Table").Where("MyCol", "abc").OrWhereFalse("IsActive"); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE [MyCol] = 'abc' OR [IsActive] = cast(0 as bit)", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Table\" WHERE \"MyCol\" = 'abc' OR \"IsActive\" = false", c[EngineCodes.PostgreSql]); } [Fact] public void OrWhereTrue() { var query = new Query("Table").Where("MyCol", "abc").OrWhereTrue("IsActive"); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE [MyCol] = 'abc' OR [IsActive] = cast(1 as bit)", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Table\" WHERE \"MyCol\" = 'abc' OR \"IsActive\" = true", c[EngineCodes.PostgreSql]); } [Fact] public void OrWhereNull() { var query = new Query("Table").Where("MyCol", "abc").OrWhereNull("IsActive"); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE [MyCol] = 'abc' OR [IsActive] IS NULL", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Table\" WHERE \"MyCol\" = 'abc' OR \"IsActive\" IS NULL", c[EngineCodes.PostgreSql]); } [Fact] public void WhereSub() { var subQuery = new Query("Table2").WhereColumns("Table2.Column", "=", "Table.MyCol").AsCount(); var query = new Query("Table").WhereSub(subQuery, 1); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE (SELECT COUNT(*) AS [count] FROM [Table2] WHERE [Table2].[Column] = [Table].[MyCol]) = 1", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Table\" WHERE (SELECT COUNT(*) AS \"count\" FROM \"Table2\" WHERE \"Table2\".\"Column\" = \"Table\".\"MyCol\") = 1", c[EngineCodes.PostgreSql]); } [Fact] public void OrWhereSub() { var subQuery = new Query("Table2").WhereColumns("Table2.Column", "=", "Table.MyCol").AsCount(); var query = new Query("Table").WhereNull("MyCol").OrWhereSub(subQuery, "<", 1); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE [MyCol] IS NULL OR (SELECT COUNT(*) AS [count] FROM [Table2] WHERE [Table2].[Column] = [Table].[MyCol]) < 1", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Table\" WHERE \"MyCol\" IS NULL OR (SELECT COUNT(*) AS \"count\" FROM \"Table2\" WHERE \"Table2\".\"Column\" = \"Table\".\"MyCol\") < 1", c[EngineCodes.PostgreSql]); } [Fact] public void PassingArrayAsParameter() { var query = new Query("Table").WhereRaw("[Id] in (?)", new object[] { new object[] { 1, 2, 3 } }); var c = Compile(query); Assert.Equal("SELECT * FROM [Table] WHERE [Id] in (1,2,3)", c[EngineCodes.SqlServer]); } [Fact] public void UsingJsonArray() { var query = new Query("Table").WhereRaw("[Json]->'address'->>'country' in (?)", new[] { 1, 2, 3, 4 }); var c = Compile(query); Assert.Equal("SELECT * FROM \"Table\" WHERE \"Json\"->'address'->>'country' in (1,2,3,4)", c[EngineCodes.PostgreSql]); } [Fact] public void Union() { var laptops = new Query("Laptops"); var mobiles = new Query("Phones").Union(laptops); var c = Compile(mobiles); Assert.Equal("SELECT * FROM [Phones] UNION SELECT * FROM [Laptops]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Phones\" UNION SELECT * FROM \"Laptops\"", c[EngineCodes.Sqlite]); Assert.Equal("SELECT * FROM \"PHONES\" UNION SELECT * FROM \"LAPTOPS\"", c[EngineCodes.Firebird]); } [Fact] public void UnionWithBindings() { var laptops = new Query("Laptops").Where("Type", "A"); var mobiles = new Query("Phones").Union(laptops); var c = Compile(mobiles); Assert.Equal("SELECT * FROM [Phones] UNION SELECT * FROM [Laptops] WHERE [Type] = 'A'", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Phones\" UNION SELECT * FROM \"Laptops\" WHERE \"Type\" = 'A'", c[EngineCodes.Sqlite]); Assert.Equal("SELECT * FROM `Phones` UNION SELECT * FROM `Laptops` WHERE `Type` = 'A'", c[EngineCodes.MySql]); Assert.Equal("SELECT * FROM \"PHONES\" UNION SELECT * FROM \"LAPTOPS\" WHERE \"TYPE\" = 'A'", c[EngineCodes.Firebird]); } [Fact] public void RawUnionWithBindings() { var mobiles = new Query("Phones").UnionRaw("UNION SELECT * FROM [Laptops] WHERE [Type] = ?", "A"); var c = Compile(mobiles); Assert.Equal("SELECT * FROM [Phones] UNION SELECT * FROM [Laptops] WHERE [Type] = 'A'", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM `Phones` UNION SELECT * FROM `Laptops` WHERE `Type` = 'A'", c[EngineCodes.MySql]); } [Fact] public void MultipleUnion() { var laptops = new Query("Laptops"); var tablets = new Query("Tablets"); var mobiles = new Query("Phones").Union(laptops).Union(tablets); var c = Compile(mobiles); Assert.Equal("SELECT * FROM [Phones] UNION SELECT * FROM [Laptops] UNION SELECT * FROM [Tablets]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"PHONES\" UNION SELECT * FROM \"LAPTOPS\" UNION SELECT * FROM \"TABLETS\"", c[EngineCodes.Firebird]); } [Fact] public void MultipleUnionWithBindings() { var laptops = new Query("Laptops").Where("Price", ">", 1000); var tablets = new Query("Tablets").Where("Price", ">", 2000); var mobiles = new Query("Phones").Where("Price", "<", 3000).Union(laptops).Union(tablets); var c = Compile(mobiles); Assert.Equal( "SELECT * FROM [Phones] WHERE [Price] < 3000 UNION SELECT * FROM [Laptops] WHERE [Price] > 1000 UNION SELECT * FROM [Tablets] WHERE [Price] > 2000", c[EngineCodes.SqlServer]); Assert.Equal( "SELECT * FROM \"PHONES\" WHERE \"PRICE\" < 3000 UNION SELECT * FROM \"LAPTOPS\" WHERE \"PRICE\" > 1000 UNION SELECT * FROM \"TABLETS\" WHERE \"PRICE\" > 2000", c[EngineCodes.Firebird]); } [Fact] public void MultipleUnionWithBindingsAndPagination() { var laptops = new Query("Laptops").Where("Price", ">", 1000); var tablets = new Query("Tablets").Where("Price", ">", 2000).ForPage(2); var mobiles = new Query("Phones").Where("Price", "<", 3000).Union(laptops).UnionAll(tablets); var c = Compile(mobiles); Assert.Equal( "SELECT * FROM [Phones] WHERE [Price] < 3000 UNION SELECT * FROM [Laptops] WHERE [Price] > 1000 UNION ALL SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [row_num] FROM [Tablets] WHERE [Price] > 2000) AS [results_wrapper] WHERE [row_num] BETWEEN 16 AND 30", c[EngineCodes.SqlServer]); Assert.Equal( "SELECT * FROM \"PHONES\" WHERE \"PRICE\" < 3000 UNION SELECT * FROM \"LAPTOPS\" WHERE \"PRICE\" > 1000 UNION ALL SELECT * FROM \"TABLETS\" WHERE \"PRICE\" > 2000 ROWS 16 TO 30", c[EngineCodes.Firebird]); } [Fact] public void UnionWithCallbacks() { var mobiles = new Query("Phones") .Where("Price", "<", 3000) .Union(q => q.From("Laptops")) .UnionAll(q => q.From("Tablets")); var c = Compile(mobiles); Assert.Equal( "SELECT * FROM [Phones] WHERE [Price] < 3000 UNION SELECT * FROM [Laptops] UNION ALL SELECT * FROM [Tablets]", c[EngineCodes.SqlServer]); Assert.Equal( "SELECT * FROM \"PHONES\" WHERE \"PRICE\" < 3000 UNION SELECT * FROM \"LAPTOPS\" UNION ALL SELECT * FROM \"TABLETS\"", c[EngineCodes.Firebird]); } [Fact] public void UnionWithDifferentEngine() { var mobiles = new Query("Phones") .Where("Price", "<", 300) .ForSqlServer(scope => scope.Except(q => q.From("Phones").WhereNot("Os", "iOS"))) .ForPostgreSql(scope => scope.Union(q => q.From("Laptops").Where("Price", "<", 800))) .ForMySql(scope => scope.IntersectAll(q => q.From("Watches").Where("Os", "Android"))) .ForFirebird(scope => scope.Union(q => q.From("Laptops").Where("Price", "<", 800))) .UnionAll(q => q.From("Tablets").Where("Price", "<", 100)); var c = Compile(mobiles); Assert.Equal( "SELECT * FROM [Phones] WHERE [Price] < 300 EXCEPT SELECT * FROM [Phones] WHERE NOT ([Os] = 'iOS') UNION ALL SELECT * FROM [Tablets] WHERE [Price] < 100", c[EngineCodes.SqlServer]); Assert.Equal( "SELECT * FROM `Phones` WHERE `Price` < 300 INTERSECT ALL SELECT * FROM `Watches` WHERE `Os` = 'Android' UNION ALL SELECT * FROM `Tablets` WHERE `Price` < 100", c[EngineCodes.MySql]); Assert.Equal( "SELECT * FROM \"Phones\" WHERE \"Price\" < 300 UNION SELECT * FROM \"Laptops\" WHERE \"Price\" < 800 UNION ALL SELECT * FROM \"Tablets\" WHERE \"Price\" < 100", c[EngineCodes.PostgreSql]); Assert.Equal( "SELECT * FROM \"PHONES\" WHERE \"PRICE\" < 300 UNION SELECT * FROM \"LAPTOPS\" WHERE \"PRICE\" < 800 UNION ALL SELECT * FROM \"TABLETS\" WHERE \"PRICE\" < 100", c[EngineCodes.Firebird]); } [Fact] public void CombineRaw() { var query = new Query("Mobiles").CombineRaw("UNION ALL SELECT * FROM Devices"); var c = Compile(query); Assert.Equal("SELECT * FROM [Mobiles] UNION ALL SELECT * FROM Devices", c[EngineCodes.SqlServer]); } [Fact] public void CombineRawWithPlaceholders() { var query = new Query("Mobiles").CombineRaw("UNION ALL SELECT * FROM {Devices}"); var c = Compile(query); Assert.Equal("SELECT * FROM [Mobiles] UNION ALL SELECT * FROM [Devices]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM `Mobiles` UNION ALL SELECT * FROM `Devices`", c[EngineCodes.MySql]); Assert.Equal("SELECT * FROM \"MOBILES\" UNION ALL SELECT * FROM \"Devices\"", c[EngineCodes.Firebird]); } [Fact] public void NestedEmptyWhere() { // Empty nested where should be ignored var query = new Query("A").Where(q => new Query().Where(q2 => new Query().Where(q3 => new Query()))); var c = Compile(query); Assert.Equal("SELECT * FROM [A]", c[EngineCodes.SqlServer]); } [Fact] public void NestedQuery() { var query = new Query("A").Where(q => new Query("B")); var c = Compile(query); Assert.Equal("SELECT * FROM [A]", c[EngineCodes.SqlServer]); } [Fact] public void NestedQueryAfterNestedJoin() { // in this test, i am testing the compiler dynamic caching functionality var query = new Query("users") .Join("countries", j => j.On("countries.id", "users.country_id")) .Where(q => new Query()); var c = Compile(query); Assert.Equal("SELECT * FROM [users] \nINNER JOIN [countries] ON ([countries].[id] = [users].[country_id])", c[EngineCodes.SqlServer]); } [Fact] public void MultipleCte() { var q1 = new Query("A"); var q2 = new Query("B"); var q3 = new Query("C"); var query = new Query("A") .With("A", q1) .With("B", q2) .With("C", q3); var c = Compile(query); Assert.Equal( "WITH [A] AS (SELECT * FROM [A]),\n[B] AS (SELECT * FROM [B]),\n[C] AS (SELECT * FROM [C])\nSELECT * FROM [A]", c[EngineCodes.SqlServer]); } [Fact] public void CteAndBindings() { var query = new Query("Races") .For("mysql", s => s.With("range", q => q.From("seqtbl") .Select("Id").Where("Id", "<", 33)) .WhereIn("RaceAuthor", q => q.From("Users") .Select("Name").Where("Status", "Available") ) ) .For("sqlsrv", s => s.With("range", q => q.From("Sequence").Select("Number").Where("Number", "<", 78) ) .Limit(25).Offset(20) ) .For("postgres", s => s.With("range", q => q.FromRaw("generate_series(1, 33) as d").Select("d")) .Where("Name", "3778") ) .For("firebird", s => s.With("range", q => q.FromRaw("generate_series(1, 33) as d").Select("d")) .Where("Name", "3778") ) .Where("Id", ">", 55) .WhereBetween("Value", 18, 24); var c = Compile(query); Assert.Equal( "WITH [range] AS (SELECT [Number] FROM [Sequence] WHERE [Number] < 78)\nSELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [row_num] FROM [Races] WHERE [Id] > 55 AND [Value] BETWEEN 18 AND 24) AS [results_wrapper] WHERE [row_num] BETWEEN 21 AND 45", c[EngineCodes.SqlServer]); Assert.Equal( "WITH `range` AS (SELECT `Id` FROM `seqtbl` WHERE `Id` < 33)\nSELECT * FROM `Races` WHERE `RaceAuthor` IN (SELECT `Name` FROM `Users` WHERE `Status` = 'Available') AND `Id` > 55 AND `Value` BETWEEN 18 AND 24", c[EngineCodes.MySql]); Assert.Equal( "WITH \"range\" AS (SELECT \"d\" FROM generate_series(1, 33) as d)\nSELECT * FROM \"Races\" WHERE \"Name\" = '3778' AND \"Id\" > 55 AND \"Value\" BETWEEN 18 AND 24", c[EngineCodes.PostgreSql]); Assert.Equal( "WITH \"RANGE\" AS (SELECT \"D\" FROM generate_series(1, 33) as d)\nSELECT * FROM \"RACES\" WHERE \"NAME\" = '3778' AND \"ID\" > 55 AND \"VALUE\" BETWEEN 18 AND 24", c[EngineCodes.Firebird]); } // test for issue #50 [Fact] public void CascadedCteAndBindings() { var cte1 = new Query("Table1"); cte1.Select("Column1", "Column2"); cte1.Where("Column2", 1); var cte2 = new Query("Table2"); cte2.With("cte1", cte1); cte2.Select("Column3", "Column4"); cte2.Join("cte1", join => join.On("Column1", "Column3")); cte2.Where("Column4", 2); var mainQuery = new Query("Table3"); mainQuery.With("cte2", cte2); mainQuery.Select("*"); mainQuery.From("cte2"); mainQuery.Where("Column3", 5); var c = Compile(mainQuery); Assert.Equal("WITH [cte1] AS (SELECT [Column1], [Column2] FROM [Table1] WHERE [Column2] = 1),\n[cte2] AS (SELECT [Column3], [Column4] FROM [Table2] \nINNER JOIN [cte1] ON ([Column1] = [Column3]) WHERE [Column4] = 2)\nSELECT * FROM [cte2] WHERE [Column3] = 5", c[EngineCodes.SqlServer]); Assert.Equal("WITH `cte1` AS (SELECT `Column1`, `Column2` FROM `Table1` WHERE `Column2` = 1),\n`cte2` AS (SELECT `Column3`, `Column4` FROM `Table2` \nINNER JOIN `cte1` ON (`Column1` = `Column3`) WHERE `Column4` = 2)\nSELECT * FROM `cte2` WHERE `Column3` = 5", c[EngineCodes.MySql]); Assert.Equal("WITH \"cte1\" AS (SELECT \"Column1\", \"Column2\" FROM \"Table1\" WHERE \"Column2\" = 1),\n\"cte2\" AS (SELECT \"Column3\", \"Column4\" FROM \"Table2\" \nINNER JOIN \"cte1\" ON (\"Column1\" = \"Column3\") WHERE \"Column4\" = 2)\nSELECT * FROM \"cte2\" WHERE \"Column3\" = 5", c[EngineCodes.PostgreSql]); Assert.Equal("WITH \"CTE1\" AS (SELECT \"COLUMN1\", \"COLUMN2\" FROM \"TABLE1\" WHERE \"COLUMN2\" = 1),\n\"CTE2\" AS (SELECT \"COLUMN3\", \"COLUMN4\" FROM \"TABLE2\" \nINNER JOIN \"CTE1\" ON (\"COLUMN1\" = \"COLUMN3\") WHERE \"COLUMN4\" = 2)\nSELECT * FROM \"CTE2\" WHERE \"COLUMN3\" = 5", c[EngineCodes.Firebird]); } // test for issue #50 [Fact] public void CascadedAndMultiReferencedCteAndBindings() { var cte1 = new Query("Table1"); cte1.Select("Column1", "Column2"); cte1.Where("Column2", 1); var cte2 = new Query("Table2"); cte2.With("cte1", cte1); cte2.Select("Column3", "Column4"); cte2.Join("cte1", join => join.On("Column1", "Column3")); cte2.Where("Column4", 2); var cte3 = new Query("Table3"); cte3.With("cte1", cte1); cte3.Select("Column3_3", "Column3_4"); cte3.Join("cte1", join => join.On("Column1", "Column3_3")); cte3.Where("Column3_4", 33); var mainQuery = new Query("Table3"); mainQuery.With("cte2", cte2); mainQuery.With("cte3", cte3); mainQuery.Select("*"); mainQuery.From("cte2"); mainQuery.Where("Column3", 5); var c = Compile(mainQuery); Assert.Equal("WITH [cte1] AS (SELECT [Column1], [Column2] FROM [Table1] WHERE [Column2] = 1),\n[cte2] AS (SELECT [Column3], [Column4] FROM [Table2] \nINNER JOIN [cte1] ON ([Column1] = [Column3]) WHERE [Column4] = 2),\n[cte3] AS (SELECT [Column3_3], [Column3_4] FROM [Table3] \nINNER JOIN [cte1] ON ([Column1] = [Column3_3]) WHERE [Column3_4] = 33)\nSELECT * FROM [cte2] WHERE [Column3] = 5", c[EngineCodes.SqlServer]); Assert.Equal("WITH `cte1` AS (SELECT `Column1`, `Column2` FROM `Table1` WHERE `Column2` = 1),\n`cte2` AS (SELECT `Column3`, `Column4` FROM `Table2` \nINNER JOIN `cte1` ON (`Column1` = `Column3`) WHERE `Column4` = 2),\n`cte3` AS (SELECT `Column3_3`, `Column3_4` FROM `Table3` \nINNER JOIN `cte1` ON (`Column1` = `Column3_3`) WHERE `Column3_4` = 33)\nSELECT * FROM `cte2` WHERE `Column3` = 5", c[EngineCodes.MySql]); Assert.Equal("WITH \"cte1\" AS (SELECT \"Column1\", \"Column2\" FROM \"Table1\" WHERE \"Column2\" = 1),\n\"cte2\" AS (SELECT \"Column3\", \"Column4\" FROM \"Table2\" \nINNER JOIN \"cte1\" ON (\"Column1\" = \"Column3\") WHERE \"Column4\" = 2),\n\"cte3\" AS (SELECT \"Column3_3\", \"Column3_4\" FROM \"Table3\" \nINNER JOIN \"cte1\" ON (\"Column1\" = \"Column3_3\") WHERE \"Column3_4\" = 33)\nSELECT * FROM \"cte2\" WHERE \"Column3\" = 5", c[EngineCodes.PostgreSql]); Assert.Equal("WITH \"CTE1\" AS (SELECT \"COLUMN1\", \"COLUMN2\" FROM \"TABLE1\" WHERE \"COLUMN2\" = 1),\n\"CTE2\" AS (SELECT \"COLUMN3\", \"COLUMN4\" FROM \"TABLE2\" \nINNER JOIN \"CTE1\" ON (\"COLUMN1\" = \"COLUMN3\") WHERE \"COLUMN4\" = 2),\n\"CTE3\" AS (SELECT \"COLUMN3_3\", \"COLUMN3_4\" FROM \"TABLE3\" \nINNER JOIN \"CTE1\" ON (\"COLUMN1\" = \"COLUMN3_3\") WHERE \"COLUMN3_4\" = 33)\nSELECT * FROM \"CTE2\" WHERE \"COLUMN3\" = 5", c[EngineCodes.Firebird]); } // test for issue #50 [Fact] public void MultipleCtesAndBindings() { var cte1 = new Query("Table1"); cte1.Select("Column1", "Column2"); cte1.Where("Column2", 1); var cte2 = new Query("Table2"); cte2.Select("Column3", "Column4"); cte2.Join("cte1", join => join.On("Column1", "Column3")); cte2.Where("Column4", 2); var cte3 = new Query("Table3"); cte3.Select("Column3_3", "Column3_4"); cte3.Join("cte1", join => join.On("Column1", "Column3_3")); cte3.Where("Column3_4", 33); var mainQuery = new Query("Table3"); mainQuery.With("cte1", cte1); mainQuery.With("cte2", cte2); mainQuery.With("cte3", cte3); mainQuery.Select("*"); mainQuery.From("cte3"); mainQuery.Where("Column3_4", 5); var c = Compile(mainQuery); Assert.Equal("WITH [cte1] AS (SELECT [Column1], [Column2] FROM [Table1] WHERE [Column2] = 1),\n[cte2] AS (SELECT [Column3], [Column4] FROM [Table2] \nINNER JOIN [cte1] ON ([Column1] = [Column3]) WHERE [Column4] = 2),\n[cte3] AS (SELECT [Column3_3], [Column3_4] FROM [Table3] \nINNER JOIN [cte1] ON ([Column1] = [Column3_3]) WHERE [Column3_4] = 33)\nSELECT * FROM [cte3] WHERE [Column3_4] = 5", c[EngineCodes.SqlServer]); Assert.Equal("WITH `cte1` AS (SELECT `Column1`, `Column2` FROM `Table1` WHERE `Column2` = 1),\n`cte2` AS (SELECT `Column3`, `Column4` FROM `Table2` \nINNER JOIN `cte1` ON (`Column1` = `Column3`) WHERE `Column4` = 2),\n`cte3` AS (SELECT `Column3_3`, `Column3_4` FROM `Table3` \nINNER JOIN `cte1` ON (`Column1` = `Column3_3`) WHERE `Column3_4` = 33)\nSELECT * FROM `cte3` WHERE `Column3_4` = 5", c[EngineCodes.MySql]); Assert.Equal("WITH \"cte1\" AS (SELECT \"Column1\", \"Column2\" FROM \"Table1\" WHERE \"Column2\" = 1),\n\"cte2\" AS (SELECT \"Column3\", \"Column4\" FROM \"Table2\" \nINNER JOIN \"cte1\" ON (\"Column1\" = \"Column3\") WHERE \"Column4\" = 2),\n\"cte3\" AS (SELECT \"Column3_3\", \"Column3_4\" FROM \"Table3\" \nINNER JOIN \"cte1\" ON (\"Column1\" = \"Column3_3\") WHERE \"Column3_4\" = 33)\nSELECT * FROM \"cte3\" WHERE \"Column3_4\" = 5", c[EngineCodes.PostgreSql]); Assert.Equal("WITH \"CTE1\" AS (SELECT \"COLUMN1\", \"COLUMN2\" FROM \"TABLE1\" WHERE \"COLUMN2\" = 1),\n\"CTE2\" AS (SELECT \"COLUMN3\", \"COLUMN4\" FROM \"TABLE2\" \nINNER JOIN \"CTE1\" ON (\"COLUMN1\" = \"COLUMN3\") WHERE \"COLUMN4\" = 2),\n\"CTE3\" AS (SELECT \"COLUMN3_3\", \"COLUMN3_4\" FROM \"TABLE3\" \nINNER JOIN \"CTE1\" ON (\"COLUMN1\" = \"COLUMN3_3\") WHERE \"COLUMN3_4\" = 33)\nSELECT * FROM \"CTE3\" WHERE \"COLUMN3_4\" = 5", c[EngineCodes.Firebird]); } [Fact] public void Limit() { var q = new Query().From("users").Select("id", "name").Limit(10); var c = Compile(q); // Assert.Equal(c[EngineCodes.SqlServer], "SELECT * FROM (SELECT [id], [name],ROW_NUMBER() OVER (SELECT 0) AS [row_num] FROM [users]) AS [temp_table] WHERE [row_num] >= 10"); Assert.Equal("SELECT TOP (10) [id], [name] FROM [users]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT `id`, `name` FROM `users` LIMIT 10", c[EngineCodes.MySql]); Assert.Equal("SELECT \"id\", \"name\" FROM \"users\" LIMIT 10", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT FIRST 10 \"ID\", \"NAME\" FROM \"USERS\"", c[EngineCodes.Firebird]); } [Fact] public void Offset() { var q = new Query().From("users").Offset(10); var c = Compile(q); Assert.Equal( "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [row_num] FROM [users]) AS [results_wrapper] WHERE [row_num] >= 11", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM `users` LIMIT 18446744073709551615 OFFSET 10", c[EngineCodes.MySql]); Assert.Equal("SELECT * FROM \"users\" OFFSET 10", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT SKIP 10 * FROM \"USERS\"", c[EngineCodes.Firebird]); } [Fact] public void LimitOffset() { var q = new Query().From("users").Offset(10).Limit(5); var c = Compile(q); Assert.Equal( "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [row_num] FROM [users]) AS [results_wrapper] WHERE [row_num] BETWEEN 11 AND 15", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM `users` LIMIT 5 OFFSET 10", c[EngineCodes.MySql]); Assert.Equal("SELECT * FROM \"users\" LIMIT 5 OFFSET 10", c[EngineCodes.PostgreSql]); Assert.Equal("SELECT * FROM \"USERS\" ROWS 11 TO 15", c[EngineCodes.Firebird]); } [Fact] public void BasicJoin() { var q = new Query().From("users").Join("countries", "countries.id", "users.country_id"); var c = Compile(q); Assert.Equal("SELECT * FROM [users] \nINNER JOIN [countries] ON [countries].[id] = [users].[country_id]", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM `users` \nINNER JOIN `countries` ON `countries`.`id` = `users`.`country_id`", c[EngineCodes.MySql]); } [Theory] [InlineData("inner join", "INNER JOIN")] [InlineData("left join", "LEFT JOIN")] [InlineData("right join", "RIGHT JOIN")] [InlineData("cross join", "CROSS JOIN")] public void JoinTypes(string given, string output) { var q = new Query().From("users") .Join("countries", "countries.id", "users.country_id", "=", given); var c = Compile(q); Assert.Equal($"SELECT * FROM [users] \n{output} [countries] ON [countries].[id] = [users].[country_id]", c[EngineCodes.SqlServer]); Assert.Equal($"SELECT * FROM `users` \n{output} `countries` ON `countries`.`id` = `users`.`country_id`", c[EngineCodes.MySql]); Assert.Equal( $"SELECT * FROM \"users\" \n{output} \"countries\" ON \"countries\".\"id\" = \"users\".\"country_id\"", c[EngineCodes.PostgreSql]); Assert.Equal( $"SELECT * FROM \"USERS\" \n{output} \"COUNTRIES\" ON \"COUNTRIES\".\"ID\" = \"USERS\".\"COUNTRY_ID\"", c[EngineCodes.Firebird]); } [Fact] public void OrWhereRawEscaped() { var query = new Query("Table").WhereRaw("[MyCol] = ANY(?::int\\[\\])", "{1,2,3}"); var c = Compile(query); Assert.Equal("SELECT * FROM \"Table\" WHERE \"MyCol\" = ANY('{1,2,3}'::int[])", c[EngineCodes.PostgreSql]); } [Fact] public void Having() { var q = new Query("Table1") .Having("Column1", ">", 1); var c = Compile(q); Assert.Equal("SELECT * FROM [Table1] HAVING [Column1] > 1", c[EngineCodes.SqlServer]); } [Fact] public void MultipleHaving() { var q = new Query("Table1") .Having("Column1", ">", 1) .Having("Column2", "=", 1); var c = Compile(q); Assert.Equal("SELECT * FROM [Table1] HAVING [Column1] > 1 AND [Column2] = 1", c[EngineCodes.SqlServer]); } [Fact] public void MultipleOrHaving() { var q = new Query("Table1") .Having("Column1", ">", 1) .OrHaving("Column2", "=", 1); var c = Compile(q); Assert.Equal("SELECT * FROM [Table1] HAVING [Column1] > 1 OR [Column2] = 1", c[EngineCodes.SqlServer]); } [Fact] public void ShouldUseILikeOnPostgresWhenNonCaseSensitive() { var q = new Query("Table1") .WhereLike("Column1", "%Upper Word%", false); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] WHERE LOWER([Column1]) like '%upper word%'", c[EngineCodes.SqlServer]); Assert.Equal("SELECT * FROM \"Table1\" WHERE \"Column1\" ilike '%Upper Word%'", c[EngineCodes.PostgreSql]); } [Fact] public void EscapedWhereLike() { var q = new Query("Table1") .WhereLike("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] WHERE LOWER([Column1]) like 'teststring\%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapedWhereStarts() { var q = new Query("Table1") .WhereStarts("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] WHERE LOWER([Column1]) like 'teststring\%%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapedWhereEnds() { var q = new Query("Table1") .WhereEnds("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] WHERE LOWER([Column1]) like '%teststring\%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapedWhereContains() { var q = new Query("Table1") .WhereContains("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] WHERE LOWER([Column1]) like '%teststring\%%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapedHavingLike() { var q = new Query("Table1") .HavingLike("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] HAVING LOWER([Column1]) like 'teststring\%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapedHavingStarts() { var q = new Query("Table1") .HavingStarts("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] HAVING LOWER([Column1]) like 'teststring\%%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapedHavingEnds() { var q = new Query("Table1") .HavingEnds("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] HAVING LOWER([Column1]) like '%teststring\%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapedHavingContains() { var q = new Query("Table1") .HavingContains("Column1", @"TestString\%", false, @"\"); var c = Compile(q); Assert.Equal(@"SELECT * FROM [Table1] HAVING LOWER([Column1]) like '%teststring\%%' ESCAPE '\'", c[EngineCodes.SqlServer]); } [Fact] public void EscapeClauseThrowsForMultipleCharacters() { Assert.ThrowsAny<ArgumentException>(() => { var q = new Query("Table1") .HavingContains("Column1", @"TestString\%", false, @"\aa"); }); } [Fact] public void BasicSelectRaw_WithNoTable() { var q = new Query().SelectRaw("somefunction() as c1"); var c = Compilers.CompileFor(EngineCodes.SqlServer, q); Assert.Equal("SELECT somefunction() as c1", c.ToString()); } [Fact] public void BasicSelect_WithNoTable() { var q = new Query().Select("c1"); var c = Compilers.CompileFor(EngineCodes.SqlServer, q); Assert.Equal("SELECT [c1]", c.ToString()); } [Fact] public void BasicSelect_WithNoTableAndWhereClause() { var q = new Query().Select("c1").Where("p", 1); var c = Compilers.CompileFor(EngineCodes.SqlServer, q); Assert.Equal("SELECT [c1] WHERE [p] = 1", c.ToString()); } [Fact] public void BasicSelect_WithNoTableWhereRawClause() { var q = new Query().Select("c1").WhereRaw("1 = 1"); var c = Compilers.CompileFor(EngineCodes.SqlServer, q); Assert.Equal("SELECT [c1] WHERE 1 = 1", c.ToString()); } } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.XPath; namespace HtmlAgilityPack { /// <summary> /// Represents an HTML node. /// </summary> public class HtmlNode: IXPathNavigable { /// <summary> /// Gets the name of a comment node. It is actually defined as '#comment'. /// </summary> public static readonly string HtmlNodeTypeNameComment = "#comment"; /// <summary> /// Gets the name of the document node. It is actually defined as '#document'. /// </summary> public static readonly string HtmlNodeTypeNameDocument = "#document"; /// <summary> /// Gets the name of a text node. It is actually defined as '#text'. /// </summary> public static readonly string HtmlNodeTypeNameText = "#text"; /// <summary> /// Gets a collection of flags that define specific behaviors for specific element nodes. /// The table contains a DictionaryEntry list with the lowercase tag name as the Key, and a combination of HtmlElementFlags as the Value. /// </summary> public static Hashtable ElementsFlags; internal HtmlNodeType _nodetype; internal HtmlNode _nextnode; internal HtmlNode _prevnode; internal HtmlNode _parentnode; internal HtmlDocument _ownerdocument; internal HtmlNodeCollection _childnodes; internal HtmlAttributeCollection _attributes; internal int _line = 0; internal int _lineposition = 0; internal int _streamposition = 0; internal int _innerstartindex = 0; internal int _innerlength = 0; internal int _outerstartindex = 0; internal int _outerlength = 0; internal int _namestartindex = 0; internal int _namelength = 0; internal bool _starttag = false; internal string _name; internal HtmlNode _prevwithsamename = null; internal HtmlNode _endnode; internal bool _innerchanged = false; internal bool _outerchanged = false; internal string _innerhtml; internal string _outerhtml; static HtmlNode() { // tags whose content may be anything ElementsFlags = new Hashtable(); ElementsFlags.Add("script", HtmlElementFlag.CData); ElementsFlags.Add("style", HtmlElementFlag.CData); ElementsFlags.Add("noxhtml", HtmlElementFlag.CData); // tags that can not contain other tags ElementsFlags.Add("base", HtmlElementFlag.Empty); ElementsFlags.Add("link", HtmlElementFlag.Empty); ElementsFlags.Add("meta", HtmlElementFlag.Empty); ElementsFlags.Add("isindex", HtmlElementFlag.Empty); ElementsFlags.Add("hr", HtmlElementFlag.Empty); ElementsFlags.Add("col", HtmlElementFlag.Empty); ElementsFlags.Add("img", HtmlElementFlag.Empty); ElementsFlags.Add("param", HtmlElementFlag.Empty); ElementsFlags.Add("embed", HtmlElementFlag.Empty); ElementsFlags.Add("frame", HtmlElementFlag.Empty); ElementsFlags.Add("wbr", HtmlElementFlag.Empty); ElementsFlags.Add("bgsound", HtmlElementFlag.Empty); ElementsFlags.Add("spacer", HtmlElementFlag.Empty); ElementsFlags.Add("keygen", HtmlElementFlag.Empty); ElementsFlags.Add("area", HtmlElementFlag.Empty); ElementsFlags.Add("input", HtmlElementFlag.Empty); ElementsFlags.Add("basefont", HtmlElementFlag.Empty); ElementsFlags.Add("form", HtmlElementFlag.CanOverlap | HtmlElementFlag.Empty); // they sometimes contain, and sometimes they don 't... ElementsFlags.Add("option", HtmlElementFlag.Empty); // tag whose closing tag is equivalent to open tag: // <p>bla</p>bla will be transformed into <p>bla</p>bla // <p>bla<p>bla will be transformed into <p>bla<p>bla and not <p>bla></p><p>bla</p> or <p>bla<p>bla</p></p> //<br> see above ElementsFlags.Add("br", HtmlElementFlag.Empty | HtmlElementFlag.Closed); ElementsFlags.Add("p", HtmlElementFlag.Empty | HtmlElementFlag.Closed); } /// <summary> /// Determines if an element node is closed. /// </summary> /// <param name="name">The name of the element node to check. May not be null.</param> /// <returns>true if the name is the name of a closed element node, false otherwise.</returns> public static bool IsClosedElement(string name) { if (name == null) { throw new ArgumentNullException("name"); } object flag = ElementsFlags[name.ToLower()]; if (flag == null) { return false; } return (((HtmlElementFlag)flag)&HtmlElementFlag.Closed) != 0; } /// <summary> /// Determines if an element node can be kept overlapped. /// </summary> /// <param name="name">The name of the element node to check. May not be null.</param> /// <returns>true if the name is the name of an element node that can be kept overlapped, false otherwise.</returns> public static bool CanOverlapElement(string name) { if (name == null) { throw new ArgumentNullException("name"); } object flag = ElementsFlags[name.ToLower()]; if (flag == null) { return false; } return (((HtmlElementFlag)flag)&HtmlElementFlag.CanOverlap) != 0; } /// <summary> /// Determines if a text corresponds to the closing tag of an node that can be kept overlapped. /// </summary> /// <param name="text">The text to check. May not be null.</param> /// <returns>true or false.</returns> public static bool IsOverlappedClosingElement(string text) { if (text == null) { throw new ArgumentNullException("text"); } // min is </x>: 4 if (text.Length <= 4) return false; if ((text[0] != '<') || (text[text.Length - 1] != '>') || (text[1] != '/')) return false; string name = text.Substring(2, text.Length - 3); return CanOverlapElement(name); } /// <summary> /// Determines if an element node is a CDATA element node. /// </summary> /// <param name="name">The name of the element node to check. May not be null.</param> /// <returns>true if the name is the name of a CDATA element node, false otherwise.</returns> public static bool IsCDataElement(string name) { if (name == null) { throw new ArgumentNullException("name"); } object flag = ElementsFlags[name.ToLower()]; if (flag == null) { return false; } return (((HtmlElementFlag)flag)&HtmlElementFlag.CData) != 0; } /// <summary> /// Determines if an element node is defined as empty. /// </summary> /// <param name="name">The name of the element node to check. May not be null.</param> /// <returns>true if the name is the name of an empty element node, false otherwise.</returns> public static bool IsEmptyElement(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { return true; } // <!DOCTYPE ... if ('!' == name[0]) { return true; } // <?xml ... if ('?' == name[0]) { return true; } object flag = ElementsFlags[name.ToLower()]; if (flag == null) { return false; } return (((HtmlElementFlag)flag)&HtmlElementFlag.Empty) != 0; } /// <summary> /// Creates an HTML node from a string representing literal HTML. /// </summary> /// <param name="html">The HTML text.</param> /// <returns>The newly created node instance.</returns> public static HtmlNode CreateNode(string html) { // REVIEW: this is *not* optimum... HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); return doc.DocumentNode.FirstChild; } /// <summary> /// Creates a duplicate of the node and the subtree under it. /// </summary> /// <param name="node">The node to duplicate. May not be null.</param> public void CopyFrom(HtmlNode node) { CopyFrom(node, true); } /// <summary> /// Creates a duplicate of the node. /// </summary> /// <param name="node">The node to duplicate. May not be null.</param> /// <param name="deep">true to recursively clone the subtree under the specified node, false to clone only the node itself.</param> public void CopyFrom(HtmlNode node, bool deep) { if (node == null) { throw new ArgumentNullException("node"); } Attributes.RemoveAll(); if (node.HasAttributes) { foreach(HtmlAttribute att in node.Attributes) { SetAttributeValue(att.Name, att.Value); } } if (!deep) { RemoveAllChildren(); if (node.HasChildNodes) { foreach(HtmlNode child in node.ChildNodes) { AppendChild(child.CloneNode(true)); } } } } internal HtmlNode(HtmlNodeType type, HtmlDocument ownerdocument, int index) { _nodetype = type; _ownerdocument = ownerdocument; _outerstartindex = index; switch(type) { case HtmlNodeType.Comment: _name = HtmlNodeTypeNameComment; _endnode = this; break; case HtmlNodeType.Document: _name = HtmlNodeTypeNameDocument; _endnode = this; break; case HtmlNodeType.Text: _name = HtmlNodeTypeNameText; _endnode = this; break; } if (_ownerdocument._openednodes != null) { if (!Closed) { // we use the index as the key // -1 means the node comes from public if (-1 != index) { _ownerdocument._openednodes.Add(index, this); } } } if ((-1 == index) && (type != HtmlNodeType.Comment) && (type != HtmlNodeType.Text)) { // innerhtml and outerhtml must be calculated _outerchanged = true; _innerchanged = true; } } internal void CloseNode(HtmlNode endnode) { if (!_ownerdocument.OptionAutoCloseOnEnd) { // close all children if (_childnodes != null) { foreach(HtmlNode child in _childnodes) { if (child.Closed) continue; // create a fake closer node HtmlNode close = new HtmlNode(NodeType, _ownerdocument, -1); close._endnode = close; child.CloseNode(close); } } } if (!Closed) { _endnode = endnode; if (_ownerdocument._openednodes != null) { _ownerdocument._openednodes.Remove(_outerstartindex); } HtmlNode self = _ownerdocument._lastnodes[Name] as HtmlNode; if (self == this) { _ownerdocument._lastnodes.Remove(Name); _ownerdocument.UpdateLastParentNode(); } if (endnode == this) return; // create an inner section _innerstartindex = _outerstartindex + _outerlength; _innerlength = endnode._outerstartindex - _innerstartindex; // update full length _outerlength = (endnode._outerstartindex + endnode._outerlength) - _outerstartindex; } } internal HtmlNode EndNode { get { return _endnode; } } internal string GetId() { HtmlAttribute att = Attributes["id"]; if (att == null) { return null; } return att.Value; } internal void SetId(string id) { HtmlAttribute att = Attributes["id"]; if (att == null) { att = _ownerdocument.CreateAttribute("id"); } att.Value = id; _ownerdocument.SetIdForNode(this, att.Value); _outerchanged = true; } /// <summary> /// Creates a new XPathNavigator object for navigating this HTML node. /// </summary> /// <returns>An XPathNavigator object. The XPathNavigator is positioned on the node from which the method was called. It is not positioned on the root of the document.</returns> public XPathNavigator CreateNavigator() { return new HtmlNodeNavigator(_ownerdocument, this); } /// <summary> /// Selects the first XmlNode that matches the XPath expression. /// </summary> /// <param name="xpath">The XPath expression. May not be null.</param> /// <returns>The first HtmlNode that matches the XPath query or a null reference if no matching node was found.</returns> public HtmlNode SelectSingleNode(string xpath) { if (xpath == null) { throw new ArgumentNullException("xpath"); } HtmlNodeNavigator nav = new HtmlNodeNavigator(_ownerdocument, this); XPathNodeIterator it = nav.Select(xpath); if (!it.MoveNext()) { return null; } HtmlNodeNavigator node = (HtmlNodeNavigator)it.Current; return node.CurrentNode; } /// <summary> /// Selects a list of nodes matching the XPath expression. /// </summary> /// <param name="xpath">The XPath expression.</param> /// <returns>An HtmlNodeCollection containing a collection of nodes matching the XPath query, or null if no node matched the XPath expression.</returns> public HtmlNodeCollection SelectNodes(string xpath) { HtmlNodeCollection list = new HtmlNodeCollection(null); HtmlNodeNavigator nav = new HtmlNodeNavigator(_ownerdocument, this); XPathNodeIterator it = nav.Select(xpath); while (it.MoveNext()) { HtmlNodeNavigator n = (HtmlNodeNavigator)it.Current; list.Add(n.CurrentNode); } if (list.Count == 0) { return null; } return list; } /// <summary> /// Gets or sets the value of the 'id' HTML attribute. The document must have been parsed using the OptionUseIdAttribute set to true. /// </summary> public string Id { get { if (_ownerdocument._nodesid == null) { throw new Exception(HtmlDocument.HtmlExceptionUseIdAttributeFalse); } return GetId(); } set { if (_ownerdocument._nodesid == null) { throw new Exception(HtmlDocument.HtmlExceptionUseIdAttributeFalse); } if (value == null) { throw new ArgumentNullException("value"); } SetId(value); } } /// <summary> /// Gets the line number of this node in the document. /// </summary> public int Line { get { return _line; } } /// <summary> /// Gets the column number of this node in the document. /// </summary> public int LinePosition { get { return _lineposition; } } /// <summary> /// Gets the stream position of this node in the document, relative to the start of the document. /// </summary> public int StreamPosition { get { return _streamposition; } } /// <summary> /// Gets a value indicating if this node has been closed or not. /// </summary> public bool Closed { get { return (_endnode != null); } } /// <summary> /// Gets or sets this node's name. /// </summary> public string Name { get { if (_name == null) { _name = _ownerdocument._text.Substring(_namestartindex, _namelength).ToLower(); } return _name; } set { _name = value; } } /// <summary> /// Gets or Sets the text between the start and end tags of the object. /// </summary> public virtual string InnerText { get { if (_nodetype == HtmlNodeType.Text) { return ((HtmlTextNode)this).Text; } if (_nodetype == HtmlNodeType.Comment) { return ((HtmlCommentNode)this).Comment; } // note: right now, this method is *slow*, because we recompute everything. // it could be optimised like innerhtml if (!HasChildNodes) { return string.Empty; } string s = null; foreach(HtmlNode node in ChildNodes) { s += node.InnerText; } return s; } } /// <summary> /// Gets or Sets the HTML between the start and end tags of the object. /// </summary> public virtual string InnerHtml { get { if (_innerchanged) { _innerhtml = WriteContentTo(); _innerchanged = false; return _innerhtml; } if (_innerhtml != null) { return _innerhtml; } if (_innerstartindex < 0) { return string.Empty; } return _ownerdocument._text.Substring(_innerstartindex, _innerlength); } set { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(value); RemoveAllChildren(); AppendChildren(doc.DocumentNode.ChildNodes); } } /// <summary> /// Gets or Sets the object and its content in HTML. /// </summary> public virtual string OuterHtml { get { if (_outerchanged) { _outerhtml = WriteTo(); _outerchanged = false; return _outerhtml; } if (_outerhtml != null) { return _outerhtml; } if (_outerstartindex < 0) { return string.Empty; } return _ownerdocument._text.Substring(_outerstartindex, _outerlength); } } /// <summary> /// Creates a duplicate of the node /// </summary> /// <returns></returns> public HtmlNode Clone() { return CloneNode(true); } /// <summary> /// Creates a duplicate of the node and changes its name at the same time. /// </summary> /// <param name="newName">The new name of the cloned node. May not be null.</param> /// <returns>The cloned node.</returns> public HtmlNode CloneNode(string newName) { return CloneNode(newName, true); } /// <summary> /// Creates a duplicate of the node and changes its name at the same time. /// </summary> /// <param name="newName">The new name of the cloned node. May not be null.</param> /// <param name="deep">true to recursively clone the subtree under the specified node; false to clone only the node itself.</param> /// <returns>The cloned node.</returns> public HtmlNode CloneNode(string newName, bool deep) { if (newName == null) { throw new ArgumentNullException("newName"); } HtmlNode node = CloneNode(deep); node._name = newName; return node; } /// <summary> /// Creates a duplicate of the node. /// </summary> /// <param name="deep">true to recursively clone the subtree under the specified node; false to clone only the node itself.</param> /// <returns>The cloned node.</returns> public HtmlNode CloneNode(bool deep) { HtmlNode node = _ownerdocument.CreateNode(_nodetype); node._name = Name; switch(_nodetype) { case HtmlNodeType.Comment: ((HtmlCommentNode)node).Comment = ((HtmlCommentNode)this).Comment; return node; case HtmlNodeType.Text: ((HtmlTextNode)node).Text = ((HtmlTextNode)this).Text; return node; } // attributes if (HasAttributes) { foreach(HtmlAttribute att in _attributes) { HtmlAttribute newatt = att.Clone(); node.Attributes.Append(newatt); } } // closing attributes if (HasClosingAttributes) { node._endnode = _endnode.CloneNode(false); foreach(HtmlAttribute att in _endnode._attributes) { HtmlAttribute newatt = att.Clone(); node._endnode._attributes.Append(newatt); } } if (!deep) { return node; } if (!HasChildNodes) { return node; } // child nodes foreach(HtmlNode child in _childnodes) { HtmlNode newchild = child.Clone(); node.AppendChild(newchild); } return node; } /// <summary> /// Gets the HTML node immediately following this element. /// </summary> public HtmlNode NextSibling { get { return _nextnode; } } /// <summary> /// Gets the node immediately preceding this node. /// </summary> public HtmlNode PreviousSibling { get { return _prevnode; } } /// <summary> /// Removes all the children and/or attributes of the current node. /// </summary> public void RemoveAll() { RemoveAllChildren(); if (HasAttributes) { _attributes.Clear(); } if ((_endnode != null) && (_endnode != this)) { if (_endnode._attributes != null) { _endnode._attributes.Clear(); } } _outerchanged = true; _innerchanged = true; } /// <summary> /// Removes all the children of the current node. /// </summary> public void RemoveAllChildren() { if (!HasChildNodes) { return; } if (_ownerdocument.OptionUseIdAttribute) { // remove nodes from id list foreach(HtmlNode node in _childnodes) { _ownerdocument.SetIdForNode(null, node.GetId()); } } _childnodes.Clear(); _outerchanged = true; _innerchanged = true; } /// <summary> /// Removes the specified child node. /// </summary> /// <param name="oldChild">The node being removed. May not be null.</param> /// <returns>The node removed.</returns> public HtmlNode RemoveChild(HtmlNode oldChild) { if (oldChild == null) { throw new ArgumentNullException("oldChild"); } int index = -1; if (_childnodes != null) { index = _childnodes[oldChild]; } if (index == -1) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } _childnodes.Remove(index); _ownerdocument.SetIdForNode(null, oldChild.GetId()); _outerchanged = true; _innerchanged = true; return oldChild; } /// <summary> /// Removes the specified child node. /// </summary> /// <param name="oldChild">The node being removed. May not be null.</param> /// <param name="keepGrandChildren">true to keep grand children of the node, false otherwise.</param> /// <returns>The node removed.</returns> public HtmlNode RemoveChild(HtmlNode oldChild, bool keepGrandChildren) { if (oldChild == null) { throw new ArgumentNullException("oldChild"); } if ((oldChild._childnodes != null) && keepGrandChildren) { // get prev sibling HtmlNode prev = oldChild.PreviousSibling; // reroute grand children to ourselves foreach(HtmlNode grandchild in oldChild._childnodes) { InsertAfter(grandchild, prev); } } RemoveChild(oldChild); _outerchanged = true; _innerchanged = true; return oldChild; } /// <summary> /// Replaces the child node oldChild with newChild node. /// </summary> /// <param name="newChild">The new node to put in the child list.</param> /// <param name="oldChild">The node being replaced in the list.</param> /// <returns>The node replaced.</returns> public HtmlNode ReplaceChild(HtmlNode newChild, HtmlNode oldChild) { if (newChild == null) { return RemoveChild(oldChild); } if (oldChild == null) { return AppendChild(newChild); } int index = -1; if (_childnodes != null) { index = _childnodes[oldChild]; } if (index == -1) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } _childnodes.Replace(index, newChild); _ownerdocument.SetIdForNode(null, oldChild.GetId()); _ownerdocument.SetIdForNode(newChild, newChild.GetId()); _outerchanged = true; _innerchanged = true; return newChild; } /// <summary> /// Inserts the specified node immediately before the specified reference node. /// </summary> /// <param name="newChild">The node to insert. May not be null.</param> /// <param name="refChild">The node that is the reference node. The newChild is placed before this node.</param> /// <returns>The node being inserted.</returns> public HtmlNode InsertBefore(HtmlNode newChild, HtmlNode refChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } if (refChild == null) { return AppendChild(newChild); } if (newChild == refChild) { return newChild; } int index = -1; if (_childnodes != null) { index = _childnodes[refChild]; } if (index == -1) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } _childnodes.Insert(index, newChild); _ownerdocument.SetIdForNode(newChild, newChild.GetId()); _outerchanged = true; _innerchanged = true; return newChild; } /// <summary> /// Inserts the specified node immediately after the specified reference node. /// </summary> /// <param name="newChild">The node to insert. May not be null.</param> /// <param name="refChild">The node that is the reference node. The newNode is placed after the refNode.</param> /// <returns>The node being inserted.</returns> public HtmlNode InsertAfter(HtmlNode newChild, HtmlNode refChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } if (refChild == null) { return PrependChild(newChild); } if (newChild == refChild) { return newChild; } int index = -1; if (_childnodes != null) { index = _childnodes[refChild]; } if (index == -1) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } _childnodes.Insert(index + 1, newChild); _ownerdocument.SetIdForNode(newChild, newChild.GetId()); _outerchanged = true; _innerchanged = true; return newChild; } /// <summary> /// Gets the first child of the node. /// </summary> public HtmlNode FirstChild { get { if (!HasChildNodes) { return null; } return _childnodes[0]; } } /// <summary> /// Gets the last child of the node. /// </summary> public HtmlNode LastChild { get { if (!HasChildNodes) { return null; } return _childnodes[_childnodes.Count-1]; } } /// <summary> /// Gets the type of this node. /// </summary> public HtmlNodeType NodeType { get { return _nodetype; } } /// <summary> /// Gets the parent of this node (for nodes that can have parents). /// </summary> public HtmlNode ParentNode { get { return _parentnode; } } /// <summary> /// Gets the HtmlDocument to which this node belongs. /// </summary> public HtmlDocument OwnerDocument { get { return _ownerdocument; } } /// <summary> /// Gets all the children of the node. /// </summary> public HtmlNodeCollection ChildNodes { get { if (_childnodes == null) { _childnodes = new HtmlNodeCollection(this); } return _childnodes; } } /// <summary> /// Adds the specified node to the beginning of the list of children of this node. /// </summary> /// <param name="newChild">The node to add. May not be null.</param> /// <returns>The node added.</returns> public HtmlNode PrependChild(HtmlNode newChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } ChildNodes.Prepend(newChild); _ownerdocument.SetIdForNode(newChild, newChild.GetId()); _outerchanged = true; _innerchanged = true; return newChild; } /// <summary> /// Adds the specified node list to the beginning of the list of children of this node. /// </summary> /// <param name="newChildren">The node list to add. May not be null.</param> public void PrependChildren(HtmlNodeCollection newChildren) { if (newChildren == null) { throw new ArgumentNullException("newChildren"); } foreach(HtmlNode newChild in newChildren) { PrependChild(newChild); } } /// <summary> /// Adds the specified node to the end of the list of children of this node. /// </summary> /// <param name="newChild">The node to add. May not be null.</param> /// <returns>The node added.</returns> public HtmlNode AppendChild(HtmlNode newChild) { if (newChild == null) { throw new ArgumentNullException("newChild"); } ChildNodes.Append(newChild); _ownerdocument.SetIdForNode(newChild, newChild.GetId()); _outerchanged = true; _innerchanged = true; return newChild; } /// <summary> /// Adds the specified node to the end of the list of children of this node. /// </summary> /// <param name="newChildren">The node list to add. May not be null.</param> public void AppendChildren(HtmlNodeCollection newChildren) { if (newChildren == null) throw new ArgumentNullException("newChildrend"); foreach(HtmlNode newChild in newChildren) { AppendChild(newChild); } } /// <summary> /// Gets a value indicating whether the current node has any attributes. /// </summary> public bool HasAttributes { get { if (_attributes == null) { return false; } if (_attributes.Count <= 0) { return false; } return true; } } /// <summary> /// Gets a value indicating whether the current node has any attributes on the closing tag. /// </summary> public bool HasClosingAttributes { get { if ((_endnode == null) || (_endnode == this)) { return false; } if (_endnode._attributes == null) { return false; } if (_endnode._attributes.Count <= 0) { return false; } return true; } } /// <summary> /// Gets a value indicating whether this node has any child nodes. /// </summary> public bool HasChildNodes { get { if (_childnodes == null) { return false; } if (_childnodes.Count <= 0) { return false; } return true; } } /// <summary> /// Helper method to get the value of an attribute of this node. If the attribute is not found, the default value will be returned. /// </summary> /// <param name="name">The name of the attribute to get. May not be null.</param> /// <param name="def">The default value to return if not found.</param> /// <returns>The value of the attribute if found, the default value if not found.</returns> public string GetAttributeValue(string name, string def) { if (name == null) { throw new ArgumentNullException("name"); } if (!HasAttributes) { return def; } HtmlAttribute att = Attributes[name]; if (att == null) { return def; } return att.Value; } /// <summary> /// Helper method to get the value of an attribute of this node. If the attribute is not found, the default value will be returned. /// </summary> /// <param name="name">The name of the attribute to get. May not be null.</param> /// <param name="def">The default value to return if not found.</param> /// <returns>The value of the attribute if found, the default value if not found.</returns> public int GetAttributeValue(string name, int def) { if (name == null) { throw new ArgumentNullException("name"); } if (!HasAttributes) { return def; } HtmlAttribute att = Attributes[name]; if (att == null) { return def; } try { return Convert.ToInt32(att.Value); } catch { return def; } } /// <summary> /// Helper method to get the value of an attribute of this node. If the attribute is not found, the default value will be returned. /// </summary> /// <param name="name">The name of the attribute to get. May not be null.</param> /// <param name="def">The default value to return if not found.</param> /// <returns>The value of the attribute if found, the default value if not found.</returns> public bool GetAttributeValue(string name, bool def) { if (name == null) { throw new ArgumentNullException("name"); } if (!HasAttributes) { return def; } HtmlAttribute att = Attributes[name]; if (att == null) { return def; } try { return Convert.ToBoolean(att.Value); } catch { return def; } } /// <summary> /// Helper method to set the value of an attribute of this node. If the attribute is not found, it will be created automatically. /// </summary> /// <param name="name">The name of the attribute to set. May not be null.</param> /// <param name="value">The value for the attribute.</param> /// <returns>The corresponding attribute instance.</returns> public HtmlAttribute SetAttributeValue(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } HtmlAttribute att = Attributes[name]; if (att == null) { return Attributes.Append(_ownerdocument.CreateAttribute(name, value)); } att.Value = value; return att; } /// <summary> /// Gets the collection of HTML attributes for this node. May not be null. /// </summary> public HtmlAttributeCollection Attributes { get { if (!HasAttributes) { _attributes = new HtmlAttributeCollection(this); } return _attributes; } } /// <summary> /// Gets the collection of HTML attributes for the closing tag. May not be null. /// </summary> public HtmlAttributeCollection ClosingAttributes { get { if (!HasClosingAttributes) { return new HtmlAttributeCollection(this); } return _endnode.Attributes; } } internal void WriteAttribute(TextWriter outText, HtmlAttribute att) { string name; if (_ownerdocument.OptionOutputAsXml) { if (_ownerdocument.OptionOutputUpperCase) { name = att.XmlName.ToUpper(); } else { name = att.XmlName; } outText.Write(" " + name + "=\"" + HtmlDocument.HtmlEncode(att.XmlValue) + "\""); } else { if (_ownerdocument.OptionOutputUpperCase) { name = att.Name.ToUpper(); } else { name = att.Name; } if (att.Name.Length >= 4) { if ((att.Name[0] == '<') && (att.Name[1] == '%') && (att.Name[att.Name.Length-1] == '>') && (att.Name[att.Name.Length-2] == '%')) { outText.Write(" " + name); return; } } if (_ownerdocument.OptionOutputOptimizeAttributeValues) { if (att.Value.IndexOfAny(new Char[]{(char)10, (char)13, (char)9, ' '}) < 0) { outText.Write(" " + name + "=" + att.Value); } else { outText.Write(" " + name + "=\"" + att.Value + "\""); } } else { outText.Write(" " + name + "=\"" + att.Value + "\""); } } } internal static void WriteAttributes(XmlWriter writer, HtmlNode node) { if (!node.HasAttributes) { return; } // we use _hashitems to make sure attributes are written only once foreach(HtmlAttribute att in node.Attributes._hashitems.Values) { writer.WriteAttributeString(att.XmlName, att.Value); } } internal void WriteAttributes(TextWriter outText, bool closing) { if (_ownerdocument.OptionOutputAsXml) { if (_attributes == null) { return; } // we use _hashitems to make sure attributes are written only once foreach(HtmlAttribute att in _attributes._hashitems.Values) { WriteAttribute(outText, att); } return; } if (!closing) { if (_attributes != null) { foreach(HtmlAttribute att in _attributes) { WriteAttribute(outText, att); } } if (_ownerdocument.OptionAddDebuggingAttributes) { WriteAttribute(outText, _ownerdocument.CreateAttribute("_closed", Closed.ToString())); WriteAttribute(outText, _ownerdocument.CreateAttribute("_children", ChildNodes.Count.ToString())); int i = 0; foreach(HtmlNode n in ChildNodes) { WriteAttribute(outText, _ownerdocument.CreateAttribute("_child_" + i, n.Name)); i++; } } } else { if (_endnode == null) { return; } if (_endnode._attributes == null) { return; } if (_endnode == this) { return; } foreach(HtmlAttribute att in _endnode._attributes) { WriteAttribute(outText, att); } if (_ownerdocument.OptionAddDebuggingAttributes) { WriteAttribute(outText, _ownerdocument.CreateAttribute("_closed", Closed.ToString())); WriteAttribute(outText, _ownerdocument.CreateAttribute("_children", ChildNodes.Count.ToString())); } } } internal static string GetXmlComment(HtmlCommentNode comment) { string s = comment.Comment; return s.Substring(4, s.Length-7).Replace("--", " - -"); } /// <summary> /// Saves the current node to the specified TextWriter. /// </summary> /// <param name="outText">The TextWriter to which you want to save.</param> public void WriteTo(TextWriter outText) { string html; switch(_nodetype) { case HtmlNodeType.Comment: html = ((HtmlCommentNode)this).Comment; if (_ownerdocument.OptionOutputAsXml) { outText.Write("<!--" + GetXmlComment((HtmlCommentNode)this) + " -->"); } else { outText.Write(html); } break; case HtmlNodeType.Document: if (_ownerdocument.OptionOutputAsXml) { outText.Write("<?xml version=\"1.0\" encoding=\"" + _ownerdocument.GetOutEncoding().BodyName + "\"?>"); // check there is a root element if (_ownerdocument.DocumentNode.HasChildNodes) { int rootnodes = _ownerdocument.DocumentNode._childnodes.Count; if (rootnodes > 0) { HtmlNode xml = _ownerdocument.GetXmlDeclaration(); if (xml != null) { rootnodes --; } if (rootnodes > 1) { if (_ownerdocument.OptionOutputUpperCase) { outText.Write("<SPAN>"); WriteContentTo(outText); outText.Write("</SPAN>"); } else { outText.Write("<span>"); WriteContentTo(outText); outText.Write("</span>"); } break; } } } } WriteContentTo(outText); break; case HtmlNodeType.Text: html = ((HtmlTextNode)this).Text; if (_ownerdocument.OptionOutputAsXml) { outText.Write(HtmlDocument.HtmlEncode(html)); } else { outText.Write(html); } break; case HtmlNodeType.Element: string name; if (_ownerdocument.OptionOutputUpperCase) { name = Name.ToUpper(); } else { name = Name; } if (_ownerdocument.OptionOutputAsXml) { if (name.Length > 0) { if (name[0] == '?') { // forget this one, it's been done at the document level break; } if (name.Trim().Length == 0) { break; } name = HtmlDocument.GetXmlName(name); } else { break; } } outText.Write("<" + name); WriteAttributes(outText, false); if (!HasChildNodes) { if (HtmlNode.IsEmptyElement(Name)) { if ((_ownerdocument.OptionWriteEmptyNodes) || (_ownerdocument.OptionOutputAsXml)) { outText.Write(" />"); } else { if (Name.Length > 0) { if (Name[0] == '?') { outText.Write("?"); } } outText.Write(">"); } } else { outText.Write("></" + name + ">"); } } else { outText.Write(">"); bool cdata = false; if (_ownerdocument.OptionOutputAsXml) { if (HtmlNode.IsCDataElement(Name)) { // this code and the following tries to output things as nicely as possible for old browsers. cdata = true; outText.Write("\r\n//<![CDATA[\r\n"); } } if (cdata) { if (HasChildNodes) { // child must be a text ChildNodes[0].WriteTo(outText); } outText.Write("\r\n//]]>//\r\n"); } else { WriteContentTo(outText); } outText.Write("</" + name); if (!_ownerdocument.OptionOutputAsXml) { WriteAttributes(outText, true); } outText.Write(">"); } break; } } /// <summary> /// Saves the current node to the specified XmlWriter. /// </summary> /// <param name="writer">The XmlWriter to which you want to save.</param> public void WriteTo(XmlWriter writer) { string html; switch(_nodetype) { case HtmlNodeType.Comment: writer.WriteComment(GetXmlComment((HtmlCommentNode)this)); break; case HtmlNodeType.Document: writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"" + _ownerdocument.GetOutEncoding().BodyName + "\""); if (HasChildNodes) { foreach(HtmlNode subnode in ChildNodes) { subnode.WriteTo(writer); } } break; case HtmlNodeType.Text: html = ((HtmlTextNode)this).Text; writer.WriteString(html); break; case HtmlNodeType.Element: string name; if (_ownerdocument.OptionOutputUpperCase) { name = Name.ToUpper(); } else { name = Name; } writer.WriteStartElement(name); WriteAttributes(writer, this); if (HasChildNodes) { foreach(HtmlNode subnode in ChildNodes) { subnode.WriteTo(writer); } } writer.WriteEndElement(); break; } } /// <summary> /// Saves all the children of the node to the specified TextWriter. /// </summary> /// <param name="outText">The TextWriter to which you want to save.</param> public void WriteContentTo(TextWriter outText) { if (_childnodes == null) { return; } foreach(HtmlNode node in _childnodes) { node.WriteTo(outText); } } /// <summary> /// Saves the current node to a string. /// </summary> /// <returns>The saved string.</returns> public string WriteTo() { StringWriter sw = new StringWriter(); WriteTo(sw); sw.Flush(); return sw.ToString(); } /// <summary> /// Saves all the children of the node to a string. /// </summary> /// <returns>The saved string.</returns> public string WriteContentTo() { StringWriter sw = new StringWriter(); WriteContentTo(sw); sw.Flush(); return sw.ToString(); } } }
// // TaskActionInvoker.cs // // Authors: // Marek Safar <marek.safar@gmail.com> // // Copyright 2011 Xamarin 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.Threading; namespace System.Threading.Tasks { abstract class TaskActionInvoker { public static readonly TaskActionInvoker Empty = new EmptyTaskActionInvoker (); public static readonly TaskActionInvoker Promise = new EmptyTaskActionInvoker (); public static readonly TaskActionInvoker Delay = new DelayTaskInvoker (); sealed class EmptyTaskActionInvoker : TaskActionInvoker { public override Delegate Action { get { return null; } } public override void Invoke (Task owner, object state, Task context) { } } sealed class ActionInvoke : TaskActionInvoker { readonly Action action; public ActionInvoke (Action action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { action (); } } sealed class ActionObjectInvoke : TaskActionInvoker { readonly Action<object> action; public ActionObjectInvoke (Action<object> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { action (state); } } sealed class ActionTaskInvoke : TaskActionInvoker { readonly Action<Task> action; public ActionTaskInvoke (Action<Task> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { action (owner); } } sealed class ActionTasksInvoke : TaskActionInvoker { readonly Action<Task[]> action; readonly Task[] tasks; public ActionTasksInvoke (Action<Task[]> action, Task[] tasks) { this.action = action; this.tasks = tasks; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { owner.TrySetExceptionObserved (); action (tasks); } } sealed class ActionTaskObjectInvoke : TaskActionInvoker { readonly Action<Task, object> action; public ActionTaskObjectInvoke (Action<Task, object> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { action (owner, state); } } sealed class ActionTaskObjectInvoke<TResult> : TaskActionInvoker { readonly Action<Task<TResult>, object> action; public ActionTaskObjectInvoke (Action<Task<TResult>, object> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { action ((Task<TResult>) owner, state); } } sealed class ActionTaskInvoke<TResult> : TaskActionInvoker { readonly Action<Task<TResult>> action; public ActionTaskInvoke (Action<Task<TResult>> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { action ((Task<TResult>) owner); } } sealed class ActionTaskSelected : TaskActionInvoker { readonly Action<Task> action; public ActionTaskSelected (Action<Task> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { action (((Task<Task>)owner).Result); } } sealed class FuncInvoke<TResult> : TaskActionInvoker { readonly Func<TResult> action; public FuncInvoke (Func<TResult> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { ((Task<TResult>) context).Result = action (); } } sealed class FuncTaskInvoke<TResult> : TaskActionInvoker { readonly Func<Task, TResult> action; public FuncTaskInvoke (Func<Task, TResult> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { ((Task<TResult>) context).Result = action (owner); } } sealed class FuncTasksInvoke<TResult> : TaskActionInvoker { readonly Func<Task[], TResult> action; readonly Task[] tasks; public FuncTasksInvoke (Func<Task[], TResult> action, Task[] tasks) { this.action = action; this.tasks = tasks; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { owner.TrySetExceptionObserved (); ((Task<TResult>) context).Result = action (tasks); } } sealed class FuncTaskSelected<TResult> : TaskActionInvoker { readonly Func<Task, TResult> action; public FuncTaskSelected (Func<Task, TResult> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { var result = ((Task<Task>) owner).Result; ((Task<TResult>) context).Result = action (result); } } sealed class FuncTaskInvoke<TResult, TNewResult> : TaskActionInvoker { readonly Func<Task<TResult>, TNewResult> action; public FuncTaskInvoke (Func<Task<TResult>, TNewResult> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { ((Task<TNewResult>) context).Result = action ((Task<TResult>) owner); } } sealed class FuncObjectInvoke<TResult> : TaskActionInvoker { readonly Func<object, TResult> action; public FuncObjectInvoke (Func<object, TResult> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { ((Task<TResult>) context).Result = action (state); } } sealed class FuncTaskObjectInvoke<TResult> : TaskActionInvoker { readonly Func<Task, object, TResult> action; public FuncTaskObjectInvoke (Func<Task, object, TResult> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { ((Task<TResult>) context).Result = action (owner, state); } } sealed class FuncTaskObjectInvoke<TResult, TNewResult> : TaskActionInvoker { readonly Func<Task<TResult>, object, TNewResult> action; public FuncTaskObjectInvoke (Func<Task<TResult>, object, TNewResult> action) { this.action = action; } public override Delegate Action { get { return action; } } public override void Invoke (Task owner, object state, Task context) { ((Task<TNewResult>) context).Result = action ((Task<TResult>) owner, state); } } sealed class DelayTaskInvoker : TaskActionInvoker { public override Delegate Action { get { return null; } } public override void Invoke (Task owner, object state, Task context) { var mre = new ManualResetEventSlim (); int timeout = (int) state; mre.Wait (timeout, context.CancellationToken); } } public static TaskActionInvoker Create (Action action) { return new ActionInvoke (action); } public static TaskActionInvoker Create (Action<object> action) { return new ActionObjectInvoke (action); } public static TaskActionInvoker Create (Action<Task> action) { return new ActionTaskInvoke (action); } public static TaskActionInvoker Create (Action<Task, object> action) { return new ActionTaskObjectInvoke (action); } public static TaskActionInvoker Create<TResult> (Action<Task<TResult>> action) { return new ActionTaskInvoke<TResult> (action); } public static TaskActionInvoker Create<TResult> (Action<Task<TResult>, object> action) { return new ActionTaskObjectInvoke<TResult> (action); } public static TaskActionInvoker Create<TResult> (Func<TResult> action) { return new FuncInvoke<TResult> (action); } public static TaskActionInvoker Create<TResult> (Func<object, TResult> action) { return new FuncObjectInvoke<TResult> (action); } public static TaskActionInvoker Create<TResult> (Func<Task, TResult> action) { return new FuncTaskInvoke<TResult> (action); } public static TaskActionInvoker Create<TResult> (Func<Task, object, TResult> action) { return new FuncTaskObjectInvoke<TResult> (action); } public static TaskActionInvoker Create<TResult, TNewResult> (Func<Task<TResult>, TNewResult> action) { return new FuncTaskInvoke<TResult, TNewResult> (action); } public static TaskActionInvoker Create<TResult, TNewResult> (Func<Task<TResult>, object, TNewResult> action) { return new FuncTaskObjectInvoke<TResult, TNewResult> (action); } #region Used by ContinueWhenAll public static TaskActionInvoker Create (Action<Task[]> action, Task[] tasks) { return new ActionTasksInvoke (action, tasks); } public static TaskActionInvoker Create<TResult> (Func<Task[], TResult> action, Task[] tasks) { return new FuncTasksInvoke<TResult> (action, tasks); } #endregion #region Used by ContinueWhenAny public static TaskActionInvoker CreateSelected (Action<Task> action) { return new ActionTaskSelected (action); } public static TaskActionInvoker CreateSelected<TResult> (Func<Task, TResult> action) { return new FuncTaskSelected<TResult> (action); } #endregion public abstract Delegate Action { get; } public abstract void Invoke (Task owner, object state, Task context); } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework; using StateInterpolationPlugin; using FlatRedBall.Glue.StateInterpolation; using FlatRedBall.Math.Splines; using FlatRedBall.Math; using FishKing.Extensions; using FishKing.Managers; namespace FishKing.Entities { public partial class Bobber { private SoundEffectInstance bobberSoundInstance; private AudioListener listener; private AudioEmitter emitter; private float originalTextureScale; private bool wasCastHorizontally = false; public bool FrameJustChanged { get { return BobberSpriteInstance.JustChangedFrame; } } public bool IsMoving { get; private set; } public Vector3 LineOriginationPosition { get { BobberSpriteInstance.UpdateDependencies(FlatRedBall.TimeManager.CurrentTime); return BobberSpriteInstance.GetKeyPixelPosition(); } } /// <summary> /// Initialization logic which is execute only one time for this Entity (unless the Entity is pooled). /// This method is called when the Entity is added to managers. Entities which are instantiated but not /// added to managers will not have this method called. /// </summary> private void CustomInitialize() { bobberSoundInstance = BobberDrop.CreateInstance(); listener = new AudioListener(); listener.Position = Vector3.Zero; emitter = new AudioEmitter(); IsMoving = false; ShadowInstance.SpriteInstanceWidth = this.BobberSpriteInstance.Width * 0.9f; ShadowInstance.SpriteInstanceAlpha = 0.5f; originalTextureScale = this.BobberSpriteInstance.TextureScale; } /// <summary> /// Update the fishing line as the bobber moves through the air, and hide the splash after it has played /// </summary> private void CustomActivity() { if (Visible) { if (IsMoving) { ShadowInstance.Visible = true; ShadowInstance.RelativeY = -RelativeY; if (wasCastHorizontally) { ShadowInstance.RelativeY = -8 + -RelativeY; ShadowInstance.SpriteInstanceWidth = BobberSpriteInstance.Width * (1 - (RelativeY / 128)); ShadowInstance.SpriteInstanceAlpha = 0.5f * (1 - (RelativeY / 128)); } else { ShadowInstance.RelativeY = (-128 * (1 - (originalTextureScale / BobberSpriteInstance.TextureScale))); ShadowInstance.SpriteInstanceWidth = BobberSpriteInstance.Width * (originalTextureScale / BobberSpriteInstance.TextureScale); ShadowInstance.SpriteInstanceAlpha = 0.5f * (originalTextureScale / BobberSpriteInstance.TextureScale); } } else { ShadowInstance.Visible = false; } } else { ShadowInstance.Visible = false; var tweenManager = TweenerManager.Self; if (tweenManager.IsObjectReferencedByTweeners(this)) { tweenManager.StopAllTweenersOwnedBy(this); } } } private void CustomDestroy() { } private static void CustomLoadStaticContent(string contentManagerName) { } /// <summary> /// Move the bobber to the designated location, relative to the character /// </summary> /// <param name="relativeDestination">Designated location, relative to the caller</param> /// <param name="tileSize">Number of pixels per tile to determine tile distance traveled</param> public void TraverseTo(Vector3 relativeDestination, int tileSize) { IsMoving = true; CurrentState = VariableState.OutOfWater; this.RelativePosition = Vector3.Zero; ShadowInstance.RelativeZ = -0.5f; this.Visible = true; Tweener distanceTweener; Tweener verticalTweener; double tweenDuration = 0.75; wasCastHorizontally = relativeDestination.X != this.RelativeX; if (wasCastHorizontally) { this.RelativeY += tileSize; if (relativeDestination.X > this.RelativeX) { this.RelativeX += tileSize*1.3f; } else { this.RelativeX -= tileSize*1.3f; } distanceTweener = this.Tween("RelativeX").To(relativeDestination.X).During(tweenDuration).Using(InterpolationType.Sinusoidal, Easing.Out); verticalTweener = this.Tween("RelativeY").To(RelativeY*1.5f).During(tweenDuration/2).Using(InterpolationType.Sinusoidal, Easing.Out); verticalTweener.Ended += () => { this.Tween("RelativeY").To(-5).During(tweenDuration / 2).Using(InterpolationType.Quadratic, Easing.In).Start(); }; } else { var castingUp = relativeDestination.Y > this.RelativeY; if (castingUp) { this.RelativeY += tileSize*1.1f; this.RelativeX += tileSize*0.2f; } distanceTweener = this.Tween("RelativeY").To(relativeDestination.Y).During(tweenDuration).Using(InterpolationType.Sinusoidal, Easing.Out); if (castingUp) { this.Tween("RelativeX").To(relativeDestination.X - tileSize*0.25f).During(tweenDuration).Using(InterpolationType.Linear, Easing.InOut).Start(); } var currentScale = this.BobberSpriteInstance.TextureScale; var newScale = currentScale * 1.5f; verticalTweener = this.BobberSpriteInstance.Tween("TextureScale").To(newScale).During(tweenDuration / 2).Using(InterpolationType.Sinusoidal, Easing.Out); verticalTweener.Ended += () => { this.BobberSpriteInstance.Tween("TextureScale").To(currentScale).During(tweenDuration / 2).Using(InterpolationType.Quadratic, Easing.In).Start(); }; } //Determine positional sound of bobber when it hits emitter.Position = new Vector3(relativeDestination.X / tileSize, relativeDestination.Y / tileSize, 0); bobberSoundInstance.Apply3D(listener, emitter); //Start movement distanceTweener.Ended += WaterTouchDown; distanceTweener.Start(); verticalTweener.Start(); } /// <summary> /// Occurs when the bobber hits the water /// </summary> private void WaterTouchDown() { if (Visible) { WaterSplashInstance.Play(); bobberSoundInstance.Volume = OptionsManager.Options.SoundEffectsVolume; bobberSoundInstance.Play(); IsMoving = false; CurrentState = VariableState.BobInWater; } } } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System.Collections.Generic; using System.Windows.Forms; using XenAdmin.Actions; using XenAdmin.Controls; using XenAdmin.Dialogs; using XenAPI; using System.Linq; using System.IO; using XenAdmin.Alerts; namespace XenAdmin.Wizards.PatchingWizard { /// <summary> /// Remember that equals for patches dont work across connections because /// we are not allow to override equals. YOU SHOULD NOT USE ANY OPERATION THAT IMPLIES CALL EQUALS OF Pool_path or Host_patch /// You should do it manually or use delegates. /// </summary> public partial class PatchingWizard : XenWizardBase { private readonly PatchingWizard_PatchingPage PatchingWizard_PatchingPage; private readonly PatchingWizard_SelectPatchPage PatchingWizard_SelectPatchPage; private readonly PatchingWizard_ModePage PatchingWizard_ModePage; private readonly PatchingWizard_SelectServers PatchingWizard_SelectServers; private readonly PatchingWizard_UploadPage PatchingWizard_UploadPage; private readonly PatchingWizard_PrecheckPage PatchingWizard_PrecheckPage; private readonly PatchingWizard_FirstPage PatchingWizard_FirstPage; private readonly PatchingWizard_AutoUpdatingPage PatchingWizard_AutoUpdatingPage; public PatchingWizard() { InitializeComponent(); PatchingWizard_PatchingPage = new PatchingWizard_PatchingPage(); PatchingWizard_SelectPatchPage = new PatchingWizard_SelectPatchPage(); PatchingWizard_ModePage = new PatchingWizard_ModePage(); PatchingWizard_SelectServers = new PatchingWizard_SelectServers(); PatchingWizard_UploadPage = new PatchingWizard_UploadPage(); PatchingWizard_PrecheckPage = new PatchingWizard_PrecheckPage(); PatchingWizard_FirstPage = new PatchingWizard_FirstPage(); PatchingWizard_AutoUpdatingPage = new PatchingWizard_AutoUpdatingPage(); AddPage(PatchingWizard_FirstPage); AddPage(PatchingWizard_SelectPatchPage); AddPage(PatchingWizard_SelectServers); AddPage(PatchingWizard_UploadPage); AddPage(PatchingWizard_PrecheckPage); AddPage(PatchingWizard_ModePage); AddPage(PatchingWizard_PatchingPage); } public void AddAlert(XenServerPatchAlert alert) { PatchingWizard_SelectPatchPage.SelectDownloadAlert(alert); PatchingWizard_SelectPatchPage.SelectedUpdateAlert = alert; PatchingWizard_SelectServers.SelectedUpdateAlert = alert; PatchingWizard_UploadPage.SelectedUpdateAlert = alert; } public void AddFile(string path) { PatchingWizard_SelectPatchPage.AddFile(path); } public void SelectServers(List<Host> selectedServers) { PatchingWizard_SelectServers.SelectServers(selectedServers); PatchingWizard_SelectServers.DisableUnselectedServers(); } protected override void UpdateWizardContent(XenTabPage senderPage) { var prevPageType = senderPage.GetType(); if (prevPageType == typeof(PatchingWizard_SelectPatchPage)) { var wizardModeAutomatic = PatchingWizard_SelectPatchPage.IsInAutomaticMode; var updateType = wizardModeAutomatic ? UpdateType.NewRetail : PatchingWizard_SelectPatchPage.SelectedUpdateType; var newPatch = wizardModeAutomatic ? null : PatchingWizard_SelectPatchPage.SelectedNewPatch; var existPatch = wizardModeAutomatic ? null : PatchingWizard_SelectPatchPage.SelectedExistingPatch; var alertPatch = wizardModeAutomatic ? null : PatchingWizard_SelectPatchPage.SelectedUpdateAlert; var fileFromDiskAlertPatch = wizardModeAutomatic ? null : PatchingWizard_SelectPatchPage.FileFromDiskAlert; PatchingWizard_SelectServers.IsInAutomaticMode = wizardModeAutomatic; PatchingWizard_SelectServers.SelectedUpdateType = updateType; PatchingWizard_SelectServers.Patch = existPatch; PatchingWizard_SelectServers.SelectedUpdateAlert = alertPatch; PatchingWizard_SelectServers.FileFromDiskAlert = fileFromDiskAlertPatch; RemovePage(PatchingWizard_UploadPage); RemovePage(PatchingWizard_ModePage); RemovePage(PatchingWizard_PatchingPage); RemovePage(PatchingWizard_AutoUpdatingPage); if (!wizardModeAutomatic) { AddAfterPage(PatchingWizard_SelectServers, PatchingWizard_UploadPage); AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_ModePage); AddAfterPage(PatchingWizard_ModePage, PatchingWizard_PatchingPage); } else { AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_AutoUpdatingPage); } PatchingWizard_UploadPage.SelectedUpdateType = updateType; PatchingWizard_UploadPage.SelectedExistingPatch = existPatch; PatchingWizard_UploadPage.SelectedNewPatchPath = newPatch; PatchingWizard_UploadPage.SelectedUpdateAlert = alertPatch; PatchingWizard_ModePage.Patch = existPatch; PatchingWizard_ModePage.SelectedUpdateAlert = alertPatch; PatchingWizard_PrecheckPage.IsInAutomaticMode = wizardModeAutomatic; PatchingWizard_PrecheckPage.Patch = existPatch; PatchingWizard_PatchingPage.Patch = existPatch; PatchingWizard_PrecheckPage.SelectedUpdateType = updateType; PatchingWizard_ModePage.SelectedUpdateType = updateType; PatchingWizard_PatchingPage.SelectedUpdateType = updateType; PatchingWizard_PatchingPage.SelectedNewPatch = newPatch; } else if (prevPageType == typeof(PatchingWizard_SelectServers)) { var selectedServers = PatchingWizard_SelectServers.SelectedServers; var selectedPools = PatchingWizard_SelectServers.SelectedPools; var selectedMasters = PatchingWizard_SelectServers.SelectedMasters; PatchingWizard_PrecheckPage.SelectedServers = selectedServers; PatchingWizard_ModePage.SelectedServers = selectedServers; PatchingWizard_PatchingPage.SelectedMasters = selectedMasters; PatchingWizard_PatchingPage.SelectedServers = selectedServers; PatchingWizard_PatchingPage.SelectedPools = selectedPools; PatchingWizard_UploadPage.SelectedMasters = selectedMasters; PatchingWizard_UploadPage.SelectedServers = selectedServers; PatchingWizard_AutoUpdatingPage.SelectedPools = selectedPools; } else if (prevPageType == typeof(PatchingWizard_UploadPage)) { if (PatchingWizard_SelectPatchPage.SelectedUpdateType == UpdateType.NewRetail) { PatchingWizard_SelectPatchPage.SelectedUpdateType = UpdateType.Existing; PatchingWizard_SelectPatchPage.SelectedExistingPatch = PatchingWizard_UploadPage.Patch; PatchingWizard_SelectServers.SelectedUpdateType = UpdateType.Existing; PatchingWizard_SelectServers.Patch = PatchingWizard_UploadPage.Patch; PatchingWizard_PrecheckPage.Patch = PatchingWizard_UploadPage.Patch; PatchingWizard_ModePage.Patch = PatchingWizard_UploadPage.Patch; PatchingWizard_PatchingPage.Patch = PatchingWizard_UploadPage.Patch; } PatchingWizard_PrecheckPage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate; PatchingWizard_PatchingPage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate; PatchingWizard_ModePage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate; PatchingWizard_PatchingPage.SuppPackVdis = PatchingWizard_UploadPage.SuppPackVdis; } else if (prevPageType == typeof(PatchingWizard_ModePage)) { PatchingWizard_PatchingPage.ManualTextInstructions = PatchingWizard_ModePage.ManualTextInstructions; PatchingWizard_PatchingPage.IsAutomaticMode = PatchingWizard_ModePage.IsAutomaticMode; PatchingWizard_PatchingPage.RemoveUpdateFile = PatchingWizard_ModePage.RemoveUpdateFile; } else if (prevPageType == typeof(PatchingWizard_PrecheckPage)) { PatchingWizard_PatchingPage.ProblemsResolvedPreCheck = PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck; PatchingWizard_PatchingPage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost; PatchingWizard_ModePage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost; PatchingWizard_AutoUpdatingPage.ProblemsResolvedPreCheck = PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck; } } private delegate List<AsyncAction> GetActionsDelegate(); private List<AsyncAction> BuildSubActions(params GetActionsDelegate[] getActionsDelegate) { List<AsyncAction> result = new List<AsyncAction>(); foreach (GetActionsDelegate getActionDelegate in getActionsDelegate) { var list = getActionDelegate(); if (list != null && list.Count > 0) result.AddRange(list); } return result; } private List<AsyncAction> GetUnwindChangesActions() { if (PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck == null) return null; var actionList = (from problem in PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck where problem.SolutionActionCompleted select problem.UnwindChanges()); return actionList.Where(action => action != null && action.Connection != null && action.Connection.IsConnected).ToList(); } private List<AsyncAction> GetRemovePatchActions(List<Pool_patch> patchesToRemove) { if (patchesToRemove == null) return null; List<AsyncAction> list = new List<AsyncAction>(); foreach (Pool_patch patch in patchesToRemove) { if (patch.Connection != null && patch.Connection.IsConnected) { if (patch.HostsAppliedTo().Count == 0) { list.Add(new RemovePatchAction(patch)); } else { list.Add(new DelegatedAsyncAction(patch.Connection, Messages.REMOVE_PATCH, "", "", session => Pool_patch.async_pool_clean(session, patch.opaque_ref))); } } } return list; } private List<AsyncAction> GetRemovePatchActions() { return GetRemovePatchActions(PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList()); } private List<AsyncAction> GetRemoveVdiActions(List<VDI> vdisToRemove) { if (vdisToRemove == null) return null; var list = (from vdi in vdisToRemove where vdi.Connection != null && vdi.Connection.IsConnected select new DestroyDiskAction(vdi)); return list.OfType<AsyncAction>().ToList(); } private List<AsyncAction> GetRemoveVdiActions() { return GetRemoveVdiActions(PatchingWizard_UploadPage.AllCreatedSuppPackVdis); ; } private void RunMultipleActions(string title, string startDescription, string endDescription, List<AsyncAction> subActions) { if (subActions.Count > 0) { using (MultipleAction multipleAction = new MultipleAction(xenConnection, title, startDescription, endDescription, subActions, false, true)) { using (var dialog = new ActionProgressDialog(multipleAction, ProgressBarStyle.Blocks)) dialog.ShowDialog(Program.MainWindow); } } } protected override void OnCancel() { base.OnCancel(); List<AsyncAction> subActions = BuildSubActions(GetUnwindChangesActions, GetRemovePatchActions, GetRemoveVdiActions, GetCleanUpPoolUpdateActions); RunMultipleActions(Messages.REVERT_WIZARD_CHANGES, Messages.REVERTING_WIZARD_CHANGES, Messages.REVERTED_WIZARD_CHANGES, subActions); RemoveDownloadedPatches(); } private void RemoveUnwantedPatches(List<Pool_patch> patchesToRemove) { List<AsyncAction> subActions = GetRemovePatchActions(patchesToRemove); RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions); } private void RemoveTemporaryVdis() { List<AsyncAction> subActions = GetRemoveVdiActions(); RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions); } private void CleanUpPoolUpdates() { var subActions = GetCleanUpPoolUpdateActions(); RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions); } private void RemoveDownloadedPatches() { var isInAutomaticMode = PatchingWizard_SelectPatchPage.IsInAutomaticMode; List<string> listOfDownloadedFiles = new List<string>(); if (isInAutomaticMode) { listOfDownloadedFiles.AddRange(PatchingWizard_AutoUpdatingPage.AllDownloadedPatches.Values); } else { listOfDownloadedFiles.AddRange(PatchingWizard_UploadPage.AllDownloadedPatches.Values); } foreach (string downloadedPatch in listOfDownloadedFiles) { try { if (File.Exists(downloadedPatch)) { File.Delete(downloadedPatch); } } catch { log.DebugFormat("Could not remove downloaded patch {0} ", downloadedPatch); } } } protected override void FinishWizard() { if (PatchingWizard_UploadPage.NewUploadedPatches != null) { List<Pool_patch> patchesToRemove = PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList().Where( patch => !string.Equals(patch.uuid, PatchingWizard_UploadPage.Patch.uuid, System.StringComparison.OrdinalIgnoreCase)).ToList(); RemoveUnwantedPatches(patchesToRemove); } if (PatchingWizard_UploadPage.AllCreatedSuppPackVdis != null) RemoveTemporaryVdis(); CleanUpPoolUpdates(); RemoveDownloadedPatches(); base.FinishWizard(); } private List<AsyncAction> GetCleanUpPoolUpdateActions() { if (PatchingWizard_UploadPage.AllIntroducedPoolUpdates != null && PatchingWizard_UploadPage.AllIntroducedPoolUpdates.Count > 0) { return PatchingWizard_UploadPage.AllIntroducedPoolUpdates.Select(GetCleanUpPoolUpdateAction).ToList(); } return new List<AsyncAction>(); } private static AsyncAction GetCleanUpPoolUpdateAction(Pool_update poolUpdate) { return new DelegatedAsyncAction(poolUpdate.Connection, Messages.REMOVE_PATCH, "", "", session => { try { Pool_update.pool_clean(session, poolUpdate.opaque_ref); if(!poolUpdate.AppliedOnHosts.Any()) Pool_update.destroy(session, poolUpdate.opaque_ref); } catch (Failure f) { log.Error("Clean up failed", f); } }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Reactive.Testing; using MoreLinq.Extensions; using Xunit; namespace BFF.DataVirtualizingCollection.Tests.Integration.DataVirtualizingCollectionDataAccess { public class SyncDataAccessTests { // ReSharper disable once MemberCanBePrivate.Global public static IEnumerable<object[]> Combinations => Enum.GetValues(typeof(PageLoadingBehavior)).OfType<PageLoadingBehavior>() .Cartesian( Enum.GetValues(typeof(PageRemovalBehavior)).OfType<PageRemovalBehavior>(), Enum.GetValues(typeof(FetchersKind)).OfType<FetchersKind>().Except(new [] { FetchersKind.TaskBased }), (first, second, third) => new object[] {first, second, third, IndexAccessBehavior.Synchronous}); [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_FirstEntry_0( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, scheduler); // Act + Assert Assert.Equal(0, collection[0]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_70thEntry_69( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, scheduler); // Act + Assert Assert.Equal(69, collection[69]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_124thEntry_123( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, scheduler); // Act + Assert Assert.Equal(123, collection[123]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_6001thEntry_6000( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, scheduler); // Act + Assert Assert.Equal(6000, collection[6000]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_6969thEntry_6968( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, scheduler); // Act + Assert Assert.Equal(6968, collection[6968]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_6970thEntry_ThrowsIndexOutOfRangeException( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, scheduler); // Act + Assert Assert.Throws<IndexOutOfRangeException>(() => collection[6969]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWith6969Elements_MinusFirstEntry_ThrowsIndexOutOfRangeException( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalInteger( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 100, scheduler); // Act + Assert Assert.Throws<IndexOutOfRangeException>(() => collection[-1]); } [Theory] [MemberData(nameof(Combinations))] public async Task BuildingCollectionWherePageFetcherIgnoresGivenPageSize23_70thEntry_69( PageLoadingBehavior pageLoadingBehavior, PageRemovalBehavior pageRemovalBehavior, FetchersKind fetchersKind, IndexAccessBehavior indexAccessBehavior) { // Arrange var scheduler = new TestScheduler(); await using var collection = DataVirtualizingCollectionFactory.CreateCollectionWithIncrementalIntegerWhereFetchersIgnorePageSize( pageLoadingBehavior, pageRemovalBehavior, fetchersKind, indexAccessBehavior, 6969, 23, scheduler); // Act + Assert Assert.Equal(69, collection[69]); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using webapispikes.Areas.HelpPage.Models; namespace webapispikes.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// $ANTLR 3.1.3 Mar 18, 2009 10:09:25 C:\\Development\\TT.Net\\TT\\Template.g 2009-06-09 20:10:09 #define ANTLR_DEBUG // The variable 'variable' is assigned but its value is never used. #pragma warning disable 168, 219 // Unreachable code detected. #pragma warning disable 162 using System; using Antlr.Runtime; using IList = System.Collections.IList; using ArrayList = System.Collections.ArrayList; using Stack = Antlr.Runtime.Collections.StackList; using Antlr.Runtime.Debug; using IOException = System.IO.IOException; using Antlr.Runtime.Tree; namespace TT { public partial class TemplateParser : DebugParser { public static readonly string[] tokenNames = new string[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "GET", "SET", "PRINT", "DOCUMENT", "WS", "TSTART", "TSTOP", "QUOTE", "SQUOTE", "ILITERAL", "LITERAL", "CALL", "DEFAULT", "INSERT", "PROCESS", "INCLUDE", "WRAPPER", "BLOCK", "FOREACH", "WHILE", "IF", "UNLESS", "ELSIF", "ELSE", "SWITCH", "CASE", "MACRO", "FILTER", "USE", "PERL", "RAWPERL", "TRY", "THROW", "CATCH", "FINAL", "NEXT", "LAST", "RETURN", "STOP", "TAGS", "COMMENTS", "ID", "NUMBER", "DECIMAL", "ADD", "SUB", "MULT", "DIV", "ASSIGN", "EQUAL", "CHAR", "'GET'", "'SET'" }; public const int WHILE = 23; public const int CASE = 29; public const int CHAR = 54; public const int RAWPERL = 34; public const int SUB = 49; public const int ID = 45; public const int EOF = -1; public const int TSTART = 9; public const int IF = 24; public const int T__55 = 55; public const int T__56 = 56; public const int QUOTE = 11; public const int TSTOP = 10; public const int FINAL = 38; public const int COMMENTS = 44; public const int INSERT = 17; public const int DOCUMENT = 7; public const int EQUAL = 53; public const int INCLUDE = 19; public const int RETURN = 41; public const int GET = 4; public const int NEXT = 39; public const int LAST = 40; public const int UNLESS = 25; public const int ILITERAL = 13; public const int ADD = 48; public const int SWITCH = 28; public const int DEFAULT = 16; public const int ELSE = 27; public const int NUMBER = 46; public const int TAGS = 43; public const int STOP = 42; public const int LITERAL = 14; public const int SET = 5; public const int MULT = 50; public const int SQUOTE = 12; public const int WRAPPER = 20; public const int PRINT = 6; public const int TRY = 35; public const int PERL = 33; public const int WS = 8; public const int DECIMAL = 47; public const int BLOCK = 21; public const int ASSIGN = 52; public const int FILTER = 31; public const int FOREACH = 22; public const int CALL = 15; public const int ELSIF = 26; public const int USE = 32; public const int DIV = 51; public const int PROCESS = 18; public const int CATCH = 37; public const int MACRO = 30; public const int THROW = 36; // delegates // delegators public static readonly string[] ruleNames = new string[] { "invalidRule", "document", "statement", "setExpr", "block", "getExpr" }; private int ruleLevel = 0; public int RuleLevel { get { return ruleLevel; } } public void IncRuleLevel() { ruleLevel++; } public void DecRuleLevel() { ruleLevel--; } public TemplateParser(ITokenStream input) : this(input, DebugEventSocketProxy.DEFAULT_DEBUGGER_PORT, new RecognizerSharedState()) { } public TemplateParser(ITokenStream input, int port, RecognizerSharedState state) : base(input, state) { DebugEventSocketProxy dbg = new DebugEventSocketProxy(this, port, adaptor); DebugListener = dbg; TokenStream = new DebugTokenStream(input,dbg); try { dbg.Handshake(); } catch (IOException ioe) { ReportError(ioe); } InitializeCyclicDFAs(dbg); ITreeAdaptor adap = new CommonTreeAdaptor(); TreeAdaptor = adap; dbg.TreeAdaptor = adap; } public TemplateParser(ITokenStream input, IDebugEventListener dbg) : base(input, dbg) { InitializeCyclicDFAs(dbg); ITreeAdaptor adap = new CommonTreeAdaptor(); TreeAdaptor = adap; } protected bool EvalPredicate(bool result, string predicate) { dbg.SemanticPredicate(result, predicate); return result; } protected DebugTreeAdaptor adaptor; public ITreeAdaptor TreeAdaptor { get { return this.adaptor; } set { this.adaptor = new DebugTreeAdaptor(dbg, value); } } override public string[] TokenNames { get { return TemplateParser.tokenNames; } } override public string GrammarFileName { get { return "C:\\Development\\TT.Net\\TT\\Template.g"; } } public class document_return : ParserRuleReturnScope { private CommonTree tree; override public object Tree { get { return tree; } set { tree = (CommonTree) value; } } }; // $ANTLR start "document" // C:\\Development\\TT.Net\\TT\\Template.g:72:1: document : ( block )* -> ^( DOCUMENT ( block )* ) ; public TemplateParser.document_return document() // throws RecognitionException [1] { TemplateParser.document_return retval = new TemplateParser.document_return(); retval.Start = input.LT(1); CommonTree root_0 = null; TemplateParser.block_return block1 = default(TemplateParser.block_return); RewriteRuleSubtreeStream stream_block = new RewriteRuleSubtreeStream(adaptor,"rule block"); try { dbg.EnterRule(GrammarFileName, "document"); if ( RuleLevel==0 ) {dbg.Commence();} IncRuleLevel(); dbg.Location(72, 1); try { // C:\\Development\\TT.Net\\TT\\Template.g:73:2: ( ( block )* -> ^( DOCUMENT ( block )* ) ) dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:73:4: ( block )* { dbg.Location(73,4); // C:\\Development\\TT.Net\\TT\\Template.g:73:4: ( block )* try { dbg.EnterSubRule(1); do { int alt1 = 2; try { dbg.EnterDecision(1); int LA1_0 = input.LA(1); if ( (LA1_0 == TSTART) ) { alt1 = 1; } } finally { dbg.ExitDecision(1); } switch (alt1) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:73:4: block { dbg.Location(73,4); PushFollow(FOLLOW_block_in_document467); block1 = block(); state.followingStackPointer--; stream_block.Add(block1.Tree); } break; default: goto loop1; } } while (true); loop1: ; // Stops C# compiler whining that label 'loop1' has no statements } finally { dbg.ExitSubRule(1); } // AST REWRITE // elements: block // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.Tree = root_0; RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null); root_0 = (CommonTree)adaptor.GetNilNode(); // 73:11: -> ^( DOCUMENT ( block )* ) { dbg.Location(73,14); // C:\\Development\\TT.Net\\TT\\Template.g:73:14: ^( DOCUMENT ( block )* ) { CommonTree root_1 = (CommonTree)adaptor.GetNilNode(); dbg.Location(73,16); root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(DOCUMENT, "DOCUMENT"), root_1); dbg.Location(73,25); // C:\\Development\\TT.Net\\TT\\Template.g:73:25: ( block )* while ( stream_block.HasNext() ) { dbg.Location(73,25); adaptor.AddChild(root_1, stream_block.NextTree()); } stream_block.Reset(); adaptor.AddChild(root_0, root_1); } } retval.Tree = root_0;retval.Tree = root_0; } retval.Stop = input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); // Conversion of the second argument necessary, but harmless retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re); } finally { } dbg.Location(74, 2); } finally { dbg.ExitRule(GrammarFileName, "document"); DecRuleLevel(); if ( RuleLevel==0 ) {dbg.Terminate();} } return retval; } // $ANTLR end "document" public class block_return : ParserRuleReturnScope { private CommonTree tree; override public object Tree { get { return tree; } set { tree = (CommonTree) value; } } }; // $ANTLR start "block" // C:\\Development\\TT.Net\\TT\\Template.g:76:1: block : TSTART statement TSTOP ; public TemplateParser.block_return block() // throws RecognitionException [1] { TemplateParser.block_return retval = new TemplateParser.block_return(); retval.Start = input.LT(1); CommonTree root_0 = null; IToken TSTART2 = null; IToken TSTOP4 = null; TemplateParser.statement_return statement3 = default(TemplateParser.statement_return); CommonTree TSTART2_tree=null; CommonTree TSTOP4_tree=null; try { dbg.EnterRule(GrammarFileName, "block"); if ( RuleLevel==0 ) {dbg.Commence();} IncRuleLevel(); dbg.Location(76, 1); try { // C:\\Development\\TT.Net\\TT\\Template.g:77:2: ( TSTART statement TSTOP ) dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:77:4: TSTART statement TSTOP { root_0 = (CommonTree)adaptor.GetNilNode(); dbg.Location(77,10); TSTART2=(IToken)Match(input,TSTART,FOLLOW_TSTART_in_block488); dbg.Location(77,12); PushFollow(FOLLOW_statement_in_block491); statement3 = statement(); state.followingStackPointer--; adaptor.AddChild(root_0, statement3.Tree); dbg.Location(77,27); TSTOP4=(IToken)Match(input,TSTOP,FOLLOW_TSTOP_in_block493); } retval.Stop = input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); // Conversion of the second argument necessary, but harmless retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re); } finally { } dbg.Location(78, 2); } finally { dbg.ExitRule(GrammarFileName, "block"); DecRuleLevel(); if ( RuleLevel==0 ) {dbg.Terminate();} } return retval; } // $ANTLR end "block" public class statement_return : ParserRuleReturnScope { private CommonTree tree; override public object Tree { get { return tree; } set { tree = (CommonTree) value; } } }; // $ANTLR start "statement" // C:\\Development\\TT.Net\\TT\\Template.g:80:1: statement : ( getExpr | setExpr ); public TemplateParser.statement_return statement() // throws RecognitionException [1] { TemplateParser.statement_return retval = new TemplateParser.statement_return(); retval.Start = input.LT(1); CommonTree root_0 = null; TemplateParser.getExpr_return getExpr5 = default(TemplateParser.getExpr_return); TemplateParser.setExpr_return setExpr6 = default(TemplateParser.setExpr_return); try { dbg.EnterRule(GrammarFileName, "statement"); if ( RuleLevel==0 ) {dbg.Commence();} IncRuleLevel(); dbg.Location(80, 1); try { // C:\\Development\\TT.Net\\TT\\Template.g:81:2: ( getExpr | setExpr ) int alt2 = 2; try { dbg.EnterDecision(2); switch ( input.LA(1) ) { case ILITERAL: case LITERAL: case 55: { alt2 = 1; } break; case ID: { int LA2_2 = input.LA(2); if ( (LA2_2 == ASSIGN) ) { alt2 = 2; } else if ( (LA2_2 == TSTOP) ) { alt2 = 1; } else { NoViableAltException nvae_d2s2 = new NoViableAltException("", 2, 2, input); dbg.RecognitionException(nvae_d2s2); throw nvae_d2s2; } } break; case 56: { alt2 = 2; } break; default: NoViableAltException nvae_d2s0 = new NoViableAltException("", 2, 0, input); dbg.RecognitionException(nvae_d2s0); throw nvae_d2s0; } } finally { dbg.ExitDecision(2); } switch (alt2) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:81:4: getExpr { root_0 = (CommonTree)adaptor.GetNilNode(); dbg.Location(81,4); PushFollow(FOLLOW_getExpr_in_statement506); getExpr5 = getExpr(); state.followingStackPointer--; adaptor.AddChild(root_0, getExpr5.Tree); } break; case 2 : dbg.EnterAlt(2); // C:\\Development\\TT.Net\\TT\\Template.g:82:4: setExpr { root_0 = (CommonTree)adaptor.GetNilNode(); dbg.Location(82,4); PushFollow(FOLLOW_setExpr_in_statement511); setExpr6 = setExpr(); state.followingStackPointer--; adaptor.AddChild(root_0, setExpr6.Tree); } break; } retval.Stop = input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); // Conversion of the second argument necessary, but harmless retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re); } finally { } dbg.Location(83, 2); } finally { dbg.ExitRule(GrammarFileName, "statement"); DecRuleLevel(); if ( RuleLevel==0 ) {dbg.Terminate();} } return retval; } // $ANTLR end "statement" public class getExpr_return : ParserRuleReturnScope { private CommonTree tree; override public object Tree { get { return tree; } set { tree = (CommonTree) value; } } }; // $ANTLR start "getExpr" // C:\\Development\\TT.Net\\TT\\Template.g:85:1: getExpr : ( ( 'GET' )? ID -> ^( GET ID ) | ( 'GET' )? LITERAL -> ^( GET LITERAL ) | ( 'GET' )? ILITERAL -> ^( GET ILITERAL ) ); public TemplateParser.getExpr_return getExpr() // throws RecognitionException [1] { TemplateParser.getExpr_return retval = new TemplateParser.getExpr_return(); retval.Start = input.LT(1); CommonTree root_0 = null; IToken string_literal7 = null; IToken ID8 = null; IToken string_literal9 = null; IToken LITERAL10 = null; IToken string_literal11 = null; IToken ILITERAL12 = null; CommonTree string_literal7_tree=null; CommonTree ID8_tree=null; CommonTree string_literal9_tree=null; CommonTree LITERAL10_tree=null; CommonTree string_literal11_tree=null; CommonTree ILITERAL12_tree=null; RewriteRuleTokenStream stream_LITERAL = new RewriteRuleTokenStream(adaptor,"token LITERAL"); RewriteRuleTokenStream stream_55 = new RewriteRuleTokenStream(adaptor,"token 55"); RewriteRuleTokenStream stream_ID = new RewriteRuleTokenStream(adaptor,"token ID"); RewriteRuleTokenStream stream_ILITERAL = new RewriteRuleTokenStream(adaptor,"token ILITERAL"); try { dbg.EnterRule(GrammarFileName, "getExpr"); if ( RuleLevel==0 ) {dbg.Commence();} IncRuleLevel(); dbg.Location(85, 1); try { // C:\\Development\\TT.Net\\TT\\Template.g:86:2: ( ( 'GET' )? ID -> ^( GET ID ) | ( 'GET' )? LITERAL -> ^( GET LITERAL ) | ( 'GET' )? ILITERAL -> ^( GET ILITERAL ) ) int alt6 = 3; try { dbg.EnterDecision(6); switch ( input.LA(1) ) { case 55: { switch ( input.LA(2) ) { case ILITERAL: { alt6 = 3; } break; case ID: { alt6 = 1; } break; case LITERAL: { alt6 = 2; } break; default: NoViableAltException nvae_d6s1 = new NoViableAltException("", 6, 1, input); dbg.RecognitionException(nvae_d6s1); throw nvae_d6s1; } } break; case ID: { alt6 = 1; } break; case LITERAL: { alt6 = 2; } break; case ILITERAL: { alt6 = 3; } break; default: NoViableAltException nvae_d6s0 = new NoViableAltException("", 6, 0, input); dbg.RecognitionException(nvae_d6s0); throw nvae_d6s0; } } finally { dbg.ExitDecision(6); } switch (alt6) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:86:4: ( 'GET' )? ID { dbg.Location(86,4); // C:\\Development\\TT.Net\\TT\\Template.g:86:4: ( 'GET' )? int alt3 = 2; try { dbg.EnterSubRule(3); try { dbg.EnterDecision(3); int LA3_0 = input.LA(1); if ( (LA3_0 == 55) ) { alt3 = 1; } } finally { dbg.ExitDecision(3); } switch (alt3) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:86:4: 'GET' { dbg.Location(86,4); string_literal7=(IToken)Match(input,55,FOLLOW_55_in_getExpr522); stream_55.Add(string_literal7); } break; } } finally { dbg.ExitSubRule(3); } dbg.Location(86,11); ID8=(IToken)Match(input,ID,FOLLOW_ID_in_getExpr525); stream_ID.Add(ID8); // AST REWRITE // elements: ID // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.Tree = root_0; RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null); root_0 = (CommonTree)adaptor.GetNilNode(); // 86:20: -> ^( GET ID ) { dbg.Location(86,23); // C:\\Development\\TT.Net\\TT\\Template.g:86:23: ^( GET ID ) { CommonTree root_1 = (CommonTree)adaptor.GetNilNode(); dbg.Location(86,25); root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(GET, "GET"), root_1); dbg.Location(86,29); adaptor.AddChild(root_1, stream_ID.NextNode()); adaptor.AddChild(root_0, root_1); } } retval.Tree = root_0;retval.Tree = root_0; } break; case 2 : dbg.EnterAlt(2); // C:\\Development\\TT.Net\\TT\\Template.g:87:4: ( 'GET' )? LITERAL { dbg.Location(87,4); // C:\\Development\\TT.Net\\TT\\Template.g:87:4: ( 'GET' )? int alt4 = 2; try { dbg.EnterSubRule(4); try { dbg.EnterDecision(4); int LA4_0 = input.LA(1); if ( (LA4_0 == 55) ) { alt4 = 1; } } finally { dbg.ExitDecision(4); } switch (alt4) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:87:4: 'GET' { dbg.Location(87,4); string_literal9=(IToken)Match(input,55,FOLLOW_55_in_getExpr544); stream_55.Add(string_literal9); } break; } } finally { dbg.ExitSubRule(4); } dbg.Location(87,11); LITERAL10=(IToken)Match(input,LITERAL,FOLLOW_LITERAL_in_getExpr547); stream_LITERAL.Add(LITERAL10); // AST REWRITE // elements: LITERAL // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.Tree = root_0; RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null); root_0 = (CommonTree)adaptor.GetNilNode(); // 87:20: -> ^( GET LITERAL ) { dbg.Location(87,23); // C:\\Development\\TT.Net\\TT\\Template.g:87:23: ^( GET LITERAL ) { CommonTree root_1 = (CommonTree)adaptor.GetNilNode(); dbg.Location(87,25); root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(GET, "GET"), root_1); dbg.Location(87,29); adaptor.AddChild(root_1, stream_LITERAL.NextNode()); adaptor.AddChild(root_0, root_1); } } retval.Tree = root_0;retval.Tree = root_0; } break; case 3 : dbg.EnterAlt(3); // C:\\Development\\TT.Net\\TT\\Template.g:88:4: ( 'GET' )? ILITERAL { dbg.Location(88,4); // C:\\Development\\TT.Net\\TT\\Template.g:88:4: ( 'GET' )? int alt5 = 2; try { dbg.EnterSubRule(5); try { dbg.EnterDecision(5); int LA5_0 = input.LA(1); if ( (LA5_0 == 55) ) { alt5 = 1; } } finally { dbg.ExitDecision(5); } switch (alt5) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:88:4: 'GET' { dbg.Location(88,4); string_literal11=(IToken)Match(input,55,FOLLOW_55_in_getExpr561); stream_55.Add(string_literal11); } break; } } finally { dbg.ExitSubRule(5); } dbg.Location(88,11); ILITERAL12=(IToken)Match(input,ILITERAL,FOLLOW_ILITERAL_in_getExpr564); stream_ILITERAL.Add(ILITERAL12); // AST REWRITE // elements: ILITERAL // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.Tree = root_0; RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null); root_0 = (CommonTree)adaptor.GetNilNode(); // 88:20: -> ^( GET ILITERAL ) { dbg.Location(88,23); // C:\\Development\\TT.Net\\TT\\Template.g:88:23: ^( GET ILITERAL ) { CommonTree root_1 = (CommonTree)adaptor.GetNilNode(); dbg.Location(88,25); root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(GET, "GET"), root_1); dbg.Location(88,29); adaptor.AddChild(root_1, stream_ILITERAL.NextNode()); adaptor.AddChild(root_0, root_1); } } retval.Tree = root_0;retval.Tree = root_0; } break; } retval.Stop = input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); // Conversion of the second argument necessary, but harmless retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re); } finally { } dbg.Location(89, 2); } finally { dbg.ExitRule(GrammarFileName, "getExpr"); DecRuleLevel(); if ( RuleLevel==0 ) {dbg.Terminate();} } return retval; } // $ANTLR end "getExpr" public class setExpr_return : ParserRuleReturnScope { private CommonTree tree; override public object Tree { get { return tree; } set { tree = (CommonTree) value; } } }; // $ANTLR start "setExpr" // C:\\Development\\TT.Net\\TT\\Template.g:91:1: setExpr : ( ( 'SET' )? ID ASSIGN LITERAL -> ^( SET ID LITERAL ) | ( 'SET' )? ID ASSIGN NUMBER -> ^( SET ID NUMBER ) | ( 'SET' )? ID ASSIGN DECIMAL -> ^( SET ID DECIMAL ) ); public TemplateParser.setExpr_return setExpr() // throws RecognitionException [1] { TemplateParser.setExpr_return retval = new TemplateParser.setExpr_return(); retval.Start = input.LT(1); CommonTree root_0 = null; IToken string_literal13 = null; IToken ID14 = null; IToken ASSIGN15 = null; IToken LITERAL16 = null; IToken string_literal17 = null; IToken ID18 = null; IToken ASSIGN19 = null; IToken NUMBER20 = null; IToken string_literal21 = null; IToken ID22 = null; IToken ASSIGN23 = null; IToken DECIMAL24 = null; CommonTree string_literal13_tree=null; CommonTree ID14_tree=null; CommonTree ASSIGN15_tree=null; CommonTree LITERAL16_tree=null; CommonTree string_literal17_tree=null; CommonTree ID18_tree=null; CommonTree ASSIGN19_tree=null; CommonTree NUMBER20_tree=null; CommonTree string_literal21_tree=null; CommonTree ID22_tree=null; CommonTree ASSIGN23_tree=null; CommonTree DECIMAL24_tree=null; RewriteRuleTokenStream stream_LITERAL = new RewriteRuleTokenStream(adaptor,"token LITERAL"); RewriteRuleTokenStream stream_56 = new RewriteRuleTokenStream(adaptor,"token 56"); RewriteRuleTokenStream stream_DECIMAL = new RewriteRuleTokenStream(adaptor,"token DECIMAL"); RewriteRuleTokenStream stream_ID = new RewriteRuleTokenStream(adaptor,"token ID"); RewriteRuleTokenStream stream_NUMBER = new RewriteRuleTokenStream(adaptor,"token NUMBER"); RewriteRuleTokenStream stream_ASSIGN = new RewriteRuleTokenStream(adaptor,"token ASSIGN"); try { dbg.EnterRule(GrammarFileName, "setExpr"); if ( RuleLevel==0 ) {dbg.Commence();} IncRuleLevel(); dbg.Location(91, 1); try { // C:\\Development\\TT.Net\\TT\\Template.g:92:2: ( ( 'SET' )? ID ASSIGN LITERAL -> ^( SET ID LITERAL ) | ( 'SET' )? ID ASSIGN NUMBER -> ^( SET ID NUMBER ) | ( 'SET' )? ID ASSIGN DECIMAL -> ^( SET ID DECIMAL ) ) int alt10 = 3; try { dbg.EnterDecision(10); int LA10_0 = input.LA(1); if ( (LA10_0 == 56) ) { int LA10_1 = input.LA(2); if ( (LA10_1 == ID) ) { int LA10_2 = input.LA(3); if ( (LA10_2 == ASSIGN) ) { switch ( input.LA(4) ) { case LITERAL: { alt10 = 1; } break; case NUMBER: { alt10 = 2; } break; case DECIMAL: { alt10 = 3; } break; default: NoViableAltException nvae_d10s3 = new NoViableAltException("", 10, 3, input); dbg.RecognitionException(nvae_d10s3); throw nvae_d10s3; } } else { NoViableAltException nvae_d10s2 = new NoViableAltException("", 10, 2, input); dbg.RecognitionException(nvae_d10s2); throw nvae_d10s2; } } else { NoViableAltException nvae_d10s1 = new NoViableAltException("", 10, 1, input); dbg.RecognitionException(nvae_d10s1); throw nvae_d10s1; } } else if ( (LA10_0 == ID) ) { int LA10_2 = input.LA(2); if ( (LA10_2 == ASSIGN) ) { switch ( input.LA(3) ) { case LITERAL: { alt10 = 1; } break; case NUMBER: { alt10 = 2; } break; case DECIMAL: { alt10 = 3; } break; default: NoViableAltException nvae_d10s3 = new NoViableAltException("", 10, 3, input); dbg.RecognitionException(nvae_d10s3); throw nvae_d10s3; } } else { NoViableAltException nvae_d10s2 = new NoViableAltException("", 10, 2, input); dbg.RecognitionException(nvae_d10s2); throw nvae_d10s2; } } else { NoViableAltException nvae_d10s0 = new NoViableAltException("", 10, 0, input); dbg.RecognitionException(nvae_d10s0); throw nvae_d10s0; } } finally { dbg.ExitDecision(10); } switch (alt10) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:92:4: ( 'SET' )? ID ASSIGN LITERAL { dbg.Location(92,4); // C:\\Development\\TT.Net\\TT\\Template.g:92:4: ( 'SET' )? int alt7 = 2; try { dbg.EnterSubRule(7); try { dbg.EnterDecision(7); int LA7_0 = input.LA(1); if ( (LA7_0 == 56) ) { alt7 = 1; } } finally { dbg.ExitDecision(7); } switch (alt7) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:92:4: 'SET' { dbg.Location(92,4); string_literal13=(IToken)Match(input,56,FOLLOW_56_in_setExpr583); stream_56.Add(string_literal13); } break; } } finally { dbg.ExitSubRule(7); } dbg.Location(92,11); ID14=(IToken)Match(input,ID,FOLLOW_ID_in_setExpr586); stream_ID.Add(ID14); dbg.Location(92,14); ASSIGN15=(IToken)Match(input,ASSIGN,FOLLOW_ASSIGN_in_setExpr588); stream_ASSIGN.Add(ASSIGN15); dbg.Location(92,21); LITERAL16=(IToken)Match(input,LITERAL,FOLLOW_LITERAL_in_setExpr590); stream_LITERAL.Add(LITERAL16); // AST REWRITE // elements: ID, LITERAL // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.Tree = root_0; RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null); root_0 = (CommonTree)adaptor.GetNilNode(); // 92:29: -> ^( SET ID LITERAL ) { dbg.Location(92,32); // C:\\Development\\TT.Net\\TT\\Template.g:92:32: ^( SET ID LITERAL ) { CommonTree root_1 = (CommonTree)adaptor.GetNilNode(); dbg.Location(92,34); root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(SET, "SET"), root_1); dbg.Location(92,38); adaptor.AddChild(root_1, stream_ID.NextNode()); dbg.Location(92,41); adaptor.AddChild(root_1, stream_LITERAL.NextNode()); adaptor.AddChild(root_0, root_1); } } retval.Tree = root_0;retval.Tree = root_0; } break; case 2 : dbg.EnterAlt(2); // C:\\Development\\TT.Net\\TT\\Template.g:93:4: ( 'SET' )? ID ASSIGN NUMBER { dbg.Location(93,4); // C:\\Development\\TT.Net\\TT\\Template.g:93:4: ( 'SET' )? int alt8 = 2; try { dbg.EnterSubRule(8); try { dbg.EnterDecision(8); int LA8_0 = input.LA(1); if ( (LA8_0 == 56) ) { alt8 = 1; } } finally { dbg.ExitDecision(8); } switch (alt8) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:93:4: 'SET' { dbg.Location(93,4); string_literal17=(IToken)Match(input,56,FOLLOW_56_in_setExpr605); stream_56.Add(string_literal17); } break; } } finally { dbg.ExitSubRule(8); } dbg.Location(93,11); ID18=(IToken)Match(input,ID,FOLLOW_ID_in_setExpr608); stream_ID.Add(ID18); dbg.Location(93,14); ASSIGN19=(IToken)Match(input,ASSIGN,FOLLOW_ASSIGN_in_setExpr610); stream_ASSIGN.Add(ASSIGN19); dbg.Location(93,21); NUMBER20=(IToken)Match(input,NUMBER,FOLLOW_NUMBER_in_setExpr612); stream_NUMBER.Add(NUMBER20); // AST REWRITE // elements: NUMBER, ID // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.Tree = root_0; RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null); root_0 = (CommonTree)adaptor.GetNilNode(); // 93:29: -> ^( SET ID NUMBER ) { dbg.Location(93,32); // C:\\Development\\TT.Net\\TT\\Template.g:93:32: ^( SET ID NUMBER ) { CommonTree root_1 = (CommonTree)adaptor.GetNilNode(); dbg.Location(93,34); root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(SET, "SET"), root_1); dbg.Location(93,38); adaptor.AddChild(root_1, stream_ID.NextNode()); dbg.Location(93,41); adaptor.AddChild(root_1, stream_NUMBER.NextNode()); adaptor.AddChild(root_0, root_1); } } retval.Tree = root_0;retval.Tree = root_0; } break; case 3 : dbg.EnterAlt(3); // C:\\Development\\TT.Net\\TT\\Template.g:94:4: ( 'SET' )? ID ASSIGN DECIMAL { dbg.Location(94,4); // C:\\Development\\TT.Net\\TT\\Template.g:94:4: ( 'SET' )? int alt9 = 2; try { dbg.EnterSubRule(9); try { dbg.EnterDecision(9); int LA9_0 = input.LA(1); if ( (LA9_0 == 56) ) { alt9 = 1; } } finally { dbg.ExitDecision(9); } switch (alt9) { case 1 : dbg.EnterAlt(1); // C:\\Development\\TT.Net\\TT\\Template.g:94:4: 'SET' { dbg.Location(94,4); string_literal21=(IToken)Match(input,56,FOLLOW_56_in_setExpr628); stream_56.Add(string_literal21); } break; } } finally { dbg.ExitSubRule(9); } dbg.Location(94,11); ID22=(IToken)Match(input,ID,FOLLOW_ID_in_setExpr631); stream_ID.Add(ID22); dbg.Location(94,14); ASSIGN23=(IToken)Match(input,ASSIGN,FOLLOW_ASSIGN_in_setExpr633); stream_ASSIGN.Add(ASSIGN23); dbg.Location(94,21); DECIMAL24=(IToken)Match(input,DECIMAL,FOLLOW_DECIMAL_in_setExpr635); stream_DECIMAL.Add(DECIMAL24); // AST REWRITE // elements: DECIMAL, ID // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.Tree = root_0; RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null); root_0 = (CommonTree)adaptor.GetNilNode(); // 94:29: -> ^( SET ID DECIMAL ) { dbg.Location(94,32); // C:\\Development\\TT.Net\\TT\\Template.g:94:32: ^( SET ID DECIMAL ) { CommonTree root_1 = (CommonTree)adaptor.GetNilNode(); dbg.Location(94,34); root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(SET, "SET"), root_1); dbg.Location(94,38); adaptor.AddChild(root_1, stream_ID.NextNode()); dbg.Location(94,41); adaptor.AddChild(root_1, stream_DECIMAL.NextNode()); adaptor.AddChild(root_0, root_1); } } retval.Tree = root_0;retval.Tree = root_0; } break; } retval.Stop = input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); // Conversion of the second argument necessary, but harmless retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re); } finally { } dbg.Location(95, 2); } finally { dbg.ExitRule(GrammarFileName, "setExpr"); DecRuleLevel(); if ( RuleLevel==0 ) {dbg.Terminate();} } return retval; } // $ANTLR end "setExpr" // Delegated rules private void InitializeCyclicDFAs(IDebugEventListener dbg) { } public static readonly BitSet FOLLOW_block_in_document467 = new BitSet(new ulong[]{0x0000000000000202UL}); public static readonly BitSet FOLLOW_TSTART_in_block488 = new BitSet(new ulong[]{0x0180200000006000UL}); public static readonly BitSet FOLLOW_statement_in_block491 = new BitSet(new ulong[]{0x0000000000000400UL}); public static readonly BitSet FOLLOW_TSTOP_in_block493 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_getExpr_in_statement506 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_setExpr_in_statement511 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_55_in_getExpr522 = new BitSet(new ulong[]{0x0000200000000000UL}); public static readonly BitSet FOLLOW_ID_in_getExpr525 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_55_in_getExpr544 = new BitSet(new ulong[]{0x0000000000004000UL}); public static readonly BitSet FOLLOW_LITERAL_in_getExpr547 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_55_in_getExpr561 = new BitSet(new ulong[]{0x0000000000002000UL}); public static readonly BitSet FOLLOW_ILITERAL_in_getExpr564 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_56_in_setExpr583 = new BitSet(new ulong[]{0x0000200000000000UL}); public static readonly BitSet FOLLOW_ID_in_setExpr586 = new BitSet(new ulong[]{0x0010000000000000UL}); public static readonly BitSet FOLLOW_ASSIGN_in_setExpr588 = new BitSet(new ulong[]{0x0000000000004000UL}); public static readonly BitSet FOLLOW_LITERAL_in_setExpr590 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_56_in_setExpr605 = new BitSet(new ulong[]{0x0000200000000000UL}); public static readonly BitSet FOLLOW_ID_in_setExpr608 = new BitSet(new ulong[]{0x0010000000000000UL}); public static readonly BitSet FOLLOW_ASSIGN_in_setExpr610 = new BitSet(new ulong[]{0x0000400000000000UL}); public static readonly BitSet FOLLOW_NUMBER_in_setExpr612 = new BitSet(new ulong[]{0x0000000000000002UL}); public static readonly BitSet FOLLOW_56_in_setExpr628 = new BitSet(new ulong[]{0x0000200000000000UL}); public static readonly BitSet FOLLOW_ID_in_setExpr631 = new BitSet(new ulong[]{0x0010000000000000UL}); public static readonly BitSet FOLLOW_ASSIGN_in_setExpr633 = new BitSet(new ulong[]{0x0000800000000000UL}); public static readonly BitSet FOLLOW_DECIMAL_in_setExpr635 = new BitSet(new ulong[]{0x0000000000000002UL}); } }
using System.Diagnostics; using u32 = System.UInt32; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** in order to generate code for DELETE FROM statements. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" /* ** While a SrcList can in general represent multiple tables and subqueries ** (as in the FROM clause of a SELECT statement) in this case it contains ** the name of a single table, as one might find in an INSERT, DELETE, ** or UPDATE statement. Look up that table in the symbol table and ** return a pointer. Set an error message and return NULL if the table ** name is not found or if any other error occurs. ** ** The following fields are initialized appropriate in pSrc: ** ** pSrc->a[0].pTab Pointer to the Table object ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one ** */ private static Table sqlite3SrcListLookup(Parse pParse, SrcList pSrc) { SrcList_item pItem = pSrc.a[0]; Table pTab; Debug.Assert(pItem != null && pSrc.nSrc == 1); pTab = sqlite3LocateTable(pParse, 0, pItem.zName, pItem.zDatabase); sqlite3DeleteTable(pParse.db, ref pItem.pTab); pItem.pTab = pTab; if (pTab != null) { pTab.nRef++; } if (sqlite3IndexedByLookup(pParse, pItem) != 0) { pTab = null; } return pTab; } /* ** Check to make sure the given table is writable. If it is not ** writable, generate an error message and return 1. If it is ** writable return 0; */ private static bool sqlite3IsReadOnly(Parse pParse, Table pTab, int viewOk) { /* A table is not writable under the following circumstances: ** ** 1) It is a virtual table and no implementation of the xUpdate method ** has been provided, or ** 2) It is a system table (i.e. sqlite_master), this call is not ** part of a nested parse and writable_schema pragma has not ** been specified. ** ** In either case leave an error message in pParse and return non-zero. */ if ( (IsVirtual(pTab) && sqlite3GetVTable(pParse.db, pTab).pMod.pModule.xUpdate == null) || ((pTab.tabFlags & TF_Readonly) != 0 && (pParse.db.flags & SQLITE_WriteSchema) == 0 && pParse.nested == 0) ) { sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab.zName); return true; } #if !SQLITE_OMIT_VIEW if (viewOk == 0 && pTab.pSelect != null) { sqlite3ErrorMsg(pParse, "cannot modify %s because it is a view", pTab.zName); return true; } #endif return false; } #if !SQLITE_OMIT_VIEW && !SQLITE_OMIT_TRIGGER /* ** Evaluate a view and store its result in an ephemeral table. The ** pWhere argument is an optional WHERE clause that restricts the ** set of rows in the view that are to be added to the ephemeral table. */ private static void sqlite3MaterializeView( Parse pParse, /* Parsing context */ Table pView, /* View definition */ Expr pWhere, /* Optional WHERE clause to be added */ int iCur /* VdbeCursor number for ephemerial table */ ) { SelectDest dest = new SelectDest(); Select pDup; sqlite3 db = pParse.db; pDup = sqlite3SelectDup(db, pView.pSelect, 0); if (pWhere != null) { SrcList pFrom; pWhere = sqlite3ExprDup(db, pWhere, 0); pFrom = sqlite3SrcListAppend(db, null, null, null); //if ( pFrom != null ) //{ Debug.Assert(pFrom.nSrc == 1); pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName ); pFrom.a[0].pSelect = pDup; Debug.Assert(pFrom.a[0].pOn == null); Debug.Assert(pFrom.a[0].pUsing == null); //} //else //{ // sqlite3SelectDelete( db, ref pDup ); //} pDup = sqlite3SelectNew(pParse, null, pFrom, pWhere, null, null, null, 0, null, null); } sqlite3SelectDestInit(dest, SRT_EphemTab, iCur); sqlite3Select(pParse, pDup, ref dest); sqlite3SelectDelete(db, ref pDup); } #endif //* !SQLITE_OMIT_VIEW) && !SQLITE_OMIT_TRIGGER) */ #if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY) /* ** Generate an expression tree to implement the WHERE, ORDER BY, ** and LIMIT/OFFSET portion of DELETE and UPDATE statements. ** ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; ** \__________________________/ ** pLimitWhere (pInClause) */ Expr sqlite3LimitWhere( Parse pParse, /* The parser context */ SrcList pSrc, /* the FROM clause -- which tables to scan */ Expr pWhere, /* The WHERE clause. May be null */ ExprList pOrderBy, /* The ORDER BY clause. May be null */ Expr pLimit, /* The LIMIT clause. May be null */ Expr pOffset, /* The OFFSET clause. May be null */ char zStmtType /* Either DELETE or UPDATE. For error messages. */ ){ Expr pWhereRowid = null; /* WHERE rowid .. */ Expr pInClause = null; /* WHERE rowid IN ( select ) */ Expr pSelectRowid = null; /* SELECT rowid ... */ ExprList pEList = null; /* Expression list contaning only pSelectRowid */ SrcList pSelectSrc = null; /* SELECT rowid FROM x ... (dup of pSrc) */ Select pSelect = null; /* Complete SELECT tree */ /* Check that there isn't an ORDER BY without a LIMIT clause. */ if( pOrderBy!=null && (pLimit == null) ) { sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); pParse.parseError = 1; goto limit_where_cleanup_2; } /* We only need to generate a select expression if there ** is a limit/offset term to enforce. */ if ( pLimit == null ) { /* if pLimit is null, pOffset will always be null as well. */ Debug.Assert( pOffset == null ); return pWhere; } /* Generate a select expression tree to enforce the limit/offset ** term for the DELETE or UPDATE statement. For example: ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** becomes: ** DELETE FROM table_a WHERE rowid IN ( ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** ); */ pSelectRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null ); if( pSelectRowid == null ) goto limit_where_cleanup_2; pEList = sqlite3ExprListAppend( pParse, null, pSelectRowid); if( pEList == null ) goto limit_where_cleanup_2; /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree ** and the SELECT subtree. */ pSelectSrc = sqlite3SrcListDup(pParse.db, pSrc,0); if( pSelectSrc == null ) { sqlite3ExprListDelete(pParse.db, pEList); goto limit_where_cleanup_2; } /* generate the SELECT expression tree. */ pSelect = sqlite3SelectNew( pParse, pEList, pSelectSrc, pWhere, null, null, pOrderBy, 0, pLimit, pOffset ); if( pSelect == null ) return null; /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ pWhereRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null ); if( pWhereRowid == null ) goto limit_where_cleanup_1; pInClause = sqlite3PExpr( pParse, TK_IN, pWhereRowid, null, null ); if( pInClause == null ) goto limit_where_cleanup_1; pInClause->x.pSelect = pSelect; pInClause->flags |= EP_xIsSelect; sqlite3ExprSetHeight(pParse, pInClause); return pInClause; /* something went wrong. clean up anything allocated. */ limit_where_cleanup_1: sqlite3SelectDelete(pParse.db, pSelect); return null; limit_where_cleanup_2: sqlite3ExprDelete(pParse.db, ref pWhere); sqlite3ExprListDelete(pParse.db, pOrderBy); sqlite3ExprDelete(pParse.db, ref pLimit); sqlite3ExprDelete(pParse.db, ref pOffset); return null; } #endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ /* ** Generate code for a DELETE FROM statement. ** ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; ** \________/ \________________/ ** pTabList pWhere */ private static void sqlite3DeleteFrom( Parse pParse, /* The parser context */ SrcList pTabList, /* The table from which we should delete things */ Expr pWhere /* The WHERE clause. May be null */ ) { Vdbe v; /* The virtual database engine */ Table pTab; /* The table from which records will be deleted */ int end, addr = 0; /* A couple addresses of generated code */ int i; /* Loop counter */ WhereInfo pWInfo; /* Information about the WHERE clause */ Index pIdx; /* For looping over indices of the table */ int iCur; /* VDBE VdbeCursor number for pTab */ sqlite3 db; /* Main database structure */ AuthContext sContext; /* Authorization context */ NameContext sNC; /* Name context to resolve expressions in */ int iDb; /* Database number */ int memCnt = -1; /* Memory cell used for change counting */ int rcauth; /* Value returned by authorization callback */ #if !SQLITE_OMIT_TRIGGER bool isView; /* True if attempting to delete from a view */ Trigger pTrigger; /* List of table triggers, if required */ #endif sContext = new AuthContext();//memset(&sContext, 0, sizeof(sContext)); db = pParse.db; if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) { goto delete_from_cleanup; } Debug.Assert(pTabList.nSrc == 1); /* Locate the table which we want to delete. This table has to be ** put in an SrcList structure because some of the subroutines we ** will be calling are designed to work with multiple tables and expect ** an SrcList* parameter instead of just a Table* parameter. */ pTab = sqlite3SrcListLookup(pParse, pTabList); if (pTab == null) goto delete_from_cleanup; /* Figure out if we have any triggers and if the table being ** deleted from is a view */ #if !SQLITE_OMIT_TRIGGER int iDummy; pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, null, out iDummy); isView = pTab.pSelect != null; #else const Trigger pTrigger = null; bool isView = false; #endif #if SQLITE_OMIT_VIEW //# undef isView isView = false; #endif /* If pTab is really a view, make sure it has been initialized. */ if (sqlite3ViewGetColumnNames(pParse, pTab) != 0) { goto delete_from_cleanup; } if (sqlite3IsReadOnly(pParse, pTab, (pTrigger != null ? 1 : 0))) { goto delete_from_cleanup; } iDb = sqlite3SchemaToIndex(db, pTab.pSchema); Debug.Assert(iDb < db.nDb); #if !SQLITE_OMIT_AUTHORIZATION string zDb = db.aDb[iDb].zName; /* Name of database holding pTab */ rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb); #else rcauth = SQLITE_OK; #endif Debug.Assert(rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE); if (rcauth == SQLITE_DENY) { goto delete_from_cleanup; } Debug.Assert(!isView || pTrigger != null); /* Assign cursor number to the table and all its indices. */ Debug.Assert(pTabList.nSrc == 1); iCur = pTabList.a[0].iCursor = pParse.nTab++; for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) { pParse.nTab++; } #if !SQLITE_OMIT_AUTHORIZATION /* Start the view context */ if( isView ){ sqlite3AuthContextPush(pParse, sContext, pTab.zName); } #endif /* Begin generating code. */ v = sqlite3GetVdbe(pParse); if (v == null) { goto delete_from_cleanup; } if (pParse.nested == 0) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, 1, iDb); /* If we are trying to delete from a view, realize that view into ** a ephemeral table. */ #if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER) if (isView) { sqlite3MaterializeView(pParse, pTab, pWhere, iCur); } #endif /* Resolve the column names in the WHERE clause. */ sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) ); sNC.pParse = pParse; sNC.pSrcList = pTabList; if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0) { goto delete_from_cleanup; } /* Initialize the counter of the number of rows deleted, if ** we are counting rows. */ if ((db.flags & SQLITE_CountRows) != 0) { memCnt = ++pParse.nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); } #if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION /* Special case: A DELETE without a WHERE clause deletes everything. ** It is easier just to erase the whole table. Prior to version 3.6.5, ** this optimization caused the row change count (the value returned by ** API function sqlite3_count_changes) to be set incorrectly. */ if (rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual(pTab) && 0 == sqlite3FkRequired(pParse, pTab, null, 0) ) { Debug.Assert(!isView); sqlite3VdbeAddOp4(v, OP_Clear, pTab.tnum, iDb, memCnt, pTab.zName, P4_STATIC); for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) { Debug.Assert(pIdx.pSchema == pTab.pSchema); sqlite3VdbeAddOp2(v, OP_Clear, pIdx.tnum, iDb); } } else #endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ /* The usual case: There is a WHERE clause so we have to scan through ** the table and pick which records to delete. */ { int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */ int iRowid = ++pParse.nMem; /* Used for storing rowid values. */ int regRowid; /* Actual register containing rowids */ /* Collect rowids of every row to be deleted. */ sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); ExprList elDummy = null; pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK); if (pWInfo == null) goto delete_from_cleanup; regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid); sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid); if ((db.flags & SQLITE_CountRows) != 0) { sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); } sqlite3WhereEnd(pWInfo); /* Delete every item whose key was written to the list during the ** database scan. We have to delete items after the scan is complete ** because deleting an item can change the scan order. */ end = sqlite3VdbeMakeLabel(v); /* Unless this is a view, open cursors for the table we are ** deleting from and all its indices. If this is a view, then the ** only effect this statement has is to fire the INSTEAD OF ** triggers. */ if (!isView) { sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite); } addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid); /* Delete the row */ #if !SQLITE_OMIT_VIRTUALTABLE if (IsVirtual(pTab)) { VTable pVTab = sqlite3GetVTable(db, pTab); sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB); sqlite3VdbeChangeP5(v, OE_Abort); sqlite3MayAbort(pParse); } else #endif { int count = (pParse.nested == 0) ? 1 : 0; /* True to count changes */ sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default); } /* End of the delete loop */ sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); sqlite3VdbeResolveLabel(v, end); /* Close the cursors open on the table and its indexes. */ if (!isView && !IsVirtual(pTab)) { for (i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext) { sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx.tnum); } sqlite3VdbeAddOp1(v, OP_Close, iCur); } } /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if (pParse.nested == 0 && pParse.pTriggerTab == null) { sqlite3AutoincrementEnd(pParse); } /* Return the number of rows that were deleted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if ((db.flags & SQLITE_CountRows) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab) { sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); } delete_from_cleanup: #if !SQLITE_OMIT_AUTHORIZATION sqlite3AuthContextPop(sContext); #endif sqlite3SrcListDelete(db, ref pTabList); sqlite3ExprDelete(db, ref pWhere); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** thely may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ //#if isView // #undef isView //#endif //#if pTrigger // #undef pTrigger //#endif /* ** This routine generates VDBE code that causes a single row of a ** single table to be deleted. ** ** The VDBE must be in a particular state when this routine is called. ** These are the requirements: ** ** 1. A read/write cursor pointing to pTab, the table containing the row ** to be deleted, must be opened as cursor number $iCur. ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number base+i for the i-th index. ** ** 3. The record number of the row to be deleted must be stored in ** memory cell iRowid. ** ** This routine generates code to remove both the table record and all ** index entries that point to that record. */ private static void sqlite3GenerateRowDelete( Parse pParse, /* Parsing context */ Table pTab, /* Table containing the row to be deleted */ int iCur, /* VdbeCursor number for the table */ int iRowid, /* Memory cell that contains the rowid to delete */ int count, /* If non-zero, increment the row change counter */ Trigger pTrigger, /* List of triggers to (potentially) fire */ int onconf /* Default ON CONFLICT policy for triggers */ ) { Vdbe v = pParse.pVdbe; /* Vdbe */ int iOld = 0; /* First register in OLD.* array */ int iLabel; /* Label resolved to end of generated code */ /* Vdbe is guaranteed to have been allocated by this stage. */ Debug.Assert(v != null); /* Seek cursor iCur to the row to delete. If this row no longer exists ** (this can happen if a trigger program has already deleted it), do ** not attempt to delete it or fire any DELETE triggers. */ iLabel = sqlite3VdbeMakeLabel(v); sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid); /* If there are any triggers to fire, allocate a range of registers to ** use for the old.* references in the triggers. */ if (sqlite3FkRequired(pParse, pTab, null, 0) != 0 || pTrigger != null) { u32 mask; /* Mask of OLD.* columns in use */ int iCol; /* Iterator used while populating OLD.* */ /* TODO: Could use temporary registers here. Also could attempt to ** avoid copying the contents of the rowid register. */ mask = sqlite3TriggerColmask( pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf ); mask |= sqlite3FkOldmask(pParse, pTab); iOld = pParse.nMem + 1; pParse.nMem += (1 + pTab.nCol); /* Populate the OLD.* pseudo-table register array. These values will be ** used by any BEFORE and AFTER triggers that exist. */ sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld); for (iCol = 0; iCol < pTab.nCol; iCol++) { if (mask == 0xffffffff || (mask & (1 << iCol)) != 0) { sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld + iCol + 1); } } /* Invoke BEFORE DELETE trigger programs. */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel ); /* Seek the cursor to the row to be deleted again. It may be that ** the BEFORE triggers coded above have already removed the row ** being deleted. Do not attempt to delete the row a second time, and ** do not fire AFTER triggers. */ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid); /* Do FK processing. This call checks that any FK constraints that ** refer to this table (i.e. constraints attached to other tables) ** are not violated by deleting this row. */ sqlite3FkCheck(pParse, pTab, iOld, 0); } /* Delete the index and table entries. Skip this step if pTab is really ** a view (in which case the only effect of the DELETE statement is to ** fire the INSTEAD OF triggers). */ if (pTab.pSelect == null) { sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0); sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count != 0 ? (int)OPFLAG_NCHANGE : 0)); if (count != 0) { sqlite3VdbeChangeP4(v, -1, pTab.zName, P4_TRANSIENT); } } /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just deleted. */ sqlite3FkActions(pParse, pTab, null, iOld); /* Invoke AFTER DELETE trigger programs. */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel ); /* Jump here if the row had already been deleted before any BEFORE ** trigger programs were invoked. Or if a trigger program throws a ** RAISE(IGNORE) exception. */ sqlite3VdbeResolveLabel(v, iLabel); } /* ** This routine generates VDBE code that causes the deletion of all ** index entries associated with a single row of a single table. ** ** The VDBE must be in a particular state when this routine is called. ** These are the requirements: ** ** 1. A read/write cursor pointing to pTab, the table containing the row ** to be deleted, must be opened as cursor number "iCur". ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number iCur+i for the i-th index. ** ** 3. The "iCur" cursor must be pointing to the row that is to be ** deleted. */ private static void sqlite3GenerateRowIndexDelete( Parse pParse, /* Parsing and code generating context */ Table pTab, /* Table containing the row to be deleted */ int iCur, /* VdbeCursor number for the table */ int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ ) { int[] aRegIdx = null; sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx); } private static void sqlite3GenerateRowIndexDelete( Parse pParse, /* Parsing and code generating context */ Table pTab, /* Table containing the row to be deleted */ int iCur, /* VdbeCursor number for the table */ int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ ) { int i; Index pIdx; int r1; for (i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext) { if (aRegIdx != null && aRegIdx[i - 1] == 0) continue; r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, false); sqlite3VdbeAddOp3(pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1); } } /* ** Generate code that will assemble an index key and put it in register ** regOut. The key with be for index pIdx which is an index on pTab. ** iCur is the index of a cursor open on the pTab table and pointing to ** the entry that needs indexing. ** ** Return a register number which is the first in a block of ** registers that holds the elements of the index key. The ** block of registers has already been deallocated by the time ** this routine returns. */ private static int sqlite3GenerateIndexKey( Parse pParse, /* Parsing context */ Index pIdx, /* The index for which to generate a key */ int iCur, /* VdbeCursor number for the pIdx.pTable table */ int regOut, /* Write the new index key to this register */ bool doMakeRec /* Run the OP_MakeRecord instruction if true */ ) { Vdbe v = pParse.pVdbe; int j; Table pTab = pIdx.pTable; int regBase; int nCol; nCol = pIdx.nColumn; regBase = sqlite3GetTempRange(pParse, nCol + 1); sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase + nCol); for (j = 0; j < nCol; j++) { int idx = pIdx.aiColumn[j]; if (idx == pTab.iPKey) { sqlite3VdbeAddOp2(v, OP_SCopy, regBase + nCol, regBase + j); } else { sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase + j); sqlite3ColumnDefault(v, pTab, idx, -1); } } if (doMakeRec) { string zAff; if (pTab.pSelect != null || (pParse.db.flags & SQLITE_IdxRealAsInt) != 0) { zAff = ""; } else { zAff = sqlite3IndexAffinityStr(v, pIdx); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol + 1, regOut); sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); } sqlite3ReleaseTempRange(pParse, regBase, nCol + 1); return regBase; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Threading; using CoreAnimation; namespace Xamarin.Forms.Platform.iOS { public class VisualElementTracker : IDisposable { readonly EventHandler<EventArg<VisualElement>> _batchCommittedHandler; readonly PropertyChangedEventHandler _propertyChangedHandler; readonly EventHandler _sizeChangedEventHandler; bool _disposed; VisualElement _element; // Track these by hand because the calls down into iOS are too expensive bool _isInteractive; Rectangle _lastBounds; CALayer _layer; int _updateCount; public VisualElementTracker(IVisualElementRenderer renderer) { if (renderer == null) throw new ArgumentNullException("renderer"); _propertyChangedHandler = HandlePropertyChanged; _sizeChangedEventHandler = HandleSizeChanged; _batchCommittedHandler = HandleRedrawNeeded; Renderer = renderer; renderer.ElementChanged += OnRendererElementChanged; SetElement(null, renderer.Element); } IVisualElementRenderer Renderer { get; set; } public void Dispose() { Dispose(true); } public event EventHandler NativeControlUpdated; protected virtual void Dispose(bool disposing) { if (_disposed) return; _disposed = true; if (disposing) { SetElement(_element, null); if (_layer != null) { _layer.Dispose(); _layer = null; } Renderer.ElementChanged -= OnRendererElementChanged; Renderer = null; } } void HandlePropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == VisualElement.XProperty.PropertyName || e.PropertyName == VisualElement.YProperty.PropertyName || e.PropertyName == VisualElement.WidthProperty.PropertyName || e.PropertyName == VisualElement.HeightProperty.PropertyName || e.PropertyName == VisualElement.AnchorXProperty.PropertyName || e.PropertyName == VisualElement.AnchorYProperty.PropertyName || e.PropertyName == VisualElement.TranslationXProperty.PropertyName || e.PropertyName == VisualElement.TranslationYProperty.PropertyName || e.PropertyName == VisualElement.ScaleProperty.PropertyName || e.PropertyName == VisualElement.RotationProperty.PropertyName || e.PropertyName == VisualElement.RotationXProperty.PropertyName || e.PropertyName == VisualElement.RotationYProperty.PropertyName || e.PropertyName == VisualElement.IsVisibleProperty.PropertyName || e.PropertyName == VisualElement.IsEnabledProperty.PropertyName || e.PropertyName == VisualElement.InputTransparentProperty.PropertyName || e.PropertyName == VisualElement.OpacityProperty.PropertyName) UpdateNativeControl(); // poorly optimized } void HandleRedrawNeeded(object sender, EventArgs e) { UpdateNativeControl(); } void HandleSizeChanged(object sender, EventArgs e) { UpdateNativeControl(); } void OnRendererElementChanged(object s, VisualElementChangedEventArgs e) { if (_element == e.NewElement) return; SetElement(_element, e.NewElement); } void OnUpdateNativeControl(CALayer caLayer) { var view = Renderer.Element; var uiview = Renderer.NativeView; if (view == null || view.Batched) return; var shouldInteract = !view.InputTransparent && view.IsEnabled; if (_isInteractive != shouldInteract) { uiview.UserInteractionEnabled = shouldInteract; _isInteractive = shouldInteract; } var boundsChanged = _lastBounds != view.Bounds; var thread = !boundsChanged && !caLayer.Frame.IsEmpty; var anchorX = (float)view.AnchorX; var anchorY = (float)view.AnchorY; var translationX = (float)view.TranslationX; var translationY = (float)view.TranslationY; var rotationX = (float)view.RotationX; var rotationY = (float)view.RotationY; var rotation = (float)view.Rotation; var scale = (float)view.Scale; var width = (float)view.Width; var height = (float)view.Height; var x = (float)view.X; var y = (float)view.Y; var opacity = (float)view.Opacity; var isVisible = view.IsVisible; var updateTarget = Interlocked.Increment(ref _updateCount); Action update = () => { if (updateTarget != _updateCount) return; var visualElement = view; var parent = view.RealParent; var shouldRelayoutSublayers = false; if (isVisible && caLayer.Hidden) { caLayer.Hidden = false; if (!caLayer.Frame.IsEmpty) shouldRelayoutSublayers = true; } if (!isVisible && !caLayer.Hidden) { caLayer.Hidden = true; shouldRelayoutSublayers = true; } // ripe for optimization var transform = CATransform3D.Identity; // Dont ever attempt to actually change the layout of a Page unless it is a ContentPage // iOS is a really big fan of you not actually modifying the View's of the UIViewControllers if ((!(visualElement is Page) || visualElement is ContentPage) && width > 0 && height > 0 && parent != null && boundsChanged) { var target = new RectangleF(x, y, width, height); // must reset transform prior to setting frame... caLayer.Transform = transform; uiview.Frame = target; if (shouldRelayoutSublayers) caLayer.LayoutSublayers(); } else if (width <= 0 || height <= 0) { caLayer.Hidden = true; return; } caLayer.AnchorPoint = new PointF(anchorX, anchorY); caLayer.Opacity = opacity; const double epsilon = 0.001; // position is relative to anchor point if (Math.Abs(anchorX - .5) > epsilon) transform = transform.Translate((anchorX - .5f) * width, 0, 0); if (Math.Abs(anchorY - .5) > epsilon) transform = transform.Translate(0, (anchorY - .5f) * height, 0); if (Math.Abs(translationX) > epsilon || Math.Abs(translationY) > epsilon) transform = transform.Translate(translationX, translationY, 0); if (Math.Abs(scale - 1) > epsilon) transform = transform.Scale(scale); // not just an optimization, iOS will not "pixel align" a view which has m34 set if (Math.Abs(rotationY % 180) > epsilon || Math.Abs(rotationX % 180) > epsilon) transform.m34 = 1.0f / -400f; if (Math.Abs(rotationX % 360) > epsilon) transform = transform.Rotate(rotationX * (float)Math.PI / 180.0f, 1.0f, 0.0f, 0.0f); if (Math.Abs(rotationY % 360) > epsilon) transform = transform.Rotate(rotationY * (float)Math.PI / 180.0f, 0.0f, 1.0f, 0.0f); transform = transform.Rotate(rotation * (float)Math.PI / 180.0f, 0.0f, 0.0f, 1.0f); caLayer.Transform = transform; }; if (thread) Device.BeginInvokeOnMainThread(update); else update(); _lastBounds = view.Bounds; } void SetElement(VisualElement oldElement, VisualElement newElement) { if (oldElement != null) { oldElement.PropertyChanged -= _propertyChangedHandler; oldElement.SizeChanged -= _sizeChangedEventHandler; oldElement.BatchCommitted -= _batchCommittedHandler; } _element = newElement; if (newElement != null) { newElement.BatchCommitted += _batchCommittedHandler; newElement.SizeChanged += _sizeChangedEventHandler; newElement.PropertyChanged += _propertyChangedHandler; UpdateNativeControl(); } } void UpdateNativeControl() { if (_disposed) return; if (_layer == null) { _layer = Renderer.NativeView.Layer; _isInteractive = Renderer.NativeView.UserInteractionEnabled; } OnUpdateNativeControl(_layer); if (NativeControlUpdated != null) NativeControlUpdated(this, EventArgs.Empty); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.Security.KeyVault.Secrets; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; using Moq; using NUnit.Framework; namespace Azure.Extensions.AspNetCore.Configuration.Secrets.Tests { public class AzureKeyVaultConfigurationTests { private static readonly TimeSpan NoReloadDelay = TimeSpan.FromMilliseconds(1); private void SetPages(Mock<SecretClient> mock, params KeyVaultSecret[][] pages) { SetPages(mock, null, pages); } private void SetPages(Mock<SecretClient> mock, Func<string, Task> getSecretCallback, params KeyVaultSecret[][] pages) { getSecretCallback ??= (_ => Task.CompletedTask); var pagesOfProperties = pages.Select( page => page.Select(secret => secret.Properties).ToArray()).ToArray(); mock.Setup(m => m.GetPropertiesOfSecretsAsync(default)).Returns(new MockAsyncPageable(pagesOfProperties)); foreach (var page in pages) { foreach (var secret in page) { mock.Setup(client => client.GetSecretAsync(secret.Name, null, default)) .Returns(async (string name, string label, CancellationToken token) => { await getSecretCallback(name); return Response.FromValue(secret, Mock.Of<Response>()); } ); } } } private class MockAsyncPageable : AsyncPageable<SecretProperties> { private readonly SecretProperties[][] _pages; public MockAsyncPageable(SecretProperties[][] pages) { _pages = pages; } public override async IAsyncEnumerable<Page<SecretProperties>> AsPages(string continuationToken = null, int? pageSizeHint = null) { foreach (var page in _pages) { yield return Page<SecretProperties>.FromValues(page, null, Mock.Of<Response>()); } await Task.CompletedTask; } } [Test] public void LoadsAllSecretsFromVault() { var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1") }, new[] { CreateSecret("Secret2", "Value2") } ); // Act using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() })) { provider.Load(); var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), null).ToArray(); Assert.AreEqual(new[] { "Secret1", "Secret2" }, childKeys); Assert.AreEqual("Value1", provider.Get("Secret1")); Assert.AreEqual("Value2", provider.Get("Secret2")); } } private KeyVaultSecret CreateSecret(string name, string value, bool? enabled = true, DateTimeOffset? updated = null) { var id = new Uri("http://azure.keyvault/" + name); var secretProperties = SecretModelFactory.SecretProperties(id, name: name, updatedOn: updated); secretProperties.Enabled = enabled; return SecretModelFactory.KeyVaultSecret(secretProperties, value); } [Test] public void DoesNotLoadFilteredItems() { var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1") }, new[] { CreateSecret("Secret2", "Value2") } ); // Act using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new EndsWithOneKeyVaultSecretManager() })) { provider.Load(); // Assert var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), null).ToArray(); Assert.AreEqual(new[] { "Secret1" }, childKeys); Assert.AreEqual("Value1", provider.Get("Secret1")); } } [Test] public void DoesNotLoadDisabledItems() { var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1") }, new[] { CreateSecret("Secret2", "Value2", enabled: false), CreateSecret("Secret3", "Value3", enabled: null), } ); // Act using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() })) { provider.Load(); // Assert var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), null).ToArray(); Assert.AreEqual(new[] { "Secret1" }, childKeys); Assert.AreEqual("Value1", provider.Get("Secret1")); Assert.Throws<InvalidOperationException>(() => provider.Get("Secret2")); Assert.Throws<InvalidOperationException>(() => provider.Get("Secret3")); } } [Test] public void SupportsReload() { var updated = DateTime.Now; var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1", enabled: true, updated: updated) } ); // Act & Assert using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() })) { provider.Load(); Assert.AreEqual("Value1", provider.Get("Secret1")); SetPages(client, new[] { CreateSecret("Secret1", "Value2", enabled: true, updated: updated.AddSeconds(1)) } ); provider.Load(); Assert.AreEqual("Value2", provider.Get("Secret1")); } } [Test] public async Task SupportsAutoReload() { var updated = DateTime.Now; int numOfTokensFired = 0; var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1", enabled: true, updated: updated) } ); // Act & Assert using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay)) { ChangeToken.OnChange( () => provider.GetReloadToken(), () => { numOfTokensFired++; }); provider.Load(); Assert.AreEqual("Value1", provider.Get("Secret1")); await provider.Wait(); SetPages(client, new[] { CreateSecret("Secret1", "Value2", enabled: true, updated: updated.AddSeconds(1)) } ); provider.Release(); await provider.Wait(); Assert.AreEqual("Value2", provider.Get("Secret1")); Assert.AreEqual(1, numOfTokensFired); } } [Test] public async Task DoesntReloadUnchanged() { var updated = DateTime.Now; int numOfTokensFired = 0; var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1", enabled: true, updated: updated) } ); // Act & Assert using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay)) { ChangeToken.OnChange( () => provider.GetReloadToken(), () => { numOfTokensFired++; }); provider.Load(); Assert.AreEqual("Value1", provider.Get("Secret1")); await provider.Wait(); provider.Release(); await provider.Wait(); Assert.AreEqual("Value1", provider.Get("Secret1")); Assert.AreEqual(0, numOfTokensFired); } } [Test] public async Task SupportsReloadOnRemove() { int numOfTokensFired = 0; var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1"), CreateSecret("Secret2", "Value2") } ); // Act & Assert using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay)) { ChangeToken.OnChange( () => provider.GetReloadToken(), () => { numOfTokensFired++; }); provider.Load(); Assert.AreEqual("Value1", provider.Get("Secret1")); await provider.Wait(); SetPages(client, new[] { CreateSecret("Secret1", "Value2") } ); provider.Release(); await provider.Wait(); Assert.Throws<InvalidOperationException>(() => provider.Get("Secret2")); Assert.AreEqual(1, numOfTokensFired); } } [Test] public async Task SupportsReloadOnEnabledChange() { int numOfTokensFired = 0; var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1"), CreateSecret("Secret2", "Value2") } ); // Act & Assert using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay)) { ChangeToken.OnChange( () => provider.GetReloadToken(), () => { numOfTokensFired++; }); provider.Load(); Assert.AreEqual("Value2", provider.Get("Secret2")); await provider.Wait(); SetPages(client, new[] { CreateSecret("Secret1", "Value2"), CreateSecret("Secret2", "Value2", enabled: false) } ); provider.Release(); await provider.Wait(); Assert.Throws<InvalidOperationException>(() => provider.Get("Secret2")); Assert.AreEqual(1, numOfTokensFired); } } [Test] public async Task SupportsReloadOnAdd() { int numOfTokensFired = 0; var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "Value1") } ); // Act & Assert using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay)) { ChangeToken.OnChange( () => provider.GetReloadToken(), () => { numOfTokensFired++; }); provider.Load(); Assert.AreEqual("Value1", provider.Get("Secret1")); await provider.Wait(); SetPages(client, new[] { CreateSecret("Secret1", "Value1"), }, new[] { CreateSecret("Secret2", "Value2") } ); provider.Release(); await provider.Wait(); Assert.AreEqual("Value1", provider.Get("Secret1")); Assert.AreEqual("Value2", provider.Get("Secret2")); Assert.AreEqual(1, numOfTokensFired); } } [Test] public void ReplaceDoubleMinusInKeyName() { var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Section--Secret1", "Value1") } ); // Act using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() })) { provider.Load(); // Assert Assert.AreEqual("Value1", provider.Get("Section:Secret1")); } } [Test] public void HandleCollisions() { var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Section---Secret1", "Value1") }, new[] { CreateSecret("Section--Secret1", "Value2") } ); // Act using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManagerMultiDash() })) { provider.Load(); // Assert Assert.AreEqual("Value1", provider.Get("Section:Secret1")); } } [Test] public void HandleCollisionsUseLatestValue() { var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Section----Secret1", "Value1", updated: new DateTimeOffset(new DateTime(2038, 1, 19), TimeSpan.Zero)) }, new[] { CreateSecret("Section---Secret1", "Value2", updated: new DateTimeOffset(new DateTime(2038, 1, 20), TimeSpan.Zero)) }, new[] { CreateSecret("Section--Secret1", "Value3", updated: new DateTimeOffset(new DateTime(2038, 1, 18), TimeSpan.Zero)) } ); // Act using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManagerMultiDash() })) { provider.Load(); // Assert Assert.AreEqual("Value2", provider.Get("Section:Secret1")); } } [Test] public void CanCustomizeSecretTransformation() { var client = new Mock<SecretClient>(); SetPages(client, new[] { CreateSecret("Secret1", "{\"innerKey1\": \"innerValue1\", \"innerKey2\": \"innerValue2\"}", updated: new DateTimeOffset(new DateTime(2038, 1, 19), TimeSpan.Zero)), CreateSecret("Secret2", "{\"innerKey3\": \"innerValue3\"}", updated: new DateTimeOffset(new DateTime(2038, 1, 18), TimeSpan.Zero)) } ); // Act using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new JsonKeyVaultSecretManager() })) { provider.Load(); // Assert Assert.AreEqual("innerValue1", provider.Get("innerKey1")); Assert.AreEqual("innerValue2", provider.Get("innerKey2")); Assert.AreEqual("innerValue3", provider.Get("innerKey3")); } } [Test] public async Task LoadsSecretsInParallel() { var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); var expectedCount = 2; var client = new Mock<SecretClient>(); SetPages(client, async (string id) => { if (Interlocked.Decrement(ref expectedCount) == 0) { tcs.SetResult(null); } await tcs.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); }, new[] { CreateSecret("Secret1", "Value1"), CreateSecret("Secret2", "Value2") } ); // Act var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }); provider.Load(); await tcs.Task; // Assert Assert.AreEqual("Value1", provider.Get("Secret1")); Assert.AreEqual("Value2", provider.Get("Secret2")); } [Test] public void LimitsMaxParallelism() { var expectedCount = 100; var currentParallel = 0; var maxParallel = 0; var client = new Mock<SecretClient>(); // Create 10 pages of 10 secrets var pages = Enumerable.Range(0, 10).Select(a => Enumerable.Range(0, 10).Select(b => CreateSecret("Secret" + (a * 10 + b), (a * 10 + b).ToString())).ToArray() ).ToArray(); SetPages(client, async (string id) => { var i = Interlocked.Increment(ref currentParallel); maxParallel = Math.Max(i, maxParallel); await Task.Delay(30); Interlocked.Decrement(ref currentParallel); }, pages ); // Act var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }); provider.Load(); // Assert for (int i = 0; i < expectedCount; i++) { Assert.AreEqual(i.ToString(), provider.Get("Secret" + i)); } Assert.LessOrEqual(maxParallel, 32); } [Test] public void ConstructorThrowsForNullManager() { Assert.Throws<ArgumentNullException>(() => new AzureKeyVaultConfigurationProvider(Mock.Of<SecretClient>(), new AzureKeyVaultConfigurationOptions() { Manager = null })); } [Test] public void ConstructorThrowsForZeroRefreshPeriodValue() { Assert.Throws<ArgumentOutOfRangeException>(() => new AzureKeyVaultConfigurationProvider(Mock.Of<SecretClient>(), new AzureKeyVaultConfigurationOptions() { ReloadInterval = TimeSpan.Zero })); } [Test] public void ConstructorThrowsForNegativeRefreshPeriodValue() { Assert.Throws<ArgumentOutOfRangeException>(() => new AzureKeyVaultConfigurationProvider(Mock.Of<SecretClient>(), new AzureKeyVaultConfigurationOptions() { ReloadInterval = TimeSpan.FromMilliseconds(-1) })); } private class EndsWithOneKeyVaultSecretManager : KeyVaultSecretManager { public override bool Load(SecretProperties secret) { return secret.Name.EndsWith("1"); } } private class ReloadControlKeyVaultProvider : AzureKeyVaultConfigurationProvider { private TaskCompletionSource<object> _releaseTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); private TaskCompletionSource<object> _signalTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); public ReloadControlKeyVaultProvider(SecretClient client, KeyVaultSecretManager manager, TimeSpan? reloadPollDelay = null) : base(client, new AzureKeyVaultConfigurationOptions() { Manager = manager, ReloadInterval = reloadPollDelay}) { } internal override async Task WaitForReload() { _signalTaskCompletionSource.SetResult(null); await _releaseTaskCompletionSource.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); } public async Task Wait() { await _signalTaskCompletionSource.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); } public void Release() { if (!_signalTaskCompletionSource.Task.IsCompleted) { throw new InvalidOperationException("Provider is not waiting for reload"); } var releaseTaskCompletionSource = _releaseTaskCompletionSource; _releaseTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); _signalTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); releaseTaskCompletionSource.SetResult(null); } } private class KeyVaultSecretManagerMultiDash : KeyVaultSecretManager { public override string GetKey(KeyVaultSecret secret) { return secret.Name .Replace("----", ConfigurationPath.KeyDelimiter) .Replace("---", ConfigurationPath.KeyDelimiter) .Replace("--", ConfigurationPath.KeyDelimiter); } } private class JsonKeyVaultSecretManager: KeyVaultSecretManager { public override Dictionary<string, string> GetData(IEnumerable<KeyVaultSecret> secrets) { var data = new Dictionary<string, string>(); foreach (var secret in secrets) { using var doc = JsonDocument.Parse(secret.Value); foreach (var property in doc.RootElement.EnumerateObject()) { data[property.Name] = property.Value.GetString(); } } return data; } } } }
#region File Description //----------------------------------------------------------------------------- // MeleeCombatAction.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using RolePlayingGameData; using Microsoft.Xna.Framework.Graphics; #endregion namespace RolePlaying { /// <summary> /// A melee-attack combat action, including related data and calculations. /// </summary> class MeleeCombatAction : CombatAction { #region State /// <summary> /// Returns true if the action is offensive, targeting the opponents. /// </summary> public override bool IsOffensive { get { return true; } } /// <summary> /// Returns true if this action requires a target. /// </summary> public override bool IsTargetNeeded { get { return true; } } #endregion #region Advancing/Returning Data /// <summary> /// The speed at which the advancing character moves, in units per second. /// </summary> private const float advanceSpeed = 300f; /// <summary> /// The offset from the advance destination to the target position /// </summary> private static readonly Vector2 advanceOffset = new Vector2(85f, 0f); /// <summary> /// The direction of the advancement. /// </summary> private Vector2 advanceDirection; /// <summary> /// The distance covered so far by the advance/return action /// </summary> private float advanceDistanceCovered = 0f; /// <summary> /// The total distance between the original combatant position and the target. /// </summary> private float totalAdvanceDistance; #endregion #region Combat Stage /// <summary> /// Starts a new combat stage. Called right after the stage changes. /// </summary> /// <remarks>The stage never changes into NotStarted.</remarks> protected override void StartStage() { switch (stage) { case CombatActionStage.Preparing: // called from Start() { // play the animation combatant.CombatSprite.PlayAnimation("Idle"); } break; case CombatActionStage.Advancing: { // play the animation combatant.CombatSprite.PlayAnimation("Walk"); // calculate the advancing destination if (Target.Position.X > Combatant.Position.X) { advanceDirection = Target.Position - Combatant.OriginalPosition - advanceOffset; } else { advanceDirection = Target.Position - Combatant.OriginalPosition + advanceOffset; } totalAdvanceDistance = advanceDirection.Length(); advanceDirection.Normalize(); advanceDistanceCovered = 0f; } break; case CombatActionStage.Executing: { // play the animation combatant.CombatSprite.PlayAnimation("Attack"); // play the audio Weapon weapon = combatant.Character.GetEquippedWeapon(); if (weapon != null) { AudioManager.PlayCue(weapon.SwingCueName); } else { AudioManager.PlayCue("StaffSwing"); } } break; case CombatActionStage.Returning: { // play the animation combatant.CombatSprite.PlayAnimation("Walk"); // calculate the damage Int32Range damageRange = combatant.Character.TargetDamageRange + combatant.Statistics.PhysicalOffense; Int32Range defenseRange = Target.Character.HealthDefenseRange + Target.Statistics.PhysicalDefense; int damage = Math.Max(0, damageRange.GenerateValue(Session.Random) - defenseRange.GenerateValue(Session.Random)); // apply the damage if (damage > 0) { // play the audio Weapon weapon = combatant.Character.GetEquippedWeapon(); if (weapon != null) { AudioManager.PlayCue(weapon.HitCueName); } else { AudioManager.PlayCue("StaffHit"); } // damage the target Target.DamageHealth(damage, 0); if ((weapon != null) && (weapon.Overlay != null)) { weapon.Overlay.PlayAnimation(0); weapon.Overlay.ResetAnimation(); } } } break; case CombatActionStage.Finishing: { // play the animation combatant.CombatSprite.PlayAnimation("Idle"); } break; case CombatActionStage.Complete: { // play the animation combatant.CombatSprite.PlayAnimation("Idle"); } break; } } /// <summary> /// Update the action for the current stage. /// </summary> /// <remarks> /// This function is guaranteed to be called at least once per stage. /// </remarks> protected override void UpdateCurrentStage(GameTime gameTime) { float elapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds; switch (stage) { case CombatActionStage.Advancing: { // move to the destination if (advanceDistanceCovered < totalAdvanceDistance) { advanceDistanceCovered = Math.Min(advanceDistanceCovered + advanceSpeed * elapsedSeconds, totalAdvanceDistance); } // update the combatant's position combatant.Position = combatant.OriginalPosition + advanceDirection * advanceDistanceCovered; } break; case CombatActionStage.Returning: { // move to the destination if (advanceDistanceCovered > 0f) { advanceDistanceCovered -= advanceSpeed * elapsedSeconds; } combatant.Position = combatant.OriginalPosition + advanceDirection * advanceDistanceCovered; } break; } } /// <summary> /// Returns true if the combat action is ready to proceed to the next stage. /// </summary> protected override bool IsReadyForNextStage { get { switch (stage) { case CombatActionStage.Preparing: // ready to advance? return true; case CombatActionStage.Advancing: // ready to execute? if (advanceDistanceCovered >= totalAdvanceDistance) { advanceDistanceCovered = totalAdvanceDistance; combatant.Position = combatant.OriginalPosition + advanceDirection * totalAdvanceDistance; return true; } else { return false; } case CombatActionStage.Executing: // ready to return? return combatant.CombatSprite.IsPlaybackComplete; case CombatActionStage.Returning: // ready to finish? if (advanceDistanceCovered <= 0f) { advanceDistanceCovered = 0f; combatant.Position = combatant.OriginalPosition; return true; } else { return false; } case CombatActionStage.Finishing: // ready to complete? return true; } // fall through to the base behavior return base.IsReadyForNextStage; } } #endregion #region Heuristic /// <summary> /// The heuristic used to compare actions of this type to similar ones. /// </summary> public override int Heuristic { get { return combatant.Character.TargetDamageRange.Average; } } #endregion #region Initialization /// <summary> /// Constructs a new MeleeCombatAction object. /// </summary> /// <param name="character">The character performing the action.</param> public MeleeCombatAction(Combatant combatant) : base(combatant) { } #endregion #region Updating /// <summary> /// Updates the action over time. /// </summary> public override void Update(GameTime gameTime) { // update the weapon animation float elapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds; Weapon weapon = Combatant.Character.GetEquippedWeapon(); if ((weapon != null) && (weapon.Overlay != null)) { weapon.Overlay.UpdateAnimation(elapsedSeconds); } // update the action base.Update(gameTime); } #endregion #region Drawing /// <summary> /// Draw any elements of the action that are independent of the character. /// </summary> public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) { // draw the weapon overlay (typically blood) Weapon weapon = Combatant.Character.GetEquippedWeapon(); if ((weapon != null) && (weapon.Overlay != null) && !weapon.Overlay.IsPlaybackComplete) { weapon.Overlay.Draw(spriteBatch, Target.Position, 0f); } base.Draw(gameTime, spriteBatch); } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; #if WCF_SUPPORTED using System.ServiceModel; using System.ServiceModel.Channels; #endif using System.Threading; #if SILVERLIGHT using System.Windows; using System.Windows.Threading; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.LogReceiverService; /// <summary> /// Sends log messages to a NLog Receiver Service (using WCF or Web Services). /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/LogReceiverService-target">Documentation on NLog Wiki</seealso> [Target("LogReceiverService")] public class LogReceiverWebServiceTarget : Target { private LogEventInfoBuffer buffer = new LogEventInfoBuffer(10000, false, 10000); private bool inCall; /// <summary> /// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class. /// </summary> public LogReceiverWebServiceTarget() { this.Parameters = new List<MethodCallParameter>(); } /// <summary> /// Gets or sets the endpoint address. /// </summary> /// <value>The endpoint address.</value> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] public virtual string EndpointAddress { get; set; } #if WCF_SUPPORTED /// <summary> /// Gets or sets the name of the endpoint configuration in WCF configuration file. /// </summary> /// <value>The name of the endpoint configuration.</value> /// <docgen category='Connection Options' order='10' /> public string EndpointConfigurationName { get; set; } /// <summary> /// Gets or sets a value indicating whether to use binary message encoding. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool UseBinaryEncoding { get; set; } /// <summary> /// Gets or sets a value indicating whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply) /// </summary> /// <docgen category='Connection Options' order='10' /> public bool UseOneWayContract { get; set; } #endif /// <summary> /// Gets or sets the client ID. /// </summary> /// <value>The client ID.</value> /// <docgen category='Payload Options' order='10' /> public Layout ClientId { get; set; } /// <summary> /// Gets the list of parameters. /// </summary> /// <value>The parameters.</value> /// <docgen category='Payload Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "parameter")] public IList<MethodCallParameter> Parameters { get; private set; } /// <summary> /// Gets or sets a value indicating whether to include per-event properties in the payload sent to the server. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Called when log events are being sent (test hook). /// </summary> /// <param name="events">The events.</param> /// <param name="asyncContinuations">The async continuations.</param> /// <returns>True if events should be sent, false to stop processing them.</returns> protected internal virtual bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { return true; } /// <summary> /// Writes logging event to the log target. Must be overridden in inheriting /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected override void Write(AsyncLogEventInfo logEvent) { this.Write(new[] { logEvent }); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Append" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(AsyncLogEventInfo[] logEvents) { // if web service call is being processed, buffer new events and return // lock is being held here if (this.inCall) { foreach (var ev in logEvents) { this.buffer.Append(ev); } return; } var networkLogEvents = this.TranslateLogEvents(logEvents); this.Send(networkLogEvents, logEvents); } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { this.SendBufferedEvents(); asyncContinuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } } private static int AddValueAndGetStringOrdinal(NLogEvents context, Dictionary<string, int> stringTable, string value) { int stringIndex; if (!stringTable.TryGetValue(value, out stringIndex)) { stringIndex = context.Strings.Count; stringTable.Add(value, stringIndex); context.Strings.Add(value); } return stringIndex; } private NLogEvents TranslateLogEvents(AsyncLogEventInfo[] logEvents) { if (logEvents.Length == 0 && !LogManager.ThrowExceptions) { InternalLogger.Error("LogEvents array is empty, sending empty event..."); return new NLogEvents(); } string clientID = string.Empty; if (this.ClientId != null) { clientID = this.ClientId.Render(logEvents[0].LogEvent); } var networkLogEvents = new NLogEvents { ClientName = clientID, LayoutNames = new StringCollection(), Strings = new StringCollection(), BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks }; var stringTable = new Dictionary<string, int>(); for (int i = 0; i < this.Parameters.Count; ++i) { networkLogEvents.LayoutNames.Add(this.Parameters[i].Name); } if (this.IncludeEventProperties) { for (int i = 0; i < logEvents.Length; ++i) { var ev = logEvents[i].LogEvent; // add all event-level property names in 'LayoutNames' collection. foreach (var prop in ev.Properties) { string propName = prop.Key as string; if (propName != null) { if (!networkLogEvents.LayoutNames.Contains(propName)) { networkLogEvents.LayoutNames.Add(propName); } } } } } networkLogEvents.Events = new NLogEvent[logEvents.Length]; for (int i = 0; i < logEvents.Length; ++i) { networkLogEvents.Events[i] = this.TranslateEvent(logEvents[i].LogEvent, networkLogEvents, stringTable); } return networkLogEvents; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Client is disposed asynchronously.")] private void Send(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { if (!this.OnSend(events, asyncContinuations)) { return; } #if WCF_SUPPORTED var client = CreateLogReceiver(); client.ProcessLogMessagesCompleted += (sender, e) => { // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(e.Error); } // send any buffered events this.SendBufferedEvents(); }; this.inCall = true; #if SILVERLIGHT if (!Deployment.Current.Dispatcher.CheckAccess()) { Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events)); } else { client.ProcessLogMessagesAsync(events); } #else client.ProcessLogMessagesAsync(events); #endif #else var client = new SoapLogReceiverClient(this.EndpointAddress); this.inCall = true; client.BeginProcessLogMessages( events, result => { Exception exception = null; try { client.EndProcessLogMessages(result); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } exception = ex; } // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(exception); } // send any buffered events this.SendBufferedEvents(); }, null); #endif } #if WCF_SUPPORTED /// <summary> /// Creating a new instance of WcfLogReceiverClient /// /// Inheritors can override this method and provide their own /// service configuration - binding and endpoint address /// </summary> /// <returns></returns> [Obsolete("Ths may be removed in a future release. Use CreateLogReceiver.")] protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient() { WcfLogReceiverClient client; if (string.IsNullOrEmpty(this.EndpointConfigurationName)) { // endpoint not specified - use BasicHttpBinding Binding binding; if (this.UseBinaryEncoding) { binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); } else { binding = new BasicHttpBinding(); } client = new WcfLogReceiverClient(UseOneWayContract, binding, new EndpointAddress(this.EndpointAddress)); } else { client = new WcfLogReceiverClient(UseOneWayContract, this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress)); } client.ProcessLogMessagesCompleted += ClientOnProcessLogMessagesCompleted; return client; } /// <summary> /// Creating a new instance of IWcfLogReceiverClient /// /// Inheritors can override this method and provide their own /// service configuration - binding and endpoint address /// </summary> /// <returns></returns> protected IWcfLogReceiverClient CreateLogReceiver() { #pragma warning disable 612, 618 return this.CreateWcfLogReceiverClient(); #pragma warning restore 612, 618 } private void ClientOnProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs) { var client = sender as WcfLogReceiverClient; if (client != null && client.State == CommunicationState.Opened) { client.CloseCommunicationObject(); } } #endif private void SendBufferedEvents() { lock (this.SyncRoot) { // clear inCall flag AsyncLogEventInfo[] bufferedEvents = this.buffer.GetEventsAndClear(); if (bufferedEvents.Length > 0) { var networkLogEvents = this.TranslateLogEvents(bufferedEvents); this.Send(networkLogEvents, bufferedEvents); } else { // nothing in the buffer, clear in-call flag this.inCall = false; } } } private NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary<string, int> stringTable) { var nlogEvent = new NLogEvent(); nlogEvent.Id = eventInfo.SequenceID; nlogEvent.MessageOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.FormattedMessage); nlogEvent.LevelOrdinal = eventInfo.Level.Ordinal; nlogEvent.LoggerOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.LoggerName); nlogEvent.TimeDelta = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc; for (int i = 0; i < this.Parameters.Count; ++i) { var param = this.Parameters[i]; var value = param.Layout.Render(eventInfo); int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } // layout names beyond Parameters.Count are per-event property names. for (int i = this.Parameters.Count; i < context.LayoutNames.Count; ++i) { string value; object propertyValue; if (eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue)) { value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture); } else { value = string.Empty; } int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } if (eventInfo.Exception != null) { nlogEvent.ValueIndexes.Add(AddValueAndGetStringOrdinal(context, stringTable, eventInfo.Exception.ToString())); } return nlogEvent; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DatabaseObjectToScriptedDirectoryProcessor.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Database.SqlServer.Administration { using System; using System.Collections.Generic; using System.IO; using Microsoft.SqlServer.Management.Smo; using OBeautifulCode.Validation.Recipes; /// <summary> /// Manage processing objects to disk along with documentation if applicable. /// </summary> public class DatabaseObjectToScriptedDirectoryProcessor { private const string FileExtensionStoredProcedure = ".prc"; private const string FileExtensionTable = ".tab"; private const string FileExtensionFunction = ".fnc"; private const string FileExtensionRole = ".sql"; private const string FileExtensionView = ".viw"; private const string FileExtensionIndex = ".idx"; private const string FileExtensionTrigger = ".trg"; private const string FileExtensionChecks = ".sql"; private const string FileExtensionForeignKey = ".fky"; private const string FileExtensionUser = ".usr"; private const string FileExtensionUserDefinedDataType = ".udt"; private readonly List<string> createdDirectories = new List<string>(); private readonly IDocumentGenerator documentGenerator; private readonly DatabaseDocumenter databaseDocumenter; private readonly string tablePath; private readonly string sprocPath; private readonly string securityPath; private readonly string funcPath; private readonly string viewPath; private readonly string userDefinedDataTypePath; /// <summary> /// Initializes a new instance of the <see cref="DatabaseObjectToScriptedDirectoryProcessor"/> class. /// </summary> /// <param name="documentGenerator">Document generator to use.</param> /// <param name="basePath">Path to write output.</param> public DatabaseObjectToScriptedDirectoryProcessor(IDocumentGenerator documentGenerator, string basePath) { new { documentGenerator }.Must().NotBeNull(); new { basePath }.Must().NotBeNullNorWhiteSpace(); this.documentGenerator = documentGenerator; this.databaseDocumenter = new DatabaseDocumenter(this.documentGenerator); this.tablePath = this.CreateDatabaseObjectDirectory("table", basePath); this.sprocPath = this.CreateDatabaseObjectDirectory("sproc", basePath); this.funcPath = this.CreateDatabaseObjectDirectory("function", basePath); this.viewPath = this.CreateDatabaseObjectDirectory("view", basePath); this.securityPath = this.CreateDatabaseObjectDirectory("security", basePath); this.userDefinedDataTypePath = this.CreateDatabaseObjectDirectory("type", basePath); } private string CreateDatabaseObjectDirectory(string childFolderName, string basePath) { string ret = Path.Combine(basePath, childFolderName); if (!Directory.Exists(ret)) { Directory.CreateDirectory(ret); this.createdDirectories.Add(ret); } return ret; } /// <summary> /// Process tables. /// </summary> /// <param name="tables">Object to process.</param> public void Process(TableCollection tables) { new { tables }.Must().NotBeNull(); if (tables.Count > 0) { this.documentGenerator.AddEntry("TABLES", 16, true); } this.documentGenerator.Indent(); foreach (Table table in tables) { if (!table.IsSystemObject) { string tableName = table.Name; this.databaseDocumenter.Document(table); ScriptAndWriteToFile(table, this.tablePath, FileExtensionTable); this.Process(table.Columns, tableName); this.Process(table.Indexes, tableName, this.tablePath); this.Process(table.Triggers, tableName, this.tablePath); this.Process(table.ForeignKeys, tableName); this.Process(table.Checks, tableName); } } this.documentGenerator.Undent(); } /// <summary> /// Process views. /// </summary> /// <param name="views">Object to process.</param> public void Process(ViewCollection views) { new { views }.Must().NotBeNull(); if (views.Count > 0) { this.documentGenerator.AddEntry("VIEWS", 16, true); } this.documentGenerator.Indent(); foreach (View view in views) { if (!view.IsSystemObject) { string viewName = view.Name; this.databaseDocumenter.Document(view); ScriptAndWriteToFile(view, this.viewPath, FileExtensionView); this.Process(view.Columns, viewName); this.Process(view.Indexes, viewName, this.viewPath); this.Process(view.Triggers, viewName, this.viewPath); } } this.documentGenerator.Undent(); } /// <summary> /// Process stored procedures. /// </summary> /// <param name="storedProcedures">Object to process.</param> public void Process(StoredProcedureCollection storedProcedures) { new { storedProcedures }.Must().NotBeNull(); if (storedProcedures.Count > 0) { this.documentGenerator.AddEntry("STORED PROCEDURES", 16, true); } this.documentGenerator.Indent(); foreach (StoredProcedure storedProcedure in storedProcedures) { if (!storedProcedure.IsSystemObject) { this.databaseDocumenter.Document(storedProcedure); ScriptAndWriteToFile(storedProcedure, this.sprocPath, FileExtensionStoredProcedure); if (storedProcedure.Parameters.Count > 0) { this.documentGenerator.AddEntry("Parameters", 12, true); } this.documentGenerator.Indent(); this.databaseDocumenter.Document(storedProcedure.Parameters); this.documentGenerator.Undent(); } } this.documentGenerator.Undent(); } /// <summary> /// Process user defined functions. /// </summary> /// <param name="userDefinedFunctions">Object to process.</param> public void Process(UserDefinedFunctionCollection userDefinedFunctions) { new { userDefinedFunctions }.Must().NotBeNull(); if (userDefinedFunctions.Count > 0) { this.documentGenerator.AddEntry("USER DEFINED FUNCTIONS", 16, true); } this.documentGenerator.Indent(); foreach (UserDefinedFunction userDefinedFunction in userDefinedFunctions) { if (!userDefinedFunction.IsSystemObject) { this.databaseDocumenter.Document(userDefinedFunction); ScriptAndWriteToFile(userDefinedFunction, this.funcPath, FileExtensionFunction); if (userDefinedFunction.Parameters.Count > 0) { this.documentGenerator.AddEntry("Parameters", 12, true); } this.documentGenerator.Indent(); this.databaseDocumenter.Document(userDefinedFunction.Parameters); this.documentGenerator.Undent(); } } this.documentGenerator.Undent(); } /// <summary> /// Process roles. /// </summary> /// <param name="roles">Object to process.</param> public void Process(DatabaseRoleCollection roles) { new { roles }.Must().NotBeNull(); if (roles.Count > 0) { this.documentGenerator.AddEntry("ROLES", 16, true); } this.documentGenerator.Indent(); foreach (DatabaseRole role in roles) { if (!role.IsFixedRole && role.Name != "public") { this.databaseDocumenter.Document(role); ScriptAndWriteToFile(role, this.securityPath, FileExtensionRole); } } this.documentGenerator.Undent(); } /// <summary> /// Process columns. /// </summary> /// <param name="columns">Object to process.</param> /// <param name="tableOrViewName">Name of table or view containing columns.</param> public void Process(ColumnCollection columns, string tableOrViewName) { new { columns }.Must().NotBeNull(); if (columns.Count > 0) { this.documentGenerator.AddEntry("Columns on table - " + tableOrViewName, 12, true); } this.documentGenerator.Indent(); this.databaseDocumenter.Document(columns); this.documentGenerator.Undent(); } /// <summary> /// Process indexes. /// </summary> /// <param name="indexes">Object to process.</param> /// <param name="tableOrViewName">Name of table or view containing indexes.</param> /// <param name="fileBasePath">FIle path to write to (might differ between view and table).</param> public void Process(IndexCollection indexes, string tableOrViewName, string fileBasePath) { new { indexes }.Must().NotBeNull(); new { tableOrViewName }.Must().NotBeNullNorWhiteSpace(); new { fileBasePath }.Must().NotBeNullNorWhiteSpace(); var filtered = FilterPrimaryUniqueKeys(indexes); if (filtered.Count > 0) { this.documentGenerator.AddEntry("Indexes on table - " + tableOrViewName, 12, true); } this.documentGenerator.Indent(); foreach (Index index in filtered) { if (!index.IsSystemObject) { this.databaseDocumenter.Document(index); ScriptAndWriteToFile(index, fileBasePath, FileExtensionIndex); } } this.documentGenerator.Undent(); } /// <summary> /// Process triggers. /// </summary> /// <param name="triggers">Object to process.</param> /// <param name="tableOrViewName">Name of table or view containing triggers.</param> /// <param name="fileBasePath">FIle path to write to (might differ between view and table).</param> public void Process(TriggerCollection triggers, string tableOrViewName, string fileBasePath) { new { triggers }.Must().NotBeNull(); new { tableOrViewName }.Must().NotBeNullNorWhiteSpace(); new { fileBasePath }.Must().NotBeNullNorWhiteSpace(); if (triggers.Count > 0) { this.documentGenerator.AddEntry("Triggers on table - " + tableOrViewName, 12, true); } this.documentGenerator.Indent(); foreach (Trigger trigger in triggers) { if (!trigger.IsSystemObject) { this.databaseDocumenter.Document(trigger); ScriptAndWriteToFile(trigger, fileBasePath, FileExtensionTrigger); } } this.documentGenerator.Undent(); } /// <summary> /// Process checks. /// </summary> /// <param name="checks">Object to process.</param> /// <param name="tableName">Name of table or view containing checks.</param> public void Process(CheckCollection checks, string tableName) { new { checks }.Must().NotBeNull(); new { tableName }.Must().NotBeNullNorWhiteSpace(); if (checks.Count > 0) { this.documentGenerator.AddEntry("Checks for table - " + tableName, 12, true); } this.documentGenerator.Indent(); foreach (Check check in checks) { this.databaseDocumenter.Document(check); ScriptAndWriteToFile(check, this.tablePath, FileExtensionChecks); } this.documentGenerator.Undent(); } /// <summary> /// Process foreign keys. /// </summary> /// <param name="foreignKeys">Object to process.</param> /// <param name="tableName">Name of table foreign keys.</param> public void Process(ForeignKeyCollection foreignKeys, string tableName) { new { foreignKeys }.Must().NotBeNull(); new { tableName }.Must().NotBeNullNorWhiteSpace(); if (foreignKeys.Count > 0) { this.documentGenerator.AddEntry("Foreign Keys for table - " + tableName, 12, true); } this.documentGenerator.Indent(); foreach (ForeignKey foreignKey in foreignKeys) { this.databaseDocumenter.Document(foreignKey); ScriptAndWriteToFile(foreignKey, this.tablePath, FileExtensionForeignKey); } this.documentGenerator.Undent(); } /// <summary> /// Process users. /// </summary> /// <param name="users">Object to process.</param> public void Process(UserCollection users) { new { users }.Must().NotBeNull(); if (users.Count > 0) { this.documentGenerator.AddEntry("USERS", 16, true); } this.documentGenerator.Indent(); foreach (User user in users) { if (!user.IsSystemObject) { this.databaseDocumenter.Document(user); ScriptAndWriteToFile(user, this.securityPath, FileExtensionUser); } } this.documentGenerator.Undent(); } /// <summary> /// Process user defined data types. /// </summary> /// <param name="userDefinedDataTypes">Object to process.</param> public void Process(UserDefinedDataTypeCollection userDefinedDataTypes) { new { userDefinedDataTypes }.Must().NotBeNull(); if (userDefinedDataTypes.Count > 0) { this.documentGenerator.AddEntry("USER DEFINED DATA TYPES", 16, true); } this.documentGenerator.Indent(); foreach (UserDefinedDataType userDefinedDataType in userDefinedDataTypes) { this.databaseDocumenter.Document(userDefinedDataType); ScriptAndWriteToFile(userDefinedDataType, this.userDefinedDataTypePath, FileExtensionUserDefinedDataType); } this.documentGenerator.Undent(); } private static ICollection<Index> FilterPrimaryUniqueKeys(IndexCollection idxs) { var ret = new List<Index>(idxs.Count); foreach (Index idx in idxs) { // these are scripted with tables if (idx.IndexKeyType != IndexKeyType.DriPrimaryKey && idx.IndexKeyType != IndexKeyType.DriUniqueKey) { ret.Add(idx); } } return ret; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Legacy code, not fixing right now.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "FilePathAndName", Justification = "Spelling/name is correct.")] private static void ScriptAndWriteToFile(IScriptable scriptableObject, string basePath, string extensionWithPeriod) { string script = SqlObjectScripter.Script(scriptableObject); if (!string.IsNullOrEmpty(script)) { string fileName = "[Not assigned]"; string filePathAndName = "[Not assigned]"; try { fileName = ((NamedSmoObject)scriptableObject).Name.Replace(@"\", "--"); // for domain names mainly, making sure to not mess up file path fileName = fileName.Replace(":", "_-COLON-_"); filePathAndName = Path.Combine(basePath, fileName); filePathAndName = Path.ChangeExtension(filePathAndName, extensionWithPeriod); using (TextWriter writer = new StreamWriter(filePathAndName, false)) { writer.WriteLine(script); } } catch (Exception e) { Console.WriteLine("Exception encountered."); Console.WriteLine("FileName: {0} FilePathAndName: {1}", fileName, filePathAndName); Console.WriteLine(e); } } } /// <summary> /// Remove directories in output that never had objects placed in them. /// </summary> public void CleanUpEmptyDirectories() { foreach (string path in this.createdDirectories) { if (Directory.GetFiles(path).Length == 0 && Directory.GetDirectories(path).Length == 0) { Console.WriteLine("Removing {0}", path); Directory.Delete(path); } } } } }
using System; using System.Globalization; using System.Text; using Google.GData.Client; namespace Google.GData.Spreadsheets { /// <summary> /// A subclass of FeedQuery, to create a Spreadsheets list query URI. /// Provides public properties that describe the different /// aspects of the URI, as well as a composite URI. /// </summary> public class ListQuery : FeedQuery { private string orderByColumn; private bool orderByPosition; private bool reverse; /// <summary> /// Constructor /// </summary> /// <param name="key">The spreadsheet key</param> /// <param name="worksheetId">The unique identifier or position of the worksheet</param> /// <param name="visibility">public or private</param> /// <param name="projection">full, values, or basic</param> public ListQuery(string key, string worksheetId, string visibility, string projection) : base("https://spreadsheets.google.com/feeds/list/" + key + "/" + worksheetId + "/" + visibility + "/" + projection) { Reset(); } /// <summary> /// Constructor - Sets the base URI /// </summary> /// <param name="baseUri">The feed base</param> /// <param name="key">The spreadsheet key</param> /// <param name="worksheetId">The unique identifier or position of the worksheet</param> /// <param name="visibility">public or private</param> /// <param name="projection">full, values, or basic</param> public ListQuery(string baseUri, string key, string worksheetId, string visibility, string projection) : base(baseUri + "/" + key + "/" + worksheetId + "/" + visibility + "/" + projection) { Reset(); } /// <summary> /// Constructor /// </summary> /// <param name="baseUri">The feed base with the key, worksheetId, visibility and /// projections are appended and delimited by "/"</param> public ListQuery(string baseUri) : base(baseUri) { Reset(); } /// <summary> /// A spreadsheet query string, if set to a non-null value, /// then the FullTextQuery will be set to null /// </summary> public string SpreadsheetQuery { get; set; } /// <summary> /// The header of the column to sort results by. Sets OrderByPosition to false. /// </summary> public string OrderByColumn { get { return orderByColumn; } set { if (value != null) { orderByPosition = false; } orderByColumn = value; } } /// <summary> /// If true, then results will be ordered by the position in the spreadsheet. /// Sets OrderByColumn to null. /// </summary> public bool OrderByPosition { get { return orderByPosition; } set { if (value) { orderByColumn = null; } orderByPosition = value; } } /// <summary> /// If true, then however the results are ordered will be reversed. /// </summary> public bool Reverse { get { return reverse; } set { if (OrderByColumn != null || OrderByPosition) { reverse = value; } } } /// <summary> /// Parses an incoming URI string and sets the instance variables /// of this object. /// </summary> /// <param name="targetUri">Takes an incoming Uri string and parses all the properties of it</param> /// <returns>Throws a query exception when it finds something wrong with the input, otherwise returns a baseuri.</returns> protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] delimiters = {'?', '&'}; string source = HttpUtility.UrlDecode(targetUri.Query); TokenCollection tokens = new TokenCollection(source, delimiters); foreach (string token in tokens) { if (token.Length > 0) { char[] otherDelimiters = {'='}; string[] parameters = token.Split(otherDelimiters, 2); switch (parameters[0]) { case "sq": SpreadsheetQuery = parameters[1]; break; case "orderby": if (parameters[1].Equals("position")) { OrderByPosition = true; } else if (parameters[1].StartsWith("column:")) { OrderByColumn = parameters[1].Substring(("column:").Length); } else { throw new ClientQueryException(); } break; case "reverse": Reverse = bool.Parse(parameters[1]); break; } } } } return Uri; } /// <summary> /// Resets object state to default, as if newly created. /// </summary> protected override void Reset() { base.Reset(); SpreadsheetQuery = null; OrderByColumn = null; OrderByPosition = false; Reverse = false; } /// <summary> /// Creates the partial URI query string based on all set properties. /// </summary> /// <returns> string => the query part of the URI </returns> protected override string CalculateQuery(string basePath) { string path = base.CalculateQuery(basePath); StringBuilder newPath = new StringBuilder(path, 2048); char paramInsertion = InsertionParameter(path); if (OrderByPosition) { newPath.Append(paramInsertion); newPath.Append("orderby=position"); paramInsertion = '&'; } else if (OrderByColumn != null && OrderByColumn.Length > 0) { newPath.Append(paramInsertion); newPath.AppendFormat(CultureInfo.InvariantCulture, "orderby=column:{0}", Utilities.UriEncodeReserved(OrderByColumn)); paramInsertion = '&'; } if (Reverse) { newPath.Append(paramInsertion); newPath.AppendFormat(CultureInfo.InvariantCulture, "reverse={0}", Utilities.UriEncodeReserved(true.ToString())); paramInsertion = '&'; } if (SpreadsheetQuery != null && SpreadsheetQuery.Length > 0) { newPath.Append(paramInsertion); newPath.AppendFormat(CultureInfo.InvariantCulture, "sq={0}", Utilities.UriEncodeReserved(SpreadsheetQuery)); paramInsertion = '&'; } return newPath.ToString(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Log; using Microsoft.Win32; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; /// <summary> /// Native utility methods. /// </summary> internal static class IgniteUtils { /** Environment variable: JAVA_HOME. */ private const string EnvJavaHome = "JAVA_HOME"; /** Lookup paths. */ private static readonly string[] JvmDllLookupPaths = {@"jre\bin\server", @"jre\bin\default"}; /** Registry lookup paths. */ private static readonly string[] JreRegistryKeys = { @"Software\JavaSoft\Java Runtime Environment", @"Software\Wow6432Node\JavaSoft\Java Runtime Environment" }; /** File: jvm.dll. */ internal const string FileJvmDll = "jvm.dll"; /** File: Ignite.Jni.dll. */ internal const string FileIgniteJniDll = "ignite.jni.dll"; /** Prefix for temp directory names. */ private const string DirIgniteTmp = "Ignite_"; /** Loaded. */ private static bool _loaded; /** Thread-local random. */ [ThreadStatic] private static Random _rnd; /// <summary> /// Initializes the <see cref="IgniteUtils"/> class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability.")] static IgniteUtils() { TryCleanTempDirectories(); } /// <summary> /// Gets thread local random. /// </summary> /// <value>Thread local random.</value> public static Random ThreadLocalRandom { get { return _rnd ?? (_rnd = new Random()); } } /// <summary> /// Returns shuffled list copy. /// </summary> /// <returns>Shuffled list copy.</returns> public static IList<T> Shuffle<T>(IList<T> list) { int cnt = list.Count; if (cnt > 1) { List<T> res = new List<T>(list); Random rnd = ThreadLocalRandom; while (cnt > 1) { cnt--; int idx = rnd.Next(cnt + 1); T val = res[idx]; res[idx] = res[cnt]; res[cnt] = val; } return res; } return list; } /// <summary> /// Load JVM DLL if needed. /// </summary> /// <param name="configJvmDllPath">JVM DLL path from config.</param> /// <param name="log">Log.</param> public static void LoadDlls(string configJvmDllPath, ILogger log) { if (_loaded) { log.Debug("JNI dll is already loaded."); return; } // 1. Load JNI dll. LoadJvmDll(configJvmDllPath, log); // 2. Load GG JNI dll. UnmanagedUtils.Initialize(); _loaded = true; } /// <summary> /// Create new instance of specified class. /// </summary> /// <param name="typeName">Class name</param> /// <param name="props">Properties to set.</param> /// <returns>New Instance.</returns> public static T CreateInstance<T>(string typeName, IEnumerable<KeyValuePair<string, object>> props = null) { IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); var type = new TypeResolver().ResolveType(typeName); if (type == null) throw new IgniteException("Failed to create class instance [className=" + typeName + ']'); var res = (T) Activator.CreateInstance(type); if (props != null) SetProperties(res, props); return res; } /// <summary> /// Set properties on the object. /// </summary> /// <param name="target">Target object.</param> /// <param name="props">Properties.</param> private static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props) { if (props == null) return; IgniteArgumentCheck.NotNull(target, "target"); Type typ = target.GetType(); foreach (KeyValuePair<string, object> prop in props) { PropertyInfo prop0 = typ.GetProperty(prop.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (prop0 == null) throw new IgniteException("Property is not found [type=" + typ.Name + ", property=" + prop.Key + ']'); prop0.SetValue(target, prop.Value, null); } } /// <summary> /// Loads the JVM DLL. /// </summary> private static void LoadJvmDll(string configJvmDllPath, ILogger log) { var messages = new List<string>(); foreach (var dllPath in GetJvmDllPaths(configJvmDllPath)) { log.Debug("Trying to load JVM dll from [option={0}, path={1}]...", dllPath.Key, dllPath.Value); var errCode = LoadDll(dllPath.Value, FileJvmDll); if (errCode == 0) { log.Debug("jvm.dll successfully loaded from [option={0}, path={1}]", dllPath.Key, dllPath.Value); return; } var message = string.Format(CultureInfo.InvariantCulture, "[option={0}, path={1}, error={2}]", dllPath.Key, dllPath.Value, FormatWin32Error(errCode)); messages.Add(message); log.Debug("Failed to load jvm.dll: " + message); if (dllPath.Value == configJvmDllPath) break; // if configJvmDllPath is specified and is invalid - do not try other options } if (!messages.Any()) // not loaded and no messages - everything was null messages.Add(string.Format(CultureInfo.InvariantCulture, "Please specify IgniteConfiguration.JvmDllPath or {0}.", EnvJavaHome)); if (messages.Count == 1) throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0} ({1})", FileJvmDll, messages[0])); var combinedMessage = messages.Aggregate((x, y) => string.Format(CultureInfo.InvariantCulture, "{0}\n{1}", x, y)); throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0}:\n{1}", FileJvmDll, combinedMessage)); } /// <summary> /// Formats the Win32 error. /// </summary> [ExcludeFromCodeCoverage] public static string FormatWin32Error(int errorCode) { if (errorCode == NativeMethods.ERROR_BAD_EXE_FORMAT) { var mode = Environment.Is64BitProcess ? "x64" : "x86"; return string.Format("DLL could not be loaded (193: ERROR_BAD_EXE_FORMAT). " + "This is often caused by x64/x86 mismatch. " + "Current process runs in {0} mode, and DLL is not {0}.", mode); } if (errorCode == NativeMethods.ERROR_MOD_NOT_FOUND) { return "DLL could not be loaded (126: ERROR_MOD_NOT_FOUND). " + "This can be caused by missing dependencies. " + "Make sure that Microsoft Visual C++ 2010 Redistributable Package is installed " + "(https://www.microsoft.com/en-us/download/details.aspx?id=14632)."; } return string.Format("{0}: {1}", errorCode, new Win32Exception(errorCode).Message); } /// <summary> /// Try loading DLLs first using file path, then using it's simple name. /// </summary> /// <param name="filePath"></param> /// <param name="simpleName"></param> /// <returns>Zero in case of success, error code in case of failure.</returns> private static int LoadDll(string filePath, string simpleName) { int res = 0; IntPtr ptr; if (filePath != null) { ptr = NativeMethods.LoadLibrary(filePath); if (ptr == IntPtr.Zero) res = Marshal.GetLastWin32Error(); else return res; } // Failed to load using file path, fallback to simple name. ptr = NativeMethods.LoadLibrary(simpleName); if (ptr == IntPtr.Zero) { // Preserve the first error code, if any. if (res == 0) res = Marshal.GetLastWin32Error(); } else res = 0; return res; } /// <summary> /// Gets the JVM DLL paths in order of lookup priority. /// </summary> private static IEnumerable<KeyValuePair<string, string>> GetJvmDllPaths(string configJvmDllPath) { if (!string.IsNullOrEmpty(configJvmDllPath)) yield return new KeyValuePair<string, string>("IgniteConfiguration.JvmDllPath", configJvmDllPath); var javaHomeDir = Environment.GetEnvironmentVariable(EnvJavaHome); if (!string.IsNullOrEmpty(javaHomeDir)) foreach (var path in JvmDllLookupPaths) yield return new KeyValuePair<string, string>(EnvJavaHome, Path.Combine(javaHomeDir, path, FileJvmDll)); // Get paths from the Windows Registry foreach (var regPath in JreRegistryKeys) { using (var jSubKey = Registry.LocalMachine.OpenSubKey(regPath)) { if (jSubKey == null) continue; var curVer = jSubKey.GetValue("CurrentVersion") as string; // Current version comes first var versions = new[] {curVer}.Concat(jSubKey.GetSubKeyNames().Where(x => x != curVer)); foreach (var ver in versions.Where(v => !string.IsNullOrEmpty(v))) { using (var verKey = jSubKey.OpenSubKey(ver)) { var dllPath = verKey == null ? null : verKey.GetValue("RuntimeLib") as string; if (dllPath != null) yield return new KeyValuePair<string, string>(verKey.Name, dllPath); } } } } } /// <summary> /// Unpacks an embedded resource into a temporary folder and returns the full path of resulting file. /// </summary> /// <param name="resourceName">Resource name.</param> /// <param name="fileName">Name of the resulting file.</param> /// <returns> /// Path to a temp file with an unpacked resource. /// </returns> public static string UnpackEmbeddedResource(string resourceName, string fileName) { var dllRes = Assembly.GetExecutingAssembly().GetManifestResourceNames() .Single(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase)); return WriteResourceToTempFile(dllRes, fileName); } /// <summary> /// Writes the resource to temporary file. /// </summary> /// <param name="resource">The resource.</param> /// <param name="name">File name prefix</param> /// <returns>Path to the resulting temp file.</returns> private static string WriteResourceToTempFile(string resource, string name) { // Dll file name should not be changed, so we create a temp folder with random name instead. var file = Path.Combine(GetTempDirectoryName(), name); using (var src = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) using (var dest = File.OpenWrite(file)) { // ReSharper disable once PossibleNullReferenceException src.CopyTo(dest); return file; } } /// <summary> /// Tries to clean temporary directories created with <see cref="GetTempDirectoryName"/>. /// </summary> private static void TryCleanTempDirectories() { foreach (var dir in Directory.GetDirectories(Path.GetTempPath(), DirIgniteTmp + "*")) { try { Directory.Delete(dir, true); } catch (IOException) { // Expected } catch (UnauthorizedAccessException) { // Expected } } } /// <summary> /// Creates a uniquely named, empty temporary directory on disk and returns the full path of that directory. /// </summary> /// <returns>The full path of the temporary directory.</returns> internal static string GetTempDirectoryName() { while (true) { var dir = Path.Combine(Path.GetTempPath(), DirIgniteTmp + Path.GetRandomFileName()); try { return Directory.CreateDirectory(dir).FullName; } catch (IOException) { // Expected } catch (UnauthorizedAccessException) { // Expected } } } /// <summary> /// Convert unmanaged char array to string. /// </summary> /// <param name="chars">Char array.</param> /// <param name="charsLen">Char array length.</param> /// <returns></returns> public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen) { IntPtr ptr = new IntPtr(chars); if (ptr == IntPtr.Zero) return null; byte[] arr = new byte[charsLen]; Marshal.Copy(ptr, arr, 0, arr.Length); return Encoding.UTF8.GetString(arr); } /// <summary> /// Convert string to unmanaged byte array. /// </summary> /// <param name="str">String.</param> /// <returns>Unmanaged byte array.</returns> public static unsafe sbyte* StringToUtf8Unmanaged(string str) { var ptr = IntPtr.Zero; if (str != null) { byte[] strBytes = Encoding.UTF8.GetBytes(str); ptr = Marshal.AllocHGlobal(strBytes.Length + 1); Marshal.Copy(strBytes, 0, ptr, strBytes.Length); *((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator. } return (sbyte*)ptr.ToPointer(); } /// <summary> /// Reads node collection from stream. /// </summary> /// <param name="reader">Reader.</param> /// <param name="pred">The predicate.</param> /// <returns> Nodes list or null. </returns> public static List<IClusterNode> ReadNodes(BinaryReader reader, Func<ClusterNodeImpl, bool> pred = null) { var cnt = reader.ReadInt(); if (cnt < 0) return null; var res = new List<IClusterNode>(cnt); var ignite = reader.Marshaller.Ignite; if (pred == null) { for (var i = 0; i < cnt; i++) res.Add(ignite.GetNode(reader.ReadGuid())); } else { for (var i = 0; i < cnt; i++) { var node = ignite.GetNode(reader.ReadGuid()); if (pred(node)) res.Add(node); } } return res; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.Util { using System; using System.Collections.Generic; using NPOI.SS.UserModel; /** * Various utility functions that make working with a cells and rows easier. The various methods * that deal with style's allow you to create your CellStyles as you need them. When you apply a * style change to a cell, the code will attempt to see if a style already exists that meets your * needs. If not, then it will create a new style. This is to prevent creating too many styles. * there is an upper limit in Excel on the number of styles that can be supported. * *@author Eric Pugh epugh@upstate.com *@author (secondary) Avinash Kewalramani akewalramani@accelrys.com */ public class CellUtil { public const string ALIGNMENT = "alignment"; public const string BORDER_BOTTOM = "borderBottom"; public const string BORDER_LEFT = "borderLeft"; public const string BORDER_RIGHT = "borderRight"; public const string BORDER_TOP = "borderTop"; public const string BOTTOM_BORDER_COLOR = "bottomBorderColor"; public const string DATA_FORMAT = "dataFormat"; public const string FILL_BACKGROUND_COLOR = "fillBackgroundColor"; public const string FILL_FOREGROUND_COLOR = "fillForegroundColor"; public const string FILL_PATTERN = "fillPattern"; public const string FONT = "font"; public const string HIDDEN = "hidden"; public const string INDENTION = "indention"; public const string LEFT_BORDER_COLOR = "leftBorderColor"; public const string LOCKED = "locked"; public const string RIGHT_BORDER_COLOR = "rightBorderColor"; public const string ROTATION = "rotation"; public const string TOP_BORDER_COLOR = "topBorderColor"; public const string VERTICAL_ALIGNMENT = "verticalAlignment"; public const string WRAP_TEXT = "wrapText"; private static UnicodeMapping[] unicodeMappings; private class UnicodeMapping { public String entityName; public String resolvedValue; public UnicodeMapping(String pEntityName, String pResolvedValue) { entityName = "&" + pEntityName + ";"; resolvedValue = pResolvedValue; } } private CellUtil() { // no instances of this class } public static ICell CopyCell(IRow row, int sourceIndex, int targetIndex) { if (sourceIndex == targetIndex) throw new ArgumentException("sourceIndex and targetIndex cannot be same"); // Grab a copy of the old/new cell ICell oldCell = row.GetCell(sourceIndex); // If the old cell is null jump to next cell if (oldCell == null) { return null; } ICell newCell = row.GetCell(targetIndex); if (newCell == null) //not exist { newCell = row.CreateCell(targetIndex); } else { //TODO:shift cells } // Copy style from old cell and apply to new cell if (oldCell.CellStyle != null) { newCell.CellStyle = oldCell.CellStyle; } // If there is a cell comment, copy if (oldCell.CellComment != null) { newCell.CellComment = oldCell.CellComment; } // If there is a cell hyperlink, copy if (oldCell.Hyperlink != null) { newCell.Hyperlink = oldCell.Hyperlink; } // Set the cell data type newCell.SetCellType(oldCell.CellType); // Set the cell data value switch (oldCell.CellType) { case CellType.Blank: newCell.SetCellValue(oldCell.StringCellValue); break; case CellType.Boolean: newCell.SetCellValue(oldCell.BooleanCellValue); break; case CellType.Error: newCell.SetCellErrorValue(oldCell.ErrorCellValue); break; case CellType.Formula: newCell.SetCellFormula(oldCell.CellFormula); break; case CellType.Numeric: newCell.SetCellValue(oldCell.NumericCellValue); break; case CellType.String: newCell.SetCellValue(oldCell.RichStringCellValue); break; } return newCell; } /** * Get a row from the spreadsheet, and create it if it doesn't exist. * *@param rowIndex The 0 based row number *@param sheet The sheet that the row is part of. *@return The row indicated by the rowCounter */ public static IRow GetRow(int rowIndex, ISheet sheet) { IRow row = sheet.GetRow(rowIndex); if (row == null) { row = sheet.CreateRow(rowIndex); } return row; } /** * Get a specific cell from a row. If the cell doesn't exist, then create it. * *@param row The row that the cell is part of *@param columnIndex The column index that the cell is in. *@return The cell indicated by the column. */ public static ICell GetCell(IRow row, int columnIndex) { ICell cell = row.GetCell(columnIndex); if (cell == null) { cell = row.CreateCell(columnIndex); } return cell; } /** * Creates a cell, gives it a value, and applies a style if provided * * @param row the row to create the cell in * @param column the column index to create the cell in * @param value The value of the cell * @param style If the style is not null, then set * @return A new Cell */ public static ICell CreateCell(IRow row, int column, String value, ICellStyle style) { ICell cell = GetCell(row, column); cell.SetCellValue(cell.Row.Sheet.Workbook.GetCreationHelper() .CreateRichTextString(value)); if (style != null) { cell.CellStyle = style; } return cell; } /** * Create a cell, and give it a value. * *@param row the row to create the cell in *@param column the column index to create the cell in *@param value The value of the cell *@return A new Cell. */ public static ICell CreateCell(IRow row, int column, String value) { return CreateCell(row, column, value, null); } /** * Take a cell, and align it. * *@param cell the cell to set the alignment for *@param workbook The workbook that is being worked with. *@param align the column alignment to use. * * @see CellStyle for alignment options */ public static void SetAlignment(ICell cell, IWorkbook workbook, short align) { SetCellStyleProperty(cell, workbook, ALIGNMENT, align); } /** * Take a cell, and apply a font to it * *@param cell the cell to set the alignment for *@param workbook The workbook that is being worked with. *@param font The Font that you want to set... */ public static void SetFont(ICell cell, IWorkbook workbook, IFont font) { SetCellStyleProperty(cell, workbook, FONT, font.Index); } /** * This method attempt to find an already existing CellStyle that matches what you want the * style to be. If it does not find the style, then it creates a new one. If it does create a * new one, then it applies the propertyName and propertyValue to the style. This is necessary * because Excel has an upper limit on the number of Styles that it supports. * *@param workbook The workbook that is being worked with. *@param propertyName The name of the property that is to be changed. *@param propertyValue The value of the property that is to be changed. *@param cell The cell that needs it's style changes */ public static void SetCellStyleProperty(ICell cell, IWorkbook workbook, String propertyName, Object propertyValue) { ICellStyle originalStyle = cell.CellStyle; ICellStyle newStyle = null; Dictionary<String, Object> values = GetFormatProperties(originalStyle); if (values.ContainsKey(propertyName)) values[propertyName] = propertyValue; else values.Add(propertyName, propertyValue); // index seems like what index the cellstyle is in the list of styles for a workbook. // not good to compare on! short numberCellStyles = workbook.NumCellStyles; for (short i = 0; i < numberCellStyles; i++) { ICellStyle wbStyle = workbook.GetCellStyleAt(i); Dictionary<String, Object> wbStyleMap = GetFormatProperties(wbStyle); if (values.Keys.Count != wbStyleMap.Keys.Count) continue; bool found = true; foreach (string key in values.Keys) { if (!wbStyleMap.ContainsKey(key)) { found = false; break; } if (values[key].Equals(wbStyleMap[key])) continue; found = false; break; } if (found) { newStyle = wbStyle; break; } } if (newStyle == null) { newStyle = workbook.CreateCellStyle(); SetFormatProperties(newStyle, workbook, values); } cell.CellStyle = newStyle; } /** * Returns a map containing the format properties of the given cell style. * * @param style cell style * @return map of format properties (String -> Object) * @see #setFormatProperties(org.apache.poi.ss.usermodel.CellStyle, org.apache.poi.ss.usermodel.Workbook, java.util.Map) */ private static Dictionary<String, Object> GetFormatProperties(ICellStyle style) { Dictionary<String, Object> properties = new Dictionary<String, Object>(); PutShort(properties, ALIGNMENT, (short)style.Alignment); PutShort(properties, BORDER_BOTTOM, (short)style.BorderBottom); PutShort(properties, BORDER_LEFT, (short)style.BorderLeft); PutShort(properties, BORDER_RIGHT, (short)style.BorderRight); PutShort(properties, BORDER_TOP, (short)style.BorderTop); PutShort(properties, BOTTOM_BORDER_COLOR, style.BottomBorderColor); PutShort(properties, DATA_FORMAT, style.DataFormat); PutShort(properties, FILL_BACKGROUND_COLOR, style.FillBackgroundColor); PutShort(properties, FILL_FOREGROUND_COLOR, style.FillForegroundColor); PutShort(properties, FILL_PATTERN, (short)style.FillPattern); PutShort(properties, FONT, style.FontIndex); PutBoolean(properties, HIDDEN, style.IsHidden); PutShort(properties, INDENTION, style.Indention); PutShort(properties, LEFT_BORDER_COLOR, style.LeftBorderColor); PutBoolean(properties, LOCKED, style.IsLocked); PutShort(properties, RIGHT_BORDER_COLOR, style.RightBorderColor); PutShort(properties, ROTATION, style.Rotation); PutShort(properties, TOP_BORDER_COLOR, style.TopBorderColor); PutShort(properties, VERTICAL_ALIGNMENT, (short)style.VerticalAlignment); PutBoolean(properties, WRAP_TEXT, style.WrapText); return properties; } /** * Sets the format properties of the given style based on the given map. * * @param style cell style * @param workbook parent workbook * @param properties map of format properties (String -> Object) * @see #getFormatProperties(CellStyle) */ private static void SetFormatProperties(ICellStyle style, IWorkbook workbook, Dictionary<String, Object> properties) { style.Alignment = (HorizontalAlignment)GetShort(properties, ALIGNMENT); style.BorderBottom = (BorderStyle)GetShort(properties, BORDER_BOTTOM); style.BorderLeft = (BorderStyle)GetShort(properties, BORDER_LEFT); style.BorderRight = (BorderStyle)GetShort(properties, BORDER_RIGHT); style.BorderTop = (BorderStyle)GetShort(properties, BORDER_TOP); style.BottomBorderColor = GetShort(properties, BOTTOM_BORDER_COLOR); style.DataFormat =GetShort(properties, DATA_FORMAT); style.FillBackgroundColor = GetShort(properties, FILL_BACKGROUND_COLOR); style.FillForegroundColor = GetShort(properties, FILL_FOREGROUND_COLOR); style.FillPattern = (FillPattern)GetShort(properties, FILL_PATTERN); style.SetFont(workbook.GetFontAt(GetShort(properties, FONT))); style.IsHidden = GetBoolean(properties, HIDDEN); style.Indention = GetShort(properties, INDENTION); style.LeftBorderColor = GetShort(properties, LEFT_BORDER_COLOR); style.IsLocked = GetBoolean(properties, LOCKED); style.RightBorderColor = GetShort(properties, RIGHT_BORDER_COLOR); style.Rotation = GetShort(properties, ROTATION); style.TopBorderColor = GetShort(properties, TOP_BORDER_COLOR); style.VerticalAlignment = (VerticalAlignment)GetShort(properties, VERTICAL_ALIGNMENT); style.WrapText = GetBoolean(properties, WRAP_TEXT); } /** * Utility method that returns the named short value form the given map. * @return zero if the property does not exist, or is not a {@link Short}. * * @param properties map of named properties (String -> Object) * @param name property name * @return property value, or zero */ private static short GetShort(Dictionary<String, Object> properties, String name) { Object value = properties[name]; short result = 0; if (short.TryParse(value.ToString(), out result)) return result; return 0; } /** * Utility method that returns the named boolean value form the given map. * @return false if the property does not exist, or is not a {@link Boolean}. * * @param properties map of properties (String -> Object) * @param name property name * @return property value, or false */ private static bool GetBoolean(Dictionary<String, Object> properties, String name) { Object value = properties[name]; bool result = false; if (bool.TryParse(value.ToString(), out result)) return result; return false; } /** * Utility method that puts the named short value to the given map. * * @param properties map of properties (String -> Object) * @param name property name * @param value property value */ private static void PutShort(Dictionary<String, Object> properties, String name, short value) { if (properties.ContainsKey(name)) properties[name] = value; else properties.Add(name, value); } /** * Utility method that puts the named boolean value to the given map. * * @param properties map of properties (String -> Object) * @param name property name * @param value property value */ private static void PutBoolean(Dictionary<String, Object> properties, String name, bool value) { if (properties.ContainsKey(name)) properties[name] = value; else properties.Add(name, value); } /** * Looks for text in the cell that should be unicode, like an alpha and provides the * unicode version of it. * *@param cell The cell to check for unicode values *@return translated to unicode */ public static ICell TranslateUnicodeValues(ICell cell) { String s = cell.RichStringCellValue.String; bool foundUnicode = false; String lowerCaseStr = s.ToLower(); for (int i = 0; i < unicodeMappings.Length; i++) { UnicodeMapping entry = unicodeMappings[i]; String key = entry.entityName; if (lowerCaseStr.IndexOf(key, StringComparison.Ordinal) != -1) { s = s.Replace(key, entry.resolvedValue); foundUnicode = true; } } if (foundUnicode) { cell.SetCellValue(cell.Row.Sheet.Workbook.GetCreationHelper() .CreateRichTextString(s)); } return cell; } static CellUtil() { unicodeMappings = new UnicodeMapping[] { um("alpha", "\u03B1" ), um("beta", "\u03B2" ), um("gamma", "\u03B3" ), um("delta", "\u03B4" ), um("epsilon", "\u03B5" ), um("zeta", "\u03B6" ), um("eta", "\u03B7" ), um("theta", "\u03B8" ), um("iota", "\u03B9" ), um("kappa", "\u03BA" ), um("lambda", "\u03BB" ), um("mu", "\u03BC" ), um("nu", "\u03BD" ), um("xi", "\u03BE" ), um("omicron", "\u03BF" ), }; } private static UnicodeMapping um(String entityName, String resolvedValue) { return new UnicodeMapping(entityName, resolvedValue); } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.EntityState.Appearance { /// <summary> /// Enumeration values for LifeFormAppearance (es.appear.lifeform, Life Forms Kind, /// section 4.3.3) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public struct LifeFormAppearance { /// <summary> /// Describes the paint scheme of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the paint scheme of an entity")] public enum PaintSchemeValue : uint { /// <summary> /// Uniform color /// </summary> UniformColor = 0, /// <summary> /// Camouflage /// </summary> Camouflage = 1 } /// <summary> /// Describes the damaged visual appearance of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the damaged visual appearance of an entity")] public enum HealthValue : uint { /// <summary> /// No injury /// </summary> NoInjury = 0, /// <summary> /// Slight injury /// </summary> SlightInjury = 1, /// <summary> /// Moderate injury /// </summary> ModerateInjury = 2, /// <summary> /// Fatal injury /// </summary> FatalInjury = 3 } /// <summary> /// Describes compliance of life form /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes compliance of life form")] public enum ComplianceValue : uint { /// <summary> /// null /// </summary> Unknown = 0, /// <summary> /// Detained /// </summary> Detained = 1, /// <summary> /// Surrender /// </summary> Surrender = 2, /// <summary> /// Using fists /// </summary> UsingFists = 3, /// <summary> /// Verbal abuse level 1 /// </summary> VerbalAbuseLevel1 = 4, /// <summary> /// Verbal abuse level 2 /// </summary> VerbalAbuseLevel2 = 5, /// <summary> /// Verbal abuse level 3 /// </summary> VerbalAbuseLevel3 = 6, /// <summary> /// Passive resistance level 1 /// </summary> PassiveResistanceLevel1 = 7, /// <summary> /// Passive resistance level 2 /// </summary> PassiveResistanceLevel2 = 8, /// <summary> /// Passive resistance level 3 /// </summary> PassiveResistanceLevel3 = 9, /// <summary> /// Using non-lethal weapon 1 /// </summary> UsingNonLethalWeapon1 = 10, /// <summary> /// Using non-lethal weapon 2 /// </summary> UsingNonLethalWeapon2 = 11, /// <summary> /// Using non-lethal weapon 3 /// </summary> UsingNonLethalWeapon3 = 12, /// <summary> /// Using non-lethal weapon 4 /// </summary> UsingNonLethalWeapon4 = 13, /// <summary> /// Using non-lethal weapon 5 /// </summary> UsingNonLethalWeapon5 = 14, /// <summary> /// Using non-lethal weapon 6 /// </summary> UsingNonLethalWeapon6 = 15 } /// <summary> /// Describes whether Flash Lights are on or off. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether Flash Lights are on or off.")] public enum FlashLightsValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } /// <summary> /// Describes the state of the life form /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the state of the life form")] public enum LifeFormStateValue : uint { /// <summary> /// null /// </summary> Unknown = 0, /// <summary> /// Upright, standing still /// </summary> UprightStandingStill = 1, /// <summary> /// Upright, walking /// </summary> UprightWalking = 2, /// <summary> /// Upright, running /// </summary> UprightRunning = 3, /// <summary> /// Kneeling /// </summary> Kneeling = 4, /// <summary> /// Prone /// </summary> Prone = 5, /// <summary> /// Crawling /// </summary> Crawling = 6, /// <summary> /// Swimming /// </summary> Swimming = 7, /// <summary> /// Parachuting /// </summary> Parachuting = 8, /// <summary> /// Jumping /// </summary> Jumping = 9, /// <summary> /// Sitting /// </summary> Sitting = 10, /// <summary> /// Squatting /// </summary> Squatting = 11, /// <summary> /// Crouching /// </summary> Crouching = 12, /// <summary> /// Wading /// </summary> Wading = 13, /// <summary> /// Surrender /// </summary> Surrender = 14, /// <summary> /// Detained /// </summary> Detained = 15 } /// <summary> /// Describes the frozen status of a life form /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the frozen status of a life form")] public enum FrozenStatusValue : uint { /// <summary> /// Not frozen /// </summary> NotFrozen = 0, /// <summary> /// Frozen (Frozen entities should not be dead-reckoned, i.e. they should be displayed as fixed at the current location even if nonzero velocity, acceleration or rotation data is received from the frozen entity) /// </summary> FrozenFrozenEntitiesShouldNotBeDeadReckonedIETheyShouldBeDisplayedAsFixedAtTheCurrentLocationEvenIfNonzeroVelocityAccelerationOrRotationDataIsReceivedFromTheFrozenEntity = 1 } /// <summary> /// Describes the state of a life form /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the state of a life form")] public enum StateValue : uint { /// <summary> /// Active /// </summary> Active = 0, /// <summary> /// Deactivated /// </summary> Deactivated = 1 } /// <summary> /// Describes the position of the life form's primary weapon /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the position of the life form's primary weapon")] public enum Weapon1Value : uint { /// <summary> /// No primary weapon present /// </summary> NoPrimaryWeaponPresent = 0, /// <summary> /// Primary weapon is stowed /// </summary> PrimaryWeaponIsStowed = 1, /// <summary> /// Primary weapon is deployed /// </summary> PrimaryWeaponIsDeployed = 2, /// <summary> /// Primary weapon is in firing position /// </summary> PrimaryWeaponIsInFiringPosition = 3 } /// <summary> /// Describes the position of the life form's secondary weapon /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the position of the life form's secondary weapon")] public enum Weapon2Value : uint { /// <summary> /// No secondary weapon present /// </summary> NoSecondaryWeaponPresent = 0, /// <summary> /// Secondary weapon is stowed /// </summary> SecondaryWeaponIsStowed = 1, /// <summary> /// Secondary weapon is deployed /// </summary> SecondaryWeaponIsDeployed = 2, /// <summary> /// Secondary weapon is in firing position /// </summary> SecondaryWeaponIsInFiringPosition = 3 } /// <summary> /// Describes the type of camouflage /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the type of camouflage")] public enum CamouflageTypeValue : uint { /// <summary> /// Desert camouflage /// </summary> DesertCamouflage = 0, /// <summary> /// Winter camouflage /// </summary> WinterCamouflage = 1, /// <summary> /// Forest camouflage /// </summary> ForestCamouflage = 2, /// <summary> /// null /// </summary> Unknown = 3 } /// <summary> /// Describes the type of stationary concealment /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the type of stationary concealment")] public enum ConcealedStationaryValue : uint { /// <summary> /// Not concealed /// </summary> NotConcealed = 0, /// <summary> /// Entity in a prepared concealed position /// </summary> EntityInAPreparedConcealedPosition = 1 } /// <summary> /// Describes the type of concealed movement /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the type of concealed movement")] public enum ConcealedMovementValue : uint { /// <summary> /// Open movement /// </summary> OpenMovement = 0, /// <summary> /// Rushes between covered positions /// </summary> RushesBetweenCoveredPositions = 1 } private LifeFormAppearance.PaintSchemeValue paintScheme; private LifeFormAppearance.HealthValue health; private LifeFormAppearance.ComplianceValue compliance; private LifeFormAppearance.FlashLightsValue flashLights; private LifeFormAppearance.LifeFormStateValue lifeFormState; private LifeFormAppearance.FrozenStatusValue frozenStatus; private LifeFormAppearance.StateValue state; private LifeFormAppearance.Weapon1Value weapon1; private LifeFormAppearance.Weapon2Value weapon2; private LifeFormAppearance.CamouflageTypeValue camouflageType; private LifeFormAppearance.ConcealedStationaryValue concealedStationary; private LifeFormAppearance.ConcealedMovementValue concealedMovement; /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(LifeFormAppearance left, LifeFormAppearance right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(LifeFormAppearance left, LifeFormAppearance right) { if (object.ReferenceEquals(left, right)) { return true; } // If parameters are null return false (cast to object to prevent recursive loop!) if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> to <see cref="System.UInt32"/>. /// </summary> /// <param name="obj">The <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> scheme instance.</param> /// <returns>The result of the conversion.</returns> public static explicit operator uint(LifeFormAppearance obj) { return obj.ToUInt32(); } /// <summary> /// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/>. /// </summary> /// <param name="value">The uint value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator LifeFormAppearance(uint value) { return LifeFormAppearance.FromUInt32(value); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance from the byte array. /// </summary> /// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/>.</param> /// <param name="index">The starting position within value.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance, represented by a byte array.</returns> /// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception> /// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception> public static LifeFormAppearance FromByteArray(byte[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length - 1 || index + 4 > array.Length - 1) { throw new IndexOutOfRangeException(); } return FromUInt32(BitConverter.ToUInt32(array, index)); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance from the uint value. /// </summary> /// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance, represented by the uint value.</returns> public static LifeFormAppearance FromUInt32(uint value) { LifeFormAppearance ps = new LifeFormAppearance(); uint mask0 = 0x0001; byte shift0 = 0; uint newValue0 = value & mask0 >> shift0; ps.PaintScheme = (LifeFormAppearance.PaintSchemeValue)newValue0; uint mask2 = 0x0018; byte shift2 = 3; uint newValue2 = value & mask2 >> shift2; ps.Health = (LifeFormAppearance.HealthValue)newValue2; uint mask3 = 0x01e0; byte shift3 = 5; uint newValue3 = value & mask3 >> shift3; ps.Compliance = (LifeFormAppearance.ComplianceValue)newValue3; uint mask5 = 0x1000; byte shift5 = 12; uint newValue5 = value & mask5 >> shift5; ps.FlashLights = (LifeFormAppearance.FlashLightsValue)newValue5; uint mask7 = 0xf0000; byte shift7 = 16; uint newValue7 = value & mask7 >> shift7; ps.LifeFormState = (LifeFormAppearance.LifeFormStateValue)newValue7; uint mask9 = 0x200000; byte shift9 = 21; uint newValue9 = value & mask9 >> shift9; ps.FrozenStatus = (LifeFormAppearance.FrozenStatusValue)newValue9; uint mask11 = 0x800000; byte shift11 = 23; uint newValue11 = value & mask11 >> shift11; ps.State = (LifeFormAppearance.StateValue)newValue11; uint mask12 = 0x3000000; byte shift12 = 24; uint newValue12 = value & mask12 >> shift12; ps.Weapon1 = (LifeFormAppearance.Weapon1Value)newValue12; uint mask13 = 0xc000000; byte shift13 = 26; uint newValue13 = value & mask13 >> shift13; ps.Weapon2 = (LifeFormAppearance.Weapon2Value)newValue13; uint mask14 = 0x30000000; byte shift14 = 28; uint newValue14 = value & mask14 >> shift14; ps.CamouflageType = (LifeFormAppearance.CamouflageTypeValue)newValue14; uint mask15 = 0x40000000; byte shift15 = 30; uint newValue15 = value & mask15 >> shift15; ps.ConcealedStationary = (LifeFormAppearance.ConcealedStationaryValue)newValue15; uint mask16 = 0x80000000; byte shift16 = 31; uint newValue16 = value & mask16 >> shift16; ps.ConcealedMovement = (LifeFormAppearance.ConcealedMovementValue)newValue16; return ps; } /// <summary> /// Gets or sets the paintscheme. /// </summary> /// <value>The paintscheme.</value> public LifeFormAppearance.PaintSchemeValue PaintScheme { get { return this.paintScheme; } set { this.paintScheme = value; } } /// <summary> /// Gets or sets the health. /// </summary> /// <value>The health.</value> public LifeFormAppearance.HealthValue Health { get { return this.health; } set { this.health = value; } } /// <summary> /// Gets or sets the compliance. /// </summary> /// <value>The compliance.</value> public LifeFormAppearance.ComplianceValue Compliance { get { return this.compliance; } set { this.compliance = value; } } /// <summary> /// Gets or sets the flashlights. /// </summary> /// <value>The flashlights.</value> public LifeFormAppearance.FlashLightsValue FlashLights { get { return this.flashLights; } set { this.flashLights = value; } } /// <summary> /// Gets or sets the lifeformstate. /// </summary> /// <value>The lifeformstate.</value> public LifeFormAppearance.LifeFormStateValue LifeFormState { get { return this.lifeFormState; } set { this.lifeFormState = value; } } /// <summary> /// Gets or sets the frozenstatus. /// </summary> /// <value>The frozenstatus.</value> public LifeFormAppearance.FrozenStatusValue FrozenStatus { get { return this.frozenStatus; } set { this.frozenStatus = value; } } /// <summary> /// Gets or sets the state. /// </summary> /// <value>The state.</value> public LifeFormAppearance.StateValue State { get { return this.state; } set { this.state = value; } } /// <summary> /// Gets or sets the weapon1. /// </summary> /// <value>The weapon1.</value> public LifeFormAppearance.Weapon1Value Weapon1 { get { return this.weapon1; } set { this.weapon1 = value; } } /// <summary> /// Gets or sets the weapon2. /// </summary> /// <value>The weapon2.</value> public LifeFormAppearance.Weapon2Value Weapon2 { get { return this.weapon2; } set { this.weapon2 = value; } } /// <summary> /// Gets or sets the camouflagetype. /// </summary> /// <value>The camouflagetype.</value> public LifeFormAppearance.CamouflageTypeValue CamouflageType { get { return this.camouflageType; } set { this.camouflageType = value; } } /// <summary> /// Gets or sets the concealedstationary. /// </summary> /// <value>The concealedstationary.</value> public LifeFormAppearance.ConcealedStationaryValue ConcealedStationary { get { return this.concealedStationary; } set { this.concealedStationary = value; } } /// <summary> /// Gets or sets the concealedmovement. /// </summary> /// <value>The concealedmovement.</value> public LifeFormAppearance.ConcealedMovementValue ConcealedMovement { get { return this.concealedMovement; } set { this.concealedMovement = value; } } /// <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) { if (obj == null) { return false; } if (!(obj is LifeFormAppearance)) { return false; } return this.Equals((LifeFormAppearance)obj); } /// <summary> /// Determines whether the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(LifeFormAppearance other) { // If parameter is null return false (cast to object to prevent recursive loop!) if ((object)other == null) { return false; } return this.PaintScheme == other.PaintScheme && this.Health == other.Health && this.Compliance == other.Compliance && this.FlashLights == other.FlashLights && this.LifeFormState == other.LifeFormState && this.FrozenStatus == other.FrozenStatus && this.State == other.State && this.Weapon1 == other.Weapon1 && this.Weapon2 == other.Weapon2 && this.CamouflageType == other.CamouflageType && this.ConcealedStationary == other.ConcealedStationary && this.ConcealedMovement == other.ConcealedMovement; } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> to the byte array. /// </summary> /// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance.</returns> public byte[] ToByteArray() { return BitConverter.GetBytes(this.ToUInt32()); } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> to the uint value. /// </summary> /// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.LifeFormAppearance"/> instance.</returns> public uint ToUInt32() { uint val = 0; val |= (uint)((uint)this.PaintScheme << 0); val |= (uint)((uint)this.Health << 3); val |= (uint)((uint)this.Compliance << 5); val |= (uint)((uint)this.FlashLights << 12); val |= (uint)((uint)this.LifeFormState << 16); val |= (uint)((uint)this.FrozenStatus << 21); val |= (uint)((uint)this.State << 23); val |= (uint)((uint)this.Weapon1 << 24); val |= (uint)((uint)this.Weapon2 << 26); val |= (uint)((uint)this.CamouflageType << 28); val |= (uint)((uint)this.ConcealedStationary << 30); val |= (uint)((uint)this.ConcealedMovement << 31); return val; } /// <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() { int hash = 17; // Overflow is fine, just wrap unchecked { hash = (hash * 29) + this.PaintScheme.GetHashCode(); hash = (hash * 29) + this.Health.GetHashCode(); hash = (hash * 29) + this.Compliance.GetHashCode(); hash = (hash * 29) + this.FlashLights.GetHashCode(); hash = (hash * 29) + this.LifeFormState.GetHashCode(); hash = (hash * 29) + this.FrozenStatus.GetHashCode(); hash = (hash * 29) + this.State.GetHashCode(); hash = (hash * 29) + this.Weapon1.GetHashCode(); hash = (hash * 29) + this.Weapon2.GetHashCode(); hash = (hash * 29) + this.CamouflageType.GetHashCode(); hash = (hash * 29) + this.ConcealedStationary.GetHashCode(); hash = (hash * 29) + this.ConcealedMovement.GetHashCode(); } return hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net.Http.HPack; using System.Reflection; using System.Text; using Microsoft.Net.Http.Headers; namespace CodeGenerator { public class KnownHeaders { public static readonly KnownHeader[] RequestHeaders; public static readonly KnownHeader[] ResponseHeaders; public static readonly KnownHeader[] ResponseTrailers; public static readonly string[] InternalHeaderAccessors = new[] { HeaderNames.Allow, HeaderNames.AltSvc, HeaderNames.TransferEncoding, HeaderNames.ContentLength, HeaderNames.Connection, HeaderNames.Scheme, HeaderNames.Path, HeaderNames.Method, HeaderNames.Authority, HeaderNames.Host, }; public static readonly string[] DefinedHeaderNames = typeof(HeaderNames).GetFields(BindingFlags.Static | BindingFlags.Public).Select(h => h.Name).ToArray(); public static readonly string[] ObsoleteHeaderNames = new[] { HeaderNames.DNT, }; public static readonly string[] PsuedoHeaderNames = new[] { "Authority", // :authority "Method", // :method "Path", // :path "Scheme", // :scheme "Status" // :status }; public static readonly string[] NonApiHeaders = ObsoleteHeaderNames .Concat(PsuedoHeaderNames) .ToArray(); public static readonly string[] ApiHeaderNames = DefinedHeaderNames .Except(NonApiHeaders) .ToArray(); public static readonly long InvalidH2H3ResponseHeadersBits; static KnownHeaders() { var requestPrimaryHeaders = new[] { HeaderNames.Accept, HeaderNames.Connection, HeaderNames.Host, HeaderNames.UserAgent }; var responsePrimaryHeaders = new[] { HeaderNames.Connection, HeaderNames.Date, HeaderNames.ContentType, HeaderNames.Server, HeaderNames.ContentLength, }; var commonHeaders = new[] { HeaderNames.CacheControl, HeaderNames.Connection, HeaderNames.Date, HeaderNames.GrpcEncoding, HeaderNames.KeepAlive, HeaderNames.Pragma, HeaderNames.TransferEncoding, HeaderNames.Upgrade, HeaderNames.Via, HeaderNames.Warning, HeaderNames.ContentType, }; // http://www.w3.org/TR/cors/#syntax var corsRequestHeaders = new[] { HeaderNames.Origin, HeaderNames.AccessControlRequestMethod, HeaderNames.AccessControlRequestHeaders, }; var requestHeadersExistence = new[] { HeaderNames.Connection, HeaderNames.TransferEncoding, }; var requestHeadersCount = new[] { HeaderNames.Host }; RequestHeaders = commonHeaders.Concat(new[] { HeaderNames.Authority, HeaderNames.Method, HeaderNames.Path, HeaderNames.Scheme, HeaderNames.Accept, HeaderNames.AcceptCharset, HeaderNames.AcceptEncoding, HeaderNames.AcceptLanguage, HeaderNames.Authorization, HeaderNames.Cookie, HeaderNames.Expect, HeaderNames.From, HeaderNames.GrpcAcceptEncoding, HeaderNames.GrpcTimeout, HeaderNames.Host, HeaderNames.IfMatch, HeaderNames.IfModifiedSince, HeaderNames.IfNoneMatch, HeaderNames.IfRange, HeaderNames.IfUnmodifiedSince, HeaderNames.MaxForwards, HeaderNames.ProxyAuthorization, HeaderNames.Referer, HeaderNames.Range, HeaderNames.TE, HeaderNames.Translate, HeaderNames.UserAgent, HeaderNames.UpgradeInsecureRequests, HeaderNames.RequestId, HeaderNames.CorrelationContext, HeaderNames.TraceParent, HeaderNames.TraceState, HeaderNames.Baggage, }) .Concat(corsRequestHeaders) .OrderBy(header => header) .OrderBy(header => !requestPrimaryHeaders.Contains(header)) .Select((header, index) => new KnownHeader { Name = header, Index = index, PrimaryHeader = requestPrimaryHeaders.Contains(header), ExistenceCheck = requestHeadersExistence.Contains(header), FastCount = requestHeadersCount.Contains(header) }) .Concat(new[] { new KnownHeader { Name = HeaderNames.ContentLength, Index = -1, PrimaryHeader = requestPrimaryHeaders.Contains(HeaderNames.ContentLength) }}) .ToArray(); var responseHeadersExistence = new[] { HeaderNames.Connection, HeaderNames.Server, HeaderNames.Date, HeaderNames.TransferEncoding, HeaderNames.AltSvc }; var enhancedHeaders = new[] { HeaderNames.Connection, HeaderNames.Server, HeaderNames.Date, HeaderNames.TransferEncoding, HeaderNames.AltSvc }; // http://www.w3.org/TR/cors/#syntax var corsResponseHeaders = new[] { HeaderNames.AccessControlAllowCredentials, HeaderNames.AccessControlAllowHeaders, HeaderNames.AccessControlAllowMethods, HeaderNames.AccessControlAllowOrigin, HeaderNames.AccessControlExposeHeaders, HeaderNames.AccessControlMaxAge, }; ResponseHeaders = commonHeaders.Concat(new[] { HeaderNames.AcceptRanges, HeaderNames.Age, HeaderNames.Allow, HeaderNames.AltSvc, HeaderNames.ETag, HeaderNames.Location, HeaderNames.ProxyAuthenticate, HeaderNames.ProxyConnection, HeaderNames.RetryAfter, HeaderNames.Server, HeaderNames.SetCookie, HeaderNames.Vary, HeaderNames.Expires, HeaderNames.WWWAuthenticate, HeaderNames.ContentRange, HeaderNames.ContentEncoding, HeaderNames.ContentLanguage, HeaderNames.ContentLocation, HeaderNames.ContentMD5, HeaderNames.LastModified, HeaderNames.Trailer, }) .Concat(corsResponseHeaders) .OrderBy(header => header) .OrderBy(header => !responsePrimaryHeaders.Contains(header)) .Select((header, index) => new KnownHeader { Name = header, Index = index, EnhancedSetter = enhancedHeaders.Contains(header), ExistenceCheck = responseHeadersExistence.Contains(header), PrimaryHeader = responsePrimaryHeaders.Contains(header) }) .Concat(new[] { new KnownHeader { Name = HeaderNames.ContentLength, Index = 63, EnhancedSetter = enhancedHeaders.Contains(HeaderNames.ContentLength), PrimaryHeader = responsePrimaryHeaders.Contains(HeaderNames.ContentLength) }}) .ToArray(); ResponseTrailers = new[] { HeaderNames.ETag, HeaderNames.GrpcMessage, HeaderNames.GrpcStatus } .OrderBy(header => header) .OrderBy(header => !responsePrimaryHeaders.Contains(header)) .Select((header, index) => new KnownHeader { Name = header, Index = index, EnhancedSetter = enhancedHeaders.Contains(header), ExistenceCheck = responseHeadersExistence.Contains(header), PrimaryHeader = responsePrimaryHeaders.Contains(header) }) .ToArray(); var invalidH2H3ResponseHeaders = new[] { HeaderNames.Connection, HeaderNames.TransferEncoding, HeaderNames.KeepAlive, HeaderNames.Upgrade, HeaderNames.ProxyConnection }; InvalidH2H3ResponseHeadersBits = ResponseHeaders .Where(header => invalidH2H3ResponseHeaders.Contains(header.Name)) .Select(header => 1L << header.Index) .Aggregate((a, b) => a | b); } static string Each<T>(IEnumerable<T> values, Func<T, string> formatter) { return values.Any() ? values.Select(formatter).Aggregate((a, b) => a + b) : ""; } static string Each<T>(IEnumerable<T> values, Func<T, int, string> formatter) { return values.Any() ? values.Select(formatter).Aggregate((a, b) => a + b) : ""; } static string AppendSwitch(IEnumerable<IGrouping<int, KnownHeader>> values) => $@"switch (name.Length) {{{Each(values, byLength => $@" case {byLength.Key}:{AppendSwitchSection(byLength.Key, byLength.OrderBy(h => h, KnownHeaderComparer.Instance).ToList())} break;")} }}"; static string AppendHPackSwitch(IEnumerable<HPackGroup> values) => $@"switch (index) {{{Each(values, header => $@"{Each(header.HPackStaticTableIndexes, index => $@" case {index}:")} {AppendHPackSwitchSection(header)}")} }}"; static string AppendValue(bool returnTrue = false) => $@"// Matched a known header if ((_previousBits & flag) != 0) {{ // Had a previous string for this header, mark it as used so we don't clear it OnHeadersComplete or consider it if we get a second header _previousBits ^= flag; // We will only reuse this header if there was only one previous header if (values.Count == 1) {{ var previousValue = values.ToString(); // Check lengths are the same, then if the bytes were converted to an ascii string if they would be the same. // We do not consider Utf8 headers for reuse. if (previousValue.Length == value.Length && StringUtilities.BytesOrdinalEqualsStringAndAscii(previousValue, value)) {{ // The previous string matches what the bytes would convert to, so we will just use that one. _bits |= flag; return{(returnTrue ? " true" : "")}; }} }} }} // We didn't have a previous matching header value, or have already added a header, so get the string for this value. var valueStr = value.GetRequestHeaderString(nameStr, EncodingSelector, checkForNewlineChars); if ((_bits & flag) == 0) {{ // We didn't already have a header set, so add a new one. _bits |= flag; values = new StringValues(valueStr); }} else {{ // We already had a header set, so concatenate the new one. values = AppendValue(values, valueStr); }}"; static string AppendHPackSwitchSection(HPackGroup group) { var header = group.Header; if (header.Name == HeaderNames.ContentLength) { return $@"var customEncoding = ReferenceEquals(EncodingSelector, KestrelServerOptions.DefaultHeaderEncodingSelector) ? null : EncodingSelector(HeaderNames.ContentLength); if (customEncoding == null) {{ AppendContentLength(value); }} else {{ AppendContentLengthCustomEncoding(value, customEncoding); }} return true;"; } else { return $@"flag = {header.FlagBit()}; values = ref _headers._{header.Identifier}; nameStr = HeaderNames.{header.Identifier}; break;"; } } static string AppendSwitchSection(int length, IList<KnownHeader> values) { var useVarForFirstTerm = values.Count > 1 && values.Select(h => h.FirstNameIgnoreCaseSegment()).Distinct().Count() == 1; var firstTermVarExpression = values.Select(h => h.FirstNameIgnoreCaseSegment()).FirstOrDefault(); var firstTermVar = $"firstTerm{length}"; var start = ""; if (useVarForFirstTerm) { start = $@" var {firstTermVar} = {firstTermVarExpression};"; } else { firstTermVar = ""; } string GenerateIfBody(KnownHeader header, string extraIndent = "") { if (header.Name == HeaderNames.ContentLength) { return $@" {extraIndent}var customEncoding = ReferenceEquals(EncodingSelector, KestrelServerOptions.DefaultHeaderEncodingSelector) {extraIndent} ? null : EncodingSelector(HeaderNames.ContentLength); {extraIndent}if (customEncoding == null) {extraIndent}{{ {extraIndent} AppendContentLength(value); {extraIndent}}} {extraIndent}else {extraIndent}{{ {extraIndent} AppendContentLengthCustomEncoding(value, customEncoding); {extraIndent}}} {extraIndent}return;"; } else { return $@" {extraIndent}flag = {header.FlagBit()}; {extraIndent}values = ref _headers._{header.Identifier}; {extraIndent}nameStr = HeaderNames.{header.Identifier};"; } } // Group headers together that have the same ignore equal case equals check for the first term. // There will probably only be more than one item in a group for Content-Encoding, Content-Language, Content-Location. var groups = values.GroupBy(header => header.EqualIgnoreCaseBytesFirstTerm()) .OrderBy(g => g.First(), KnownHeaderComparer.Instance) .ToList(); return start + $@"{Each(groups, (byFirstTerm, i) => $@"{(byFirstTerm.Count() == 1 ? $@"{Each(byFirstTerm, header => $@" {(i > 0 ? "else " : "")}if ({header.EqualIgnoreCaseBytes(firstTermVar)}) {{{GenerateIfBody(header)} }}")}" : $@" if ({byFirstTerm.Key.Replace(firstTermVarExpression, firstTermVar)}) {{{Each(byFirstTerm, (header, i) => $@" {(i > 0 ? "else " : "")}if ({header.EqualIgnoreCaseBytesSecondTermOnwards()}) {{{GenerateIfBody(header, extraIndent: " ")} }}")} }}")}")}"; } [DebuggerDisplay("{Name}")] public class KnownHeader { public string Name { get; set; } public int Index { get; set; } public string Identifier => ResolveIdentifier(Name); public byte[] Bytes => Encoding.ASCII.GetBytes($"\r\n{Name}: "); public int BytesOffset { get; set; } public int BytesCount { get; set; } public bool ExistenceCheck { get; set; } public bool FastCount { get; set; } public bool EnhancedSetter { get; set; } public bool PrimaryHeader { get; set; } public string FlagBit() => $"{"0x" + (1L << Index).ToString("x", CultureInfo.InvariantCulture)}L"; public string TestBitCore(string name) => $"({name} & {"0x" + (1L << Index).ToString("x", CultureInfo.InvariantCulture)}L) != 0"; public string TestBit() => TestBitCore("_bits"); public string TestTempBit() => TestBitCore("tempBits"); public string TestNotTempBit() => $"(tempBits & ~{"0x" + (1L << Index).ToString("x", CultureInfo.InvariantCulture)}L) == 0"; public string TestNotBit() => $"(_bits & {"0x" + (1L << Index).ToString("x", CultureInfo.InvariantCulture)}L) == 0"; public string SetBit() => $"_bits |= {"0x" + (1L << Index).ToString("x", CultureInfo.InvariantCulture)}L"; public string ClearBit() => $"_bits &= ~{"0x" + (1L << Index).ToString("x", CultureInfo.InvariantCulture)}L"; private string ResolveIdentifier(string name) { // Check the 3 lowercase headers switch (name) { case "baggage": return "Baggage"; case "traceparent": return "TraceParent"; case "tracestate": return "TraceState"; } var identifier = name.Replace("-", ""); // Pseudo headers start with a colon. A colon isn't valid in C# names so // remove it and pascal case the header name. e.g. :path -> Path, :scheme -> Scheme. // This identifier will match the names in HeadersNames.cs if (identifier.StartsWith(':')) { identifier = char.ToUpperInvariant(identifier[1]) + identifier.Substring(2); } return identifier; } private void GetMaskAndComp(string name, int offset, int count, out ulong mask, out ulong comp) { mask = 0; comp = 0; for (var scan = 0; scan < count; scan++) { var ch = (byte)name[offset + count - scan - 1]; var isAlpha = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); comp = (comp << 8) + (ch & (isAlpha ? 0xdfu : 0xffu)); mask = (mask << 8) + (isAlpha ? 0xdfu : 0xffu); } } private string NameTerm(string name, int offset, int count, string type, string suffix) { GetMaskAndComp(name, offset, count, out var mask, out var comp); if (offset == 0) { if (type == "byte") { return $"(nameStart & 0x{mask:x}{suffix})"; } else { return $"(ReadUnalignedLittleEndian_{type}(ref nameStart) & 0x{mask:x}{suffix})"; } } else { if (type == "byte") { return $"(Unsafe.AddByteOffset(ref nameStart, (IntPtr){offset / count}) & 0x{mask:x}{suffix})"; } else if ((offset / count) == 1) { return $"(ReadUnalignedLittleEndian_{type}(ref Unsafe.AddByteOffset(ref nameStart, (IntPtr)sizeof({type}))) & 0x{mask:x}{suffix})"; } else { return $"(ReadUnalignedLittleEndian_{type}(ref Unsafe.AddByteOffset(ref nameStart, (IntPtr)({offset / count} * sizeof({type})))) & 0x{mask:x}{suffix})"; } } } private string EqualityTerm(string name, int offset, int count, string type, string suffix) { GetMaskAndComp(name, offset, count, out var mask, out var comp); return $"0x{comp:x}{suffix}"; } private string Term(string name, int offset, int count, string type, string suffix) { GetMaskAndComp(name, offset, count, out var mask, out var comp); return $"({NameTerm(name, offset, count, type, suffix)} == {EqualityTerm(name, offset, count, type, suffix)})"; } public string FirstNameIgnoreCaseSegment() { var result = ""; if (Name.Length >= 8) { result = NameTerm(Name, 0, 8, "ulong", "uL"); } else if (Name.Length >= 4) { result = NameTerm(Name, 0, 4, "uint", "u"); } else if (Name.Length >= 2) { result = NameTerm(Name, 0, 2, "ushort", "u"); } else { result = NameTerm(Name, 0, 1, "byte", "u"); } return result; } public string EqualIgnoreCaseBytes(string firstTermVar = "") { if (!string.IsNullOrEmpty(firstTermVar)) { return EqualIgnoreCaseBytesWithVar(firstTermVar); } var result = ""; var delim = ""; var index = 0; while (index != Name.Length) { if (Name.Length - index >= 8) { result += delim + Term(Name, index, 8, "ulong", "uL"); index += 8; } else if (Name.Length - index >= 4) { result += delim + Term(Name, index, 4, "uint", "u"); index += 4; } else if (Name.Length - index >= 2) { result += delim + Term(Name, index, 2, "ushort", "u"); index += 2; } else { result += delim + Term(Name, index, 1, "byte", "u"); index += 1; } delim = " && "; } return result; string EqualIgnoreCaseBytesWithVar(string firstTermVar) { var result = ""; var delim = " && "; var index = 0; var isFirst = true; while (index != Name.Length) { if (Name.Length - index >= 8) { if (isFirst) { result = $"({firstTermVar} == {EqualityTerm(Name, index, 8, "ulong", "uL")})"; } else { result += delim + Term(Name, index, 8, "ulong", "uL"); } index += 8; } else if (Name.Length - index >= 4) { if (isFirst) { result = $"({firstTermVar} == {EqualityTerm(Name, index, 4, "uint", "u")})"; } else { result += delim + Term(Name, index, 4, "uint", "u"); } index += 4; } else if (Name.Length - index >= 2) { if (isFirst) { result = $"({firstTermVar} == {EqualityTerm(Name, index, 2, "ushort", "u")})"; } else { result += delim + Term(Name, index, 2, "ushort", "u"); } index += 2; } else { if (isFirst) { result = $"({firstTermVar} == {EqualityTerm(Name, index, 1, "byte", "u")})"; } else { result += delim + Term(Name, index, 1, "byte", "u"); } index += 1; } isFirst = false; } return result; } } public string EqualIgnoreCaseBytesFirstTerm() { var result = ""; if (Name.Length >= 8) { result = Term(Name, 0, 8, "ulong", "uL"); } else if (Name.Length >= 4) { result = Term(Name, 0, 4, "uint", "u"); } else if (Name.Length >= 2) { result = Term(Name, 0, 2, "ushort", "u"); } else { result = Term(Name, 0, 1, "byte", "u"); } return result; } public string EqualIgnoreCaseBytesSecondTermOnwards() { var result = ""; var delim = ""; var index = 0; var isFirst = true; while (index != Name.Length) { if (Name.Length - index >= 8) { if (!isFirst) { result += delim + Term(Name, index, 8, "ulong", "uL"); } index += 8; } else if (Name.Length - index >= 4) { if (!isFirst) { result += delim + Term(Name, index, 4, "uint", "u"); } index += 4; } else if (Name.Length - index >= 2) { if (!isFirst) { result += delim + Term(Name, index, 2, "ushort", "u"); } index += 2; } else { if (!isFirst) { result += delim + Term(Name, index, 1, "byte", "u"); } index += 1; } if (isFirst) { isFirst = false; } else { delim = " && "; } } return result; } } public static string GeneratedFile() { var requestHeaders = RequestHeaders; Debug.Assert(requestHeaders.Length <= 64); Debug.Assert(requestHeaders.Max(x => x.Index) <= 62); // 63 for responseHeaders as it steals one bit for Content-Length in CopyTo(ref MemoryPoolIterator output) var responseHeaders = ResponseHeaders; Debug.Assert(responseHeaders.Length <= 63); Debug.Assert(responseHeaders.Count(x => x.Index == 63) == 1); var responseTrailers = ResponseTrailers; var allHeaderNames = RequestHeaders.Concat(ResponseHeaders).Concat(ResponseTrailers) .Select(h => h.Identifier).Distinct().OrderBy(n => n, StringComparer.InvariantCulture).ToArray(); var loops = new[] { new { Headers = requestHeaders, HeadersByLength = requestHeaders.OrderBy(x => x.Name.Length).GroupBy(x => x.Name.Length), ClassName = "HttpRequestHeaders", Bytes = default(byte[]) }, new { Headers = responseHeaders, HeadersByLength = responseHeaders.OrderBy(x => x.Name.Length).GroupBy(x => x.Name.Length), ClassName = "HttpResponseHeaders", Bytes = responseHeaders.SelectMany(header => header.Bytes).ToArray() }, new { Headers = responseTrailers, HeadersByLength = responseTrailers.OrderBy(x => x.Name.Length).GroupBy(x => x.Name.Length), ClassName = "HttpResponseTrailers", Bytes = responseTrailers.SelectMany(header => header.Bytes).ToArray() } }; foreach (var loop in loops.Where(l => l.Bytes != null)) { var offset = 0; foreach (var header in loop.Headers) { header.BytesOffset = offset; header.BytesCount += header.Bytes.Length; offset += header.BytesCount; } } var s = $@"// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Buffers; using System.Buffers.Binary; using System.IO.Pipelines; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; #nullable enable namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http {{ internal enum KnownHeaderType {{ Unknown,{Each(allHeaderNames, n => @" " + n + ",")} }} internal partial class HttpHeaders {{ {GetHeaderLookup()} }} {Each(loops, loop => $@" internal partial class {loop.ClassName} : IHeaderDictionary {{{(loop.Bytes != null ? $@" private static ReadOnlySpan<byte> HeaderBytes => new byte[] {{ {Each(loop.Bytes, b => $"{b},")} }};" : "")} private HeaderReferences _headers; {Each(loop.Headers.Where(header => header.ExistenceCheck), header => $@" public bool Has{header.Identifier} => {header.TestBit()};")} {Each(loop.Headers.Where(header => header.FastCount), header => $@" public int {header.Identifier}Count => _headers._{header.Identifier}.Count;")} {Each(loop.Headers.Where(header => Array.IndexOf(InternalHeaderAccessors, header.Name) >= 0), header => $@" public {(header.Name == HeaderNames.Connection ? "override " : "")}StringValues Header{header.Identifier} {{{(header.Name == HeaderNames.ContentLength ? $@" get {{ StringValues value = default; if (_contentLength.HasValue) {{ value = new StringValues(HeaderUtilities.FormatNonNegativeInt64(_contentLength.Value)); }} return value; }} set {{ _contentLength = ParseContentLength(value.ToString()); }}" : $@" get {{ StringValues value = default; if ({header.TestBit()}) {{ value = _headers._{header.Identifier}; }} return value; }} set {{ if (!StringValues.IsNullOrEmpty(value)) {{ {header.SetBit()}; }} else {{ {header.ClearBit()}; }} _headers._{header.Identifier} = value; {(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")} }}")} }}")} {Each(loop.Headers.Where(header => header.Name != HeaderNames.ContentLength && !NonApiHeaders.Contains(header.Identifier)), header => $@" StringValues IHeaderDictionary.{header.Identifier} {{ get {{ var value = _headers._{header.Identifier}; if ({header.TestBit()}) {{ return value; }} return default; }} set {{ if (_isReadOnly) {{ ThrowHeadersReadOnlyException(); }} var flag = {header.FlagBit()}; if (value.Count > 0) {{{(loop.ClassName != "HttpRequestHeaders" ? $@" ValidateHeaderValueCharacters(HeaderNames.{header.Identifier}, value, EncodingSelector);" : "")} _bits |= flag; _headers._{header.Identifier} = value; }} else {{ _bits &= ~flag; _headers._{header.Identifier} = default; }}{(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")} }} }}")} {Each(ApiHeaderNames.Where(header => header != "ContentLength" && !loop.Headers.Select(kh => kh.Identifier).Contains(header)), header => $@" StringValues IHeaderDictionary.{header} {{ get {{ StringValues value = default; if (!TryGetUnknown(HeaderNames.{header}, ref value)) {{ value = default; }} return value; }} set {{ if (_isReadOnly) {{ ThrowHeadersReadOnlyException(); }}{(loop.ClassName != "HttpRequestHeaders" ? $@" ValidateHeaderValueCharacters(HeaderNames.{header}, value, EncodingSelector);" : "")} SetValueUnknown(HeaderNames.{header}, value); }} }}")} {Each(loop.Headers.Where(header => header.EnhancedSetter), header => $@" public void SetRaw{header.Identifier}(StringValues value, byte[] raw) {{ {header.SetBit()}; _headers._{header.Identifier} = value; _headers._raw{header.Identifier} = raw; }}")} protected override int GetCountFast() {{ return (_contentLength.HasValue ? 1 : 0 ) + BitOperations.PopCount((ulong)_bits) + (MaybeUnknown?.Count ?? 0); }} protected override bool TryGetValueFast(string key, out StringValues value) {{ value = default; switch (key.Length) {{{Each(loop.HeadersByLength, byLength => $@" case {byLength.Key}: {{{Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (ReferenceEquals(HeaderNames.{header.Identifier}, key)) {{{(header.Name == HeaderNames.ContentLength ? @" if (_contentLength.HasValue) { value = HeaderUtilities.FormatNonNegativeInt64(_contentLength.Value); return true; } return false;" : $@" if ({header.TestBit()}) {{ value = _headers._{header.Identifier}; return true; }} return false;")} }}")} {Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (HeaderNames.{header.Identifier}.Equals(key, StringComparison.OrdinalIgnoreCase)) {{{(header.Name == HeaderNames.ContentLength ? @" if (_contentLength.HasValue) { value = HeaderUtilities.FormatNonNegativeInt64(_contentLength.Value); return true; } return false;" : $@" if ({header.TestBit()}) {{ value = _headers._{header.Identifier}; return true; }} return false;")} }}")} break; }}")} }} return TryGetUnknown(key, ref value); }} protected override void SetValueFast(string key, StringValues value) {{{(loop.ClassName != "HttpRequestHeaders" ? @" ValidateHeaderValueCharacters(key, value, EncodingSelector);" : "")} switch (key.Length) {{{Each(loop.HeadersByLength, byLength => $@" case {byLength.Key}: {{{Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (ReferenceEquals(HeaderNames.{header.Identifier}, key)) {{{(header.Name == HeaderNames.ContentLength ? $@" _contentLength = ParseContentLength(value.ToString());" : $@" {header.SetBit()}; _headers._{header.Identifier} = value;{(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")}")} return; }}")} {Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (HeaderNames.{header.Identifier}.Equals(key, StringComparison.OrdinalIgnoreCase)) {{{(header.Name == HeaderNames.ContentLength ? $@" _contentLength = ParseContentLength(value.ToString());" : $@" {header.SetBit()}; _headers._{header.Identifier} = value;{(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")}")} return; }}")} break; }}")} }} SetValueUnknown(key, value); }} protected override bool AddValueFast(string key, StringValues value) {{{(loop.ClassName != "HttpRequestHeaders" ? @" ValidateHeaderValueCharacters(key, value, EncodingSelector);" : "")} switch (key.Length) {{{Each(loop.HeadersByLength, byLength => $@" case {byLength.Key}: {{{Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (ReferenceEquals(HeaderNames.{header.Identifier}, key)) {{{(header.Name == HeaderNames.ContentLength ? $@" if (!_contentLength.HasValue) {{ _contentLength = ParseContentLength(value.ToString()); return true; }} return false;" : $@" if ({header.TestNotBit()}) {{ {header.SetBit()}; _headers._{header.Identifier} = value;{(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")} return true; }} return false;")} }}")} {Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (HeaderNames.{header.Identifier}.Equals(key, StringComparison.OrdinalIgnoreCase)) {{{(header.Name == HeaderNames.ContentLength ? $@" if (!_contentLength.HasValue) {{ _contentLength = ParseContentLength(value.ToString()); return true; }} return false;" : $@" if ({header.TestNotBit()}) {{ {header.SetBit()}; _headers._{header.Identifier} = value;{(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")} return true; }} return false;")} }}")} break; }}")} }} return AddValueUnknown(key, value); }} protected override bool RemoveFast(string key) {{ switch (key.Length) {{{Each(loop.HeadersByLength, byLength => $@" case {byLength.Key}: {{{Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (ReferenceEquals(HeaderNames.{header.Identifier}, key)) {{{(header.Name == HeaderNames.ContentLength ? @" if (_contentLength.HasValue) { _contentLength = null; return true; } return false;" : $@" if ({header.TestBit()}) {{ {header.ClearBit()}; _headers._{header.Identifier} = default(StringValues);{(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")} return true; }} return false;")} }}")} {Each(byLength.OrderBy(h => !h.PrimaryHeader), header => $@" if (HeaderNames.{header.Identifier}.Equals(key, StringComparison.OrdinalIgnoreCase)) {{{(header.Name == HeaderNames.ContentLength ? @" if (_contentLength.HasValue) { _contentLength = null; return true; } return false;" : $@" if ({header.TestBit()}) {{ {header.ClearBit()}; _headers._{header.Identifier} = default(StringValues);{(header.EnhancedSetter == false ? "" : $@" _headers._raw{header.Identifier} = null;")} return true; }} return false;")} }}")} break; }}")} }} return RemoveUnknown(key); }} {(loop.ClassName != "HttpRequestHeaders" ? $@" protected override void ClearFast() {{ MaybeUnknown?.Clear(); _contentLength = null; var tempBits = _bits; _bits = 0; if(BitOperations.PopCount((ulong)tempBits) > 12) {{ _headers = default(HeaderReferences); return; }} {Each(loop.Headers.Where(header => header.Identifier != "ContentLength").OrderBy(h => !h.PrimaryHeader), header => $@" if ({header.TestTempBit()}) {{ _headers._{header.Identifier} = default; if({header.TestNotTempBit()}) {{ return; }} tempBits &= ~{"0x" + (1L << header.Index).ToString("x", CultureInfo.InvariantCulture)}L; }} ")} }} " : $@" private void Clear(long bitsToClear) {{ var tempBits = bitsToClear; {Each(loop.Headers.Where(header => header.Identifier != "ContentLength").OrderBy(h => !h.PrimaryHeader), header => $@" if ({header.TestTempBit()}) {{ _headers._{header.Identifier} = default; if({header.TestNotTempBit()}) {{ return; }} tempBits &= ~{"0x" + (1L << header.Index).ToString("x" , CultureInfo.InvariantCulture)}L; }} ")} }} ")} protected override bool CopyToFast(KeyValuePair<string, StringValues>[] array, int arrayIndex) {{ if (arrayIndex < 0) {{ return false; }} {Each(loop.Headers.Where(header => header.Identifier != "ContentLength"), header => $@" if ({header.TestBit()}) {{ if (arrayIndex == array.Length) {{ return false; }} array[arrayIndex] = new KeyValuePair<string, StringValues>(HeaderNames.{header.Identifier}, _headers._{header.Identifier}); ++arrayIndex; }}")} if (_contentLength.HasValue) {{ if (arrayIndex == array.Length) {{ return false; }} array[arrayIndex] = new KeyValuePair<string, StringValues>(HeaderNames.ContentLength, HeaderUtilities.FormatNonNegativeInt64(_contentLength.Value)); ++arrayIndex; }} ((ICollection<KeyValuePair<string, StringValues>>?)MaybeUnknown)?.CopyTo(array, arrayIndex); return true; }} {(loop.ClassName == "HttpResponseHeaders" ? $@" internal bool HasInvalidH2H3Headers => (_bits & {InvalidH2H3ResponseHeadersBits}) != 0; internal void ClearInvalidH2H3Headers() {{ _bits &= ~{InvalidH2H3ResponseHeadersBits}; }} internal unsafe void CopyToFast(ref BufferWriter<PipeWriter> output) {{ var tempBits = (ulong)_bits; // Set exact next var next = BitOperations.TrailingZeroCount(tempBits); // Output Content-Length now as it isn't contained in the bit flags. if (_contentLength.HasValue) {{ output.Write(HeaderBytes.Slice(640, 18)); output.WriteNumeric((ulong)ContentLength.GetValueOrDefault()); }} if (tempBits == 0) {{ return; }} ref readonly StringValues values = ref Unsafe.AsRef<StringValues>(null); do {{ int keyStart; int keyLength; var headerName = string.Empty; switch (next) {{{Each(loop.Headers.OrderBy(h => h.Index).Where(h => h.Identifier != "ContentLength"), header => $@" case {header.Index}: // Header: ""{header.Name}"" Debug.Assert({header.TestTempBit()});{(header.EnhancedSetter == false ? $@" values = ref _headers._{header.Identifier}; keyStart = {header.BytesOffset}; keyLength = {header.BytesCount};" : $@" if (_headers._raw{header.Identifier} != null) {{ // Clear and set next as not using common output. tempBits ^= {"0x" + (1L << header.Index).ToString("x", CultureInfo.InvariantCulture)}L; next = BitOperations.TrailingZeroCount(tempBits); output.Write(_headers._raw{header.Identifier}); continue; // Jump to next, already output header }} else {{ values = ref _headers._{header.Identifier}; keyStart = {header.BytesOffset}; keyLength = {header.BytesCount}; headerName = HeaderNames.{header.Identifier}; }}")} break; // OutputHeader ")} default: ThrowInvalidHeaderBits(); return; }} // OutputHeader {{ // Clear bit tempBits ^= (1UL << next); var encoding = ReferenceEquals(EncodingSelector, KestrelServerOptions.DefaultHeaderEncodingSelector) ? null : EncodingSelector(headerName); var valueCount = values.Count; Debug.Assert(valueCount > 0); var headerKey = HeaderBytes.Slice(keyStart, keyLength); for (var i = 0; i < valueCount; i++) {{ var value = values[i]; if (value != null) {{ output.Write(headerKey); if (encoding is null) {{ output.WriteAscii(value); }} else {{ output.WriteEncoded(value, encoding); }} }} }} // Set exact next next = BitOperations.TrailingZeroCount(tempBits); }} }} while (tempBits != 0); }}" : "")}{(loop.ClassName == "HttpRequestHeaders" ? $@" {Each(new string[] {"ushort", "uint", "ulong"}, type => $@" [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe {type} ReadUnalignedLittleEndian_{type}(ref byte source) {{ {type} result = Unsafe.ReadUnaligned<{type}>(ref source); if (!BitConverter.IsLittleEndian) {{ result = BinaryPrimitives.ReverseEndianness(result); }} return result; }}")} [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe void Append(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value, bool checkForNewlineChars) {{ ref byte nameStart = ref MemoryMarshal.GetReference(name); var nameStr = string.Empty; ref StringValues values = ref Unsafe.AsRef<StringValues>(null); var flag = 0L; // Does the name match any ""known"" headers {AppendSwitch(loop.Headers.GroupBy(x => x.Name.Length).OrderBy(x => x.Key))} if (flag != 0) {{ {AppendValue()} }} else {{ // The header was not one of the ""known"" headers. // Convert value to string first, because passing two spans causes 8 bytes stack zeroing in // this method with rep stosd, which is slower than necessary. nameStr = name.GetHeaderName(); var valueStr = value.GetRequestHeaderString(nameStr, EncodingSelector, checkForNewlineChars); AppendUnknownHeaders(nameStr, valueStr); }} }} [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe bool TryHPackAppend(int index, ReadOnlySpan<byte> value) {{ ref StringValues values = ref Unsafe.AsRef<StringValues>(null); var nameStr = string.Empty; var flag = 0L; var checkForNewlineChars = true; // Does the HPack static index match any ""known"" headers {AppendHPackSwitch(GroupHPack(loop.Headers))} if (flag != 0) {{ {AppendValue(returnTrue: true)} return true; }} else {{ return false; }} }}" : "")} private struct HeaderReferences {{{Each(loop.Headers.Where(header => header.Identifier != "ContentLength"), header => @" public StringValues _" + header.Identifier + ";")} {Each(loop.Headers.Where(header => header.EnhancedSetter), header => @" public byte[]? _raw" + header.Identifier + ";")} }} public partial struct Enumerator {{ // Compiled to Jump table public bool MoveNext() {{ switch (_next) {{{Each(loop.Headers.Where(header => header.Identifier != "ContentLength"), header => $@" case {header.Index}: // Header: ""{header.Name}"" Debug.Assert({header.TestBitCore("_currentBits")}); _current = new KeyValuePair<string, StringValues>(HeaderNames.{header.Identifier}, _collection._headers._{header.Identifier}); {(loop.ClassName.Contains("Request") ? "" : @$"_currentKnownType = KnownHeaderType.{header.Identifier}; ")}_currentBits ^= {"0x" + (1L << header.Index).ToString("x", CultureInfo.InvariantCulture)}L; break;")} {(!loop.ClassName.Contains("Trailers") ? $@"case {loop.Headers.Length - 1}: // Header: ""Content-Length"" Debug.Assert(_currentBits == 0); _current = new KeyValuePair<string, StringValues>(HeaderNames.ContentLength, HeaderUtilities.FormatNonNegativeInt64(_collection._contentLength.GetValueOrDefault())); {(loop.ClassName.Contains("Request") ? "" : @"_currentKnownType = KnownHeaderType.ContentLength; ")}_next = -1; return true;" : "")} default: if (!_hasUnknown || !_unknownEnumerator.MoveNext()) {{ _current = default(KeyValuePair<string, StringValues>); {(loop.ClassName.Contains("Request") ? "" : @"_currentKnownType = default; ")}return false; }} _current = _unknownEnumerator.Current; {(loop.ClassName.Contains("Request") ? "" : @"_currentKnownType = KnownHeaderType.Unknown; ")}return true; }} if (_currentBits != 0) {{ _next = BitOperations.TrailingZeroCount(_currentBits); return true; }} else {{ {(!loop.ClassName.Contains("Trailers") ? $@"_next = _collection._contentLength.HasValue ? {loop.Headers.Length - 1} : -1;" : "_next = -1;")} return true; }} }} }} }} ")}}}"; return s; } private static string GetHeaderLookup() { return @$"private readonly static HashSet<string> _internedHeaderNames = new HashSet<string>({DefinedHeaderNames.Length}, StringComparer.OrdinalIgnoreCase) {{{Each(DefinedHeaderNames, (h) => @" HeaderNames." + h + ",")} }};"; } private static IEnumerable<HPackGroup> GroupHPack(KnownHeader[] headers) { var staticHeaders = new (int Index, HeaderField HeaderField)[H2StaticTable.Count]; for (var i = 0; i < H2StaticTable.Count; i++) { staticHeaders[i] = (i + 1, H2StaticTable.Get(i)); } var groupedHeaders = staticHeaders.GroupBy(h => Encoding.ASCII.GetString(h.HeaderField.Name)).Select(g => { return new HPackGroup { Name = g.Key, Header = headers.SingleOrDefault(knownHeader => string.Equals(knownHeader.Name, g.Key, StringComparison.OrdinalIgnoreCase)), HPackStaticTableIndexes = g.Select(h => h.Index).ToArray() }; }).Where(g => g.Header != null).ToList(); return groupedHeaders; } private class HPackGroup { public int[] HPackStaticTableIndexes { get; set; } public KnownHeader Header { get; set; } public string Name { get; set; } } private class KnownHeaderComparer : IComparer<KnownHeader> { public static readonly KnownHeaderComparer Instance = new KnownHeaderComparer(); public int Compare(KnownHeader x, KnownHeader y) { // Primary headers appear first if (x.PrimaryHeader && !y.PrimaryHeader) { return -1; } if (y.PrimaryHeader && !x.PrimaryHeader) { return 1; } // Then alphabetical return StringComparer.InvariantCulture.Compare(x.Name, y.Name); } } } }
using Assets.PostProcessing.Runtime; using Assets.PostProcessing.Runtime.Utils; using UnityEditorInternal; using UnityEngine; namespace UnityEditor.PostProcessing { using HistogramMode = PostProcessingProfile.MonitorSettings.HistogramMode; public class HistogramMonitor : PostProcessingMonitor { static GUIContent s_MonitorTitle = new GUIContent("Histogram"); ComputeShader m_ComputeShader; ComputeBuffer m_Buffer; Material m_Material; RenderTexture m_HistogramTexture; Rect m_MonitorAreaRect; public HistogramMonitor() { m_ComputeShader = EditorResources.Load<ComputeShader>("Monitors/HistogramCompute.compute"); } public override void Dispose() { GraphicsUtils.Destroy(m_Material); GraphicsUtils.Destroy(m_HistogramTexture); if (m_Buffer != null) m_Buffer.Release(); m_Material = null; m_HistogramTexture = null; m_Buffer = null; } public override bool IsSupported() { return m_ComputeShader != null && GraphicsUtils.supportsDX11; } public override GUIContent GetMonitorTitle() { return s_MonitorTitle; } public override void OnMonitorSettings() { EditorGUI.BeginChangeCheck(); bool refreshOnPlay = m_MonitorSettings.refreshOnPlay; var mode = m_MonitorSettings.histogramMode; refreshOnPlay = GUILayout.Toggle(refreshOnPlay, new GUIContent(FxStyles.playIcon, "Keep refreshing the histogram in play mode; this may impact performances."), FxStyles.preButton); mode = (HistogramMode)EditorGUILayout.EnumPopup(mode, FxStyles.preDropdown, GUILayout.MaxWidth(100f)); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(m_BaseEditor.serializedObject.targetObject, "Histogram Settings Changed"); m_MonitorSettings.refreshOnPlay = refreshOnPlay; m_MonitorSettings.histogramMode = mode; InternalEditorUtility.RepaintAllViews(); } } public override void OnMonitorGUI(Rect r) { if (Event.current.type == EventType.Repaint) { // If m_MonitorAreaRect isn't set the preview was just opened so refresh the render to get the histogram data if (Mathf.Approximately(m_MonitorAreaRect.width, 0) && Mathf.Approximately(m_MonitorAreaRect.height, 0)) InternalEditorUtility.RepaintAllViews(); // Sizing float width = m_HistogramTexture != null ? Mathf.Min(m_HistogramTexture.width, r.width - 65f) : r.width; float height = m_HistogramTexture != null ? Mathf.Min(m_HistogramTexture.height, r.height - 45f) : r.height; m_MonitorAreaRect = new Rect( Mathf.Floor(r.x + r.width / 2f - width / 2f), Mathf.Floor(r.y + r.height / 2f - height / 2f - 5f), width, height ); if (m_HistogramTexture != null) { Graphics.DrawTexture(m_MonitorAreaRect, m_HistogramTexture); var color = Color.white; const float kTickSize = 5f; // Rect, lines & ticks points if (m_MonitorSettings.histogramMode == HistogramMode.RGBSplit) { // A B C D E // N F // M G // L K J I H var A = new Vector3(m_MonitorAreaRect.x - 1f, m_MonitorAreaRect.y - 1f); var E = new Vector3(A.x + m_MonitorAreaRect.width + 2f, m_MonitorAreaRect.y - 1f); var H = new Vector3(E.x, E.y + m_MonitorAreaRect.height + 2f); var L = new Vector3(A.x, H.y); var N = new Vector3(A.x, A.y + (L.y - A.y) / 3f); var M = new Vector3(A.x, A.y + (L.y - A.y) * 2f / 3f); var F = new Vector3(E.x, E.y + (H.y - E.y) / 3f); var G = new Vector3(E.x, E.y + (H.y - E.y) * 2f / 3f); var C = new Vector3(A.x + (E.x - A.x) / 2f, A.y); var J = new Vector3(L.x + (H.x - L.x) / 2f, L.y); var B = new Vector3(A.x + (C.x - A.x) / 2f, A.y); var D = new Vector3(C.x + (E.x - C.x) / 2f, C.y); var I = new Vector3(J.x + (H.x - J.x) / 2f, J.y); var K = new Vector3(L.x + (J.x - L.x) / 2f, L.y); // Borders Handles.color = color; Handles.DrawLine(A, E); Handles.DrawLine(E, H); Handles.DrawLine(H, L); Handles.DrawLine(L, new Vector3(A.x, A.y - 1f)); // Vertical ticks Handles.DrawLine(A, new Vector3(A.x - kTickSize, A.y)); Handles.DrawLine(N, new Vector3(N.x - kTickSize, N.y)); Handles.DrawLine(M, new Vector3(M.x - kTickSize, M.y)); Handles.DrawLine(L, new Vector3(L.x - kTickSize, L.y)); Handles.DrawLine(E, new Vector3(E.x + kTickSize, E.y)); Handles.DrawLine(F, new Vector3(F.x + kTickSize, F.y)); Handles.DrawLine(G, new Vector3(G.x + kTickSize, G.y)); Handles.DrawLine(H, new Vector3(H.x + kTickSize, H.y)); // Horizontal ticks Handles.DrawLine(A, new Vector3(A.x, A.y - kTickSize)); Handles.DrawLine(B, new Vector3(B.x, B.y - kTickSize)); Handles.DrawLine(C, new Vector3(C.x, C.y - kTickSize)); Handles.DrawLine(D, new Vector3(D.x, D.y - kTickSize)); Handles.DrawLine(E, new Vector3(E.x, E.y - kTickSize)); Handles.DrawLine(L, new Vector3(L.x, L.y + kTickSize)); Handles.DrawLine(K, new Vector3(K.x, K.y + kTickSize)); Handles.DrawLine(J, new Vector3(J.x, J.y + kTickSize)); Handles.DrawLine(I, new Vector3(I.x, I.y + kTickSize)); Handles.DrawLine(H, new Vector3(H.x, H.y + kTickSize)); // Separators Handles.DrawLine(N, F); Handles.DrawLine(M, G); // Labels GUI.color = color; GUI.Label(new Rect(L.x - 15f, L.y + kTickSize - 4f, 30f, 30f), "0.0", FxStyles.tickStyleCenter); GUI.Label(new Rect(J.x - 15f, J.y + kTickSize - 4f, 30f, 30f), "0.5", FxStyles.tickStyleCenter); GUI.Label(new Rect(H.x - 15f, H.y + kTickSize - 4f, 30f, 30f), "1.0", FxStyles.tickStyleCenter); } else { // A B C D E // P F // O G // N H // M L K J I var A = new Vector3(m_MonitorAreaRect.x, m_MonitorAreaRect.y); var E = new Vector3(A.x + m_MonitorAreaRect.width + 1f, m_MonitorAreaRect.y); var I = new Vector3(E.x, E.y + m_MonitorAreaRect.height + 1f); var M = new Vector3(A.x, I.y); var C = new Vector3(A.x + (E.x - A.x) / 2f, A.y); var G = new Vector3(E.x, E.y + (I.y - E.y) / 2f); var K = new Vector3(M.x + (I.x - M.x) / 2f, M.y); var O = new Vector3(A.x, A.y + (M.y - A.y) / 2f); var P = new Vector3(A.x, A.y + (O.y - A.y) / 2f); var F = new Vector3(E.x, E.y + (G.y - E.y) / 2f); var N = new Vector3(A.x, O.y + (M.y - O.y) / 2f); var H = new Vector3(E.x, G.y + (I.y - G.y) / 2f); var B = new Vector3(A.x + (C.x - A.x) / 2f, A.y); var L = new Vector3(M.x + (K.x - M.x) / 2f, M.y); var D = new Vector3(C.x + (E.x - C.x) / 2f, A.y); var J = new Vector3(K.x + (I.x - K.x) / 2f, M.y); // Borders Handles.color = color; Handles.DrawLine(A, E); Handles.DrawLine(E, I); Handles.DrawLine(I, M); Handles.DrawLine(M, new Vector3(A.x, A.y - 1f)); // Vertical ticks Handles.DrawLine(A, new Vector3(A.x - kTickSize, A.y)); Handles.DrawLine(P, new Vector3(P.x - kTickSize, P.y)); Handles.DrawLine(O, new Vector3(O.x - kTickSize, O.y)); Handles.DrawLine(N, new Vector3(N.x - kTickSize, N.y)); Handles.DrawLine(M, new Vector3(M.x - kTickSize, M.y)); Handles.DrawLine(E, new Vector3(E.x + kTickSize, E.y)); Handles.DrawLine(F, new Vector3(F.x + kTickSize, F.y)); Handles.DrawLine(G, new Vector3(G.x + kTickSize, G.y)); Handles.DrawLine(H, new Vector3(H.x + kTickSize, H.y)); Handles.DrawLine(I, new Vector3(I.x + kTickSize, I.y)); // Horizontal ticks Handles.DrawLine(A, new Vector3(A.x, A.y - kTickSize)); Handles.DrawLine(B, new Vector3(B.x, B.y - kTickSize)); Handles.DrawLine(C, new Vector3(C.x, C.y - kTickSize)); Handles.DrawLine(D, new Vector3(D.x, D.y - kTickSize)); Handles.DrawLine(E, new Vector3(E.x, E.y - kTickSize)); Handles.DrawLine(M, new Vector3(M.x, M.y + kTickSize)); Handles.DrawLine(L, new Vector3(L.x, L.y + kTickSize)); Handles.DrawLine(K, new Vector3(K.x, K.y + kTickSize)); Handles.DrawLine(J, new Vector3(J.x, J.y + kTickSize)); Handles.DrawLine(I, new Vector3(I.x, I.y + kTickSize)); // Labels GUI.color = color; GUI.Label(new Rect(A.x - kTickSize - 34f, A.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleRight); GUI.Label(new Rect(O.x - kTickSize - 34f, O.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleRight); GUI.Label(new Rect(M.x - kTickSize - 34f, M.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleRight); GUI.Label(new Rect(E.x + kTickSize + 4f, E.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleLeft); GUI.Label(new Rect(G.x + kTickSize + 4f, G.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleLeft); GUI.Label(new Rect(I.x + kTickSize + 4f, I.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleLeft); GUI.Label(new Rect(M.x - 15f, M.y + kTickSize - 4f, 30f, 30f), "0.0", FxStyles.tickStyleCenter); GUI.Label(new Rect(K.x - 15f, K.y + kTickSize - 4f, 30f, 30f), "0.5", FxStyles.tickStyleCenter); GUI.Label(new Rect(I.x - 15f, I.y + kTickSize - 4f, 30f, 30f), "1.0", FxStyles.tickStyleCenter); } } } } public override void OnFrameData(RenderTexture source) { if (Application.isPlaying && !m_MonitorSettings.refreshOnPlay) return; if (Mathf.Approximately(m_MonitorAreaRect.width, 0) || Mathf.Approximately(m_MonitorAreaRect.height, 0)) return; float ratio = (float)source.width / (float)source.height; int h = 512; int w = Mathf.FloorToInt(h * ratio); var rt = RenderTexture.GetTemporary(w, h, 0, source.format); Graphics.Blit(source, rt); ComputeHistogram(rt); m_BaseEditor.Repaint(); RenderTexture.ReleaseTemporary(rt); } void CreateBuffer(int width, int height) { m_Buffer = new ComputeBuffer(width * height, sizeof(uint) << 2); } void ComputeHistogram(RenderTexture source) { if (m_Buffer == null) { CreateBuffer(256, 1); } else if (m_Buffer.count != 256) { m_Buffer.Release(); CreateBuffer(256, 1); } if (m_Material == null) { m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Histogram Render")) { hideFlags = HideFlags.DontSave }; } var channels = Vector4.zero; switch (m_MonitorSettings.histogramMode) { case HistogramMode.Red: channels.x = 1f; break; case HistogramMode.Green: channels.y = 1f; break; case HistogramMode.Blue: channels.z = 1f; break; case HistogramMode.Luminance: channels.w = 1f; break; default: channels = new Vector4(1f, 1f, 1f, 0f); break; } var cs = m_ComputeShader; int kernel = cs.FindKernel("KHistogramClear"); cs.SetBuffer(kernel, "_Histogram", m_Buffer); cs.Dispatch(kernel, 1, 1, 1); kernel = cs.FindKernel("KHistogramGather"); cs.SetBuffer(kernel, "_Histogram", m_Buffer); cs.SetTexture(kernel, "_Source", source); cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0); cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f)); cs.SetVector("_Channels", channels); cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 16f), Mathf.CeilToInt(source.height / 16f), 1); kernel = cs.FindKernel("KHistogramScale"); cs.SetBuffer(kernel, "_Histogram", m_Buffer); cs.Dispatch(kernel, 1, 1, 1); if (m_HistogramTexture == null || m_HistogramTexture.width != source.width || m_HistogramTexture.height != source.height) { GraphicsUtils.Destroy(m_HistogramTexture); m_HistogramTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear) { hideFlags = HideFlags.DontSave, wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear }; } m_Material.SetBuffer("_Histogram", m_Buffer); m_Material.SetVector("_Size", new Vector2(m_HistogramTexture.width, m_HistogramTexture.height)); m_Material.SetColor("_ColorR", new Color(1f, 0f, 0f, 1f)); m_Material.SetColor("_ColorG", new Color(0f, 1f, 0f, 1f)); m_Material.SetColor("_ColorB", new Color(0f, 0f, 1f, 1f)); m_Material.SetColor("_ColorL", new Color(1f, 1f, 1f, 1f)); m_Material.SetInt("_Channel", (int)m_MonitorSettings.histogramMode); int pass = 0; if (m_MonitorSettings.histogramMode == HistogramMode.RGBMerged) pass = 1; else if (m_MonitorSettings.histogramMode == HistogramMode.RGBSplit) pass = 2; Graphics.Blit(null, m_HistogramTexture, m_Material, pass); } } }
//--------------------------------------------------------------------------- // // File: HtmlXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Html - Xaml conversion // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Windows; using System.Windows.Documents; using System.Xml; // TextElement internal static class HtmlCssParser { // ................................................................. // // Processing CSS Attributes // // ................................................................. internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List<XmlElement> sourceContext) { string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext); string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style"); // Combine styles from stylesheet and from inline attribute. // The order is important - the latter styles will override the former. string style = styleFromStylesheet != null ? styleFromStylesheet : null; if (styleInline != null) { style = style == null ? styleInline : (style + ";" + styleInline); } // Apply local style to current formatting properties if (style != null) { string[] styleValues = style.Split(';'); for (int i = 0; i < styleValues.Length; i++) { string[] styleNameValue; styleNameValue = styleValues[i].Split(':'); if (styleNameValue.Length == 2) { string styleName = styleNameValue[0].Trim().ToLower(); string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower(); int nextIndex = 0; switch (styleName) { case "font": ParseCssFont(styleValue, localProperties); break; case "font-family": ParseCssFontFamily(styleValue, ref nextIndex, localProperties); break; case "font-size": ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); break; case "font-style": ParseCssFontStyle(styleValue, ref nextIndex, localProperties); break; case "font-weight": ParseCssFontWeight(styleValue, ref nextIndex, localProperties); break; case "font-variant": ParseCssFontVariant(styleValue, ref nextIndex, localProperties); break; case "line-height": ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); break; case "word-spacing": // Implement word-spacing conversion break; case "letter-spacing": // Implement letter-spacing conversion break; case "color": ParseCssColor(styleValue, ref nextIndex, localProperties, "color"); break; case "text-decoration": ParseCssTextDecoration(styleValue, ref nextIndex, localProperties); break; case "text-transform": ParseCssTextTransform(styleValue, ref nextIndex, localProperties); break; case "background-color": ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color"); break; case "background": // TODO: need to parse composite background property ParseCssBackground(styleValue, ref nextIndex, localProperties); break; case "text-align": ParseCssTextAlign(styleValue, ref nextIndex, localProperties); break; case "vertical-align": ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties); break; case "text-indent": ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false); break; case "width": case "height": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "margin": // top/right/bottom/left ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "margin-top": case "margin-right": case "margin-bottom": case "margin-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "padding": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "padding-top": case "padding-right": case "padding-bottom": case "padding-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "border": ParseCssBorder(styleValue, ref nextIndex, localProperties); break; case "border-style": case "border-width": case "border-color": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "border-top": case "border-right": case "border-left": case "border-bottom": // Parse css border style break; // NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right) // In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method case "border-top-style": case "border-right-style": case "border-left-style": case "border-bottom-style": case "border-top-color": case "border-right-color": case "border-left-color": case "border-bottom-color": case "border-top-width": case "border-right-width": case "border-left-width": case "border-bottom-width": // Parse css border style break; case "display": // Implement display style conversion break; case "float": ParseCssFloat(styleValue, ref nextIndex, localProperties); break; case "clear": ParseCssClear(styleValue, ref nextIndex, localProperties); break; default: break; } } } } } // ................................................................. // // Parsing CSS - Lexical Helpers // // ................................................................. // Skips whitespaces in style values private static void ParseWhiteSpace(string styleValue, ref int nextIndex) { while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex])) { nextIndex++; } } // Checks if the following character matches to a given word and advances nextIndex // by the word's length in case of success. // Otherwise leaves nextIndex in place (except for possible whitespaces). // Returns true or false depending on success or failure of matching. private static bool ParseWord(string word, string styleValue, ref int nextIndex) { ParseWhiteSpace(styleValue, ref nextIndex); for (int i = 0; i < word.Length; i++) { if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i])) { return false; } } if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length])) { return false; } nextIndex += word.Length; return true; } // CHecks whether the following character sequence matches to one of the given words, // and advances the nextIndex to matched word length. // Returns null in case if there is no match or the word matched. private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex) { for (int i = 0; i < words.Length; i++) { if (ParseWord(words[i], styleValue, ref nextIndex)) { return words[i]; } } return null; } private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName) { string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex); if (attributeValue != null) { localProperties[attributeName] = attributeValue; } } private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative) { ParseWhiteSpace(styleValue, ref nextIndex); int startIndex = nextIndex; // Parse optional munis sign if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-') { nextIndex++; } if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex])) { while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.')) { nextIndex++; } string number = styleValue.Substring(startIndex, nextIndex - startIndex); string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex); if (unit == null) { unit = "px"; // Assuming pixels by default } if (mustBeNonNegative && styleValue[startIndex] == '-') { return "0"; } else { return number + unit; } } return null; } private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative) { string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative); if (length != null) { localValues[propertyName] = length; } } private static readonly string[] _colors = new string[] { "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen", }; private static readonly string[] _systemColors = new string[] { "activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext", }; private static string ParseCssColor(string styleValue, ref int nextIndex) { // Implement color parsing // rgb(100%,53.5%,10%) // rgb(255,91,26) // #FF5B1A // black | silver | gray | ... | aqua // transparent - for background-color ParseWhiteSpace(styleValue, ref nextIndex); string color = null; if (nextIndex < styleValue.Length) { int startIndex = nextIndex; char character = styleValue[nextIndex]; if (character == '#') { nextIndex++; while (nextIndex < styleValue.Length) { character = Char.ToUpper(styleValue[nextIndex]); if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F')) { break; } nextIndex++; } if (nextIndex > startIndex + 1) { color = styleValue.Substring(startIndex, nextIndex - startIndex); } } else if (styleValue.Substring(nextIndex, 3).ToLower() == "rbg") { // Implement real rgb() color parsing while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')') { nextIndex++; } if (nextIndex < styleValue.Length) { nextIndex++; // to skip ')' } color = "gray"; // return bogus color } else if (Char.IsLetter(character)) { color = ParseWordEnumeration(_colors, styleValue, ref nextIndex); if (color == null) { color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex); if (color != null) { // Implement smarter system color converions into real colors color = "black"; } } } } return color; } private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName) { string color = ParseCssColor(styleValue, ref nextIndex); if (color != null) { localValues[propertyName] = color; } } // ................................................................. // // Pasring CSS font Property // // ................................................................. // CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size. // An aggregated "font" property lets you specify in one action all the five in combination // with additional line-height property. // // font-family: [<family-name>,]* [<family-name> | <generic-family>] // generic-family: serif | sans-serif | monospace | cursive | fantasy // The list of families sets priorities to choose fonts; // Quotes not allowed around generic-family names // font-style: normal | italic | oblique // font-variant: normal | small-caps // font-weight: normal | bold | bolder | lighter | 100 ... 900 | // Default is "normal", normal==400 // font-size: <absolute-size> | <relative-size> | <length> | <percentage> // absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large // relative-size: larger | smaller // length: <point> | <pica> | <ex> | <em> | <points> | <millimeters> | <centimeters> | <inches> // Default: medium // font: [ <font-style> || <font-variant> || <font-weight ]? <font-size> [ / <line-height> ]? <font-family> private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" }; private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" }; private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" }; private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" }; private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" }; private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" }; private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" }; // Parses CSS string fontStyle representing a value for css font attribute private static void ParseCssFont(string styleValue, Hashtable localProperties) { int nextIndex = 0; ParseCssFontStyle(styleValue, ref nextIndex, localProperties); ParseCssFontVariant(styleValue, ref nextIndex, localProperties); ParseCssFontWeight(styleValue, ref nextIndex, localProperties); ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/') { nextIndex++; ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); } ParseCssFontFamily(styleValue, ref nextIndex, localProperties); } private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style"); } private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant"); } private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight"); } private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties) { string fontFamilyList = null; while (nextIndex < styleValue.Length) { // Try generic-family string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex); if (fontFamily == null) { // Try quoted font family name if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\'')) { char quote = styleValue[nextIndex]; nextIndex++; int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote) { nextIndex++; } fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"'; } if (fontFamily == null) { // Try unquoted font family name int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';') { nextIndex++; } if (nextIndex > startIndex) { fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim(); if (fontFamily.Length == 0) { fontFamily = null; } } } } ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',') { nextIndex++; } if (fontFamily != null) { // css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names // fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily; if (fontFamilyList == null && fontFamily.Length > 0) { if (fontFamily[0] == '"' || fontFamily[0] == '\'') { // Unquote the font family name fontFamily = fontFamily.Substring(1, fontFamily.Length - 2); } else { // Convert generic css family name } fontFamilyList = fontFamily; } } else { break; } } if (fontFamilyList != null) { localProperties["font-family"] = fontFamilyList; } } // ................................................................. // // Pasring CSS list-style Property // // ................................................................. // list-style: [ <list-style-type> || <list-style-position> || <list-style-image> ] private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" }; private static readonly string[] _listStylePositions = new string[] { "inside", "outside" }; private static void ParseCssListStyle(string styleValue, Hashtable localProperties) { int nextIndex = 0; while (nextIndex < styleValue.Length) { string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex); if (listStyleType != null) { localProperties["list-style-type"] = listStyleType; } else { string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex); if (listStylePosition != null) { localProperties["list-style-position"] = listStylePosition; } else { string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex); if (listStyleImage != null) { localProperties["list-style-image"] = listStyleImage; } else { // TODO: Process unrecognized list style value break; } } } } } private static string ParseCssListStyleType(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex); } private static string ParseCssListStylePosition(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex); } private static string ParseCssListStyleImage(string styleValue, ref int nextIndex) { // TODO: Implement URL parsing for images return null; } // ................................................................. // // Pasring CSS text-decorations Property // // ................................................................. private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" }; private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties) { // Set default text-decorations:none; for (int i = 1; i < _textDecorations.Length; i++) { localProperties["text-decoration-" + _textDecorations[i]] = "false"; } // Parse list of decorations values while (nextIndex < styleValue.Length) { string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex); if (decoration == null || decoration == "none") { break; } localProperties["text-decoration-" + decoration] = "true"; } } // ................................................................. // // Pasring CSS text-transform Property // // ................................................................. private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" }; private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform"); } // ................................................................. // // Pasring CSS text-align Property // // ................................................................. private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" }; private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align"); } // ................................................................. // // Pasring CSS vertical-align Property // // ................................................................. private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" }; private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { // Parse percentage value for vertical-align style ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align"); } // ................................................................. // // Pasring CSS float Property // // ................................................................. private static readonly string[] _floats = new string[] { "left", "right", "none" }; private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float"); } // ................................................................. // // Pasring CSS clear Property // // ................................................................. private static readonly string[] _clears = new string[] { "none", "left", "right", "both" }; private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear"); } // ................................................................. // // Pasring CSS margin and padding Properties // // ................................................................. // Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName) { // CSS Spec: // If only one value is set, then the value applies to all four sides; // If two or three values are set, then missinng value(s) are taken fromm the opposite side(s). // The order they are applied is: top/right/bottom/left Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color"); string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-top"] = value; localProperties[propertyName + "-bottom"] = value; localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-bottom"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-left"] = value; } } } return true; } return false; } // ................................................................. // // Pasring CSS border Properties // // ................................................................. // border: [ <border-width> || <border-style> || <border-color> ] private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties) { while ( ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color")) { } } // ................................................................. // // Pasring CSS border-style Propertie // // ................................................................. private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" }; private static string ParseCssBorderStyle(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex); } // ................................................................. // // What are these definitions doing here: // // ................................................................. private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" }; // ................................................................. // // Pasring CSS Background Properties // // ................................................................. private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues) { // Implement parsing background attribute } } internal class CssStylesheet { // Constructor public CssStylesheet(XmlElement htmlElement) { if (htmlElement != null) { this.DiscoverStyleDefinitions(htmlElement); } } // Recursively traverses an html tree, discovers STYLE elements and creates a style definition table // for further cascading style application public void DiscoverStyleDefinitions(XmlElement htmlElement) { if (htmlElement.LocalName.ToLower() == "link") { return; // Add LINK elements processing for included stylesheets // <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet> } if (htmlElement.LocalName.ToLower() != "style") { // This is not a STYLE element. Recurse into it for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlElement) { this.DiscoverStyleDefinitions((XmlElement)htmlChildNode); } } return; } // Add style definitions from this style. // Collect all text from this style definition StringBuilder stylesheetBuffer = new StringBuilder(); for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlText || htmlChildNode is XmlComment) { stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value)); } } // CssStylesheet has the following syntactical structure: // @import declaration; // selector { definition } // where "selector" is one of: ".classname", "tagname" // It can contain comments in the following form: /*...*/ int nextCharacterIndex = 0; while (nextCharacterIndex < stylesheetBuffer.Length) { // Extract selector int selectorStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{') { // Skip declaration directive starting from @ if (stylesheetBuffer[nextCharacterIndex] == '@') { while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';') { nextCharacterIndex++; } selectorStart = nextCharacterIndex + 1; } nextCharacterIndex++; } if (nextCharacterIndex < stylesheetBuffer.Length) { // Extract definition int definitionStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}') { nextCharacterIndex++; } // Define a style if (nextCharacterIndex - definitionStart > 2) { this.AddStyleDefinition( stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart), stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2)); } // Skip closing brace if (nextCharacterIndex < stylesheetBuffer.Length) { Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}'); nextCharacterIndex++; } } } } // Returns a string with all c-style comments replaced by spaces private string RemoveComments(string text) { int commentStart = text.IndexOf("/*"); if (commentStart < 0) { return text; } int commentEnd = text.IndexOf("*/", commentStart + 2); if (commentEnd < 0) { return text.Substring(0, commentStart); } return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2)); } public void AddStyleDefinition(string selector, string definition) { // Notrmalize parameter values selector = selector.Trim().ToLower(); definition = definition.Trim().ToLower(); if (selector.Length == 0 || definition.Length == 0) { return; } if (_styleDefinitions == null) { _styleDefinitions = new List<StyleDefinition>(); } string[] simpleSelectors = selector.Split(','); for (int i = 0; i < simpleSelectors.Length; i++) { string simpleSelector = simpleSelectors[i].Trim(); if (simpleSelector.Length > 0) { _styleDefinitions.Add(new StyleDefinition(simpleSelector, definition)); } } } public string GetStyle(string elementName, List<XmlElement> sourceContext) { Debug.Assert(sourceContext.Count > 0); Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName); // Add id processing for style selectors if (_styleDefinitions != null) { for (int i = _styleDefinitions.Count - 1; i >= 0; i--) { string selector = _styleDefinitions[i].Selector; string[] selectorLevels = selector.Split(' '); int indexInSelector = selectorLevels.Length - 1; int indexInContext = sourceContext.Count - 1; string selectorLevel = selectorLevels[indexInSelector].Trim(); if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1])) { return _styleDefinitions[i].Definition; } } } return null; } private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement) { if (selectorLevel.Length == 0) { return false; } int indexOfDot = selectorLevel.IndexOf('.'); int indexOfPound = selectorLevel.IndexOf('#'); string selectorClass = null; string selectorId = null; string selectorTag = null; if (indexOfDot >= 0) { if (indexOfDot > 0) { selectorTag = selectorLevel.Substring(0, indexOfDot); } selectorClass = selectorLevel.Substring(indexOfDot + 1); } else if (indexOfPound >= 0) { if (indexOfPound > 0) { selectorTag = selectorLevel.Substring(0, indexOfPound); } selectorId = selectorLevel.Substring(indexOfPound + 1); } else { selectorTag = selectorLevel; } if (selectorTag != null && selectorTag != xmlElement.LocalName) { return false; } if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId) { return false; } if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass) { return false; } return true; } private class StyleDefinition { public StyleDefinition(string selector, string definition) { this.Selector = selector; this.Definition = definition; } public string Selector; public string Definition; } private List<StyleDefinition> _styleDefinitions; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareNotGreaterThanOrEqualDouble() { var test = new SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[ElementCount]; private static Double[] _data2 = new Double[ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double> _dataTable; static SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareNotGreaterThanOrEqual( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareNotGreaterThanOrEqual( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareNotGreaterThanOrEqual( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareNotGreaterThanOrEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareNotGreaterThanOrEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotGreaterThanOrEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotGreaterThanOrEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble(); var result = Sse2.CompareNotGreaterThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareNotGreaterThanOrEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] >= right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != (!(left[i] >= right[i]) ? -1 : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareNotGreaterThanOrEqual)}<Double>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestAzureSpecialParametersTestClient : ServiceClient<AutoRestAzureSpecialParametersTestClient>, IAutoRestAzureSpecialParametersTestClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription id, which appears in the path, always modeled in /// credentials. The value is always '1234-5678-9012-3456' /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The api version, which appears in the query, the value is always /// '2015-07-01-preview' /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } public virtual IXMsClientRequestIdOperations XMsClientRequestId { get; private set; } public virtual ISubscriptionInCredentialsOperations SubscriptionInCredentials { get; private set; } public virtual ISubscriptionInMethodOperations SubscriptionInMethod { get; private set; } public virtual IApiVersionDefaultOperations ApiVersionDefault { get; private set; } public virtual IApiVersionLocalOperations ApiVersionLocal { get; private set; } public virtual ISkipUrlEncodingOperations SkipUrlEncoding { get; private set; } public virtual IOdataOperations Odata { get; private set; } public virtual IHeaderOperations Header { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestAzureSpecialParametersTestClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestAzureSpecialParametersTestClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestAzureSpecialParametersTestClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestAzureSpecialParametersTestClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestAzureSpecialParametersTestClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestAzureSpecialParametersTestClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestAzureSpecialParametersTestClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestAzureSpecialParametersTestClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestAzureSpecialParametersTestClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.XMsClientRequestId = new XMsClientRequestIdOperations(this); this.SubscriptionInCredentials = new SubscriptionInCredentialsOperations(this); this.SubscriptionInMethod = new SubscriptionInMethodOperations(this); this.ApiVersionDefault = new ApiVersionDefaultOperations(this); this.ApiVersionLocal = new ApiVersionLocalOperations(this); this.SkipUrlEncoding = new SkipUrlEncodingOperations(this); this.Odata = new OdataOperations(this); this.Header = new HeaderOperations(this); this.BaseUri = new Uri("http://localhost"); this.ApiVersion = "2015-07-01-preview"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using UnityEngine; using System.Collections; using System; using System.Diagnostics; public class Dinosaur2Move : MonoBehaviour { private float gameSpeed = 150; //private float maxSpeed = 40; private float maxSpeedMultiplier = 2; private bool isGrounded = true; private bool StartIsShowing = true; private bool isFacingRight = true; // Assume player is facing right private int returnAnimRate = 3; // How many frames before animation stops private int spiketimer = 5; // How many frames before reducing candy again public static bool game_is_on = false; // Game is truly running at the start private static Stopwatch screenwatch = new Stopwatch(); // Timer to get the screen properly running private Animator animations; Rigidbody2D body; // Use this for initialization void Start() { body = GetComponent<Rigidbody2D>(); animations = GetComponent<Animator>(); isFacing("right"); GetComponent<SpriteRenderer>().enabled = false; body.constraints = RigidbodyConstraints2D.FreezePositionY; } // Update is called once per frame void Update() { // Start or not to start if (Input.GetKey(KeyCode.Escape)) { Application.Quit(); } if (StartIsShowing && Input.GetKey(KeyCode.KeypadEnter) || Input.GetKey(KeyCode.Return)) { if (!screenwatch.IsRunning) { //UnityEngine.Debug.Log("Starting watch"); screenwatch.Start(); } DestroyObject(GameObject.Find("Startscreen")); StartIsShowing = false; EndingScreen.ShowInsScreen(true); } if (!StartIsShowing && Input.GetKey(KeyCode.KeypadEnter) || Input.GetKey(KeyCode.Return)) { //UnityEngine.Debug.Log("Watch: "+screenwatch.Elapsed); if (screenwatch.Elapsed.Seconds >= 1) { EndingScreen.ShowInsScreen(false); GetComponent<SpriteRenderer>().enabled = true; game_is_on = true; body.constraints = RigidbodyConstraints2D.None; body.constraints = RigidbodyConstraints2D.FreezeRotation; UpdateInfo.startgame(); screenwatch.Stop(); } } if (game_is_on) { Movement(); } gameSpeed = 150; returnAnimRate--; if (returnAnimRate == 0) { setIdle(); } if (spiketimer > 0) { spiketimer--; } if (Input.GetKey(KeyCode.R)) { //EndingScreen.ShowEndScreenA(); // For testing } if (Input.GetKey(KeyCode.P)) { EndingScreen.ShowEndScreenA(); // For testing } if (Input.GetKey(KeyCode.O)) { EndingScreen.ShowEndScreenB(); // For testing } if (Input.GetKey(KeyCode.I)) { EndingScreen.ShowEndScreenC(); // For testing } if (Input.GetKey(KeyCode.U)) { CoinCounter.AddCandy(); } } void Movement() { // Sprint if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { if (gameSpeed < (gameSpeed * maxSpeedMultiplier)) { gameSpeed = gameSpeed * maxSpeedMultiplier; } } // Walking/running right if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) { transform.Translate(Vector2.right * gameSpeed * Time.deltaTime); isFacing("right"); setAnim("IsRunningRight"); } // Walking/running left if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) { transform.Translate(Vector2.left * gameSpeed * Time.deltaTime); isFacing("left"); setAnim("IsRunningLeft"); } // Jumping if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) && isGrounded) { setIdle(); body.velocity = new Vector2(body.velocity.y, 0); returnAnimRate = 3; isGrounded = false; body.AddForce(new Vector2(0, 180), ForceMode2D.Impulse); GameObject.Find("jump").GetComponent<AudioSource>().Play(); } // Going down if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) { if (isGrounded) { setIdle(); transform.Translate(Vector2.down * gameSpeed * Time.deltaTime); } } // Try to animate jump if (isGrounded == false) // means we have jumping on going { if (isFacingRight) // we should be jumping right { setAnim("IsJumpingRight"); } else // we are jumping left { setAnim("IsJumpingLeft"); } } } // movement void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "Border" || col.gameObject.tag == "Box") { isGrounded = true; } if (col.gameObject.tag == "Finish") { game_is_on = false; if (CoinCounter.GetCoinInt() <= 20) { EndingScreen.ShowEndScreenA(); } if (CoinCounter.GetCoinInt() >= 20 && CoinCounter.GetCoinInt() < 50) { EndingScreen.ShowEndScreenB(); } if (CoinCounter.GetCoinInt() >= 50) { EndingScreen.ShowEndScreenC(); } } if (col.gameObject.tag == "Car") { CoinCounter.ReduceCandy(); } if (col.gameObject.tag == "Candy") { CoinCounter.AddCandy(); } if (col.gameObject.tag == "Mushroom") { CoinCounter.ReduceCandy(); } if (col.gameObject.tag == "Spikes") { isGrounded = true; if (spiketimer <= 0) { CoinCounter.ReduceCandy(); spiketimer = 20; } } } public static void endgame(string input) { game_is_on = false; UpdateInfo.game_end = true; UpdateInfo.UpdateText(input); EndingScreen.ShowEnd(); } private void setIdle() { animations.SetBool("IsRunningRight", false); animations.SetBool("IsRunningLeft", false); animations.SetBool("IsJumpingRight", false); animations.SetBool("IsJumpingLeft", false); } // Helper method to set animation and attempt to reduce copying code all over private void setAnim(string anim) { setIdle(); returnAnimRate = 3; animations.SetBool(anim, true); } // Method for changing idle state private void isFacing(string facing) { if (facing == "right") { isFacingRight = true; animations.SetBool("IsFaceToRight", true); } if (facing == "left") { isFacingRight = false; animations.SetBool("IsFaceToRight", false); } } }
using System; using System.Collections.Generic; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using DevelopStuff.Infix.Ast; namespace DevelopStuff.Infix { partial class InfixParser { private Program _tree; private static List<Statement> AddStatement(List<Statement> list, Statement statement) { if (list == null) { list = new List<Statement>(); } list.Add(statement); return list; } internal Program Parse(CompilerContext context) { SourceUnit unit = context.SourceUnit; Scanner scan = new Scanner(); string code = unit.GetCode(); scan.SetSource(code, 0); scanner = scan; //Trace = true; try { Parse(); return _tree; } catch (InfixSyntaxErrorException lse) { if (unit.Kind == SourceCodeKind.InteractiveCode) { if (lse.Eof) { unit.CodeProperties = SourceCodeProperties.IsIncompleteStatement; } else { throw; } } } return null; } public static object StringToNumber(object obj) { string str = obj as string; if (String.IsNullOrEmpty(str)) { return false; } switch (str[0]) { case '#': switch (str[1]) { case 'b': return StringToNumber(str.Substring(2), 2); case 'o': return StringToNumber(str.Substring(2), 8); case 'd': return StringToNumber(str.Substring(2), 10); case 'x': return StringToNumber(str.Substring(2), 16); default: return false; } default: return StringToNumber(obj, 10); } } public static object StringToNumber(object obj, object radix) { string str = obj as string; if (String.IsNullOrEmpty(str)) { return false; } radix = radix ?? 10; int r = (int)radix; switch (r) { case 2: return ParseBinary(str); case 8: return ParseOctal(str); case 10: int n; if (int.TryParse(str, out n)) { return n; } long l; if (long.TryParse(str, out l)) { return l; } double d; if (double.TryParse(str, out d)) { return d; } decimal dec; if (decimal.TryParse(str, out dec)) { return dec; } break; case 16: if (str.Length > 16) { return false; } else if (str.Length > 8) { return long.Parse(str, System.Globalization.NumberStyles.HexNumber); } else { return int.Parse(str, System.Globalization.NumberStyles.HexNumber); } default: return false; } return false; } static object ParseBinary(string str) { if (str.Length <= 32) { int b = 1; int n = 0; for (int i = 0; i < str.Length; i++, b *= 2) { char c = str[str.Length - 1 - i]; n += b * (c - '0'); } return n; } else { long b = 1; long n = 0; for (int i = 0; i < str.Length; i++, b *= 2) { char c = str[str.Length - 1 - i]; n += b * (c - '0'); } return n; } } static object ParseOctal(string str) { if (str.Length < 11) // not precise, bleh { int b = 1; int n = 0; for (int i = 0; i < str.Length; i++, b *= 8) { char c = str[str.Length - 1 - i]; n += b * (c - '0'); } return n; } else { long b = 1; long n = 0; for (int i = 0; i < str.Length; i++, b *= 8) { char c = str[str.Length - 1 - i]; n += b * (c - '0'); } return n; } } } }
using NUnit.Framework; namespace TriAxis.RunSharp.Tests { [TestFixture] public class TestIfStatement : TestBase { // g.If(l12 == l13 || l15 <= l14 || ((l15 < l14) && l12 == 2)); [Test] public void Equality1() { TestingFacade.RunMethodTest(Equality1); } public static void Equality1(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If(l1 == l2); { g.ThrowAssert(false, "Equality"); } g.Else(); { g.Return(); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void Equality2() { TestingFacade.RunMethodTest(Equality2); } public static void Equality2(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If(l1 == l1); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void And() { TestingFacade.RunMethodTest(And); } public static void And(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l1 == l1) && (l2 == l2)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void And2() { TestingFacade.RunMethodTest(And2); } public static void And2(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If(l1 == l1 && l2 == l3); { g.ThrowAssert(false, "Equality"); } g.Else(); { g.Return(); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void Or() { TestingFacade.RunMethodTest(Or); } public static void Or(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If(l1 == l1 || l2 == l2); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void Or2() { TestingFacade.RunMethodTest(Or2); } public static void Or2(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If(l1 == l1 || l2 == l3); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void Or3() { TestingFacade.RunMethodTest(Or3); } public static void Or3(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If(l2 == l3 || l1 == l1); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void Or4() { TestingFacade.RunMethodTest(Or4); } public static void Or4(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If(l2 == l3 || l1 == l2); { g.ThrowAssert(false, "Equality"); } g.Else(); { g.Return(); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void OrInAnd() { TestingFacade.RunMethodTest(OrInAnd); } public static void OrInAnd(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l2 == l2 || l1 == l2) && (l3 == l4)); { g.ThrowAssert(false, "Equality"); } g.Else(); { g.Return(); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void OrInAnd2() { TestingFacade.RunMethodTest(OrInAnd2); } public static void OrInAnd2(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l2 == l2 || l1 == l2) && (l3 == l3)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void OrInAnd3() { TestingFacade.RunMethodTest(OrInAnd3); } public static void OrInAnd3(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l3 == l3) && (l2 == l2 || l1 == l2)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void OrInAnd4() { TestingFacade.RunMethodTest(OrInAnd4); } public static void OrInAnd4(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l4 == l3) && (l2 == l2 || l1 == l2)); { g.ThrowAssert(false, "Equality"); } g.Else(); { g.Return(); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void AndInOr() { TestingFacade.RunMethodTest(AndInOr); } public static void AndInOr(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l4 == l3) || (l2 == l2 && l1 == l1)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void AndInOr2() { TestingFacade.RunMethodTest(AndInOr2); } public static void AndInOr2(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l3 == l3) || (l3 == l2 && l1 == l1)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void AndInOr3() { TestingFacade.RunMethodTest(AndInOr3); } public static void AndInOr3(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l3 == l4) || (l2 == l2 && l1 == l1)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void AndInOr4() { TestingFacade.RunMethodTest(AndInOr4); } public static void AndInOr4(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l2 == l2 && l1 == l1) || (l3 == l4)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } [Test] public void AndInOr5() { TestingFacade.RunMethodTest(AndInOr5); } public static void AndInOr5(MethodGen m) { var g = m.GetCode(); Operand l1 = 1; Operand l2 = 2; Operand l3 = 3; Operand l4 = 4; g.If((l2 == l2 && l1 == l2) || (l3 == l3)); { g.Return(); } g.Else(); { g.ThrowAssert(false, "Equality"); } g.End(); g.ThrowAssert(false, "Not returned"); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the FacRelPerfilPaginaPrincipal class. /// </summary> [Serializable] public partial class FacRelPerfilPaginaPrincipalCollection : ActiveList<FacRelPerfilPaginaPrincipal, FacRelPerfilPaginaPrincipalCollection> { public FacRelPerfilPaginaPrincipalCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>FacRelPerfilPaginaPrincipalCollection</returns> public FacRelPerfilPaginaPrincipalCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { FacRelPerfilPaginaPrincipal o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the FAC_RelPerfilPaginaPrincipal table. /// </summary> [Serializable] public partial class FacRelPerfilPaginaPrincipal : ActiveRecord<FacRelPerfilPaginaPrincipal>, IActiveRecord { #region .ctors and Default Settings public FacRelPerfilPaginaPrincipal() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public FacRelPerfilPaginaPrincipal(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public FacRelPerfilPaginaPrincipal(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public FacRelPerfilPaginaPrincipal(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("FAC_RelPerfilPaginaPrincipal", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdRelPerfilPaginaPrincipal = new TableSchema.TableColumn(schema); colvarIdRelPerfilPaginaPrincipal.ColumnName = "idRelPerfilPaginaPrincipal"; colvarIdRelPerfilPaginaPrincipal.DataType = DbType.Int32; colvarIdRelPerfilPaginaPrincipal.MaxLength = 0; colvarIdRelPerfilPaginaPrincipal.AutoIncrement = true; colvarIdRelPerfilPaginaPrincipal.IsNullable = false; colvarIdRelPerfilPaginaPrincipal.IsPrimaryKey = true; colvarIdRelPerfilPaginaPrincipal.IsForeignKey = false; colvarIdRelPerfilPaginaPrincipal.IsReadOnly = false; colvarIdRelPerfilPaginaPrincipal.DefaultSetting = @""; colvarIdRelPerfilPaginaPrincipal.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdRelPerfilPaginaPrincipal); TableSchema.TableColumn colvarIdPerfil = new TableSchema.TableColumn(schema); colvarIdPerfil.ColumnName = "idPerfil"; colvarIdPerfil.DataType = DbType.Int32; colvarIdPerfil.MaxLength = 0; colvarIdPerfil.AutoIncrement = false; colvarIdPerfil.IsNullable = false; colvarIdPerfil.IsPrimaryKey = false; colvarIdPerfil.IsForeignKey = false; colvarIdPerfil.IsReadOnly = false; colvarIdPerfil.DefaultSetting = @""; colvarIdPerfil.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPerfil); TableSchema.TableColumn colvarIdMenu = new TableSchema.TableColumn(schema); colvarIdMenu.ColumnName = "idMenu"; colvarIdMenu.DataType = DbType.Int32; colvarIdMenu.MaxLength = 0; colvarIdMenu.AutoIncrement = false; colvarIdMenu.IsNullable = false; colvarIdMenu.IsPrimaryKey = false; colvarIdMenu.IsForeignKey = false; colvarIdMenu.IsReadOnly = false; colvarIdMenu.DefaultSetting = @""; colvarIdMenu.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMenu); TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema); colvarUrl.ColumnName = "url"; colvarUrl.DataType = DbType.AnsiString; colvarUrl.MaxLength = 500; colvarUrl.AutoIncrement = false; colvarUrl.IsNullable = false; colvarUrl.IsPrimaryKey = false; colvarUrl.IsForeignKey = false; colvarUrl.IsReadOnly = false; colvarUrl.DefaultSetting = @""; colvarUrl.ForeignKeyTableName = ""; schema.Columns.Add(colvarUrl); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("FAC_RelPerfilPaginaPrincipal",schema); } } #endregion #region Props [XmlAttribute("IdRelPerfilPaginaPrincipal")] [Bindable(true)] public int IdRelPerfilPaginaPrincipal { get { return GetColumnValue<int>(Columns.IdRelPerfilPaginaPrincipal); } set { SetColumnValue(Columns.IdRelPerfilPaginaPrincipal, value); } } [XmlAttribute("IdPerfil")] [Bindable(true)] public int IdPerfil { get { return GetColumnValue<int>(Columns.IdPerfil); } set { SetColumnValue(Columns.IdPerfil, value); } } [XmlAttribute("IdMenu")] [Bindable(true)] public int IdMenu { get { return GetColumnValue<int>(Columns.IdMenu); } set { SetColumnValue(Columns.IdMenu, value); } } [XmlAttribute("Url")] [Bindable(true)] public string Url { get { return GetColumnValue<string>(Columns.Url); } set { SetColumnValue(Columns.Url, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdPerfil,int varIdMenu,string varUrl) { FacRelPerfilPaginaPrincipal item = new FacRelPerfilPaginaPrincipal(); item.IdPerfil = varIdPerfil; item.IdMenu = varIdMenu; item.Url = varUrl; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdRelPerfilPaginaPrincipal,int varIdPerfil,int varIdMenu,string varUrl) { FacRelPerfilPaginaPrincipal item = new FacRelPerfilPaginaPrincipal(); item.IdRelPerfilPaginaPrincipal = varIdRelPerfilPaginaPrincipal; item.IdPerfil = varIdPerfil; item.IdMenu = varIdMenu; item.Url = varUrl; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdRelPerfilPaginaPrincipalColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdPerfilColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdMenuColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn UrlColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string IdRelPerfilPaginaPrincipal = @"idRelPerfilPaginaPrincipal"; public static string IdPerfil = @"idPerfil"; public static string IdMenu = @"idMenu"; public static string Url = @"url"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.Internal.PropertyEditing.Model { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Text; using System.Activities.Presentation; using System.Activities.Presentation.Model; using System.Activities.Presentation.PropertyEditing; using System.Activities.Presentation.Internal.Properties; // <summary> // ModelPropertyIndexer is used to represent ModelItems in a collection. As such // and unlike ModelProperty, the class wraps around a single ModelItem instead of // one or more ModelProperties. // </summary> internal class ModelPropertyIndexer : ModelPropertyEntryBase { private static readonly ICollection EmptyCollection = new object[0]; private ModelItem _modelItem; private int _index; private ModelPropertyValueCollection _parentCollection; private CachedValues _valueCache; // <summary> // Basic ctor. Note, however, that this class should only be created by ModelPropertyValueCollection // as that class ensures that the new instance is correctly added and removed from the // ModelItemMap. // </summary> // <param name="modelItem">ModelItem to wrap around</param> // <param name="index">Index of the ModelItem in the collection</param> // <param name="parentCollection">Parent collection</param> public ModelPropertyIndexer( ModelItem modelItem, int index, ModelPropertyValueCollection parentCollection) : base(parentCollection.ParentValue) { if (modelItem == null) { throw FxTrace.Exception.ArgumentNull("modelItem"); } if (parentCollection == null) { throw FxTrace.Exception.ArgumentNull("parentCollection"); } _modelItem = modelItem; _index = index; _parentCollection = parentCollection; _valueCache = new CachedValues(this); } // <summary> // Gets the index of the underlying ModelItem. If index &lt; 0, this // ModelPropertyIndexer no longer belongs to a collection and setting its value // will fail. // </summary> public int Index { get { return _index; } internal set { _index = value; } } // <summary> // Gets the name category name of the parent collection // </summary> public override string CategoryName { get { return _parentCollection.ParentValue.ParentProperty.CategoryName; } } // <summary> // Gets the description of the parent collection // </summary> public override string Description { get { return _parentCollection.ParentValue.ParentProperty.Description; } } // <summary> // Gets the IsAdvanced flag of the parent collection // </summary> public override bool IsAdvanced { get { return _parentCollection.ParentValue.ParentProperty.IsAdvanced; } } // <summary> // Returns true // </summary> public override bool IsReadOnly { get { return true; } } // <summary> // Gets the index of this item as string // </summary> public override string PropertyName { get { return _index.ToString(CultureInfo.InvariantCulture); } } // <summary> // Gets the type of items in the parent collection // </summary> public override Type PropertyType { get { return _modelItem.ItemType; } } // <summary> // Returns null because there are no ValueEditors for values that belong to a collection // </summary> public override PropertyValueEditor PropertyValueEditor { get { // There are no ValueEditors for items in a collection return null; } } // <summary> // Returns an empty collection - there are no StandardValues for items in a collection // </summary> public override ICollection StandardValues { get { // There are no StandardValues for items in a collection return EmptyCollection; } } // <summary> // Returns false - ModelPropertyIndexers always wrap around a single ModelItem // </summary> public override bool IsMixedValue { get { return false; } } // <summary> // Returns Local - this PropertyEntry always contains a collection item value which is local // </summary> public override PropertyValueSource Source { get { return DependencyPropertyValueSource.Local; } } // <summary> // Gets the TypeConverter // </summary> public override TypeConverter Converter { get { return _valueCache.Converter; } } // <summary> // Gets the Type of the contained ModelItem // </summary> public override Type CommonValueType { get { return _modelItem.ItemType; } } // <summary> // Gets the sub-properties of the underlying item // </summary> public override PropertyEntryCollection SubProperties { get { return _valueCache.SubProperties; } } // <summary> // Gets the collection of the underlying ModelItem // </summary> public override PropertyValueCollection Collection { get { return _valueCache.Collection; } } // <summary> // Gets the depth of this property in the PI sub-property tree. // Since this class represents an item in the collection, it's depth // resets to -1 so that it's children start at depth 0 ( -1 + 1 = 0) again. // </summary> public override int Depth { get { return -1; } } // <summary> // Gets the underlying ModelItem // </summary> internal ModelItem ModelItem { get { return _modelItem; } } // <summary> // Gets a flag indicating whether the underlying collection instance has already been // initialized. Optimization. // </summary> internal override bool CollectionInstanceExists { get { return _valueCache.CollectionInstanceExists; } } // <summary> // Creates a new ModelPropertyValue instance // </summary> // <returns>New ModelPropertyValue instance</returns> protected override PropertyValue CreatePropertyValueInstance() { return new ModelPropertyValue(this); } // <summary> // Gets the actual object instance respresented by this class // </summary> // <returns>Actual object instance respresented by this class</returns> public override object GetValueCore() { return _modelItem.GetCurrentValue(); } // <summary> // Sets the value of the collection item at the same position as the // ModelItem represented by this class. Identical to removing the old // item and adding a new one // </summary> // <param name="value">Value to set</param> public override void SetValueCore(object value) { throw FxTrace.Exception.AsError(new InvalidOperationException(Resources.PropertyEditing_ErrorSetValueOnIndexer)); } // <summary> // Throws an exception -- invalid operation // </summary> public override void ClearValue() { throw FxTrace.Exception.AsError(new InvalidOperationException(Resources.PropertyEditing_ClearIndexer)); } // <summary> // Opens a new ModelEditingScope with the specified description. // </summary> // <param name="description">Change description (may be null).</param> // <returns>New, opened ModelEditingScope with the specified description</returns> internal override ModelEditingScope BeginEdit(string description) { return description == null ? _modelItem.BeginEdit() : _modelItem.BeginEdit(description); } // <summary> // Called when one of the sub-properties exposed by this class changes // </summary> protected override void OnUnderlyingSubModelChangedCore() { // Do nothing. There is nothing in CachedValues right now that would need to // be refreshed as a result of one of our sub-properties changing value } // Cached values that need to be nixed when the underlying ModelItem changes // (ie. someone calls SetValueCore()). Pretty much everything in here is an "expensive" // calculation which requires us to evaluate some attributes associated with the given // property of set of properties, so we cache the return values and keep that cache // in a single place so that it's easy to know what needs to be ----d when the underlying // ModelItem changes. private class CachedValues { private static readonly TypeConverter NoTypeConverter = new TypeConverter(); private ModelPropertyIndexer _parent; private TypeConverter _converter; private ModelPropertyEntryCollection _subProperties; private ModelPropertyValueCollection _collection; public CachedValues(ModelPropertyIndexer indexer) { _parent = indexer; } public TypeConverter Converter { get { if (_converter == null) { _converter = ExtensibilityAccessor.GetTypeConverter(_parent._modelItem); _converter = _converter ?? NoTypeConverter; } return _converter == NoTypeConverter ? null : _converter; } } public ModelPropertyEntryCollection SubProperties { get { if (_subProperties == null) { _subProperties = new ModelPropertyEntryCollection(_parent); } return _subProperties; } } public bool CollectionInstanceExists { get { return _collection != null; } } public ModelPropertyValueCollection Collection { get { if (_collection == null) { _collection = new ModelPropertyValueCollection(_parent.ModelPropertyValue); } return _collection; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Markup; using System.Windows.Media; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; namespace BindableApplicationBar { /// <summary> /// Serves as a bindable control wrapping the native ApplicationBar /// for use in MVVM applications. /// </summary> /// <remarks> /// TODO: Find out if bindings can work through ElementName - check for namescope issues. /// TODO: Find out if current/max number of buttons/menu items can be exposed as bindable properties. /// TODO: Figure out the best handling of cases when a button or menu item is added beyond the maximum number allowable. /// </remarks> [ContentProperty("Buttons")] public class BindableApplicationBar : Control { private ApplicationBar applicationBar; private PhoneApplicationPage page; private bool backgroundColorChanged; private bool foregroundColorChanged; private bool isMenuEnabledChanged; private bool isVisibleChanged; private bool modeChanged; private bool bindableOpacityChanged; private readonly DependencyObjectCollection<BindableApplicationBarButton> buttonsSourceButtons = new DependencyObjectCollection<BindableApplicationBarButton>(); private readonly DependencyObjectCollection<BindableApplicationBarMenuItem> menuItemsSourceMenuItems = new DependencyObjectCollection<BindableApplicationBarMenuItem>(); #region Buttons /// <summary> /// Buttons Dependency Property /// </summary> public static readonly DependencyProperty ButtonsProperty = DependencyProperty.Register( "Buttons", typeof(DependencyObjectCollection<BindableApplicationBarButton>), typeof(BindableApplicationBar), new PropertyMetadata(null, OnButtonsChanged)); /// <summary> /// Gets or sets the Buttons property. This dependency property /// indicates the list of BindableApplicationBarButton objects that /// map to ApplicationBarIconButton generated for the ApplicationBar. /// </summary> public DependencyObjectCollection<BindableApplicationBarButton> Buttons { get { return (DependencyObjectCollection<BindableApplicationBarButton>)GetValue(ButtonsProperty); } set { SetValue(ButtonsProperty, value); } } /// <summary> /// Handles changes to the Buttons property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnButtonsChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var target = (BindableApplicationBar)d; var oldButtons = (DependencyObjectCollection<BindableApplicationBarButton>) e.OldValue; var newButtons = target.Buttons; target.OnButtonsChanged(oldButtons, newButtons); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the Buttons property. /// </summary> /// <param name="oldButtons">The old buttons.</param> /// <param name="newButtons">The new buttons.</param> protected virtual void OnButtonsChanged( DependencyObjectCollection<BindableApplicationBarButton> oldButtons, DependencyObjectCollection<BindableApplicationBarButton> newButtons) { if (oldButtons != null) { oldButtons.CollectionChanged -= this.ButtonsCollectionChanged; } if (newButtons != null) { newButtons.CollectionChanged += this.ButtonsCollectionChanged; } } #endregion #region MenuItems /// <summary> /// MenuItems Dependency Property /// </summary> public static readonly DependencyProperty MenuItemsProperty = DependencyProperty.Register( "MenuItems", typeof(DependencyObjectCollection<BindableApplicationBarMenuItem>), typeof(BindableApplicationBar), new PropertyMetadata(null, OnMenuItemsChanged)); /// <summary> /// Gets or sets the MenuItems property. This dependency property /// indicates the list of BindableApplicationBarMenuItem objects that /// map to ApplicationBarMenuItem generated for the ApplicationBar. /// </summary> public DependencyObjectCollection<BindableApplicationBarMenuItem> MenuItems { get { return (DependencyObjectCollection<BindableApplicationBarMenuItem>)GetValue(MenuItemsProperty); } set { SetValue(MenuItemsProperty, value); } } /// <summary> /// Handles changes to the MenuItems property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnMenuItemsChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; DependencyObjectCollection<BindableApplicationBarMenuItem> oldMenuItems = (DependencyObjectCollection<BindableApplicationBarMenuItem>)e.OldValue; DependencyObjectCollection<BindableApplicationBarMenuItem> newMenuItems = target.MenuItems; target.OnMenuItemsChanged(oldMenuItems, newMenuItems); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the MenuItems property. /// </summary> /// <param name="oldMenuItems">The old menu items.</param> /// <param name="newMenuItems">The new menu items.</param> protected virtual void OnMenuItemsChanged( DependencyObjectCollection<BindableApplicationBarMenuItem> oldMenuItems, DependencyObjectCollection<BindableApplicationBarMenuItem> newMenuItems) { if (oldMenuItems != null) { oldMenuItems.CollectionChanged -= this.MenuItemsCollectionChanged; } if (newMenuItems != null) { newMenuItems.CollectionChanged += this.MenuItemsCollectionChanged; } } #endregion #region ButtonsSource /// <summary> /// ButtonsSource Dependency Property /// </summary> public static readonly DependencyProperty ButtonsSourceProperty = DependencyProperty.Register( "ButtonsSource", typeof(IEnumerable), typeof(BindableApplicationBar), new PropertyMetadata(null, OnButtonsSourceChanged)); /// <summary> /// Gets or sets the ButtonsSource property. This dependency property /// indicates the collection from which to build the button objects, /// using the <see cref="ButtonTemplate"/> DataTemplate. /// </summary> public IEnumerable ButtonsSource { get { return (IEnumerable)GetValue(ButtonsSourceProperty); } set { SetValue(ButtonsSourceProperty, value); } } /// <summary> /// Handles changes to the ButtonsSource property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnButtonsSourceChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; IEnumerable oldButtonsSource = (IEnumerable)e.OldValue; IEnumerable newButtonsSource = target.ButtonsSource; target.OnButtonsSourceChanged(oldButtonsSource, newButtonsSource); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the ButtonsSource property. /// </summary> /// <param name="oldButtonsSource">The old buttons source.</param> /// <param name="newButtonsSource">The new buttons source.</param> protected virtual void OnButtonsSourceChanged( IEnumerable oldButtonsSource, IEnumerable newButtonsSource) { if (oldButtonsSource != null && oldButtonsSource is INotifyCollectionChanged) { ((INotifyCollectionChanged)oldButtonsSource) .CollectionChanged -= this.ButtonsSourceCollectionChanged; } this.GenerateButtonsFromSource(); if (newButtonsSource != null && newButtonsSource is INotifyCollectionChanged) { ((INotifyCollectionChanged)newButtonsSource) .CollectionChanged += this.ButtonsSourceCollectionChanged; } } private void ButtonsSourceCollectionChanged( object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var buttonSource in e.OldItems) { // Copy item reference to prevent access to modified closure var dataContext = buttonSource; var button = this.buttonsSourceButtons.FirstOrDefault( b => b.DataContext == dataContext); if (button != null) { this.buttonsSourceButtons.Remove(button); } } } if (this.ButtonsSource != null && this.ButtonTemplate != null && e.NewItems != null) { foreach (var buttonSource in e.NewItems) { var button = (BindableApplicationBarButton) this.ButtonTemplate.LoadContent(); if (button == null) { throw new InvalidOperationException( "BindableApplicationBar cannot use the ButtonsSource property without a valid ButtonTemplate"); } button.DataContext = buttonSource; this.buttonsSourceButtons.Add(button); } } } #endregion #region GenerateButtonsFromSource() private void GenerateButtonsFromSource() { this.buttonsSourceButtons.Clear(); if (this.applicationBar != null) { this.applicationBar.Buttons.Clear(); } if (this.ButtonsSource != null && this.ButtonTemplate != null) { foreach (var buttonSource in this.ButtonsSource) { var button = (BindableApplicationBarButton) this.ButtonTemplate.LoadContent(); if (button == null) { throw new InvalidOperationException( "BindableApplicationBar cannot use the ButtonsSource property without a valid ButtonTemplate"); } button.DataContext = buttonSource; this.buttonsSourceButtons.Add(button); } } } #endregion #region GenerateMenuItemsFromSource() private void GenerateMenuItemsFromSource() { this.menuItemsSourceMenuItems.Clear(); if (this.applicationBar != null) { this.applicationBar.MenuItems.Clear(); } if (this.MenuItemsSource != null && this.MenuItemTemplate != null) { foreach (var menuItemSource in this.MenuItemsSource) { var menuItem = (BindableApplicationBarMenuItem) this.MenuItemTemplate.LoadContent(); if (menuItem == null) { throw new InvalidOperationException( "BindableApplicationBar cannot use the MenuItemsSource property without a valid MenuItemTemplate"); } menuItem.DataContext = menuItemSource; this.menuItemsSourceMenuItems.Add(menuItem); } } } #endregion #region ButtonTemplate /// <summary> /// ButtonTemplate Dependency Property /// </summary> public static readonly DependencyProperty ButtonTemplateProperty = DependencyProperty.Register( "ButtonTemplate", typeof(DataTemplate), typeof(BindableApplicationBar), new PropertyMetadata(null, OnButtonTemplateChanged)); /// <summary> /// Gets or sets the ButtonTemplate property. /// This dependency property indicates the template for a /// <see cref="BindableApplicationBarButton"/> that is used together /// with the <see cref="ButtonsSource"/> collection /// to create the application bar buttons. /// </summary> /// <remarks> /// The default template defines the property names to match /// the names of properties of a BindableApplicationBarButton. /// </remarks> public DataTemplate ButtonTemplate { get { return (DataTemplate)GetValue(ButtonTemplateProperty); } set { SetValue(ButtonTemplateProperty, value); } } /// <summary> /// Handles changes to the ButtonTemplate property. /// </summary> /// <param name="d"> /// The dependency property. /// </param> /// <param name="e"> /// The event arguments. /// </param> private static void OnButtonTemplateChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; DataTemplate oldButtonTemplate = (DataTemplate)e.OldValue; DataTemplate newButtonTemplate = target.ButtonTemplate; target.OnButtonTemplateChanged( oldButtonTemplate, newButtonTemplate); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the ButtonTemplate property. /// </summary> /// <param name="oldButtonTemplate">The old button template.</param> /// <param name="newButtonTemplate">The new button template.</param> protected virtual void OnButtonTemplateChanged( DataTemplate oldButtonTemplate, DataTemplate newButtonTemplate) { this.GenerateButtonsFromSource(); } #endregion #region MenuItemsSource /// <summary> /// MenuItemsSource Dependency Property /// </summary> public static readonly DependencyProperty MenuItemsSourceProperty = DependencyProperty.Register( "MenuItemsSource", typeof(IEnumerable), typeof(BindableApplicationBar), new PropertyMetadata(null, OnMenuItemsSourceChanged)); /// <summary> /// Gets or sets the MenuItemsSource property. /// This dependency property indicates the collection from which /// to build the MenuItem objects, /// using the <see cref="MenuItemTemplate"/> DataTemplate. /// </summary> public IEnumerable MenuItemsSource { get { return (IEnumerable)GetValue(MenuItemsSourceProperty); } set { SetValue(MenuItemsSourceProperty, value); } } /// <summary> /// Handles changes to the MenuItemsSource property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnMenuItemsSourceChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; IEnumerable oldMenuItemsSource = (IEnumerable)e.OldValue; IEnumerable newMenuItemsSource = target.MenuItemsSource; target.OnMenuItemsSourceChanged( oldMenuItemsSource, newMenuItemsSource); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the MenuItemsSource property. /// </summary> /// <param name="oldMenuItemsSource"> /// The old MenuItemsSource value. /// </param> /// <param name="newMenuItemsSource"> /// The new MenuItemsSource value. /// </param> protected virtual void OnMenuItemsSourceChanged( IEnumerable oldMenuItemsSource, IEnumerable newMenuItemsSource) { if (oldMenuItemsSource != null && oldMenuItemsSource is INotifyCollectionChanged) { ((INotifyCollectionChanged)oldMenuItemsSource) .CollectionChanged -= this.MenuItemsSourceCollectionChanged; } this.GenerateMenuItemsFromSource(); if (newMenuItemsSource != null && newMenuItemsSource is INotifyCollectionChanged) { ((INotifyCollectionChanged)newMenuItemsSource) .CollectionChanged += this.MenuItemsSourceCollectionChanged; } } private void MenuItemsSourceCollectionChanged( object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var menuItemSource in e.OldItems) { // Copy item reference to prevent access to modified closure var dataContext = menuItemSource; var menuItem = this.menuItemsSourceMenuItems.FirstOrDefault( b => b.DataContext == dataContext); if (menuItem != null) { this.menuItemsSourceMenuItems.Remove(menuItem); } } } if (this.MenuItemsSource != null && this.MenuItemTemplate != null && e.NewItems != null) { foreach (var menuItemSource in e.NewItems) { var menuItem = (BindableApplicationBarMenuItem) this.MenuItemTemplate.LoadContent(); if (menuItem == null) { throw new InvalidOperationException( "BindableApplicationBar cannot use the MenuItemsSource property without a valid MenuItemTemplate"); } menuItem.DataContext = menuItemSource; this.menuItemsSourceMenuItems.Add(menuItem); } } } #endregion #region MenuItemTemplate /// <summary> /// MenuItemTemplate Dependency Property /// </summary> public static readonly DependencyProperty MenuItemTemplateProperty = DependencyProperty.Register( "MenuItemTemplate", typeof(DataTemplate), typeof(BindableApplicationBar), new PropertyMetadata(null, OnMenuItemTemplateChanged)); /// <summary> /// Gets or sets the MenuItemTemplate property. /// This dependency property indicates the template /// for a <see cref="BindableApplicationBarMenuItem"/> that is used /// together with the <see cref="MenuItemsSource"/> collection /// to create the application bar MenuItems. /// </summary> /// <remarks> /// The default template defines the property names to match /// the names of properties of a BindableApplicationBarMenuItem. /// </remarks> public DataTemplate MenuItemTemplate { get { return (DataTemplate)GetValue(MenuItemTemplateProperty); } set { SetValue(MenuItemTemplateProperty, value); } } /// <summary> /// Handles changes to the MenuItemTemplate property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnMenuItemTemplateChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; DataTemplate oldMenuItemTemplate = (DataTemplate)e.OldValue; DataTemplate newMenuItemTemplate = target.MenuItemTemplate; target.OnMenuItemTemplateChanged( oldMenuItemTemplate, newMenuItemTemplate); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the MenuItemTemplate property. /// </summary> /// <param name="oldMenuItemTemplate"> /// The old MenuItemTemplate value. /// </param> /// <param name="newMenuItemTemplate"> /// The new MenuItemTemplate value. /// </param> protected virtual void OnMenuItemTemplateChanged( DataTemplate oldMenuItemTemplate, DataTemplate newMenuItemTemplate) { this.GenerateMenuItemsFromSource(); } #endregion #region IsVisible /// <summary> /// IsVisible Dependency Property /// </summary> public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.Register( "IsVisible", typeof(bool), typeof(BindableApplicationBar), new PropertyMetadata(true, OnIsVisibleChanged)); /// <summary> /// Gets or sets a value indicating whether /// the attached ApplicationBar is visible. /// </summary> public bool IsVisible { get { return (bool)GetValue(IsVisibleProperty); } set { SetValue(IsVisibleProperty, value); } } /// <summary> /// Handles changes to the IsVisible property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnIsVisibleChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; bool oldIsVisible = (bool)e.OldValue; bool newIsVisible = target.IsVisible; target.OnIsVisibleChanged(oldIsVisible, newIsVisible); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the IsVisible property. /// </summary> /// <param name="oldIsVisible">The old IsVisible value.</param> /// <param name="newIsVisible">The new IsVisible value.</param> protected virtual void OnIsVisibleChanged( bool oldIsVisible, bool newIsVisible) { if (this.applicationBar != null) { this.applicationBar.IsVisible = newIsVisible; } this.isVisibleChanged = true; } #endregion #region IsMenuEnabled /// <summary> /// IsMenuEnabled Dependency Property /// </summary> public static readonly DependencyProperty IsMenuEnabledProperty = DependencyProperty.Register( "IsMenuEnabled", typeof(bool), typeof(BindableApplicationBar), new PropertyMetadata(true, OnIsMenuEnabledChanged)); /// <summary> /// Gets or sets a value indicating whether the menu is enabled. /// </summary> public bool IsMenuEnabled { get { return (bool)GetValue(IsMenuEnabledProperty); } set { SetValue(IsMenuEnabledProperty, value); } } /// <summary> /// Handles changes to the IsMenuEnabled property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnIsMenuEnabledChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; bool oldIsMenuEnabled = (bool)e.OldValue; bool newIsMenuEnabled = target.IsMenuEnabled; target.OnIsMenuEnabledChanged( oldIsMenuEnabled, newIsMenuEnabled); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the IsMenuEnabled property. /// </summary> /// <param name="oldIsMenuEnabled"> /// The old IsMenuEnabled value. /// </param> /// <param name="newIsMenuEnabled"> /// The new IsMenuEnabled value. /// </param> protected virtual void OnIsMenuEnabledChanged( bool oldIsMenuEnabled, bool newIsMenuEnabled) { if (this.applicationBar != null) { this.applicationBar.IsMenuEnabled = newIsMenuEnabled; } this.isMenuEnabledChanged = true; } #endregion #region IsMenuVisible /// <summary> /// IsMenuVisible Dependency Property /// </summary> public static readonly DependencyProperty IsMenuVisibleProperty = DependencyProperty.Register( "IsMenuVisible", typeof(bool), typeof(BindableApplicationBar), new PropertyMetadata(false, OnIsMenuVisibleChanged)); /// <summary> /// Gets or sets a value indicating whether the menu is visible. /// </summary> public bool IsMenuVisible { get { return (bool)GetValue(IsMenuVisibleProperty); } set { SetValue(IsMenuVisibleProperty, value); } } /// <summary> /// Handles changes to the IsMenuVisible property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnIsMenuVisibleChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; bool oldIsMenuVisible = (bool)e.OldValue; bool newIsMenuVisible = target.IsMenuVisible; target.OnIsMenuVisibleChanged( oldIsMenuVisible, newIsMenuVisible); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the IsMenuVisible property. /// </summary> /// <param name="oldIsMenuVisible"> /// The old IsMenuVisible value. /// </param> /// <param name="newIsMenuVisible"> /// The new IsMenuVisible value. /// </param> protected virtual void OnIsMenuVisibleChanged( bool oldIsMenuVisible, bool newIsMenuVisible) { if (this.isMenuVisible != newIsMenuVisible) { // Make sure the property is read-only. this.IsMenuVisible = this.isMenuVisible; } } /// <summary> /// Used to make sure the dependency property is read-only. /// </summary> private bool isMenuVisible; #endregion #region BackgroundColor /// <summary> /// BackgroundColor Dependency Property /// </summary> public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register( "BackgroundColor", typeof(Color), typeof(BindableApplicationBar), new PropertyMetadata( Colors.Magenta, OnBackgroundColorChanged)); /// <summary> /// Gets or sets the BackgroundColor property. /// This dependency property indicates the BackgroundColor /// of the ApplicationBar. /// </summary> public Color BackgroundColor { get { return (Color)GetValue(BackgroundColorProperty); } set { SetValue(BackgroundColorProperty, value); } } /// <summary> /// Handles changes to the BackgroundColor property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnBackgroundColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; Color oldBackgroundColor = (Color)e.OldValue; Color newBackgroundColor = target.BackgroundColor; target.OnBackgroundColorChanged( oldBackgroundColor, newBackgroundColor); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the BackgroundColor property. /// </summary> /// <param name="oldBackgroundColor"> /// The old BackgroundColor value. /// </param> /// <param name="newBackgroundColor"> /// The new BackgroundColor value. /// </param> protected virtual void OnBackgroundColorChanged( Color oldBackgroundColor, Color newBackgroundColor) { if (this.applicationBar != null) { this.applicationBar.BackgroundColor = this.BackgroundColor; } this.backgroundColorChanged = true; } #endregion #region ForegroundColor /// <summary> /// ForegroundColor Dependency Property /// </summary> public static readonly DependencyProperty ForegroundColorProperty = DependencyProperty.Register( "ForegroundColor", typeof(Color), typeof(BindableApplicationBar), new PropertyMetadata( Colors.Magenta, OnForegroundColorChanged)); /// <summary> /// Gets or sets the ForegroundColor property. This dependency /// property indicates the ForegroundColor of the ApplicationBar. /// </summary> public Color ForegroundColor { get { return (Color)GetValue(ForegroundColorProperty); } set { SetValue(ForegroundColorProperty, value); } } /// <summary> /// Handles changes to the ForegroundColor property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnForegroundColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; Color oldForegroundColor = (Color)e.OldValue; Color newForegroundColor = target.ForegroundColor; target.OnForegroundColorChanged( oldForegroundColor, newForegroundColor); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the ForegroundColor property. /// </summary> /// <param name="oldForegroundColor"> /// The old ForegroundColor value. /// </param> /// <param name="newForegroundColor"> /// The new ForegroundColor value. /// </param> protected virtual void OnForegroundColorChanged( Color oldForegroundColor, Color newForegroundColor) { if (this.applicationBar != null) { this.applicationBar.ForegroundColor = this.ForegroundColor; } this.foregroundColorChanged = true; } #endregion #region Mode /// <summary> /// Mode Dependency Property /// </summary> public static readonly DependencyProperty ModeProperty = DependencyProperty.Register( "Mode", typeof(ApplicationBarMode), typeof(BindableApplicationBar), new PropertyMetadata( ApplicationBarMode.Default, OnModeChanged)); /// <summary> /// Gets or sets the Mode property. This dependency property /// indicates the Mode of the ApplicationBar. /// </summary> public ApplicationBarMode Mode { get { return (ApplicationBarMode)GetValue(ModeProperty); } set { SetValue(ModeProperty, value); } } /// <summary> /// Handles changes to the Mode property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnModeChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; ApplicationBarMode oldMode = (ApplicationBarMode)e.OldValue; ApplicationBarMode newMode = target.Mode; target.OnModeChanged(oldMode, newMode); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the Mode property. /// </summary> /// <param name="oldMode">The old Mode value.</param> /// <param name="newMode">The new Mode value.</param> protected virtual void OnModeChanged( ApplicationBarMode oldMode, ApplicationBarMode newMode) { if (this.applicationBar != null) { this.applicationBar.Mode = newMode; } this.modeChanged = true; } #endregion #region BindableOpacity /// <summary> /// BindableOpacity Dependency Property /// </summary> public static readonly DependencyProperty BindableOpacityProperty = DependencyProperty.Register( "BindableOpacity", typeof(double), typeof(BindableApplicationBar), new PropertyMetadata(1.0, OnBindableOpacityChanged)); /// <summary> /// Gets or sets the BindableOpacity property. /// This dependency property indicates the Opacity of /// the ApplicationBar. /// The <see cref="UIElement.Opacity"/> property can be used instead, /// since BindableOpacity is only used to allow handling changes to /// <see cref="UIElement.Opacity"/>. /// </summary> public double BindableOpacity { get { return (double)GetValue(BindableOpacityProperty); } set { SetValue(BindableOpacityProperty, value); } } /// <summary> /// Handles changes to the BindableOpacity property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnBindableOpacityChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { BindableApplicationBar target = (BindableApplicationBar)d; double oldBindableOpacity = (double)e.OldValue; double newBindableOpacity = target.BindableOpacity; target.OnBindableOpacityChanged( oldBindableOpacity, newBindableOpacity); } /// <summary> /// Provides derived classes an opportunity to handle changes to /// the BindableOpacity property. /// </summary> /// <param name="oldBindableOpacity"> /// The old BindableOpacity value. /// </param> /// <param name="newBindableOpacity"> /// The new BindableOpacity value. /// </param> protected virtual void OnBindableOpacityChanged( double oldBindableOpacity, double newBindableOpacity) { if (this.applicationBar != null) { this.applicationBar.Opacity = newBindableOpacity; } this.bindableOpacityChanged = true; } #endregion #region CTOR /// <summary> /// Initializes a new instance of the <see cref="BindableApplicationBar"/> class. /// </summary> public BindableApplicationBar() { this.Buttons = new DependencyObjectCollection<BindableApplicationBarButton>(); this.MenuItems = new DependencyObjectCollection<BindableApplicationBarMenuItem>(); DefaultStyleKey = typeof(BindableApplicationBar); this.Buttons.CollectionChanged += this.ButtonsCollectionChanged; this.MenuItems.CollectionChanged += this.MenuItemsCollectionChanged; this.buttonsSourceButtons.CollectionChanged += this.ButtonsCollectionChanged; this.menuItemsSourceMenuItems.CollectionChanged += this.MenuItemsCollectionChanged; SetBinding( BindableOpacityProperty, new Binding("Opacity") { RelativeSource = new RelativeSource(RelativeSourceMode.Self) }); } #endregion #region Attach() /// <summary> /// Attaches the BindableApplicationBar to the specified page, /// creating the ApplicationBar if required and adding the buttons /// and menu items specified in the Buttons and MenuItems properties. /// </summary> /// <param name="parentPage">The parentPage to attach to.</param> public void Attach(PhoneApplicationPage parentPage) { this.page = parentPage; this.applicationBar = (ApplicationBar)(//parentPage.ApplicationBar ?? (parentPage.ApplicationBar = new ApplicationBar())); this.applicationBar.StateChanged += this.ApplicationBarStateChanged; if (this.GetBindingExpression(DataContextProperty) == null && this.DataContext == null) { this.SetBinding( DataContextProperty, new Binding("DataContext") { Source = this.page }); } this.SynchronizeProperties(); this.AttachButtons(this.Buttons); this.AttachButtons(this.buttonsSourceButtons); this.AttachMenuItems(this.MenuItems); this.AttachMenuItems(this.menuItemsSourceMenuItems); } #endregion #region SynchronizeProperties() private void SynchronizeProperties() { if (this.isVisibleChanged) { this.applicationBar.IsVisible = this.IsVisible; } else if (GetBindingExpression(IsVisibleProperty) == null) { this.IsVisible = this.applicationBar.IsVisible; } if (this.isMenuEnabledChanged) { this.applicationBar.IsMenuEnabled = this.IsMenuEnabled; } else if (GetBindingExpression(IsMenuEnabledProperty) == null) { this.IsMenuEnabled = this.applicationBar.IsMenuEnabled; } if (this.backgroundColorChanged) { this.applicationBar.BackgroundColor = this.BackgroundColor; } else if (GetBindingExpression(BackgroundColorProperty) == null) { this.BackgroundColor = this.applicationBar.BackgroundColor; } if (this.foregroundColorChanged) { this.applicationBar.ForegroundColor = this.ForegroundColor; } else if (GetBindingExpression(ForegroundColorProperty) == null) { this.ForegroundColor = this.applicationBar.ForegroundColor; } if (this.modeChanged) { this.applicationBar.Mode = this.Mode; } else if (GetBindingExpression(ModeProperty) == null) { this.Mode = this.applicationBar.Mode; } if (this.bindableOpacityChanged) { this.applicationBar.Opacity = this.BindableOpacity; } else if (GetBindingExpression(BindableOpacityProperty) == null) { this.BindableOpacity = this.applicationBar.Opacity; } } #endregion #region AttachButtons() private void AttachButtons( IEnumerable<BindableApplicationBarButton> buttons) { int i = this.applicationBar.Buttons.Count; foreach (var button in buttons) { button.Attach(this.applicationBar, i++); if (button.GetBindingExpression( FrameworkElement.DataContextProperty) == null && button.DataContext == null) { button.SetBinding( FrameworkElement.DataContextProperty, new Binding("DataContext") { Source = this }); } } } #endregion #region AttachMenuItems() private void AttachMenuItems( IEnumerable<BindableApplicationBarMenuItem> menuItems) { int j = this.applicationBar.MenuItems.Count; foreach (var menuItem in menuItems) { menuItem.Attach(this.applicationBar, j++); if (menuItem.GetBindingExpression( FrameworkElement.DataContextProperty) == null && menuItem.DataContext == null) { menuItem.SetBinding( FrameworkElement.DataContextProperty, new Binding("DataContext") { Source = this }); } } } #endregion #region Detach() /// <summary> /// Detaches from the specified page, removing all the buttons /// and menu items specified in the Buttons and MenuItems properties. /// </summary> /// <remarks> /// Note: The code in this method has not been tested and is likely /// not to work properly, will possibly raise exceptions /// and leak memory. /// </remarks> /// <param name="parentPage">The parentPage.</param> public void Detach(PhoneApplicationPage parentPage) { if (parentPage != this.page) { throw new InvalidOperationException(); } if (this.page != parentPage) { return; } var binding = this.GetBindingExpression(DataContextProperty); if (binding != null && binding.ParentBinding.Source == this.page) { this.DataContext = null; } this.DetachButtons(this.buttonsSourceButtons); this.DetachButtons(this.Buttons); this.DetachMenuItems(this.menuItemsSourceMenuItems); this.DetachMenuItems(this.MenuItems); this.applicationBar.StateChanged -= this.ApplicationBarStateChanged; this.applicationBar = null; } #endregion #region DetachButtons() private void DetachButtons( IEnumerable<BindableApplicationBarButton> buttons) { foreach (var button in buttons) { button.Detach(); var binding = button.GetBindingExpression( FrameworkElement.DataContextProperty); if (binding != null && binding.ParentBinding.Source == this) { this.DataContext = null; } } } #endregion #region DetachMenuItems() private void DetachMenuItems( IEnumerable<BindableApplicationBarMenuItem> menuItems) { foreach (var menuItem in menuItems) { menuItem.Detach(); var binding = menuItem.GetBindingExpression( FrameworkElement.DataContextProperty); if (binding != null && binding.ParentBinding.Source == this) { this.DataContext = null; } } } #endregion #region AttachButton() private void AttachButton(BindableApplicationBarButton button, int i) { if (button.GetBindingExpression( FrameworkElement.DataContextProperty) == null && button.GetValue( FrameworkElement.DataContextProperty) == null) { button.DataContext = this.DataContext; } //button.Attach(this.applicationBar, i); if (button.IconUri != null) { button.Attach(this.applicationBar, i); } } #endregion #region DetachButton() private void DetachButton(BindableApplicationBarButton button) { if (button.GetBindingExpression(DataContextProperty) == null && button.GetValue(DataContextProperty) == this.DataContext) { button.DataContext = null; } button.Detach(); } #endregion #region AttachMenuItem() private void AttachMenuItem( BindableApplicationBarMenuItem menuItem, int i) { if (menuItem.GetBindingExpression( FrameworkElement.DataContextProperty) == null && menuItem.GetValue( FrameworkElement.DataContextProperty) == null) { menuItem.DataContext = this.DataContext; } menuItem.Attach(this.applicationBar, i); } #endregion #region DetachMenuItem() private void DetachMenuItem(BindableApplicationBarMenuItem menuItem) { if (menuItem.GetBindingExpression(DataContextProperty) == null && menuItem.GetValue(DataContextProperty) == this.DataContext) { menuItem.DataContext = null; } menuItem.Detach(); } #endregion #region ApplicationBarStateChanged() private void ApplicationBarStateChanged( object sender, ApplicationBarStateChangedEventArgs e) { this.isMenuVisible = e.IsMenuVisible; this.IsMenuVisible = this.isMenuVisible; } #endregion #region ButtonsCollectionChanged() private void ButtonsCollectionChanged( object sender, NotifyCollectionChangedEventArgs e) { if (this.applicationBar == null) { return; } if (e.OldItems != null) { foreach (var oldItem in e.OldItems) { this.DetachButton((BindableApplicationBarButton)oldItem); } } if (e.NewItems != null) { int i = 0; foreach (var newItem in e.NewItems) { this.AttachButton( (BindableApplicationBarButton)newItem, e.NewStartingIndex + i++); } } } #endregion #region MenuItemsCollectionChanged() private void MenuItemsCollectionChanged( object sender, NotifyCollectionChangedEventArgs e) { if (this.applicationBar == null) { return; } if (e.OldItems != null) { foreach (var oldItem in e.OldItems) { this.DetachMenuItem( (BindableApplicationBarMenuItem)oldItem); } } if (e.NewItems != null) { int i = 0; foreach (var newItem in e.NewItems) { this.AttachMenuItem( (BindableApplicationBarMenuItem)newItem, e.NewStartingIndex + i++); } } } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ProgressNotifyableViewModel.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if !XAMARIN namespace Catel.MVVM { using System.ComponentModel; using Data; using IoC; using MVVM.Tasks; /// <summary> /// The progress notifyable view model base. /// </summary> public class ProgressNotifyableViewModel : ViewModelBase, IProgressNotifyableViewModel { #region Constants /// <summary>Register the Task property so it is known in the class.</summary> public static readonly PropertyData TaskProperty = RegisterProperty("Task", typeof(ITask), default(ITask)); /// <summary>Register the TaskMessage property so it is known in the class.</summary> public static readonly PropertyData TaskMessageProperty = RegisterProperty("TaskMessage", typeof(string), default(string), (s, e) => ((ProgressNotifyableViewModel)s).OnTaskMessageChanged()); /// <summary>Register the TaskName property so it is known in the class.</summary> public static readonly PropertyData TaskNameProperty = RegisterProperty("TaskName", typeof(string)); /// <summary>Register the TaskPercentage property so it is known in the class.</summary> public static readonly PropertyData TaskPercentageProperty = RegisterProperty("TaskPercentage", typeof(int), default(int), (s, e) => ((ProgressNotifyableViewModel)s).OnTaskPercentageChanged()); /// <summary>Register the TaskPercentage property so it is known in the class.</summary> public static readonly PropertyData TaskIsIndeterminateProperty = RegisterProperty("TaskIsIndeterminate", typeof(bool), true); /// <summary>Register the DetailedMessage property so it is known in the class.</summary> public static readonly PropertyData DetailedMessageProperty = RegisterProperty("DetailedMessage", typeof(string)); #endregion #region Fields /// <summary> /// The _current item. /// </summary> private int _currentItem; /// <summary> /// The _total items. /// </summary> private int _totalItems; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ProgressNotifyableViewModel"/> class. /// </summary> /// <remarks>Must have a public constructor in order to be serializable.</remarks> public ProgressNotifyableViewModel() : this(false, false, false) { DispatchPropertyChangedEvent = true; } /// <summary> /// Initializes a new instance of the <see cref="ProgressNotifyableViewModel"/> class. /// </summary> /// <param name="supportIEditableObject">if set to <c>true</c>, the view model will natively support models that /// implement the <see cref="IEditableObject"/> interface.</param> /// <param name="ignoreMultipleModelsWarning">if set to <c>true</c>, the warning when using multiple models is ignored.</param> /// <param name="skipViewModelAttributesInitialization"> /// if set to <c>true</c>, the initialization will be skipped and must be done manually via <see cref="ViewModelBase.InitializeViewModelAttributes"/>. /// </param> /// <exception cref="ModelNotRegisteredException">A mapped model is not registered.</exception> /// <exception cref="PropertyNotFoundInModelException">A mapped model property is not found.</exception> public ProgressNotifyableViewModel(bool supportIEditableObject, bool ignoreMultipleModelsWarning, bool skipViewModelAttributesInitialization) : base(supportIEditableObject, ignoreMultipleModelsWarning, skipViewModelAttributesInitialization) { DispatchPropertyChangedEvent = true; } /// <summary> /// Initializes a new instance of the <see cref="ViewModelBase"/> class. /// <para/> /// This constructor allows the injection of a custom <see cref="IServiceLocator"/>. /// </summary> /// <param name="serviceLocator">The service locator to inject. If <c>null</c>, the <see cref="Catel.IoC.ServiceLocator.Default"/> will be used.</param> /// <param name="supportIEditableObject">if set to <c>true</c>, the view model will natively support models that /// implement the <see cref="IEditableObject"/> interface.</param> /// <param name="ignoreMultipleModelsWarning">if set to <c>true</c>, the warning when using multiple models is ignored.</param> /// <param name="skipViewModelAttributesInitialization">if set to <c>true</c>, the initialization will be skipped and must be done manually via <see cref="ViewModelBase.InitializeViewModelAttributes"/>.</param> /// <exception cref="ModelNotRegisteredException">A mapped model is not registered.</exception> /// <exception cref="PropertyNotFoundInModelException">A mapped model property is not found.</exception> public ProgressNotifyableViewModel(IServiceLocator serviceLocator, bool supportIEditableObject = true, bool ignoreMultipleModelsWarning = false, bool skipViewModelAttributesInitialization = false) : base(serviceLocator, supportIEditableObject, ignoreMultipleModelsWarning, skipViewModelAttributesInitialization) { DispatchPropertyChangedEvent = true; } #endregion #region Properties /// <summary> /// Gets or sets the task message. /// </summary> [ViewModelToModel("Task", "Message")] public string TaskMessage { get { return GetValue<string>(TaskMessageProperty); } } /// <summary> /// Gets or sets the task name. /// </summary> [ViewModelToModel("Task", "Name")] public string TaskName { get { return GetValue<string>(TaskNameProperty); } } /// <summary> /// Gets or sets the task percentage. /// </summary> [ViewModelToModel("Task", "Percentage")] public int TaskPercentage { get { return GetValue<int>(TaskPercentageProperty); } } /// <summary> /// Gets or sets the task percentage. /// </summary> [ViewModelToModel("Task", "IsIndeterminate")] public bool TaskIsIndeterminate { get { return GetValue<bool>(TaskIsIndeterminateProperty); } } #endregion #region IProgressNotifyableViewModel Members /// <summary> /// Gets the task. /// </summary> [Model] public ITask Task { get { return GetValue<ITask>(TaskProperty); } private set { SetValue(TaskProperty, value); } } /// <summary> /// Gets the detailed message. /// </summary> public string DetailedMessage { get { return GetValue<string>(DetailedMessageProperty); } private set { SetValue(DetailedMessageProperty, value); } } /// <summary> /// Gets the percentage. /// </summary> public int Percentage { get { if (_totalItems <= 0) { return 0; } var nextPercentage = (int)((100.0f * (_currentItem + 1)) / _totalItems); var currentPercentage = (int)((100.0f * _currentItem) / _totalItems); float deltaPercentage = nextPercentage - currentPercentage; float scaledTaskPercentage = Task.Percentage * deltaPercentage / 100.0f; return (int)(currentPercentage + scaledTaskPercentage); } } /// <summary> /// The update status. /// </summary> /// <param name="currentItem">The current item.</param> /// <param name="totalItems">The total items.</param> /// <param name="task">The task</param> /// <exception cref="System.ArgumentNullException">The <paramref name="task" /> is <c>null</c>.</exception> public void UpdateStatus(int currentItem, int totalItems, ITask task) { Argument.IsNotNull(() => task); Task = task; _currentItem = currentItem; _totalItems = totalItems; RaisePropertyChanged(() => Percentage); } #endregion #region Methods /// <summary>Occurs when the value of the TaskMessage property is changed.</summary> private void OnTaskMessageChanged() { DetailedMessage = string.Format("{0}: {1}", Task.Name, Task.Message); } /// <summary>Occurs when the value of the TaskPercentage property is changed.</summary> private void OnTaskPercentageChanged() { RaisePropertyChanged(() => Percentage); } #endregion } } #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.IO; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XmlDiff; using CoreXml.Test.XLinq; using Xunit; namespace XDocumentTests.Streaming { public class XStreamingElementAPI { private XDocument _xDoc = null; private XDocument _xmlDoc = null; private XmlDiff _diff; private bool _invokeStatus = false; private bool _invokeError = false; private Stream _sourceStream = null; private Stream _targetStream = null; public void GetFreshStream() { _sourceStream = new MemoryStream(); _targetStream = new MemoryStream(); } public void ResetStreamPos() { if (_sourceStream.CanSeek) { _sourceStream.Position = 0; } if (_targetStream.CanSeek) { _targetStream.Position = 0; } } private XmlDiff Diff { get { return _diff ?? (_diff = new XmlDiff()); } } [Fact] public void XNameAsNullConstructor() { Assert.Throws<ArgumentNullException>(() => new XStreamingElement(null)); } [Fact] public void XNameAsEmptyStringConstructor() { AssertExtensions.Throws<ArgumentException>(null, () => new XStreamingElement(string.Empty)); Assert.Throws<XmlException>(() => new XStreamingElement(" ")); } [Fact] public void XNameConstructor() { XStreamingElement streamElement = new XStreamingElement("contact"); Assert.Equal("<contact />", streamElement.ToString()); } [Fact] public void XNameWithNamespaceConstructor() { XNamespace ns = @"http:\\www.contacts.com\"; XElement contact = new XElement(ns + "contact"); XStreamingElement streamElement = new XStreamingElement(ns + "contact"); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XNameAndNullObjectConstructor() { XStreamingElement streamElement = new XStreamingElement("contact", null); Assert.Equal("<contact />", streamElement.ToString()); } [Fact] public void XNameAndXElementObjectConstructor() { XElement contact = new XElement("contact", new XElement("phone", "925-555-0134")); XStreamingElement streamElement = new XStreamingElement("contact", contact.Element("phone")); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XNameAndEmptyStringConstructor() { XElement contact = new XElement("contact", ""); XStreamingElement streamElement = new XStreamingElement("contact", ""); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XDocTypeInXStreamingElement() { XDocumentType node = new XDocumentType( "DOCTYPE", "note", "SYSTEM", "<!ELEMENT note (to,from,heading,body)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT body (#PCDATA)>"); XStreamingElement streamElement = new XStreamingElement("Root", node); Assert.Throws<InvalidOperationException>(() => streamElement.Save(new MemoryStream())); } [Fact] public void XmlDeclInXStreamingElement() { XDeclaration node = new XDeclaration("1.0", "utf-8", "yes"); XElement element = new XElement("Root", node); XStreamingElement streamElement = new XStreamingElement("Root", node); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XCDataInXStreamingElement() { XCData node = new XCData("CDATA Text '%^$#@!&*()'"); XElement element = new XElement("Root", node); XStreamingElement streamElement = new XStreamingElement("Root", node); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XCommentInXStreamingElement() { XComment node = new XComment("This is a comment"); XElement element = new XElement("Root", node); XStreamingElement streamElement = new XStreamingElement("Root", node); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XDocInXStreamingElement() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XStreamingElement streamElement = new XStreamingElement("Root", _xDoc); Assert.Throws<InvalidOperationException>(() => streamElement.Save(new MemoryStream())); } [Fact] public void XNameAndCollectionObjectConstructor() { XElement contact = new XElement( "contacts", new XElement("contact1", "jane"), new XElement("contact2", "john")); List<Object> list = new List<Object>(); list.Add(contact.Element("contact1")); list.Add(contact.Element("contact2")); XStreamingElement streamElement = new XStreamingElement("contacts", list); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XNameAndObjectArrayConstructor() { XElement contact = new XElement( "contact", new XElement("name", "jane"), new XElement("phone", new XAttribute("type", "home"), "925-555-0134")); XStreamingElement streamElement = new XStreamingElement( "contact", new object[] { contact.Element("name"), contact.Element("phone") }); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void NamePropertyGet() { XStreamingElement streamElement = new XStreamingElement("contact"); Assert.Equal("contact", streamElement.Name); } [Fact] public void NamePropertySet() { XStreamingElement streamElement = new XStreamingElement("ThisWillChangeToContact"); streamElement.Name = "contact"; Assert.Equal("contact", streamElement.Name.ToString()); } [Fact] public void NamePropertySetInvalid() { XStreamingElement streamElement = new XStreamingElement("ThisWillChangeToInValidName"); Assert.Throws<ArgumentNullException>(() => streamElement.Name = null); } [Fact] public void XMLPropertyGet() { XElement contact = new XElement("contact", new XElement("phone", "925-555-0134")); XStreamingElement streamElement = new XStreamingElement("contact", contact.Element("phone")); Assert.Equal(contact.ToString(SaveOptions.None), streamElement.ToString(SaveOptions.None)); } [Fact] public void AddWithNull() { XStreamingElement streamElement = new XStreamingElement("contact"); streamElement.Add(null); Assert.Equal("<contact />", streamElement.ToString()); } [Theory] [InlineData(9255550134)] [InlineData("9255550134")] [InlineData(9255550134.0)] public void AddObject(object content) { XElement contact = new XElement("phone", content); XStreamingElement streamElement = new XStreamingElement("phone"); streamElement.Add(content); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddTimeSpanObject() { XElement contact = new XElement("Time", TimeSpan.FromMinutes(12)); XStreamingElement streamElement = new XStreamingElement("Time"); streamElement.Add(TimeSpan.FromMinutes(12)); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddAttribute() { XElement contact = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XStreamingElement streamElement = new XStreamingElement("phone"); streamElement.Add(contact.Attribute("type")); streamElement.Add("925-555-0134"); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } //An attribute cannot be written after content. [Fact] public void AddAttributeAfterContent() { XElement contact = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134"); streamElement.Add(contact.Attribute("type")); using (XmlWriter w = XmlWriter.Create(new MemoryStream(), null)) { Assert.Throws<InvalidOperationException>(() => streamElement.WriteTo(w)); } } [Fact] public void AddIEnumerableOfNulls() { XElement element = new XElement("root", GetNulls()); XStreamingElement streamElement = new XStreamingElement("root"); streamElement.Add(GetNulls()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } ///<summary> /// This function returns an IEnumeralb of nulls ///</summary> public IEnumerable<XNode> GetNulls() { return Enumerable.Repeat((XNode)null, 1000); } [Fact] public void AddIEnumerableOfXNodes() { XElement x = InputSpace.GetElement(100, 3); XElement element = new XElement("root", x.Nodes()); XStreamingElement streamElement = new XStreamingElement("root"); streamElement.Add(x.Nodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddIEnumerableOfMixedNodes() { XElement element = new XElement("root", GetMixedNodes()); XStreamingElement streamElement = new XStreamingElement("root"); streamElement.Add(GetMixedNodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } ///<summary> /// This function returns mixed IEnumerable of XObjects with XAttributes first ///</summary> public IEnumerable<XObject> GetMixedNodes() { InputSpace.Load("Word.xml", ref _xDoc, ref _xmlDoc); foreach (XAttribute x in _xDoc.Root.Attributes()) yield return x; foreach (XNode n in _xDoc.Root.DescendantNodes()) yield return n; } [Fact] public void AddIEnumerableOfXNodesPlusString() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XElement element = new XElement("contacts", _xDoc.Root.DescendantNodes(), "This String"); XStreamingElement streamElement = new XStreamingElement("contacts"); streamElement.Add(_xDoc.Root.DescendantNodes(), "This String"); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddIEnumerableOfXNodesPlusAttribute() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XAttribute xAttrib = new XAttribute("Attribute", "Value"); XElement element = new XElement("contacts", xAttrib, _xDoc.Root.DescendantNodes()); XStreamingElement streamElement = new XStreamingElement("contacts"); streamElement.Add(xAttrib, _xDoc.Root.DescendantNodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void SaveWithNull() { XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134"); Assert.Throws<ArgumentNullException>(() => streamElement.Save((XmlWriter)null)); } [Fact] public void SaveWithXmlTextWriter() { XElement contact = new XElement( "contacts", new XElement("contact", "jane"), new XElement("contact", "john")); XStreamingElement streamElement = new XStreamingElement("contacts", contact.Elements()); GetFreshStream(); TextWriter w = new StreamWriter(_sourceStream); streamElement.Save(w); w.Flush(); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void SaveTwice() { XElement contact = new XElement( "contacts", new XElement("contact", "jane"), new XElement("contact", "john")); XStreamingElement streamElement = new XStreamingElement("contacts", contact.Elements()); GetFreshStream(); streamElement.Save(_sourceStream); _sourceStream.Position = 0; streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void WriteToWithNull() { XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134"); Assert.Throws<ArgumentNullException>(() => streamElement.WriteTo((XmlWriter)null)); } [Fact] public void ModifyOriginalElement() { XElement contact = new XElement( "contact", new XElement("name", "jane"), new XElement("phone", new XAttribute("type", "home"), "925-555-0134")); XStreamingElement streamElement = new XStreamingElement("contact", new object[] { contact.Elements() }); foreach (XElement x in contact.Elements()) { x.Remove(); } GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void NestedXStreamingElement() { XElement name = new XElement("name", "jane"); XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XElement contact = new XElement("contact", name, new XElement("phones", phone)); XStreamingElement streamElement = new XStreamingElement( "contact", name, new XStreamingElement("phones", phone)); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void NestedXStreamingElementPlusIEnumerable() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XElement element = new XElement("contacts", new XElement("Element", "Value"), _xDoc.Root.DescendantNodes()); XStreamingElement streamElement = new XStreamingElement("contacts"); streamElement.Add(new XStreamingElement("Element", "Value"), _xDoc.Root.DescendantNodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void IEnumerableLazinessTest1() { XElement name = new XElement("name", "jane"); XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XElement contact = new XElement("contact", name, phone); IEnumerable<XElement> elements = contact.Elements(); name.Remove(); phone.Remove(); XStreamingElement streamElement = new XStreamingElement("contact", new object[] { elements }); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void IEnumerableLazinessTest2() { XElement name = new XElement("name", "jane"); XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XElement contact = new XElement("contact", name, phone); // During debug this test will not work correctly since ToString() of // streamElement gets called for displaying the value in debugger local window. XStreamingElement streamElement = new XStreamingElement("contact", GetElements(contact)); GetFreshStream(); contact.Save(_targetStream); _invokeStatus = true; streamElement.Save(_sourceStream); Assert.False(_invokeError, "IEnumerable walked before expected"); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } ///<summary> /// This function is used in above variation to make sure that the /// IEnumerable is indeed walked lazily ///</summary> public IEnumerable<XElement> GetElements(XElement element) { if (_invokeStatus == false) { _invokeError = true; } foreach (XElement x in element.Elements()) { yield return x; } } [Fact] public void XStreamingElementInXElement() { XElement element = new XElement("contacts"); XStreamingElement streamElement = new XStreamingElement("contact", "SomeValue"); element.Add(streamElement); XElement x = element.Element("contact"); GetFreshStream(); streamElement.Save(_sourceStream); x.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XStreamingElementInXDocument() { _xDoc = new XDocument(); XStreamingElement streamElement = new XStreamingElement("contacts", "SomeValue"); _xDoc.Add(streamElement); GetFreshStream(); streamElement.Save(_sourceStream); _xDoc.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Xml.Schema; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Specifies the state of the XmlWriter. public enum WriteState { // Nothing has been written yet. Start, // Writing the prolog. Prolog, // Writing a the start tag for an element. Element, // Writing an attribute value. Attribute, // Writing element content. Content, // XmlWriter is closed; Close has been called. Closed, // Writer is in error state. Error, }; // Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents // that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification. public abstract partial class XmlWriter : IDisposable { // Helper buffer for WriteNode(XmlReader, bool) private char[] _writeNodeBuffer; // Constants private const int WriteNodeBufferSize = 1024; // Returns the settings describing the features of the writer. Returns null for V1 XmlWriters (XmlTextWriter). public virtual XmlWriterSettings Settings { get { return null; } } // Write methods // Writes out the XML declaration with the version "1.0". public abstract void WriteStartDocument(); //Writes out the XML declaration with the version "1.0" and the specified standalone attribute. public abstract void WriteStartDocument(bool standalone); //Closes any open elements or attributes and puts the writer back in the Start state. public abstract void WriteEndDocument(); // Writes out the DOCTYPE declaration with the specified name and optional attributes. public abstract void WriteDocType(string name, string pubid, string sysid, string subset); // Writes out the specified start tag and associates it with the given namespace. public void WriteStartElement(string localName, string ns) { WriteStartElement(null, localName, ns); } // Writes out the specified start tag and associates it with the given namespace and prefix. public abstract void WriteStartElement(string prefix, string localName, string ns); // Writes out a start tag with the specified local name with no namespace. public void WriteStartElement(string localName) { WriteStartElement(null, localName, (string)null); } // Closes one element and pops the corresponding namespace scope. public abstract void WriteEndElement(); // Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>. public abstract void WriteFullEndElement(); // Writes out the attribute with the specified LocalName, value, and NamespaceURI. public void WriteAttributeString(string localName, string ns, string value) { WriteStartAttribute(null, localName, ns); WriteString(value); WriteEndAttribute(); } // Writes out the attribute with the specified LocalName and value. public void WriteAttributeString(string localName, string value) { WriteStartAttribute(null, localName, (string)null); WriteString(value); WriteEndAttribute(); } // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value. public void WriteAttributeString(string prefix, string localName, string ns, string value) { WriteStartAttribute(prefix, localName, ns); WriteString(value); WriteEndAttribute(); } // Writes the start of an attribute. public void WriteStartAttribute(string localName, string ns) { WriteStartAttribute(null, localName, ns); } // Writes the start of an attribute. public abstract void WriteStartAttribute(string prefix, string localName, string ns); // Writes the start of an attribute. public void WriteStartAttribute(string localName) { WriteStartAttribute(null, localName, (string)null); } // Closes the attribute opened by WriteStartAttribute call. public abstract void WriteEndAttribute(); // Writes out a <![CDATA[...]]>; block containing the specified text. public abstract void WriteCData(string text); // Writes out a comment <!--...-->; containing the specified text. public abstract void WriteComment(string text); // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public abstract void WriteProcessingInstruction(string name, string text); // Writes out an entity reference as follows: "&"+name+";". public abstract void WriteEntityRef(string name); // Forces the generation of a character entity for the specified Unicode character value. public abstract void WriteCharEntity(char ch); // Writes out the given whitespace. public abstract void WriteWhitespace(string ws); // Writes out the specified text content. public abstract void WriteString(string text); // Write out the given surrogate pair as an entity reference. public abstract void WriteSurrogateCharEntity(char lowChar, char highChar); // Writes out the specified text content. public abstract void WriteChars(char[] buffer, int index, int count); // Writes raw markup from the given character buffer. public abstract void WriteRaw(char[] buffer, int index, int count); // Writes raw markup from the given string. public abstract void WriteRaw(string data); // Encodes the specified binary bytes as base64 and writes out the resulting text. public abstract void WriteBase64(byte[] buffer, int index, int count); // Encodes the specified binary bytes as binhex and writes out the resulting text. public virtual void WriteBinHex(byte[] buffer, int index, int count) { BinHexEncoder.Encode(buffer, index, count, this); } // Returns the state of the XmlWriter. public abstract WriteState WriteState { get; } // Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader. public abstract void Flush(); // Returns the closest prefix defined in the current namespace scope for the specified namespace URI. public abstract string LookupPrefix(string ns); // Gets an XmlSpace representing the current xml:space scope. public virtual XmlSpace XmlSpace { get { return XmlSpace.Default; } } // Gets the current xml:lang scope. public virtual string XmlLang { get { return string.Empty; } } // Scalar Value Methods // Writes out the specified name, ensuring it is a valid NmToken according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual void WriteNmToken(string name) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual void WriteName(string name) { WriteString(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException)); } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public virtual void WriteQualifiedName(string localName, string ns) { if (ns != null && ns.Length > 0) { string prefix = LookupPrefix(ns); if (prefix == null) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } WriteString(prefix); WriteString(":"); } WriteString(localName); } // Writes out the specified value. public virtual void WriteValue(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } WriteString(XmlUntypedStringConverter.Instance.ToString(value, null)); } // Writes out the specified value. public virtual void WriteValue(string value) { if (value == null) { return; } WriteString(value); } // Writes out the specified value. public virtual void WriteValue(bool value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(DateTime value) { WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind)); } // Writes out the specified value. public virtual void WriteValue(DateTimeOffset value) { // Under Win8P, WriteValue(DateTime) will invoke this overload, but custom writers // might not have implemented it. This base implementation should call WriteValue(DateTime). // The following conversion results in the same string as calling ToString with DateTimeOffset. if (value.Offset != TimeSpan.Zero) { WriteValue(value.LocalDateTime); } else { WriteValue(value.UtcDateTime); } } // Writes out the specified value. public virtual void WriteValue(double value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(float value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(decimal value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(int value) { WriteString(XmlConvert.ToString(value)); } // Writes out the specified value. public virtual void WriteValue(long value) { WriteString(XmlConvert.ToString(value)); } // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. public virtual void WriteAttributes(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration) { if (reader.MoveToFirstAttribute()) { WriteAttributes(reader, defattr); reader.MoveToElement(); } } else if (reader.NodeType != XmlNodeType.Attribute) { throw new XmlException(SR.Xml_InvalidPosition, string.Empty); } else { do { // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. // If either of these is true and defattr=false, we should not write the attribute out if (defattr || !reader.IsDefaultInternal) { WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI); while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { WriteEntityRef(reader.Name); } else { WriteString(reader.Value); } } WriteEndAttribute(); } } while (reader.MoveToNextAttribute()); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. public virtual void WriteNode(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); WriteAttributes(reader, defattr); if (reader.IsEmptyElement) { WriteEndElement(); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (_writeNodeBuffer == null) { _writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) { this.WriteChars(_writeNodeBuffer, 0, read); } } else { WriteString(reader.Value); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: WriteWhitespace(reader.Value); break; case XmlNodeType.CDATA: WriteCData(reader.Value); break; case XmlNodeType.EntityReference: WriteEntityRef(reader.Name); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.DocumentType: WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value); break; case XmlNodeType.Comment: WriteComment(reader.Value); break; case XmlNodeType.EndElement: WriteFullEndElement(); break; } } while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Element Helper Methods // Writes out an element with the specified name containing the specified string value. public void WriteElementString(string localName, String value) { WriteElementString(localName, null, value); } // Writes out an attribute with the specified name, namespace URI and string value. public void WriteElementString(string localName, String ns, String value) { WriteStartElement(localName, ns); if (null != value && 0 != value.Length) { WriteString(value); } WriteEndElement(); } // Writes out an attribute with the specified name, namespace URI, and string value. public void WriteElementString(string prefix, String localName, String ns, String value) { WriteStartElement(prefix, localName, ns); if (null != value && 0 != value.Length) { WriteString(value); } WriteEndElement(); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { } // // Static methods for creating writers // // Creates an XmlWriter for writing into the provided stream. public static XmlWriter Create(Stream output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided stream with the specified settings. public static XmlWriter Create(Stream output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } // Creates an XmlWriter for writing into the provided TextWriter. public static XmlWriter Create(TextWriter output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided TextWriter with the specified settings. public static XmlWriter Create(TextWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } // Creates an XmlWriter for writing into the provided StringBuilder. public static XmlWriter Create(StringBuilder output) { return Create(output, null); } // Creates an XmlWriter for writing into the provided StringBuilder with the specified settings. public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } if (output == null) { throw new ArgumentNullException(nameof(output)); } return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture)); } // Creates an XmlWriter wrapped around the provided XmlWriter with the default settings. public static XmlWriter Create(XmlWriter output) { return Create(output, null); } // Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings. public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings) { if (settings == null) { settings = new XmlWriterSettings(); } return settings.CreateWriter(output); } } }
/** * @file * This file defines the AuthListener class that provides the interface between * authentication mechanisms and applications. */ /****************************************************************************** * Copyright (c) 2012, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ using System; using System.Threading; using System.Runtime.InteropServices; namespace AllJoynUnity { public partial class AllJoyn { public abstract class AuthListener : IDisposable { /** * Constructor for AuthListener class */ public AuthListener() { _requestCredentials = new InternalRequestCredentials(this._RequestCredentials); _verifyCredentials = new InternalVerifyCredentials(this._VerifyCredentials); _securityViolation = new InternalSecurityViolation(this._SecurityViolation); _authenticationComplete = new InternalAuthenticationComplete(this._AuthenticationComplete); AuthListenerCallbacks callbacks; callbacks.requestCredentials = Marshal.GetFunctionPointerForDelegate(_requestCredentials); callbacks.verifyCredentials = Marshal.GetFunctionPointerForDelegate(_verifyCredentials); callbacks.securityViolation = Marshal.GetFunctionPointerForDelegate(_securityViolation); callbacks.authenticationComplete = Marshal.GetFunctionPointerForDelegate(_authenticationComplete); main = GCHandle.Alloc(callbacks, GCHandleType.Pinned); _authListener = alljoyn_authlistener_create(main.AddrOfPinnedObject(), IntPtr.Zero); } #region Virtual Methods /** * Authentication mechanism requests user credentials. If the user name is not an empty string * the request is for credentials for that specific user. A count allows the listener to decide * whether to allow or reject multiple authentication attempts to the same peer. * * @param authMechanism The name of the authentication mechanism issuing the request. * @param peerName The name of the remote peer being authenticated. On the initiating * side this will be a well-known-name for the remote peer. On the * accepting side this will be the unique bus name for the remote peer. * @param authCount Count (starting at 1) of the number of authentication request attempts made. * @param userName The user name for the credentials being requested. * @param credMask A bit mask identifying the credentials being requested. The application * may return none, some or all of the requested credentials. * @param[out] credentials The credentials returned. * * @return The caller should return true if the request is being accepted or false if the * requests is being rejected. If the request is rejected the authentication is * complete. */ protected abstract bool RequestCredentials(string authMechanism, string peerName, ushort authCount, string userName, Credentials.CredentialFlags credMask, Credentials credentials); /** * Authentication mechanism requests verification of credentials from a remote peer. * * @param authMechanism The name of the authentication mechanism issuing the request. * @param peerName The name of the remote peer being authenticated. On the initiating * side this will be a well-known-name for the remote peer. On the * accepting side this will be the unique bus name for the remote peer. * @param credentials The credentials to be verified. * * @return The listener should return true if the credentials are acceptable or false if the * credentials are being rejected. */ protected virtual bool VerifyCredentials(string authMechanism, string peerName, Credentials credentials) { return false; } /** * Optional method that if implemented allows an application to monitor security violations. This * function is called when an attempt to decrypt an encrypted messages failed or when an unencrypted * message was received on an interface that requires encryption. The message contains only * header information. * * @param status A status code indicating the type of security violation. * @param msg The message that cause the security violation. */ protected virtual void SecurityViolation(QStatus status, Message msg) { } /** * Reports successful or unsuccessful completion of authentication. * * @param authMechanism The name of the authentication mechanism that was used or an empty * string if the authentication failed. * @param peerName The name of the remote peer being authenticated. On the initiating * side this will be a well-known-name for the remote peer. On the * accepting side this will be the unique bus name for the remote peer. * @param success true if the authentication was successful, otherwise false. */ protected abstract void AuthenticationComplete(string authMechanism, string peerName, bool success); #endregion #region Callbacks private int _RequestCredentials(IntPtr context, IntPtr authMechanism, IntPtr peerName, ushort authCount, IntPtr userName, ushort credMask, IntPtr credentials) { return (RequestCredentials(Marshal.PtrToStringAnsi(authMechanism), Marshal.PtrToStringAnsi(peerName), authCount, Marshal.PtrToStringAnsi(userName), (Credentials.CredentialFlags)credMask, new Credentials(credentials)) ? 1 : 0); } private int _VerifyCredentials(IntPtr context, IntPtr authMechanism, IntPtr peerName, IntPtr credentials) { return (VerifyCredentials(Marshal.PtrToStringAnsi(authMechanism), Marshal.PtrToStringAnsi(peerName), new Credentials(credentials)) ? 1 : 0); } private void _SecurityViolation(IntPtr context, int status, IntPtr msg) { SecurityViolation(status, new Message(msg)); } private void _AuthenticationComplete(IntPtr context, IntPtr authMechanism, IntPtr peerName, int success) { AuthenticationComplete(Marshal.PtrToStringAnsi(authMechanism), Marshal.PtrToStringAnsi(peerName), success == 1 ? true : false); } #endregion #region Delegates [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int InternalRequestCredentials(IntPtr context, IntPtr authMechanism, IntPtr peerName, ushort authCount, IntPtr userName, ushort credMask, IntPtr credentials); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int InternalVerifyCredentials(IntPtr context, IntPtr authMechanism, IntPtr peerName, IntPtr credentials); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void InternalSecurityViolation(IntPtr context, int status, IntPtr msg); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void InternalAuthenticationComplete(IntPtr context, IntPtr authMechanism, IntPtr peerName, int success); #endregion #region DLL Imports [DllImport(DLL_IMPORT_TARGET)] private extern static IntPtr alljoyn_authlistener_create( IntPtr callbacks, IntPtr context); [DllImport(DLL_IMPORT_TARGET)] private extern static void alljoyn_authlistener_destroy(IntPtr listener); #endregion #region IDisposable ~AuthListener() { Dispose(false); } /** * Dispose the AuthListener * @param disposing describes if its activly being disposed */ protected virtual void Dispose(bool disposing) { if(!_isDisposed) { alljoyn_authlistener_destroy(_authListener); _authListener = IntPtr.Zero; main.Free(); } _isDisposed = true; } /** * Dispose the AuthListener */ public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Structs private struct AuthListenerCallbacks { public IntPtr requestCredentials; public IntPtr verifyCredentials; public IntPtr securityViolation; public IntPtr authenticationComplete; } #endregion #region Internal Properties internal IntPtr UnmanagedPtr { get { return _authListener; } } #endregion #region Data IntPtr _authListener; bool _isDisposed = false; GCHandle main; InternalRequestCredentials _requestCredentials; InternalVerifyCredentials _verifyCredentials; InternalSecurityViolation _securityViolation; InternalAuthenticationComplete _authenticationComplete; #endregion } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Monitor.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Monitor; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ActivityLogAlertsOperations operations. /// </summary> internal partial class ActivityLogAlertsOperations : IServiceOperations<MonitorManagementClient>, IActivityLogAlertsOperations { /// <summary> /// Initializes a new instance of the ActivityLogAlertsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ActivityLogAlertsOperations(MonitorManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorManagementClient /// </summary> public MonitorManagementClient Client { get; private set; } /// <summary> /// Create a new activity log alert or update an existing one. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='activityLogAlertName'> /// The name of the activity log alert. /// </param> /// <param name='activityLogAlert'> /// The activity log alert to create or use for the update. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ActivityLogAlertResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string activityLogAlertName, ActivityLogAlertResource activityLogAlert, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (activityLogAlertName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "activityLogAlertName"); } if (activityLogAlert == null) { throw new ValidationException(ValidationRules.CannotBeNull, "activityLogAlert"); } if (activityLogAlert != null) { activityLogAlert.Validate(); } string apiVersion = "2017-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("activityLogAlertName", activityLogAlertName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("activityLogAlert", activityLogAlert); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{activityLogAlertName}", System.Uri.EscapeDataString(activityLogAlertName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(activityLogAlert != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(activityLogAlert, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ActivityLogAlertResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ActivityLogAlertResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ActivityLogAlertResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an activity log alert. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='activityLogAlertName'> /// The name of the activity log alert. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ActivityLogAlertResource>> GetWithHttpMessagesAsync(string resourceGroupName, string activityLogAlertName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (activityLogAlertName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "activityLogAlertName"); } string apiVersion = "2017-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("activityLogAlertName", activityLogAlertName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{activityLogAlertName}", System.Uri.EscapeDataString(activityLogAlertName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ActivityLogAlertResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ActivityLogAlertResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete an activity log alert. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='activityLogAlertName'> /// The name of the activity log alert. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string activityLogAlertName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (activityLogAlertName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "activityLogAlertName"); } string apiVersion = "2017-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("activityLogAlertName", activityLogAlertName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{activityLogAlertName}", System.Uri.EscapeDataString(activityLogAlertName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates an existing ActivityLogAlertResource's tags. To update other fields /// use the CreateOrUpdate method. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='activityLogAlertName'> /// The name of the activity log alert. /// </param> /// <param name='activityLogAlertPatch'> /// Parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ActivityLogAlertResource>> UpdateWithHttpMessagesAsync(string resourceGroupName, string activityLogAlertName, ActivityLogAlertPatchBody activityLogAlertPatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (activityLogAlertName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "activityLogAlertName"); } if (activityLogAlertPatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "activityLogAlertPatch"); } string apiVersion = "2017-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("activityLogAlertName", activityLogAlertName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("activityLogAlertPatch", activityLogAlertPatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{activityLogAlertName}", System.Uri.EscapeDataString(activityLogAlertName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(activityLogAlertPatch != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(activityLogAlertPatch, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ActivityLogAlertResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ActivityLogAlertResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all activity log alerts in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<ActivityLogAlertResource>>> ListBySubscriptionIdWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListBySubscriptionId", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/activityLogAlerts").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<ActivityLogAlertResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<ActivityLogAlertResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all activity log alerts in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<ActivityLogAlertResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2017-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<ActivityLogAlertResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<ActivityLogAlertResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Azure.Core; using Azure.Messaging.ServiceBus.Primitives; namespace Azure.Messaging.ServiceBus.Administration { /// <summary> /// Represents the correlation rule filter expression. /// </summary> /// <remarks> /// <para> /// A CorrelationRuleFilter holds a set of conditions that are matched against one of more of an arriving message's user and system properties. /// A common use is a match against the <see cref="ServiceBusMessage.CorrelationId"/> property, but the application can also choose to match against /// <see cref="ServiceBusMessage.ContentType"/>, <see cref="ServiceBusMessage.Subject"/>, <see cref="ServiceBusMessage.MessageId"/>, <see cref="ServiceBusMessage.ReplyTo"/>, /// <see cref="ServiceBusMessage.ReplyToSessionId"/>, <see cref="ServiceBusMessage.SessionId"/>, <see cref="ServiceBusMessage.To"/>, and any user-defined properties. /// A match exists when an arriving message's value for a property is equal to the value specified in the correlation filter. For string expressions, /// the comparison is case-sensitive. When specifying multiple match properties, the filter combines them as a logical AND condition, /// meaning all conditions must match for the filter to match. /// </para> /// <para> /// The CorrelationRuleFilter provides an efficient shortcut for declarations of filters that deal only with correlation equality. /// In this case the cost of the lexicographical analysis of the expression can be avoided. /// Not only will correlation filters be optimized at declaration time, but they will also be optimized at runtime. /// Correlation filter matching can be reduced to a hashtable lookup, which aggregates the complexity of the set of defined correlation filters to O(1). /// </para> /// </remarks> public sealed class CorrelationRuleFilter : RuleFilter { /// <summary> /// Initializes a new instance of the <see cref="CorrelationRuleFilter" /> class with default values. /// </summary> public CorrelationRuleFilter() { } /// <summary> /// Initializes a new instance of the <see cref="CorrelationRuleFilter" /> class with the specified correlation identifier. /// </summary> /// <param name="correlationId">The identifier for the correlation.</param> /// <exception cref="System.ArgumentException">Thrown when the <paramref name="correlationId" /> is null or empty.</exception> public CorrelationRuleFilter(string correlationId) : this() { Argument.AssertNotNullOrWhiteSpace(correlationId, nameof(correlationId)); CorrelationId = correlationId; } internal override RuleFilter Clone() => new CorrelationRuleFilter(CorrelationId) { MessageId = MessageId, To = To, ReplyTo = ReplyTo, Subject = Subject, SessionId = SessionId, ReplyToSessionId = ReplyToSessionId, ContentType = ContentType, ApplicationProperties = (ApplicationProperties as PropertyDictionary).Clone() }; /// <summary> /// Identifier of the correlation. /// </summary> /// <value>The identifier of the correlation.</value> public string CorrelationId { get; set; } /// <summary> /// Identifier of the message. /// </summary> /// <value>The identifier of the message.</value> /// <remarks>Max MessageId size is 128 chars.</remarks> public string MessageId { get; set; } /// <summary> /// Address to send to. /// </summary> /// <value>The address to send to.</value> public string To { get; set; } /// <summary> /// Address of the queue to reply to. /// </summary> /// <value>The address of the queue to reply to.</value> public string ReplyTo { get; set; } /// <summary> /// Application specific subject. /// </summary> /// <value>The application specific subject.</value> public string Subject { get; set; } /// <summary> /// Session identifier. /// </summary> /// <value>The session identifier.</value> /// <remarks>Max size of sessionId is 128 chars.</remarks> public string SessionId { get; set; } /// <summary> /// Session identifier to reply to. /// </summary> /// <value>The session identifier to reply to.</value> /// <remarks>Max size of ReplyToSessionId is 128.</remarks> public string ReplyToSessionId { get; set; } /// <summary> /// Content type of the message. /// </summary> /// <value>The content type of the message.</value> public string ContentType { get; set; } /// <summary> /// Application specific properties of the message. /// </summary> /// <value>The application specific properties of the message.</value> /// <remarks> /// Only following value types are supported: /// byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double, decimal, /// bool, Guid, string, Uri, DateTime, DateTimeOffset, TimeSpan, Stream, byte[], /// and IList / IDictionary of supported types /// </remarks> public IDictionary<string, object> ApplicationProperties { get; internal set; } = new PropertyDictionary(); /// <summary> /// Converts the value of the current instance to its equivalent string representation. /// </summary> /// <returns>A string representation of the current instance.</returns> public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append("CorrelationRuleFilter: "); var isFirstExpression = true; AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.CorrelationId", CorrelationId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.MessageId", MessageId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.To", To); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyTo", ReplyTo); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.Label", Subject); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.SessionId", SessionId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyToSessionId", ReplyToSessionId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ContentType", ContentType); foreach (var pair in ApplicationProperties) { string propertyName = pair.Key; object propertyValue = pair.Value; AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); } return stringBuilder.ToString(); } private static void AppendPropertyExpression(ref bool firstExpression, StringBuilder builder, string propertyName, object value) { if (value != null) { if (firstExpression) { firstExpression = false; } else { builder.Append(" AND "); } builder.AppendFormat(CultureInfo.InvariantCulture, "{0} = '{1}'", propertyName, value); } } /// <inheritdoc/> public override int GetHashCode() { int hash = 13; unchecked { hash = (hash * 7) + CorrelationId?.GetHashCode() ?? 0; hash = (hash * 7) + MessageId?.GetHashCode() ?? 0; hash = (hash * 7) + SessionId?.GetHashCode() ?? 0; } return hash; } /// <inheritdoc/> public override bool Equals(object obj) { var other = obj as CorrelationRuleFilter; return Equals(other); } /// <inheritdoc/> public override bool Equals(RuleFilter other) { if (other is CorrelationRuleFilter correlationRuleFilter) { if (string.Equals(CorrelationId, correlationRuleFilter.CorrelationId, StringComparison.OrdinalIgnoreCase) && string.Equals(MessageId, correlationRuleFilter.MessageId, StringComparison.OrdinalIgnoreCase) && string.Equals(To, correlationRuleFilter.To, StringComparison.OrdinalIgnoreCase) && string.Equals(ReplyTo, correlationRuleFilter.ReplyTo, StringComparison.OrdinalIgnoreCase) && string.Equals(Subject, correlationRuleFilter.Subject, StringComparison.OrdinalIgnoreCase) && string.Equals(SessionId, correlationRuleFilter.SessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ReplyToSessionId, correlationRuleFilter.ReplyToSessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ContentType, correlationRuleFilter.ContentType, StringComparison.OrdinalIgnoreCase)) { if (ApplicationProperties.Count != correlationRuleFilter.ApplicationProperties.Count) { return false; } foreach (var param in ApplicationProperties) { if (!correlationRuleFilter.ApplicationProperties.TryGetValue(param.Key, out var otherParamValue) || (param.Value == null ^ otherParamValue == null) || (param.Value != null && !param.Value.Equals(otherParamValue))) { return false; } } return true; } } return false; } /// <summary>Compares two <see cref="CorrelationRuleFilter"/> values for equality.</summary> public static bool operator ==(CorrelationRuleFilter left, CorrelationRuleFilter right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } return left.Equals(right); } /// <summary>Compares two <see cref="CorrelationRuleFilter"/> values for inequality.</summary> public static bool operator !=(CorrelationRuleFilter left, CorrelationRuleFilter right) { return !(left == right); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal partial class InlineRenameSession { /// <summary> /// Manages state for open text buffers. /// </summary> internal class OpenTextBufferManager : ForegroundThreadAffinitizedObject { private readonly DynamicReadOnlyRegionQuery _isBufferReadOnly; private readonly InlineRenameSession _session; private readonly ITextBuffer _subjectBuffer; private readonly IEnumerable<Document> _baseDocuments; private readonly ITextBufferFactoryService _textBufferFactoryService; private static readonly object s_propagateSpansEditTag = new object(); private static readonly object s_calculateMergedSpansEditTag = new object(); /// <summary> /// The list of active tracking spans that are updated with the session's replacement text. /// These are also the only spans the user can edit during an inline rename session. /// </summary> private readonly Dictionary<TextSpan, RenameTrackingSpan> _referenceSpanToLinkedRenameSpanMap = new Dictionary<TextSpan, RenameTrackingSpan>(); private readonly List<RenameTrackingSpan> _conflictResolutionRenameTrackingSpans = new List<RenameTrackingSpan>(); private readonly IList<IReadOnlyRegion> _readOnlyRegions = new List<IReadOnlyRegion>(); private readonly IList<IWpfTextView> _textViews = new List<IWpfTextView>(); private TextSpan? _activeSpan; public OpenTextBufferManager( InlineRenameSession session, ITextBuffer subjectBuffer, Workspace workspace, IEnumerable<Document> documents, ITextBufferFactoryService textBufferFactoryService) { _session = session; _subjectBuffer = subjectBuffer; _baseDocuments = documents; _textBufferFactoryService = textBufferFactoryService; _subjectBuffer.ChangedLowPriority += OnTextBufferChanged; foreach (var view in session._textBufferAssociatedViewService.GetAssociatedTextViews(_subjectBuffer)) { ConnectToView(view); } session.UndoManager.CreateStartRenameUndoTransaction(workspace, subjectBuffer, session); _isBufferReadOnly = new DynamicReadOnlyRegionQuery((isEdit) => !_session._isApplyingEdit); UpdateReadOnlyRegions(); } public IWpfTextView ActiveTextview { get { foreach (var view in _textViews) { if (view.HasAggregateFocus) { return view; } } return _textViews.FirstOrDefault(); } } private void UpdateReadOnlyRegions(bool removeOnly = false) { AssertIsForeground(); if (!removeOnly && _session.ReplacementText == string.Empty) { return; } using (var readOnlyEdit = _subjectBuffer.CreateReadOnlyRegionEdit()) { foreach (var oldReadOnlyRegion in _readOnlyRegions) { readOnlyEdit.RemoveReadOnlyRegion(oldReadOnlyRegion); } _readOnlyRegions.Clear(); if (!removeOnly) { // We will compute the new read only regions to be all spans that are not currently in an editable span var editableSpans = GetEditableSpansForSnapshot(_subjectBuffer.CurrentSnapshot); var entireBufferSpan = _subjectBuffer.CurrentSnapshot.GetSnapshotSpanCollection(); var newReadOnlySpans = NormalizedSnapshotSpanCollection.Difference(entireBufferSpan, new NormalizedSnapshotSpanCollection(editableSpans)); foreach (var newReadOnlySpan in newReadOnlySpans) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(newReadOnlySpan, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow, _isBufferReadOnly)); } // The spans we added allow typing at the start and end. We'll add extra // zero-width read-only regions at the start and end of the file to fix this, // but only if we don't have an identifier at the start or end that _would_ let // them type there. if (editableSpans.All(s => s.Start > 0)) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly)); } if (editableSpans.All(s => s.End < _subjectBuffer.CurrentSnapshot.Length)) { _readOnlyRegions.Add(readOnlyEdit.CreateDynamicReadOnlyRegion(new Span(_subjectBuffer.CurrentSnapshot.Length, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny, _isBufferReadOnly)); } } readOnlyEdit.Apply(); } } private void OnTextViewClosed(object sender, EventArgs e) { var view = sender as IWpfTextView; view.Closed -= OnTextViewClosed; _textViews.Remove(view); if (!_session._dismissed) { _session.Cancel(); } } internal void ConnectToView(IWpfTextView textView) { textView.Closed += OnTextViewClosed; _textViews.Add(textView); } public event Action SpansChanged; private void RaiseSpansChanged() { this.SpansChanged?.Invoke(); } internal IEnumerable<RenameTrackingSpan> GetRenameTrackingSpans() { return _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Concat(_conflictResolutionRenameTrackingSpans); } internal IEnumerable<SnapshotSpan> GetEditableSpansForSnapshot(ITextSnapshot snapshot) { return _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Select(r => r.TrackingSpan.GetSpan(snapshot)); } internal void SetReferenceSpans(IEnumerable<TextSpan> spans) { AssertIsForeground(); if (spans.SetEquals(_referenceSpanToLinkedRenameSpanMap.Keys)) { return; } using (new SelectionTracking(this)) { // Revert any previous edits in case we're removing spans. Undo conflict resolution as well to avoid // handling the various edge cases where a tracking span might not map to the right span in the current snapshot _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: false); _referenceSpanToLinkedRenameSpanMap.Clear(); foreach (var span in spans) { var renameableSpan = _session._renameInfo.GetReferenceEditSpan( new InlineRenameLocation(_baseDocuments.First(), span), CancellationToken.None); var trackingSpan = new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(renameableSpan.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), RenameSpanKind.Reference); _referenceSpanToLinkedRenameSpanMap[span] = trackingSpan; } _activeSpan = _activeSpan.HasValue && spans.Contains(_activeSpan.Value) ? _activeSpan : spans.Where(s => // in tests `ActiveTextview` can be null so don't depend on it ActiveTextview == null || ActiveTextview.GetSpanInView(_subjectBuffer.CurrentSnapshot.GetSpan(s.ToSpan())).Count != 0) // spans were successfully projected .FirstOrNullable(); // filter to spans that have a projection UpdateReadOnlyRegions(); this.ApplyReplacementText(updateSelection: false); } RaiseSpansChanged(); } private void OnTextBufferChanged(object sender, TextContentChangedEventArgs args) { AssertIsForeground(); // This might be an event fired due to our own edit if (args.EditTag == s_propagateSpansEditTag || _session._isApplyingEdit) { return; } using (Logger.LogBlock(FunctionId.Rename_OnTextBufferChanged, CancellationToken.None)) { var trackingSpansAfterEdit = new NormalizedSpanCollection(GetEditableSpansForSnapshot(args.After).Select(ss => (Span)ss)); var spansTouchedInEdit = new NormalizedSpanCollection(args.Changes.Select(c => c.NewSpan)); var intersectionSpans = NormalizedSpanCollection.Intersection(trackingSpansAfterEdit, spansTouchedInEdit); if (intersectionSpans.Count == 0) { // In Razor we sometimes get formatting changes during inline rename that // do not intersect with any of our spans. Ideally this shouldn't happen at // all, but if it does happen we can just ignore it. return; } // Cases with invalid identifiers may cause there to be multiple intersection // spans, but they should still all map to a single tracked rename span (e.g. // renaming "two" to "one two three" may be interpreted as two distinct // additions of "one" and "three"). var boundingIntersectionSpan = Span.FromBounds(intersectionSpans.First().Start, intersectionSpans.Last().End); var trackingSpansTouched = GetEditableSpansForSnapshot(args.After).Where(ss => ss.IntersectsWith(boundingIntersectionSpan)); Contract.Assert(trackingSpansTouched.Count() == 1); var singleTrackingSpanTouched = trackingSpansTouched.Single(); _activeSpan = _referenceSpanToLinkedRenameSpanMap.Where(kvp => kvp.Value.TrackingSpan.GetSpan(args.After).Contains(boundingIntersectionSpan)).Single().Key; _session.UndoManager.OnTextChanged(this.ActiveTextview.Selection, singleTrackingSpanTouched); } } /// <summary> /// This is a work around for a bug in Razor where the projection spans can get out-of-sync with the /// identifiers. When that bug is fixed this helper can be deleted. /// </summary> private bool AreAllReferenceSpansMappable() { // in tests `ActiveTextview` could be null so don't depend on it return ActiveTextview == null || _referenceSpanToLinkedRenameSpanMap.Keys .Select(s => s.ToSpan()) .All(s => s.End <= _subjectBuffer.CurrentSnapshot.Length && // span is valid for the snapshot ActiveTextview.GetSpanInView(_subjectBuffer.CurrentSnapshot.GetSpan(s)).Count != 0); // spans were successfully projected } internal void ApplyReplacementText(bool updateSelection = true) { AssertIsForeground(); if (!AreAllReferenceSpansMappable()) { // don't dynamically update the reference spans for documents with unmappable projections return; } _session.UndoManager.ApplyCurrentState( _subjectBuffer, s_propagateSpansEditTag, _referenceSpanToLinkedRenameSpanMap.Values.Where(r => r.Type != RenameSpanKind.None).Select(r => r.TrackingSpan)); if (updateSelection && _activeSpan.HasValue && this.ActiveTextview != null) { var snapshot = _subjectBuffer.CurrentSnapshot; _session.UndoManager.UpdateSelection(this.ActiveTextview, _subjectBuffer, _referenceSpanToLinkedRenameSpanMap[_activeSpan.Value].TrackingSpan); } } internal void Disconnect(bool documentIsClosed, bool rollbackTemporaryEdits) { AssertIsForeground(); // Detach from the buffer; it is important that this is done before we start // undoing transactions, since the undo actions will cause buffer changes. _subjectBuffer.ChangedLowPriority -= OnTextBufferChanged; foreach (var view in _textViews) { view.Closed -= OnTextViewClosed; } // Remove any old read only regions we had UpdateReadOnlyRegions(removeOnly: true); if (rollbackTemporaryEdits && !documentIsClosed) { _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: true); } } internal void ApplyConflictResolutionEdits(IInlineRenameReplacementInfo conflictResolution, IEnumerable<Document> documents, CancellationToken cancellationToken) { AssertIsForeground(); if (!AreAllReferenceSpansMappable()) { // don't dynamically update the reference spans for documents with unmappable projections return; } using (new SelectionTracking(this)) { // 1. Undo any previous edits and update the buffer to resulting document after conflict resolution _session.UndoManager.UndoTemporaryEdits(_subjectBuffer, disconnect: false); var preMergeSolution = _session._baseSolution; var postMergeSolution = conflictResolution.NewSolution; var diffMergingSession = new LinkedFileDiffMergingSession(preMergeSolution, postMergeSolution, postMergeSolution.GetChanges(preMergeSolution), logSessionInfo: true); var mergeResult = diffMergingSession.MergeDiffsAsync(mergeConflictHandler: null, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var newDocument = mergeResult.MergedSolution.GetDocument(documents.First().Id); var originalDocument = _baseDocuments.Single(d => d.Id == newDocument.Id); var changes = GetTextChangesFromTextDifferencingServiceAsync(originalDocument, newDocument, cancellationToken).WaitAndGetResult(cancellationToken); // TODO: why does the following line hang when uncommented? // newDocument.GetTextChangesAsync(this.baseDocuments.Single(d => d.Id == newDocument.Id), cancellationToken).WaitAndGetResult(cancellationToken).Reverse(); _session.UndoManager.CreateConflictResolutionUndoTransaction(_subjectBuffer, () => { using (var edit = _subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, s_propagateSpansEditTag)) { foreach (var change in changes) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } edit.Apply(); } }); // 2. We want to update referenceSpanToLinkedRenameSpanMap where spans were affected by conflict resolution. // We also need to add the remaining document edits to conflictResolutionRenameTrackingSpans // so they get classified/tagged correctly in the editor. _conflictResolutionRenameTrackingSpans.Clear(); foreach (var document in documents) { var relevantReplacements = conflictResolution.GetReplacements(document.Id).Where(r => GetRenameSpanKind(r.Kind) != RenameSpanKind.None); if (!relevantReplacements.Any()) { continue; } var bufferContainsLinkedDocuments = documents.Skip(1).Any(); var mergedReplacements = bufferContainsLinkedDocuments ? GetMergedReplacementInfos( relevantReplacements, conflictResolution.NewSolution.GetDocument(document.Id), mergeResult.MergedSolution.GetDocument(document.Id), cancellationToken) : relevantReplacements; // Show merge conflicts comments as unresolvable conflicts, and do not // show any other rename-related spans that overlap a merge conflict comment. var mergeConflictComments = mergeResult.MergeConflictCommentSpans.ContainsKey(document.Id) ? mergeResult.MergeConflictCommentSpans[document.Id] : SpecializedCollections.EmptyEnumerable<TextSpan>(); foreach (var conflict in mergeConflictComments) { // TODO: Add these to the unresolvable conflict counts in the dashboard _conflictResolutionRenameTrackingSpans.Add(new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(conflict.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), RenameSpanKind.UnresolvedConflict)); } foreach (var replacement in mergedReplacements) { var kind = GetRenameSpanKind(replacement.Kind); if (_referenceSpanToLinkedRenameSpanMap.ContainsKey(replacement.OriginalSpan) && kind != RenameSpanKind.Complexified) { var linkedRenameSpan = _session._renameInfo.GetConflictEditSpan( new InlineRenameLocation(newDocument, replacement.NewSpan), _session.ReplacementText, cancellationToken); if (linkedRenameSpan.HasValue) { if (!mergeConflictComments.Any(s => replacement.NewSpan.IntersectsWith(s))) { _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan] = new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan( linkedRenameSpan.Value.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), kind); } } else { // We might not have a renameable span if an alias conflict completely changed the text _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan] = new RenameTrackingSpan( _referenceSpanToLinkedRenameSpanMap[replacement.OriginalSpan].TrackingSpan, RenameSpanKind.None); if (_activeSpan.HasValue && _activeSpan.Value.IntersectsWith(replacement.OriginalSpan)) { _activeSpan = null; } } } else { if (!mergeConflictComments.Any(s => replacement.NewSpan.IntersectsWith(s))) { _conflictResolutionRenameTrackingSpans.Add(new RenameTrackingSpan( _subjectBuffer.CurrentSnapshot.CreateTrackingSpan(replacement.NewSpan.ToSpan(), SpanTrackingMode.EdgeInclusive, TrackingFidelityMode.Forward), kind)); } } } } UpdateReadOnlyRegions(); // 3. Reset the undo state and notify the taggers. this.ApplyReplacementText(updateSelection: false); RaiseSpansChanged(); } } private static async Task<IEnumerable<TextChange>> GetTextChangesFromTextDifferencingServiceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken = default(CancellationToken)) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, newDocument.Name, cancellationToken)) { if (oldDocument == newDocument) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (newDocument.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } SourceText oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); SourceText newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); if (oldText == newText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var textChanges = newText.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count != 1 || textChanges[0].Span != new TextSpan(0, oldText.Length)) { return textChanges; } var textDiffService = oldDocument.Project.Solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); return await textDiffService.GetTextChangesAsync(oldDocument, newDocument, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private IEnumerable<InlineRenameReplacement> GetMergedReplacementInfos( IEnumerable<InlineRenameReplacement> relevantReplacements, Document preMergeDocument, Document postMergeDocument, CancellationToken cancellationToken) { AssertIsForeground(); var textDiffService = preMergeDocument.Project.Solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); var contentType = preMergeDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType(); // TODO: Track all spans at once ITextBufferCloneService textBufferCloneService = null; SnapshotSpan? snapshotSpanToClone = null; string preMergeDocumentTextString = null; var preMergeDocumentText = preMergeDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var snapshot = preMergeDocumentText.FindCorrespondingEditorTextSnapshot(); if (snapshot != null) { textBufferCloneService = preMergeDocument.Project.Solution.Workspace.Services.GetService<ITextBufferCloneService>(); if (textBufferCloneService != null) { snapshotSpanToClone = snapshot.GetFullSpan(); } } if (snapshotSpanToClone == null) { preMergeDocumentTextString = preMergeDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(); } foreach (var replacement in relevantReplacements) { var buffer = snapshotSpanToClone.HasValue ? textBufferCloneService.Clone(snapshotSpanToClone.Value) : _textBufferFactoryService.CreateTextBuffer(preMergeDocumentTextString, contentType); var trackingSpan = buffer.CurrentSnapshot.CreateTrackingSpan(replacement.NewSpan.ToSpan(), SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward); using (var edit = _subjectBuffer.CreateEdit(EditOptions.None, null, s_calculateMergedSpansEditTag)) { foreach (var change in textDiffService.GetTextChangesAsync(preMergeDocument, postMergeDocument, cancellationToken).WaitAndGetResult(cancellationToken)) { buffer.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } yield return new InlineRenameReplacement(replacement.Kind, replacement.OriginalSpan, trackingSpan.GetSpan(buffer.CurrentSnapshot).Span.ToTextSpan()); } } private static RenameSpanKind GetRenameSpanKind(InlineRenameReplacementKind kind) { switch (kind) { case InlineRenameReplacementKind.NoConflict: case InlineRenameReplacementKind.ResolvedReferenceConflict: return RenameSpanKind.Reference; case InlineRenameReplacementKind.ResolvedNonReferenceConflict: return RenameSpanKind.None; case InlineRenameReplacementKind.UnresolvedConflict: return RenameSpanKind.UnresolvedConflict; case InlineRenameReplacementKind.Complexified: return RenameSpanKind.Complexified; default: throw ExceptionUtilities.Unreachable; } } private struct SelectionTracking : IDisposable { private readonly int? _anchor; private readonly int? _active; private readonly TextSpan _anchorSpan; private readonly TextSpan _activeSpan; private readonly OpenTextBufferManager _openTextBufferManager; public SelectionTracking(OpenTextBufferManager openTextBufferManager) { _openTextBufferManager = openTextBufferManager; _anchor = null; _anchorSpan = default(TextSpan); _active = null; _activeSpan = default(TextSpan); var textView = openTextBufferManager.ActiveTextview; if (textView == null) { return; } var selection = textView.Selection; var snapshot = openTextBufferManager._subjectBuffer.CurrentSnapshot; var containingSpans = openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Select(kvp => { // GetSpanInView() can return an empty collection if the tracking span isn't mapped to anything // in the current view, specifically a `@model SomeModelClass` directive in a Razor file. var ss = textView.GetSpanInView(kvp.Value.TrackingSpan.GetSpan(snapshot)).FirstOrDefault(); if (ss != default(SnapshotSpan) && (ss.IntersectsWith(selection.ActivePoint.Position) || ss.IntersectsWith(selection.AnchorPoint.Position))) { return Tuple.Create(kvp.Key, ss); } else { return null; } }).WhereNotNull(); foreach (var tuple in containingSpans) { if (tuple.Item2.IntersectsWith(selection.AnchorPoint.Position)) { _anchor = tuple.Item2.End - selection.AnchorPoint.Position; _anchorSpan = tuple.Item1; } if (tuple.Item2.IntersectsWith(selection.ActivePoint.Position)) { _active = tuple.Item2.End - selection.ActivePoint.Position; _activeSpan = tuple.Item1; } } } public void Dispose() { var textView = _openTextBufferManager.ActiveTextview; if (textView == null) { return; } if (_anchor.HasValue || _active.HasValue) { var selection = textView.Selection; var snapshot = _openTextBufferManager._subjectBuffer.CurrentSnapshot; var anchorSpan = _anchorSpan; var anchorPoint = new VirtualSnapshotPoint(textView.TextSnapshot, _anchor.HasValue && _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Keys.Any(s => s.OverlapsWith(anchorSpan)) ? GetNewEndpoint(_anchorSpan) - _anchor.Value : selection.AnchorPoint.Position); var activeSpan = _activeSpan; var activePoint = new VirtualSnapshotPoint(textView.TextSnapshot, _active.HasValue && _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.Keys.Any(s => s.OverlapsWith(activeSpan)) ? GetNewEndpoint(_activeSpan) - _active.Value : selection.ActivePoint.Position); textView.SetSelection(anchorPoint, activePoint); } } private SnapshotPoint GetNewEndpoint(TextSpan span) { var snapshot = _openTextBufferManager._subjectBuffer.CurrentSnapshot; var endPoint = _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.ContainsKey(span) ? _openTextBufferManager._referenceSpanToLinkedRenameSpanMap[span].TrackingSpan.GetEndPoint(snapshot) : _openTextBufferManager._referenceSpanToLinkedRenameSpanMap.First(kvp => kvp.Key.OverlapsWith(span)).Value.TrackingSpan.GetEndPoint(snapshot); return _openTextBufferManager.ActiveTextview.BufferGraph.MapUpToBuffer(endPoint, PointTrackingMode.Positive, PositionAffinity.Successor, _openTextBufferManager.ActiveTextview.TextBuffer).Value; } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.IO; using System.Linq; using System.Threading; using System.Xml.XPath; using Examine; using Examine.LuceneEngine.SearchCriteria; using Examine.Providers; using Lucene.Net.Documents; using Lucene.Net.Store; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Dynamics; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.Models; using UmbracoExamine; using umbraco; using Umbraco.Core.Cache; using Umbraco.Core.Sync; using Umbraco.Web.Cache; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { /// <summary> /// An IPublishedMediaStore that first checks for the media in Examine, and then reverts to the database /// </summary> /// <remarks> /// NOTE: In the future if we want to properly cache all media this class can be extended or replaced when these classes/interfaces are exposed publicly. /// </remarks> internal class PublishedMediaCache : IPublishedMediaCache { public PublishedMediaCache(ApplicationContext applicationContext) { if (applicationContext == null) throw new ArgumentNullException("applicationContext"); _applicationContext = applicationContext; } /// <summary> /// Generally used for unit testing to use an explicit examine searcher /// </summary> /// <param name="applicationContext"></param> /// <param name="searchProvider"></param> /// <param name="indexProvider"></param> internal PublishedMediaCache(ApplicationContext applicationContext, BaseSearchProvider searchProvider, BaseIndexProvider indexProvider) { if (applicationContext == null) throw new ArgumentNullException("applicationContext"); if (searchProvider == null) throw new ArgumentNullException("searchProvider"); if (indexProvider == null) throw new ArgumentNullException("indexProvider"); _applicationContext = applicationContext; _searchProvider = searchProvider; _indexProvider = indexProvider; } static PublishedMediaCache() { InitializeCacheConfig(); } private readonly ApplicationContext _applicationContext; private readonly BaseSearchProvider _searchProvider; private readonly BaseIndexProvider _indexProvider; public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return GetUmbracoMedia(nodeId); } public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, Guid nodeKey) { // TODO optimize with Examine? var mapAttempt = ApplicationContext.Current.Services.IdkMap.GetIdForKey(nodeKey, UmbracoObjectTypes.Media); return mapAttempt ? GetById(umbracoContext, preview, mapAttempt.Result) : null; } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { // first check in Examine for the cache values // +(+parentID:-1) +__IndexType:media var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.ParentId(-1).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard()); var result = searchProvider.Search(filter.Compile()); if (result != null) return result.Select(x => CreateFromCacheValues(ConvertFromSearchResult(x))); } catch (Exception ex) { if (ex is FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media", ex); } else if (ex is AlreadyClosedException) { //If the app domain is shutting down and the site is under heavy load the index reader will be closed and it really cannot //be re-opened since the app domain is shutting down. In this case we have no option but to try to load the data from the db. LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media, the app domain is most likely in a shutdown state", ex); } else throw; } } //something went wrong, fetch from the db var rootMedia = _applicationContext.Services.MediaService.GetRootMedia(); return rootMedia.Select(m => CreateFromCacheValues(ConvertFromIMedia(m))); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public bool XPathNavigatorIsNavigable { get { return false; } } public virtual bool HasContent(UmbracoContext context, bool preview) { throw new NotImplementedException(); } private ExamineManager GetExamineManagerSafe() { try { return ExamineManager.Instance; } catch (TypeInitializationException) { return null; } } private BaseIndexProvider GetIndexProviderSafe() { if (_indexProvider != null) return _indexProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher var indexer = eMgr.IndexProviderCollection[Constants.Examine.InternalIndexer]; if (indexer.IndexerData.IncludeNodeTypes.Any() || indexer.IndexerData.ExcludeNodeTypes.Any()) { LogHelper.Warn<PublishedMediaCache>("The InternalIndexer for examine is configured incorrectly, it should not list any include/exclude node types or field names, it should simply be configured as: " + "<IndexSet SetName=\"InternalIndexSet\" IndexPath=\"~/App_Data/TEMP/ExamineIndexes/Internal/\" />"); } return indexer; } catch (Exception ex) { LogHelper.Error<PublishedMediaCache>("Could not retrieve the InternalIndexer", ex); //something didn't work, continue returning null. } } return null; } private BaseSearchProvider GetSearchProviderSafe() { if (_searchProvider != null) return _searchProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher return eMgr.SearchProviderCollection[Constants.Examine.InternalSearcher]; } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! } catch (NullReferenceException) { //This will occur when the search provider cannot be initialized. In newer examine versions the initialization is lazy and therefore // the manager will return the singleton without throwing initialization errors, however if examine isn't configured correctly a null // reference error will occur because the examine settings are null. } catch (AlreadyClosedException) { //If the app domain is shutting down and the site is under heavy load the index reader will be closed and it really cannot //be re-opened since the app domain is shutting down. In this case we have no option but to try to load the data from the db. } } return null; } private IPublishedContent GetUmbracoMedia(int id) { // this recreates an IPublishedContent and model each time // it is called, but at least it should NOT hit the database // nor Lucene each time, relying on the memory cache instead if (id <= 0) return null; // fail fast var cacheValues = GetCacheValues(id, GetUmbracoMediaCacheValues); return cacheValues == null ? null : CreateFromCacheValues(cacheValues); } private CacheValues GetUmbracoMediaCacheValues(int id) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { // first check in Examine as this is WAY faster // // the filter will create a query like this: // +(+__NodeId:3113 -__Path:-1,-21,*) +__IndexType:media // // note that since the use of the wildcard, it automatically escapes it in Lucene. var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.Id(id).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard()); var result = searchProvider.Search(filter.Compile()).FirstOrDefault(); if (result != null) return ConvertFromSearchResult(result); } catch (Exception ex) { if (ex is FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media", ex); } else if (ex is AlreadyClosedException) { //If the app domain is shutting down and the site is under heavy load the index reader will be closed and it really cannot //be re-opened since the app domain is shutting down. In this case we have no option but to try to load the data from the db. LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media, the app domain is most likely in a shutdown state", ex); } else throw; } } // don't log a warning here, as it can flood the log in case of eg a media picker referencing a media // that has been deleted, hence is not in the Examine index anymore (for a good reason). try to get // the media from the service, first var media = ApplicationContext.Current.Services.MediaService.GetById(id); if (media == null || media.Trashed) return null; // not found, ok // so, the media was not found in Examine's index *yet* it exists, which probably indicates that // the index is corrupted. Or not up-to-date. Log a warning, but only once, and only if seeing the // error more that a number of times. var miss = Interlocked.CompareExchange(ref _examineIndexMiss, 0, 0); // volatile read if (miss < ExamineIndexMissMax && Interlocked.Increment(ref _examineIndexMiss) == ExamineIndexMissMax) LogHelper.Warn<PublishedMediaCache>("Failed ({0} times) to retrieve medias from Examine index and had to load" + " them from DB. This may indicate that the Examine index is corrupted.", () => ExamineIndexMissMax); return ConvertFromIMedia(media); } private const int ExamineIndexMissMax = 10; private int _examineIndexMiss; internal CacheValues ConvertFromXPathNodeIterator(XPathNodeIterator media, int id) { if (media != null && media.Current != null) { return media.Current.Name.InvariantEquals("error") ? null : ConvertFromXPathNavigator(media.Current); } LogHelper.Warn<PublishedMediaCache>( "Could not retrieve media {0} from Examine index or from legacy library.GetMedia method", () => id); return null; } internal CacheValues ConvertFromSearchResult(SearchResult searchResult) { //NOTE: Some fields will not be included if the config section for the internal index has been //mucked around with. It should index everything and so the index definition should simply be: // <IndexSet SetName="InternalIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/Internal/" /> var values = new Dictionary<string, string>(searchResult.Fields); //we need to ensure some fields exist, because of the above issue if (!new[] { "template", "templateId" }.Any(values.ContainsKey)) values.Add("template", 0.ToString()); if (!new[] { "sortOrder" }.Any(values.ContainsKey)) values.Add("sortOrder", 0.ToString()); if (!new[] { "urlName" }.Any(values.ContainsKey)) values.Add("urlName", ""); if (!new[] { "nodeType" }.Any(values.ContainsKey)) values.Add("nodeType", 0.ToString()); if (!new[] { "creatorName" }.Any(values.ContainsKey)) values.Add("creatorName", ""); if (!new[] { "writerID" }.Any(values.ContainsKey)) values.Add("writerID", 0.ToString()); if (!new[] { "creatorID" }.Any(values.ContainsKey)) values.Add("creatorID", 0.ToString()); if (!new[] { "createDate" }.Any(values.ContainsKey)) values.Add("createDate", default(DateTime).ToString("yyyy-MM-dd HH:mm:ss")); if (!new[] { "level" }.Any(values.ContainsKey)) { values.Add("level", values["__Path"].Split(',').Length.ToString()); } // because, migration if (values.ContainsKey("key") == false) values["key"] = Guid.Empty.ToString(); return new CacheValues { Values = values, FromExamine = true }; //var content = new DictionaryPublishedContent(values, // d => d.ParentId != -1 //parent should be null if -1 // ? GetUmbracoMedia(d.ParentId) // : null, // //callback to return the children of the current node // d => GetChildrenMedia(d.Id), // GetProperty, // true); //return content.CreateModel(); } internal CacheValues ConvertFromXPathNavigator(XPathNavigator xpath, bool forceNav = false) { if (xpath == null) throw new ArgumentNullException("xpath"); var values = new Dictionary<string, string> { { "nodeName", xpath.GetAttribute("nodeName", "") } }; if (!UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) { values["nodeTypeAlias"] = xpath.Name; } var result = xpath.SelectChildren(XPathNodeType.Element); //add the attributes e.g. id, parentId etc if (result.Current != null && result.Current.HasAttributes) { if (result.Current.MoveToFirstAttribute()) { //checking for duplicate keys because of the 'nodeTypeAlias' might already be added above. if (!values.ContainsKey(result.Current.Name)) { values[result.Current.Name] = result.Current.Value; } while (result.Current.MoveToNextAttribute()) { if (!values.ContainsKey(result.Current.Name)) { values[result.Current.Name] = result.Current.Value; } } result.Current.MoveToParent(); } } // because, migration if (values.ContainsKey("key") == false) values["key"] = Guid.Empty.ToString(); //add the user props while (result.MoveNext()) { if (result.Current != null && !result.Current.HasAttributes) { string value = result.Current.Value; if (string.IsNullOrEmpty(value)) { if (result.Current.HasAttributes || result.Current.SelectChildren(XPathNodeType.Element).Count > 0) { value = result.Current.OuterXml; } } values[result.Current.Name] = value; } } return new CacheValues { Values = values, XPath = forceNav ? xpath : null // outside of tests we do NOT want to cache the navigator! }; //var content = new DictionaryPublishedContent(values, // d => d.ParentId != -1 //parent should be null if -1 // ? GetUmbracoMedia(d.ParentId) // : null, // //callback to return the children of the current node based on the xml structure already found // d => GetChildrenMedia(d.Id, xpath), // GetProperty, // false); //return content.CreateModel(); } internal CacheValues ConvertFromIMedia(IMedia media) { var values = new Dictionary<string, string>(); var creator = _applicationContext.Services.UserService.GetProfileById(media.CreatorId); var creatorName = creator == null ? "" : creator.Name; values["id"] = media.Id.ToString(); values["key"] = media.Key.ToString(); values["parentID"] = media.ParentId.ToString(); values["level"] = media.Level.ToString(); values["creatorID"] = media.CreatorId.ToString(); values["creatorName"] = creatorName; values["writerID"] = media.CreatorId.ToString(); values["writerName"] = creatorName; values["template"] = "0"; values["urlName"] = ""; values["sortOrder"] = media.SortOrder.ToString(); values["createDate"] = media.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"); values["updateDate"] = media.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"); values["nodeName"] = media.Name; values["path"] = media.Path; values["nodeType"] = media.ContentType.Id.ToString(); values["nodeTypeAlias"] = media.ContentType.Alias; // add the user props foreach (var prop in media.Properties) values[prop.Alias] = prop.Value == null ? null : prop.Value.ToString(); return new CacheValues { Values = values }; } /// <summary> /// We will need to first check if the document was loaded by Examine, if so we'll need to check if this property exists /// in the results, if it does not, then we'll have to revert to looking up in the db. /// </summary> /// <param name="dd"> </param> /// <param name="alias"></param> /// <returns></returns> private IPublishedProperty GetProperty(DictionaryPublishedContent dd, string alias) { //lets check if the alias does not exist on the document. //NOTE: Examine will not index empty values and we do not output empty XML Elements to the cache - either of these situations // would mean that the property is missing from the collection whether we are getting the value from Examine or from the library media cache. if (dd.Properties.All(x => x.PropertyTypeAlias.InvariantEquals(alias) == false)) { return null; } if (dd.LoadedFromExamine) { //We are going to check for a special field however, that is because in some cases we store a 'Raw' //value in the index such as for xml/html. var rawValue = dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(UmbracoContentIndexer.RawFieldPrefix + alias)); return rawValue ?? dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias)); } //if its not loaded from examine, then just return the property return dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias)); } /// <summary> /// A Helper methods to return the children for media whther it is based on examine or xml /// </summary> /// <param name="parentId"></param> /// <param name="xpath"></param> /// <returns></returns> private IEnumerable<IPublishedContent> GetChildrenMedia(int parentId, XPathNavigator xpath = null) { //if there is no navigator, try examine first, then re-look it up if (xpath == null) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { //first check in Examine as this is WAY faster var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.ParentId(parentId).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard()); //the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene. //+(+parentId:3113 -__Path:-1,-21,*) +__IndexType:media ISearchResults results; //we want to check if the indexer for this searcher has "sortOrder" flagged as sortable. //if so, we'll use Lucene to do the sorting, if not we'll have to manually sort it (slower). var indexer = GetIndexProviderSafe(); var useLuceneSort = indexer != null && indexer.IndexerData.StandardFields.Any(x => x.Name.InvariantEquals("sortOrder") && x.EnableSorting); if (useLuceneSort) { //we have a sortOrder field declared to be sorted, so we'll use Examine results = searchProvider.Search( filter.And().OrderBy(new SortableField("sortOrder", SortType.Int)).Compile()); } else { results = searchProvider.Search(filter.Compile()); } if (results.Any()) { // var medias = results.Select(ConvertFromSearchResult); var medias = results.Select(x => { int nid; if (int.TryParse(x["__NodeId"], out nid) == false && int.TryParse(x["NodeId"], out nid) == false) throw new Exception("Failed to extract NodeId from search result."); var cacheValues = GetCacheValues(nid, id => ConvertFromSearchResult(x)); return CreateFromCacheValues(cacheValues); }); return useLuceneSort ? medias : medias.OrderBy(x => x.SortOrder); } else { //if there's no result then return null. Previously we defaulted back to library.GetMedia below //but this will always get called for when we are getting descendents since many items won't have //children and then we are hitting the database again! //So instead we're going to rely on Examine to have the correct results like it should. return Enumerable.Empty<IPublishedContent>(); } } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia } } //falling back to get media var media = library.GetMedia(parentId, true); if (media != null && media.Current != null) { xpath = media.Current; } else { return Enumerable.Empty<IPublishedContent>(); } } var mediaList = new List<IPublishedContent>(); // this is so bad, really var item = xpath.Select("//*[@id='" + parentId + "']"); if (item.Current == null) return Enumerable.Empty<IPublishedContent>(); var items = item.Current.SelectChildren(XPathNodeType.Element); // and this does not work, because... meh //var q = "//* [@id='" + parentId + "']/* [@id]"; //var items = xpath.Select(q); foreach (XPathNavigator itemm in items) { int id; if (int.TryParse(itemm.GetAttribute("id", ""), out id) == false) continue; // wtf? var captured = itemm; var cacheValues = GetCacheValues(id, idd => ConvertFromXPathNavigator(captured)); mediaList.Add(CreateFromCacheValues(cacheValues)); } ////The xpath might be the whole xpath including the current ones ancestors so we need to select the current node //var item = xpath.Select("//*[@id='" + parentId + "']"); //if (item.Current == null) //{ // return Enumerable.Empty<IPublishedContent>(); //} //var children = item.Current.SelectChildren(XPathNodeType.Element); //foreach(XPathNavigator x in children) //{ // //NOTE: I'm not sure why this is here, it is from legacy code of ExamineBackedMedia, but // // will leave it here as it must have done something! // if (x.Name != "contents") // { // //make sure it's actually a node, not a property // if (!string.IsNullOrEmpty(x.GetAttribute("path", "")) && // !string.IsNullOrEmpty(x.GetAttribute("id", ""))) // { // mediaList.Add(ConvertFromXPathNavigator(x)); // } // } //} return mediaList; } /// <summary> /// An IPublishedContent that is represented all by a dictionary. /// </summary> /// <remarks> /// This is a helper class and definitely not intended for public use, it expects that all of the values required /// to create an IPublishedContent exist in the dictionary by specific aliases. /// </remarks> internal class DictionaryPublishedContent : PublishedContentWithKeyBase { // note: I'm not sure this class fully complies with IPublishedContent rules especially // I'm not sure that _properties contains all properties including those without a value, // neither that GetProperty will return a property without a value vs. null... @zpqrtbnk // List of properties that will appear in the XML and do not match // anything in the ContentType, so they must be ignored. private static readonly string[] IgnoredKeys = { "version", "isDoc" }; public DictionaryPublishedContent( IDictionary<string, string> valueDictionary, Func<int, IPublishedContent> getParent, Func<int, XPathNavigator, IEnumerable<IPublishedContent>> getChildren, Func<DictionaryPublishedContent, string, IPublishedProperty> getProperty, XPathNavigator nav, bool fromExamine) { if (valueDictionary == null) throw new ArgumentNullException("valueDictionary"); if (getParent == null) throw new ArgumentNullException("getParent"); if (getProperty == null) throw new ArgumentNullException("getProperty"); _getParent = new Lazy<IPublishedContent>(() => getParent(ParentId)); _getChildren = new Lazy<IEnumerable<IPublishedContent>>(() => getChildren(Id, nav)); _getProperty = getProperty; LoadedFromExamine = fromExamine; ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int! ValidateAndSetProperty(valueDictionary, val => _key = Guid.Parse(val), "key"); // wtf are we dealing with templates for medias?! ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId"); ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder"); ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName"); ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName"); ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName); ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType"); ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName"); ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID"); ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path"); ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate"); ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate"); ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level"); ValidateAndSetProperty(valueDictionary, val => { int pId; ParentId = -1; if (int.TryParse(val, out pId)) { ParentId = pId; } }, "parentID"); _contentType = PublishedContentType.Get(PublishedItemType.Media, _documentTypeAlias); _properties = new Collection<IPublishedProperty>(); //handle content type properties //make sure we create them even if there's no value foreach (var propertyType in _contentType.PropertyTypes) { var alias = propertyType.PropertyTypeAlias; _keysAdded.Add(alias); string value; const bool isPreviewing = false; // false :: never preview a media var property = valueDictionary.TryGetValue(alias, out value) == false || value == null ? new XmlPublishedProperty(propertyType, isPreviewing) : new XmlPublishedProperty(propertyType, isPreviewing, value); _properties.Add(property); } //loop through remaining values that haven't been applied foreach (var i in valueDictionary.Where(x => _keysAdded.Contains(x.Key) == false // not already processed && IgnoredKeys.Contains(x.Key) == false)) // not ignorable { if (i.Key.InvariantStartsWith("__")) { // no type for that one, dunno how to convert IPublishedProperty property = new PropertyResult(i.Key, i.Value, PropertyResultType.CustomProperty); _properties.Add(property); } else { // this is a property that does not correspond to anything, ignore and log LogHelper.Warn<PublishedMediaCache>("Dropping property \"" + i.Key + "\" because it does not belong to the content type."); } } } private DateTime ParseDateTimeValue(string val) { if (LoadedFromExamine) { try { //we might need to parse the date time using Lucene converters return DateTools.StringToDate(val); } catch (FormatException) { //swallow exception, its not formatted correctly so revert to just trying to parse } } return DateTime.Parse(val); } /// <summary> /// Flag to get/set if this was laoded from examine cache /// </summary> internal bool LoadedFromExamine { get; private set; } //private readonly Func<DictionaryPublishedContent, IPublishedContent> _getParent; private readonly Lazy<IPublishedContent> _getParent; //private readonly Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> _getChildren; private readonly Lazy<IEnumerable<IPublishedContent>> _getChildren; private readonly Func<DictionaryPublishedContent, string, IPublishedProperty> _getProperty; /// <summary> /// Returns 'Media' as the item type /// </summary> public override PublishedItemType ItemType { get { return PublishedItemType.Media; } } public override IPublishedContent Parent { get { return _getParent.Value; } } public int ParentId { get; private set; } public override int Id { get { return _id; } } public override Guid Key { get { return _key; } } public override int TemplateId { get { //TODO: should probably throw a not supported exception since media doesn't actually support this. return _templateId; } } public override int SortOrder { get { return _sortOrder; } } public override string Name { get { return _name; } } public override string UrlName { get { return _urlName; } } public override string DocumentTypeAlias { get { return _documentTypeAlias; } } public override int DocumentTypeId { get { return _documentTypeId; } } public override string WriterName { get { return _writerName; } } public override string CreatorName { get { return _creatorName; } } public override int WriterId { get { return _writerId; } } public override int CreatorId { get { return _creatorId; } } public override string Path { get { return _path; } } public override DateTime CreateDate { get { return _createDate; } } public override DateTime UpdateDate { get { return _updateDate; } } public override Guid Version { get { return _version; } } public override int Level { get { return _level; } } public override bool IsDraft { get { return false; } } public override ICollection<IPublishedProperty> Properties { get { return _properties; } } public override IEnumerable<IPublishedContent> Children { get { return _getChildren.Value; } } public override IPublishedProperty GetProperty(string alias) { return _getProperty(this, alias); } public override PublishedContentType ContentType { get { return _contentType; } } // override to implement cache // cache at context level, ie once for the whole request // but cache is not shared by requests because we wouldn't know how to clear it public override IPublishedProperty GetProperty(string alias, bool recurse) { if (recurse == false) return GetProperty(alias); IPublishedProperty property; string key = null; var cache = UmbracoContextCache.Current; if (cache != null) { key = string.Format("RECURSIVE_PROPERTY::{0}::{1}", Id, alias.ToLowerInvariant()); object o; if (cache.TryGetValue(key, out o)) { property = o as IPublishedProperty; if (property == null) throw new InvalidOperationException("Corrupted cache."); return property; } } // else get it for real, no cache property = base.GetProperty(alias, true); if (cache != null) cache[key] = property; return property; } private readonly List<string> _keysAdded = new List<string>(); private int _id; private Guid _key; private int _templateId; private int _sortOrder; private string _name; private string _urlName; private string _documentTypeAlias; private int _documentTypeId; private string _writerName; private string _creatorName; private int _writerId; private int _creatorId; private string _path; private DateTime _createDate; private DateTime _updateDate; private Guid _version; private int _level; private readonly ICollection<IPublishedProperty> _properties; private readonly PublishedContentType _contentType; private void ValidateAndSetProperty(IDictionary<string, string> valueDictionary, Action<string> setProperty, params string[] potentialKeys) { var key = potentialKeys.FirstOrDefault(x => valueDictionary.ContainsKey(x) && valueDictionary[x] != null); if (key == null) { throw new FormatException("The valueDictionary is not formatted correctly and is missing any of the '" + string.Join(",", potentialKeys) + "' elements"); } setProperty(valueDictionary[key]); _keysAdded.Add(key); } } // REFACTORING // caching the basic atomic values - and the parent id // but NOT caching actual parent nor children and NOT even // the list of children ids - BUT caching the path internal class CacheValues { public IDictionary<string, string> Values { get; set; } public XPathNavigator XPath { get; set; } public bool FromExamine { get; set; } } public const string PublishedMediaCacheKey = "MediaCacheMeh."; private const int PublishedMediaCacheTimespanSeconds = 4 * 60; // 4 mins private static TimeSpan _publishedMediaCacheTimespan; private static bool _publishedMediaCacheEnabled; private static void InitializeCacheConfig() { var value = ConfigurationManager.AppSettings["Umbraco.PublishedMediaCache.Seconds"]; int seconds; if (int.TryParse(value, out seconds) == false) seconds = PublishedMediaCacheTimespanSeconds; if (seconds > 0) { _publishedMediaCacheEnabled = true; _publishedMediaCacheTimespan = TimeSpan.FromSeconds(seconds); } else { _publishedMediaCacheEnabled = false; } } internal IPublishedContent CreateFromCacheValues(CacheValues cacheValues) { var content = new DictionaryPublishedContent( cacheValues.Values, parentId => parentId < 0 ? null : GetUmbracoMedia(parentId), GetChildrenMedia, GetProperty, cacheValues.XPath, // though, outside of tests, that should be null cacheValues.FromExamine ); return content.CreateModel(); } private static CacheValues GetCacheValues(int id, Func<int, CacheValues> func) { if (_publishedMediaCacheEnabled == false) return func(id); var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache; var key = PublishedMediaCacheKey + id; return (CacheValues)cache.GetCacheItem(key, () => func(id), _publishedMediaCacheTimespan); } internal static void ClearCache(int id) { var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache; var sid = id.ToString(); var key = PublishedMediaCacheKey + sid; // we do clear a lot of things... but the cache refresher is somewhat // convoluted and it's hard to tell what to clear exactly ;-( // clear the parent - NOT (why?) //var exist = (CacheValues) cache.GetCacheItem(key); //if (exist != null) // cache.ClearCacheItem(PublishedMediaCacheKey + GetValuesValue(exist.Values, "parentID")); // clear the item cache.ClearCacheItem(key); // clear all children - in case we moved and their path has changed var fid = "/" + sid + "/"; cache.ClearCacheObjectTypes<CacheValues>((k, v) => GetValuesValue(v.Values, "path", "__Path").Contains(fid)); } private static string GetValuesValue(IDictionary<string, string> d, params string[] keys) { string value = null; var ignored = keys.Any(x => d.TryGetValue(x, out value)); return value ?? ""; } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: UIElementParagraph.cs // // Description: FigureParagraph class provides a wrapper for nested UIElements, // which are treated by PTS as figures. // // Figures now are finite only. // // History: // 05/05/2003 : [....] - moving from Avalon branch. // //--------------------------------------------------------------------------- #pragma warning disable 1634, 1691 // avoid generating warnings about unknown // message numbers and unknown pragmas for PRESharp contol using System; using System.Diagnostics; using System.Security; // SecurityCritical using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using MS.Internal.Text; using MS.Internal.Documents; using MS.Internal.PtsHost.UnsafeNativeMethods; namespace MS.Internal.PtsHost { // ---------------------------------------------------------------------- // FigureParagraph class provides a wrapper for nested UIElements, which // are treated by PTS as figures. // ---------------------------------------------------------------------- internal sealed class FigureParagraph : BaseParagraph { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors // ------------------------------------------------------------------ // Constructor. // // element - Element associated with paragraph. // structuralCache - Content's structural cache // ------------------------------------------------------------------ internal FigureParagraph(DependencyObject element, StructuralCache structuralCache) : base(element, structuralCache) { } // ------------------------------------------------------------------ // IDisposable.Dispose // ------------------------------------------------------------------ public override void Dispose() { base.Dispose(); if (_mainTextSegment != null) { _mainTextSegment.Dispose(); _mainTextSegment = null; } } #endregion Constructors //------------------------------------------------------------------- // // PTS callbacks // //------------------------------------------------------------------- #region PTS callbacks //------------------------------------------------------------------- // GetParaProperties //------------------------------------------------------------------- internal override void GetParaProperties( ref PTS.FSPAP fspap) // OUT: paragraph properties { GetParaProperties(ref fspap, false); fspap.idobj = PTS.fsidobjFigure; } //------------------------------------------------------------------- // GetParaProperties //------------------------------------------------------------------- internal override void CreateParaclient( out IntPtr paraClientHandle) // OUT: opaque to PTS paragraph client { #pragma warning disable 6518 // Disable PRESharp warning 6518. FigureParaClient is an UnmamangedHandle, that adds itself // to HandleMapper that holds a reference to it. PTS manages lifetime of this object, and // calls DestroyParaclient to get rid of it. DestroyParaclient will call Dispose() on the object // and remove it from HandleMapper. FigureParaClient paraClient = new FigureParaClient(this); paraClientHandle = paraClient.Handle; #pragma warning restore 6518 // Create the main text segment if (_mainTextSegment == null) { _mainTextSegment = new ContainerParagraph(Element, StructuralCache); } } //------------------------------------------------------------------- // GetFigureProperties //------------------------------------------------------------------- ///<SecurityNote> /// Critical - as this calls Critical functions PTS.FsDestroySubpage, /// CreateSubpageBottomlessHelper and setter for SubpageHandle. /// Safe - as the parameters passed in are either generated in this function /// or they are Critical for set. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal void GetFigureProperties( FigureParaClient paraClient, // IN: int fInTextLine, // IN: it is attached to text line uint fswdir, // IN: current direction int fBottomUndefined, // IN: bottom of page is not defined out int dur, // OUT: width of figure out int dvr, // OUT: height of figure out PTS.FSFIGUREPROPS fsfigprops, // OUT: figure attributes out int cPolygons, // OUT: number of polygons out int cVertices, // OUT: total number of vertices in all polygons out int durDistTextLeft, // OUT: distance to text from MinU side out int durDistTextRight, // OUT: distance to text from MaxU side out int dvrDistTextTop, // OUT: distance to text from MinV side out int dvrDistTextBottom) // OUT: distance to text from MaxV side { Invariant.Assert(StructuralCache.CurrentFormatContext.FinitePage); uint fswdirPara = PTS.FlowDirectionToFswdir(((FlowDirection)Element.GetValue(FrameworkElement.FlowDirectionProperty))); IntPtr pfsFigureContent; PTS.FSBBOX fsbbox; int cColumns; int dvrTopSpace; PTS.FSCOLUMNINFO[] columnInfoCollection; IntPtr pmcsclientOut; MbpInfo mbp; Figure element = (Figure)Element; // Initialize the subpage size. PTS subpage margin is always set to 0 for Figures. // If width on figure is specified, use the specified value. // Border and padding of the figure is extracted from available subpage width. // We use StructuralCache.CurrentFormatContext's page dimensions as limiting values for figure MBP mbp = MbpInfo.FromElement(Element); // We do not mirror margin as it's used to dist text left and right, and is unnecessary. durDistTextLeft = durDistTextRight = dvrDistTextTop = dvrDistTextBottom = 0; // Calculate specified width. IsAuto flag is needed because Auto is formatted the same way as column and will // not return Double.NaN. bool isWidthAuto; double specifiedWidth = FigureHelper.CalculateFigureWidth(StructuralCache, element, element.Width, out isWidthAuto); double anchorLimitedWidth = LimitTotalWidthFromAnchor(specifiedWidth, TextDpi.FromTextDpi(mbp.MarginLeft + mbp.MarginRight)); int subpageWidth = Math.Max(1, TextDpi.ToTextDpi(anchorLimitedWidth) - (mbp.BPLeft + mbp.BPRight)); // Calculate figure height, IsAuto flag is used as specifiedHeight will never be NaN. bool isHeightAuto; double specifiedHeight = FigureHelper.CalculateFigureHeight(StructuralCache, element, element.Height, out isHeightAuto); double anchorLimitedHeight = LimitTotalHeightFromAnchor(specifiedHeight, TextDpi.FromTextDpi(mbp.MarginTop + mbp.MarginBottom)); int subpageHeight = Math.Max(1, TextDpi.ToTextDpi(anchorLimitedHeight) - (mbp.BPTop + mbp.BPBottom)); // Initialize column info. Figure always has just 1 column. cColumns = 1; columnInfoCollection = new PTS.FSCOLUMNINFO[cColumns]; columnInfoCollection[0].durBefore = 0; columnInfoCollection[0].durWidth = subpageWidth; // Create subpage { PTS.FSFMTR fsfmtr; IntPtr brParaOut; PTS.FSRECT marginRect = new PTS.FSRECT(0, 0, subpageWidth, subpageHeight); CreateSubpageFiniteHelper(PtsContext, IntPtr.Zero, PTS.False, _mainTextSegment.Handle, IntPtr.Zero, PTS.False, PTS.True, fswdir, subpageWidth, subpageHeight, ref marginRect, cColumns, columnInfoCollection, PTS.False, out fsfmtr, out pfsFigureContent, out brParaOut, out dvr, out fsbbox, out pmcsclientOut, out dvrTopSpace); if(brParaOut != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpageBreakRecord(PtsContext.Context, brParaOut)); } } // PTS subpage does not support autosizing, but Figure needs to autosize to its // content. To workaround this problem, second format of subpage is performed, if // necessary. It means that if the width of bounding box is smaller than subpage's // width, second formatting is performed. if(PTS.ToBoolean(fsbbox.fDefined)) { if (fsbbox.fsrc.du < subpageWidth && isWidthAuto) { // There is a need to reformat PTS subpage, so destroy any resourcces allocated by PTS // during previous formatting. if (pfsFigureContent != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpage(PtsContext.Context, pfsFigureContent), PtsContext); } if (pmcsclientOut != IntPtr.Zero) { MarginCollapsingState mcs = PtsContext.HandleToObject(pmcsclientOut) as MarginCollapsingState; PTS.ValidateHandle(mcs); mcs.Dispose(); pmcsclientOut = IntPtr.Zero; } // Create subpage with new width. subpageWidth = fsbbox.fsrc.du + 1; // add 1/300px to avoid rounding errors columnInfoCollection[0].durWidth = subpageWidth; // Create subpage PTS.FSFMTR fsfmtr; IntPtr brParaOut; PTS.FSRECT marginRect = new PTS.FSRECT(0, 0, subpageWidth, subpageHeight); CreateSubpageFiniteHelper(PtsContext, IntPtr.Zero, PTS.False, _mainTextSegment.Handle, IntPtr.Zero, PTS.False, PTS.True, fswdir, subpageWidth, subpageHeight, ref marginRect, cColumns, columnInfoCollection, PTS.False, out fsfmtr, out pfsFigureContent, out brParaOut, out dvr, out fsbbox, out pmcsclientOut, out dvrTopSpace); if(brParaOut != IntPtr.Zero) { PTS.Validate(PTS.FsDestroySubpageBreakRecord(PtsContext.Context, brParaOut)); } } } else { subpageWidth = TextDpi.ToTextDpi(TextDpi.MinWidth); } // Get the size of the figure. For height PTS already reports calculated value. // But width is the same as subpage width. Include margins in dur since we are not using // distance to text anymore. dur = subpageWidth + mbp.MBPLeft + mbp.MBPRight; // Destroy objects created by PTS, but not used here. if (pmcsclientOut != IntPtr.Zero) { MarginCollapsingState mcs = PtsContext.HandleToObject(pmcsclientOut) as MarginCollapsingState; PTS.ValidateHandle(mcs); mcs.Dispose(); pmcsclientOut = IntPtr.Zero; } dvr += mbp.MBPTop + mbp.MBPBottom; if(!isHeightAuto) { // Replace height with explicit height if specified, adding margins in addition to height // Border and padding are included in specified height but margins are external dvr = TextDpi.ToTextDpi(anchorLimitedHeight) + mbp.MarginTop + mbp.MarginBottom; } FigureHorizontalAnchor horzAnchor = element.HorizontalAnchor; FigureVerticalAnchor vertAnchor = element.VerticalAnchor; fsfigprops.fskrefU = (PTS.FSKREF)(((int)horzAnchor) / 3); fsfigprops.fskrefV = (PTS.FSKREF)(((int)vertAnchor) / 3); fsfigprops.fskalfU = (PTS.FSKALIGNFIG)(((int)horzAnchor) % 3); fsfigprops.fskalfV = (PTS.FSKALIGNFIG)(((int)vertAnchor) % 3); // PTS does not allow to anchor delayed figures to 'Character' if (!PTS.ToBoolean(fInTextLine)) { if (fsfigprops.fskrefU == PTS.FSKREF.fskrefChar) { fsfigprops.fskrefU = PTS.FSKREF.fskrefMargin; fsfigprops.fskalfU = PTS.FSKALIGNFIG.fskalfMin; } if (fsfigprops.fskrefV == PTS.FSKREF.fskrefChar) { fsfigprops.fskrefV = PTS.FSKREF.fskrefMargin; fsfigprops.fskalfV = PTS.FSKALIGNFIG.fskalfMin; } } // Always wrap text on both sides of the floater. fsfigprops.fskwrap = PTS.WrapDirectionToFskwrap(element.WrapDirection); fsfigprops.fNonTextPlane = PTS.False; fsfigprops.fAllowOverlap = PTS.False; fsfigprops.fDelayable = PTS.FromBoolean(element.CanDelayPlacement); // Tight wrap is disabled for now. cPolygons = cVertices = 0; // Update handle to PTS subpage. ((FigureParaClient)paraClient).SubpageHandle = pfsFigureContent; } //------------------------------------------------------------------- // GetFigurePolygons //------------------------------------------------------------------- /// <SecurityNote> /// Critical, because it is unsafe method. /// </SecurityNote> [SecurityCritical] internal unsafe void GetFigurePolygons( FigureParaClient paraClient, // IN: uint fswdir, // IN: current direction int ncVertices, // IN: size of array of vertex counts (= number of polygons) int nfspt, // IN: size of the array of all vertices int* rgcVertices, // OUT: array of vertex counts (array containing number of vertices for each polygon) out int ccVertices, // OUT: actual number of vertex counts PTS.FSPOINT* rgfspt, // OUT: array of all vertices out int cfspt, // OUT: actual total number of vertices in all polygons out int fWrapThrough) // OUT: fill text in empty areas within obstacles? { Debug.Assert(false, "Tight wrap is not currently supported."); ccVertices = cfspt = fWrapThrough = 0; } //------------------------------------------------------------------- // CalcFigurePosition //------------------------------------------------------------------- internal void CalcFigurePosition( FigureParaClient paraClient, // IN: uint fswdir, // IN: current direction ref PTS.FSRECT fsrcPage, // IN: page rectangle ref PTS.FSRECT fsrcMargin, // IN: rectangle within page margins ref PTS.FSRECT fsrcTrack, // IN: track rectangle ref PTS.FSRECT fsrcFigurePreliminary,// IN: prelim figure rect calculated from figure props int fMustPosition, // IN: must find position in this track? int fInTextLine, // IN: it is attached to text line out int fPushToNextTrack, // OUT: push to next track? out PTS.FSRECT fsrcFlow, // OUT: FlowAround rectangle out PTS.FSRECT fsrcOverlap, // OUT: Overlap rectangle out PTS.FSBBOX fsbbox, // OUT: bbox out PTS.FSRECT fsrcSearch) // OUT: search area for overlap { Figure element = (Figure)Element; // If overlapping happens, let PTS find another position withing // the track rectangle. FigureHorizontalAnchor horizAnchor = element.HorizontalAnchor; FigureVerticalAnchor vertAnchor = element.VerticalAnchor; fsrcSearch = CalculateSearchArea(horizAnchor, vertAnchor, ref fsrcPage, ref fsrcMargin, ref fsrcTrack, ref fsrcFigurePreliminary); if(vertAnchor == FigureVerticalAnchor.ParagraphTop && fsrcFigurePreliminary.v != fsrcMargin.v && // If we're not at the top of the column ( (fsrcFigurePreliminary.v + fsrcFigurePreliminary.dv) > (fsrcTrack.v + fsrcTrack.dv) ) && // And we exceed column height !PTS.ToBoolean(fMustPosition)) // Can delay placement is handled by figure properties. { fPushToNextTrack = PTS.True; } else { fPushToNextTrack = PTS.False; } // Use rectangle proposed by PTS and make sure that figure fits completely in the page. fsrcFlow = fsrcFigurePreliminary; if(FigureHelper.IsHorizontalColumnAnchor(horizAnchor)) { fsrcFlow.u += CalculateParagraphToColumnOffset(horizAnchor, fsrcFigurePreliminary); } // Apply horizontal and vertical offsets. Offsets are limited by page height and width fsrcFlow.u += TextDpi.ToTextDpi(element.HorizontalOffset); fsrcFlow.v += TextDpi.ToTextDpi(element.VerticalOffset); // Overlap rectangle is the same as flow around rect fsrcOverlap = fsrcFlow; /* If we're anchored to column/content left or right, inflate our overlap width to prevent from aligning two figures right next to one another by incorporating column gap information */ if(!FigureHelper.IsHorizontalPageAnchor(horizAnchor) && horizAnchor != FigureHorizontalAnchor.ColumnCenter && horizAnchor != FigureHorizontalAnchor.ContentCenter) { double columnWidth, gap, rule; int cColumns; FigureHelper.GetColumnMetrics(StructuralCache, out cColumns, out columnWidth, out gap, out rule); int duColumnWidth = TextDpi.ToTextDpi(columnWidth); int duGapWidth = TextDpi.ToTextDpi(gap); int duColumnWidthWithGap = duColumnWidth + duGapWidth; int fullColumns = (fsrcOverlap.du / duColumnWidthWithGap); int duRoundedToNearestColumn = ((fullColumns + 1) * duColumnWidthWithGap) - duGapWidth; fsrcOverlap.du = duRoundedToNearestColumn; // Round overlap rect to nearest column if(horizAnchor == FigureHorizontalAnchor.ContentRight || horizAnchor == FigureHorizontalAnchor.ColumnRight) { fsrcOverlap.u = (fsrcFlow.u + fsrcFlow.du + duGapWidth) - fsrcOverlap.du; } // Force search rect to only work vertically within overlap space. fsrcSearch.u = fsrcOverlap.u; fsrcSearch.du = fsrcOverlap.du; } // Bounding box is equal to actual size of the figure. fsbbox = new PTS.FSBBOX(); fsbbox.fDefined = PTS.True; fsbbox.fsrc = fsrcFlow; } #endregion PTS callbacks #region Internal Methods // ------------------------------------------------------------------ // Clear previously accumulated update info. // ------------------------------------------------------------------ internal override void ClearUpdateInfo() { if (_mainTextSegment != null) { _mainTextSegment.ClearUpdateInfo(); } base.ClearUpdateInfo(); } // ------------------------------------------------------------------ // Invalidate content's structural cache. // // startPosition - Position to start invalidation from. // // Returns: 'true' if entire paragraph is invalid. // ------------------------------------------------------------------ internal override bool InvalidateStructure(int startPosition) { Debug.Assert(ParagraphEndCharacterPosition >= startPosition); if (_mainTextSegment != null) { if (_mainTextSegment.InvalidateStructure(startPosition)) { _mainTextSegment.Dispose(); _mainTextSegment = null; } } return (_mainTextSegment == null); } // ------------------------------------------------------------------ // Invalidate accumulated format caches. // ------------------------------------------------------------------ internal override void InvalidateFormatCache() { if (_mainTextSegment != null) { _mainTextSegment.InvalidateFormatCache(); } } /// <summary> /// Update number of characters consumed by the main text segment. /// </summary> internal void UpdateSegmentLastFormatPositions() { _mainTextSegment.UpdateLastFormatPositions(); } #endregion Internal Methods //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods //------------------------------------------------------------------- // CreateSubpageFiniteHelper // NOTE: This helper is useful for debugging the caller of this function // because the debugger cannot show local variables in unsafe methods. //------------------------------------------------------------------- /// <SecurityNote> /// Critical, because: /// a) calls Critical function PTS.FsCreateSubpageFinite and passes /// pointer parameters directly that'll be written to, /// b) calls the Critical constructor of SubpageBreakRecord, /// c) it is unsafe method. /// </SecurityNote> [SecurityCritical] private unsafe void CreateSubpageFiniteHelper( PtsContext ptsContext, // IN: ptr to FS context IntPtr brParaIn, // IN: break record---use if !NULL int fFromPreviousPage, // IN: break record was created on previous page IntPtr nSeg, // IN: name of the segment to start from-if pointer to break rec is NULL IntPtr pFtnRej, // IN: pftnrej int fEmptyOk, // IN: fEmptyOK int fSuppressTopSpace, // IN: fSuppressTopSpace uint fswdir, // IN: fswdir int lWidth, // IN: width of subpage int lHeight, // IN: height of subpage ref PTS.FSRECT rcMargin, // IN: rectangle within subpage margins int cColumns, // IN: number of columns PTS.FSCOLUMNINFO[] columnInfoCollection, // IN: array of column info int fApplyColumnBalancing, // IN: apply column balancing? out PTS.FSFMTR fsfmtr, // OUT: why formatting was stopped out IntPtr pSubPage, // OUT: ptr to the subpage out IntPtr brParaOut, // OUT: break record of the subpage out int dvrUsed, // OUT: dvrUsed out PTS.FSBBOX fsBBox, // OUT: subpage bbox out IntPtr pfsMcsClient, // OUT: margin collapsing state at the bottom out int topSpace) // OUT: top space due to collapsed margins { // Exceptions don't need to pop, as the top level measure context will be nulled out if thrown. StructuralCache.CurrentFormatContext.PushNewPageData(new Size(TextDpi.FromTextDpi(lWidth), TextDpi.FromTextDpi(lHeight)), new Thickness(), false, true); fixed (PTS.FSCOLUMNINFO* rgColumnInfo = columnInfoCollection) { PTS.Validate(PTS.FsCreateSubpageFinite(ptsContext.Context, brParaIn, fFromPreviousPage, nSeg, pFtnRej, fEmptyOk, fSuppressTopSpace, fswdir, lWidth, lHeight, ref rcMargin, cColumns, rgColumnInfo, PTS.False, 0, null, null, 0, null, null, PTS.False, PTS.FSKSUPPRESSHARDBREAKBEFOREFIRSTPARA.fsksuppresshardbreakbeforefirstparaNone, out fsfmtr, out pSubPage, out brParaOut, out dvrUsed, out fsBBox, out pfsMcsClient, out topSpace), ptsContext); } StructuralCache.CurrentFormatContext.PopPageData(); } // ------------------------------------------------------------------ // Determines what offset is required to convert a paragraph aligned figure into a column aligned figure. // ------------------------------------------------------------------ private int CalculateParagraphToColumnOffset(FigureHorizontalAnchor horizontalAnchor, PTS.FSRECT fsrcInColumn) { Invariant.Assert(FigureHelper.IsHorizontalColumnAnchor(horizontalAnchor)); int uComparisonPoint; // Depending on anchoring, only the anchored edge (center) is guaranteed to be inside of the column, so finding affected column // requires us to compare against the anchored edge U position. if(horizontalAnchor == FigureHorizontalAnchor.ColumnLeft) { uComparisonPoint = fsrcInColumn.u; } else if(horizontalAnchor == FigureHorizontalAnchor.ColumnRight) { uComparisonPoint = fsrcInColumn.u + fsrcInColumn.du - 1; // du is non-inclusive } else { uComparisonPoint = fsrcInColumn.u + (fsrcInColumn.du / 2) - 1; // du is non-inclusive } double columnWidth, gap, rule; int cColumns; FigureHelper.GetColumnMetrics(StructuralCache, out cColumns, out columnWidth, out gap, out rule); Invariant.Assert(cColumns > 0); int duColumnTotal = TextDpi.ToTextDpi(columnWidth + gap); int affectedColumn = (uComparisonPoint - StructuralCache.CurrentFormatContext.PageMarginRect.u) / duColumnTotal; int columnLeft = StructuralCache.CurrentFormatContext.PageMarginRect.u + affectedColumn * duColumnTotal; int columnDU = TextDpi.ToTextDpi(columnWidth); int totalMarginLeft = columnLeft - fsrcInColumn.u; int totalMarginRight = (columnLeft + columnDU) - (fsrcInColumn.u + fsrcInColumn.du); if(horizontalAnchor == FigureHorizontalAnchor.ColumnLeft) { return totalMarginLeft; } else if(horizontalAnchor == FigureHorizontalAnchor.ColumnRight) { return totalMarginRight; } else { return (totalMarginRight + totalMarginLeft) / 2; } } // ------------------------------------------------------------------ // Determines the max total width for this figure element, subtracts the element margins to determine the maximum size the // Subpage can be formatted at. // ------------------------------------------------------------------ private double LimitTotalWidthFromAnchor(double width, double elementMarginWidth) { Figure element = (Figure)Element; FigureHorizontalAnchor horizAnchor = element.HorizontalAnchor; double maxTotalWidth = 0.0; // Value is in pixels. Now we limit value to max out depending on anchoring. if(FigureHelper.IsHorizontalPageAnchor(horizAnchor)) { maxTotalWidth = StructuralCache.CurrentFormatContext.PageWidth; } else if(FigureHelper.IsHorizontalContentAnchor(horizAnchor)) { Thickness pageMargin = StructuralCache.CurrentFormatContext.PageMargin; maxTotalWidth = StructuralCache.CurrentFormatContext.PageWidth - pageMargin.Left - pageMargin.Right; } else { double columnWidth, gap, rule; int cColumns; FigureHelper.GetColumnMetrics(StructuralCache, out cColumns, out columnWidth, out gap, out rule); maxTotalWidth = columnWidth; } if((width + elementMarginWidth) > maxTotalWidth) { width = Math.Max(TextDpi.MinWidth, maxTotalWidth - elementMarginWidth); } return width; } // ------------------------------------------------------------------ // Determines the max total height for this figure element, subtracts the element margins to determine the maximum size the // Subpage can be formatted at. // ------------------------------------------------------------------ private double LimitTotalHeightFromAnchor(double height, double elementMarginHeight) { Figure element = (Figure)Element; FigureVerticalAnchor vertAnchor = element.VerticalAnchor; double maxTotalHeight = 0.0; // Value is in pixels. Now we limit value to max out depending on anchoring. if(FigureHelper.IsVerticalPageAnchor(vertAnchor)) { maxTotalHeight = StructuralCache.CurrentFormatContext.PageHeight; } else { Thickness pageMargin = StructuralCache.CurrentFormatContext.PageMargin; maxTotalHeight = StructuralCache.CurrentFormatContext.PageHeight - pageMargin.Top - pageMargin.Bottom; } if((height + elementMarginHeight) > maxTotalHeight) { height = Math.Max(TextDpi.MinWidth, maxTotalHeight - elementMarginHeight); } return height; } /// <summary> /// Returns an appropriate search rectangle for collision based on anchor properties. /// </summary> private PTS.FSRECT CalculateSearchArea(FigureHorizontalAnchor horizAnchor, FigureVerticalAnchor vertAnchor, ref PTS.FSRECT fsrcPage, ref PTS.FSRECT fsrcMargin, ref PTS.FSRECT fsrcTrack, ref PTS.FSRECT fsrcFigurePreliminary) { PTS.FSRECT fsrcSearch; if(FigureHelper.IsHorizontalPageAnchor(horizAnchor)) { fsrcSearch.u = fsrcPage.u; fsrcSearch.du = fsrcPage.du; } else if(FigureHelper.IsHorizontalContentAnchor(horizAnchor)) { fsrcSearch.u = fsrcMargin.u; fsrcSearch.du = fsrcMargin.du; } else { fsrcSearch.u = fsrcTrack.u; fsrcSearch.du = fsrcTrack.du; } if(FigureHelper.IsVerticalPageAnchor(vertAnchor)) { fsrcSearch.v = fsrcPage.v; fsrcSearch.dv = fsrcPage.dv; } else if(FigureHelper.IsVerticalContentAnchor(vertAnchor)) { fsrcSearch.v = fsrcMargin.v; fsrcSearch.dv = fsrcMargin.dv; } else { fsrcSearch.v = fsrcFigurePreliminary.v; fsrcSearch.dv = (fsrcTrack.v + fsrcTrack.dv) - fsrcFigurePreliminary.v; } return fsrcSearch; } #endregion Private Methods //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields // ------------------------------------------------------------------ // Main text segment. // ------------------------------------------------------------------ private BaseParagraph _mainTextSegment; #endregion Private Fields } } #pragma warning enable 1634, 1691
namespace StockSharp.Algo { using System; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using StockSharp.Logging; using StockSharp.Messages; /// <summary> /// Level1 depth builder adapter. /// </summary> public class Level1DepthBuilderAdapter : MessageAdapterWrapper { private sealed class Level1DepthBuilder { private decimal? _bidPrice, _askPrice, _bidVolume, _askVolume; public Level1DepthBuilder(SecurityId securityId) { SecurityId = securityId; } public readonly SecurityId SecurityId; public QuoteChangeMessage Process(Level1ChangeMessage message) { var bidPrice = message.TryGetDecimal(Level1Fields.BestBidPrice); var askPrice = message.TryGetDecimal(Level1Fields.BestAskPrice); if (bidPrice == null && askPrice == null) return null; var bidVolume = message.TryGetDecimal(Level1Fields.BestBidVolume); var askVolume = message.TryGetDecimal(Level1Fields.BestAskVolume); if (_bidPrice == bidPrice && _askPrice == askPrice && _bidVolume == bidVolume && _askVolume == askVolume) return null; _bidPrice = bidPrice; _askPrice = askPrice; _bidVolume = bidVolume; _askVolume = askVolume; return new QuoteChangeMessage { SecurityId = SecurityId, ServerTime = message.ServerTime, LocalTime = message.LocalTime, BuildFrom = DataType.Level1, Bids = bidPrice == null ? Array.Empty<QuoteChange>() : new[] { new QuoteChange(bidPrice.Value, bidVolume ?? 0) }, Asks = askPrice == null ? Array.Empty<QuoteChange>() : new[] { new QuoteChange(askPrice.Value, askVolume ?? 0) }, }; } } private class BookInfo { public BookInfo(Level1DepthBuilder builder) => Builder = builder; public readonly Level1DepthBuilder Builder; public readonly CachedSynchronizedSet<long> SubscriptionIds = new(); } private readonly SyncObject _syncObject = new(); private readonly Dictionary<long, BookInfo> _byId = new(); private readonly Dictionary<SecurityId, BookInfo> _online = new(); /// <summary> /// Initializes a new instance of the <see cref="Level1DepthBuilderAdapter"/>. /// </summary> /// <param name="innerAdapter">Inner message adapter.</param> public Level1DepthBuilderAdapter(IMessageAdapter innerAdapter) : base(innerAdapter) { } /// <inheritdoc /> public override bool SendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { lock (_syncObject) { _byId.Clear(); _online.Clear(); } break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; if (mdMsg.IsSubscribe) { if (mdMsg.SecurityId == default || mdMsg.DataType2 != DataType.MarketDepth) break; if (mdMsg.BuildMode == MarketDataBuildModes.Load) break; if (mdMsg.BuildFrom != null && mdMsg.BuildFrom != DataType.Level1) break; var transId = mdMsg.TransactionId; lock (_syncObject) { var info = new BookInfo(new Level1DepthBuilder(mdMsg.SecurityId)); info.SubscriptionIds.Add(transId); _byId.Add(transId, info); } mdMsg = mdMsg.TypedClone(); mdMsg.DataType2 = DataType.Level1; message = mdMsg; this.AddDebugLog("L1->OB {0} added.", transId); } else { RemoveSubscription(mdMsg.OriginalTransactionId); } break; } } return base.SendInMessage(message); } private void RemoveSubscription(long id) { lock (_syncObject) { var changeId = true; if (!_byId.TryGetAndRemove(id, out var info)) { changeId = false; info = _online.FirstOrDefault(p => p.Value.SubscriptionIds.Contains(id)).Value; if (info == null) return; } var secId = info.Builder.SecurityId; if (info != _online.TryGetValue(secId)) return; info.SubscriptionIds.Remove(id); var ids = info.SubscriptionIds.Cache; if (ids.Length == 0) _online.Remove(secId); else if (changeId) _byId.Add(ids[0], info); } this.AddDebugLog("L1->OB {0} removed.", id); } /// <inheritdoc /> protected override void OnInnerAdapterNewOutMessage(Message message) { List<QuoteChangeMessage> books = null; switch (message.Type) { case MessageTypes.SubscriptionResponse: { var responseMsg = (SubscriptionResponseMessage)message; if (!responseMsg.IsOk()) RemoveSubscription(responseMsg.OriginalTransactionId); break; } case MessageTypes.SubscriptionFinished: { RemoveSubscription(((SubscriptionFinishedMessage)message).OriginalTransactionId); break; } case MessageTypes.SubscriptionOnline: { var id = ((SubscriptionOnlineMessage)message).OriginalTransactionId; lock (_syncObject) { if (_byId.TryGetValue(id, out var info)) { var secId = info.Builder.SecurityId; if (_online.TryGetValue(secId, out var online)) { online.SubscriptionIds.Add(id); _byId.Remove(id); } else { _online.Add(secId, info); } } } break; } case MessageTypes.Level1Change: { lock (_syncObject) { if (_byId.Count == 0 && _online.Count == 0) break; } var level1Msg = (Level1ChangeMessage)message; var ids = level1Msg.GetSubscriptionIds(); HashSet<long> leftIds = null; lock (_syncObject) { foreach (var id in ids) { if (!_byId.TryGetValue(id, out var info)) continue; var quoteMsg = info.Builder.Process(level1Msg); if (quoteMsg == null) continue; quoteMsg.SetSubscriptionIds(info.SubscriptionIds.Cache); if (books == null) books = new List<QuoteChangeMessage>(); books.Add(quoteMsg); if (leftIds == null) leftIds = new HashSet<long>(ids); leftIds.RemoveRange(info.SubscriptionIds.Cache); } } if (leftIds != null) { if (leftIds.Count == 0) { message = null; break; } level1Msg.SetSubscriptionIds(leftIds.ToArray()); } break; } } if (message != null) base.OnInnerAdapterNewOutMessage(message); if (books != null) { foreach (var book in books) { base.OnInnerAdapterNewOutMessage(book); } } } /// <summary> /// Create a copy of <see cref="Level1DepthBuilderAdapter"/>. /// </summary> /// <returns>Copy.</returns> public override IMessageChannel Clone() => new Level1DepthBuilderAdapter(InnerAdapter.TypedClone()); } }
namespace JenkinsTray.UI { partial class ClaimBuildForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ClaimBuildForm)); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.buildNumberLabel = new DevExpress.XtraEditors.LabelControl(); this.claimBuildLabel = new DevExpress.XtraEditors.LabelControl(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.stickyCheckEdit = new DevExpress.XtraEditors.CheckEdit(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this.reasonLabel = new DevExpress.XtraEditors.LabelControl(); this.reasonMemoEdit = new DevExpress.XtraEditors.MemoEdit(); this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); this.okButton = new DevExpress.XtraEditors.SimpleButton(); this.cancelButton = new DevExpress.XtraEditors.SimpleButton(); this.tableLayoutPanel1.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.stickyCheckEdit.Properties)).BeginInit(); this.tableLayoutPanel4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.reasonMemoEdit.Properties)).BeginInit(); this.tableLayoutPanel5.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 0); this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel3, 0, 2); this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel4, 0, 1); this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel5, 0, 3); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10); this.tableLayoutPanel1.RowCount = 4; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.Size = new System.Drawing.Size(329, 191); this.tableLayoutPanel1.TabIndex = 0; // // tableLayoutPanel2 // this.tableLayoutPanel2.AutoSize = true; this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel2.ColumnCount = 2; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.Controls.Add(this.buildNumberLabel, 1, 0); this.tableLayoutPanel2.Controls.Add(this.claimBuildLabel, 0, 0); this.tableLayoutPanel2.Location = new System.Drawing.Point(13, 13); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 1; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.Size = new System.Drawing.Size(83, 19); this.tableLayoutPanel2.TabIndex = 5; // // buildNumberLabel // this.buildNumberLabel.Appearance.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold); this.buildNumberLabel.Appearance.Options.UseFont = true; this.buildNumberLabel.Location = new System.Drawing.Point(73, 3); this.buildNumberLabel.Name = "buildNumberLabel"; this.buildNumberLabel.Size = new System.Drawing.Size(7, 13); this.buildNumberLabel.TabIndex = 1; this.buildNumberLabel.Text = "1"; // // claimBuildLabel // this.claimBuildLabel.Appearance.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold); this.claimBuildLabel.Appearance.Options.UseFont = true; this.claimBuildLabel.Location = new System.Drawing.Point(3, 3); this.claimBuildLabel.Name = "claimBuildLabel"; this.claimBuildLabel.Size = new System.Drawing.Size(64, 13); this.claimBuildLabel.TabIndex = 0; this.claimBuildLabel.Text = "Claim build:"; // // tableLayoutPanel3 // this.tableLayoutPanel3.AutoSize = true; this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel3.ColumnCount = 1; this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel3.Controls.Add(this.stickyCheckEdit, 0, 0); this.tableLayoutPanel3.Location = new System.Drawing.Point(13, 118); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; this.tableLayoutPanel3.RowCount = 1; this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel3.Size = new System.Drawing.Size(261, 25); this.tableLayoutPanel3.TabIndex = 6; // // stickyCheckEdit // this.stickyCheckEdit.Location = new System.Drawing.Point(3, 3); this.stickyCheckEdit.Name = "stickyCheckEdit"; this.stickyCheckEdit.Properties.AutoWidth = true; this.stickyCheckEdit.Properties.Caption = "Sticky (automatically applies if the next run fails)"; this.stickyCheckEdit.Size = new System.Drawing.Size(255, 19); this.stickyCheckEdit.TabIndex = 1; // // tableLayoutPanel4 // this.tableLayoutPanel4.AutoSize = true; this.tableLayoutPanel4.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel4.ColumnCount = 2; this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel4.Controls.Add(this.reasonLabel, 0, 0); this.tableLayoutPanel4.Controls.Add(this.reasonMemoEdit, 1, 0); this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel4.Location = new System.Drawing.Point(13, 38); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; this.tableLayoutPanel4.RowCount = 1; this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel4.Size = new System.Drawing.Size(303, 74); this.tableLayoutPanel4.TabIndex = 7; // // reasonLabel // this.reasonLabel.Location = new System.Drawing.Point(3, 3); this.reasonLabel.Name = "reasonLabel"; this.reasonLabel.Size = new System.Drawing.Size(40, 13); this.reasonLabel.TabIndex = 2; this.reasonLabel.Text = "Reason:"; // // reasonMemoEdit // this.reasonMemoEdit.Dock = System.Windows.Forms.DockStyle.Fill; this.reasonMemoEdit.Location = new System.Drawing.Point(49, 3); this.reasonMemoEdit.Name = "reasonMemoEdit"; this.reasonMemoEdit.Size = new System.Drawing.Size(251, 68); this.reasonMemoEdit.TabIndex = 0; // // tableLayoutPanel5 // this.tableLayoutPanel5.AutoSize = true; this.tableLayoutPanel5.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel5.ColumnCount = 4; this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel5.Controls.Add(this.okButton, 1, 0); this.tableLayoutPanel5.Controls.Add(this.cancelButton, 2, 0); this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel5.Location = new System.Drawing.Point(13, 149); this.tableLayoutPanel5.Name = "tableLayoutPanel5"; this.tableLayoutPanel5.RowCount = 1; this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel5.Size = new System.Drawing.Size(303, 29); this.tableLayoutPanel5.TabIndex = 8; // // okButton // this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Location = new System.Drawing.Point(73, 3); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 2; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(154, 3); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 3; this.cancelButton.Text = "Cancel"; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // ClaimBuildForm // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(329, 191); this.Controls.Add(this.tableLayoutPanel1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "ClaimBuildForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Claim build"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.tableLayoutPanel3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.stickyCheckEdit.Properties)).EndInit(); this.tableLayoutPanel4.ResumeLayout(false); this.tableLayoutPanel4.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.reasonMemoEdit.Properties)).EndInit(); this.tableLayoutPanel5.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private DevExpress.XtraEditors.LabelControl claimBuildLabel; private DevExpress.XtraEditors.LabelControl buildNumberLabel; private DevExpress.XtraEditors.LabelControl reasonLabel; private DevExpress.XtraEditors.CheckEdit stickyCheckEdit; private DevExpress.XtraEditors.MemoEdit reasonMemoEdit; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; private DevExpress.XtraEditors.SimpleButton okButton; private DevExpress.XtraEditors.SimpleButton cancelButton; } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using AutoMapper.Impl; namespace AutoMapper { public class PropertyMap { private readonly LinkedList<IValueResolver> _sourceValueResolvers = new LinkedList<IValueResolver>(); private readonly IList<Type> _valueFormattersToSkip = new List<Type>(); private readonly IList<IValueFormatter> _valueFormatters = new List<IValueFormatter>(); private bool _ignored; private int _mappingOrder; private bool _hasCustomValueResolver; private IValueResolver _customResolver; private IValueResolver _customMemberResolver; private object _nullSubstitute; private bool _sealed; private IValueResolver[] _cachedResolvers; private Func<ResolutionContext, bool> _condition; private MemberInfo _sourceMember; public PropertyMap(IMemberAccessor destinationProperty) { DestinationProperty = destinationProperty; } public IMemberAccessor DestinationProperty { get; private set; } public LambdaExpression CustomExpression { get; private set; } public MemberInfo SourceMember { get { if (_sourceMember == null) { var sourceMemberGetter = GetSourceValueResolvers() .OfType<IMemberGetter>().LastOrDefault(); return sourceMemberGetter == null ? null : sourceMemberGetter.MemberInfo; } else { return _sourceMember; } } internal set { _sourceMember = value; } } public bool CanBeSet { get { return !(DestinationProperty is PropertyAccessor) || ((PropertyAccessor)DestinationProperty).HasSetter; } } public bool UseDestinationValue { get; set; } internal bool HasCustomValueResolver { get { return _hasCustomValueResolver; } } public IEnumerable<IValueResolver> GetSourceValueResolvers() { if (_customMemberResolver != null) yield return _customMemberResolver; if (_customResolver != null) yield return _customResolver; foreach (var resolver in _sourceValueResolvers) { yield return resolver; } if (_nullSubstitute != null) yield return new NullReplacementMethod(_nullSubstitute); } public void RemoveLastResolver() { _sourceValueResolvers.RemoveLast(); } public ResolutionResult ResolveValue(ResolutionContext context) { Seal(); var result = new ResolutionResult(context); return _cachedResolvers.Aggregate(result, (current, resolver) => resolver.Resolve(current)); } internal void Seal() { if (_sealed) { return; } _cachedResolvers = GetSourceValueResolvers().ToArray(); _sealed = true; } public void ChainResolver(IValueResolver IValueResolver) { _sourceValueResolvers.AddLast(IValueResolver); } public void AddFormatterToSkip<TValueFormatter>() where TValueFormatter : IValueFormatter { _valueFormattersToSkip.Add(typeof(TValueFormatter)); } public bool FormattersToSkipContains(Type valueFormatterType) { return _valueFormattersToSkip.Contains(valueFormatterType); } public void AddFormatter(IValueFormatter valueFormatter) { _valueFormatters.Add(valueFormatter); } public IValueFormatter[] GetFormatters() { return _valueFormatters.ToArray(); } public void AssignCustomValueResolver(IValueResolver valueResolver) { _ignored = false; _customResolver = valueResolver; ResetSourceMemberChain(); _hasCustomValueResolver = true; } public void ChainTypeMemberForResolver(IValueResolver valueResolver) { ResetSourceMemberChain(); _customMemberResolver = valueResolver; } public void ChainConstructorForResolver(IValueResolver valueResolver) { _customResolver = valueResolver; } public void Ignore() { _ignored = true; } public bool IsIgnored() { return _ignored; } public void SetMappingOrder(int mappingOrder) { _mappingOrder = mappingOrder; } public int GetMappingOrder() { return _mappingOrder; } public bool IsMapped() { return _sourceValueResolvers.Count > 0 || _hasCustomValueResolver || _ignored; } public bool CanResolveValue() { return (_sourceValueResolvers.Count > 0 || _hasCustomValueResolver || UseDestinationValue) && !_ignored; } public void RemoveLastFormatter() { _valueFormatters.RemoveAt(_valueFormatters.Count - 1); } public void SetNullSubstitute(object nullSubstitute) { _nullSubstitute = nullSubstitute; } private void ResetSourceMemberChain() { _sourceValueResolvers.Clear(); } public bool Equals(PropertyMap other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.DestinationProperty, DestinationProperty); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(PropertyMap)) return false; return Equals((PropertyMap)obj); } public override int GetHashCode() { return DestinationProperty.GetHashCode(); } public void ApplyCondition(Func<ResolutionContext, bool> condition) { _condition = condition; } public bool ShouldAssignValue(ResolutionContext context) { return _condition == null || _condition(context); } public void SetCustomValueResolverExpression<TSource, TMember>(Expression<Func<TSource, TMember>> sourceMember) { if (sourceMember.Body is MemberExpression) { SourceMember = ((MemberExpression) sourceMember.Body).Member; } CustomExpression = sourceMember; AssignCustomValueResolver(new DelegateBasedResolver<TSource, TMember>(sourceMember.Compile())); } } }
namespace Atlana.World { using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel.DataAnnotations; /// <summary> /// Description of Room. /// </summary> public class Room { public static Room Create(string title, string description) { var r = new Room() { Title = title, Description = description, Exits = new List<RoomExit>() }; return r; } public Room() { this.Id = -1; this.Description = String.Empty; this.Title = String.Empty; this.MobsInRoom = new List<Mobile>(); this.Exits = null; } public int Id { get; set; } public Area Area { get; set; } public int AreaId { get; set; } public string Title { get; set; } public string Description { get; set; } public ICollection<RoomExit> Exits { get; set; } [NotMapped] public List<Mobile> MobsInRoom { get; set; } public void SetExitRoom(ExitDirections dir, Room r) { if (this.HasExit(dir)) { RoomExit e = GetExit(dir); //e.ToRoom = r; } } public bool HasExit(ExitDirections dir) { if (this.Exits.AsQueryable().Count(z => z.Direction == dir) > 0) { return true; } return false; } public RoomExit GetExit(ExitDirections dir) { return this.Exits.FirstOrDefault(z => z.Direction == dir); } public Room ExitRoom(ExitDirections dir) { var exit = this.GetExit(dir); if (exit != null) { return exit.DestinationRoom; } return null; } public void MobToRoom(Mobile m) { if (this.MobsInRoom.SingleOrDefault(z => z.Equals(m)) == null) { if (m.Room != null) { m.Room.MobFromRoom(m); } this.MobsInRoom.Add(m); m.Room = this; } } public void MobFromRoom(Mobile m) { if (this.MobsInRoom.SingleOrDefault(z => z.Equals(m)) != null) { this.MobsInRoom.Remove(m); m.Room = null; } } public void WriteToAll(Mobile except, string value) { foreach (Mobile m in this.MobsInRoom) { if (m.Equals(except)) { continue; } m.WriteLine(value); } } public void WriteToAll(Mobile except, string format, object arg0) { this.WriteToAll(except, string.Format(format, arg0)); } public void WriteToAll(Mobile except, string format, object arg0, object arg1) { this.WriteToAll(except, string.Format(format, arg0, arg1)); } public void WriteToAll(Mobile except, string format, object arg0, object arg1, object arg2) { this.WriteToAll(except, string.Format(format, arg0, arg1, arg2)); } public void WriteToAll(Mobile except, string format, params object[] args) { this.WriteToAll(except, string.Format(format, args)); } public void WriteToAll(string value) { foreach (Mobile m in this.MobsInRoom) { m.WriteLine(value); } } public void WriteToAll(string format, object arg0) { this.WriteToAll(string.Format(format, arg0)); } public void WriteToAll(string format, object arg0, object arg1) { this.WriteToAll(string.Format(format, arg0, arg1)); } public void WriteToAll(string format, object arg0, object arg1, object arg2) { this.WriteToAll(string.Format(format, arg0, arg1, arg2)); } public void WriteToAll(string format, params object[] args) { this.WriteToAll(string.Format(format, args)); } public void ShowTo(Mobile m, bool detailed) { /*string s = string.Format("/(&W{0}&G)--", this.Title); s = s.PadRight(73, '-'); s = "&G" + s; m.WriteLine("{0}\\", s);*/ m.WriteLine("&W{0}&z", this.Title); m.WriteLine("&R----------------------------------------------------------------------------&z"); m.WriteLine("&w{0}&z", this.Description); //m.WriteLine("&G\\--------------------------------------------------------------------/"); m.WriteLine("&R----------------------------------------------------------------------------&z"); if (detailed) { m.WriteLine("&WExits:"); foreach (RoomExit e in this.Exits) { m.WriteLine("&G{0} &W- &G{1}", ExitDirections.GetName(typeof(ExitDirections), (int)e.Direction), e.DestinationRoom.Title); } } m.Write("&z"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Autofac; using NUnit.Framework; using Orchard.Caching; using Orchard.Environment.Extensions; using Orchard.Environment.Extensions.Folders; using Orchard.Environment.Extensions.Loaders; using Orchard.Environment.Extensions.Models; using Orchard.FileSystems.Dependencies; using Orchard.Tests.Extensions.ExtensionTypes; using Orchard.Tests.Stubs; namespace Orchard.Tests.Environment.Extensions { [TestFixture] public class ExtensionLoaderCoordinatorTests { private IContainer _container; private IExtensionManager _manager; private StubFolders _folders; [SetUp] public void Init() { var builder = new ContainerBuilder(); _folders = new StubFolders(DefaultExtensionTypes.Module); builder.RegisterInstance(_folders).As<IExtensionFolders>(); builder.RegisterType<ExtensionManager>().As<IExtensionManager>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>(); _container = builder.Build(); _manager = _container.Resolve<IExtensionManager>(); } public class StubFolders : IExtensionFolders { private readonly string _extensionType; public StubFolders(string extensionType) { _extensionType = extensionType; Manifests = new Dictionary<string, string>(); } public IDictionary<string, string> Manifests { get; set; } public IEnumerable<ExtensionDescriptor> AvailableExtensions() { foreach (var e in Manifests) { string name = e.Key; yield return ExtensionHarvester.GetDescriptorForExtension("~/", name, _extensionType, Manifests[name]); } } } public class StubLoaders : IExtensionLoader { #region Implementation of IExtensionLoader public int Order { get { return 1; } } public string Name { get { return this.GetType().Name; } } public Assembly LoadReference(DependencyReferenceDescriptor reference) { throw new NotImplementedException(); } public void ReferenceActivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) { throw new NotImplementedException(); } public void ReferenceDeactivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) { throw new NotImplementedException(); } public bool IsCompatibleWithModuleReferences(ExtensionDescriptor extension, IEnumerable<ExtensionProbeEntry> references) { throw new NotImplementedException(); } public ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) { return new ExtensionProbeEntry { Descriptor = descriptor, Loader = this }; } public IEnumerable<ExtensionReferenceProbeEntry> ProbeReferences(ExtensionDescriptor extensionDescriptor) { throw new NotImplementedException(); } public ExtensionEntry Load(ExtensionDescriptor descriptor) { return new ExtensionEntry { Descriptor = descriptor, ExportedTypes = new[] { typeof(Alpha), typeof(Beta), typeof(Phi) } }; } public void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) { throw new NotImplementedException(); } public void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) { throw new NotImplementedException(); } public void ExtensionRemoved(ExtensionLoadingContext ctx, DependencyDescriptor dependency) { throw new NotImplementedException(); } public void Monitor(ExtensionDescriptor extension, Action<IVolatileToken> monitor) { } public IEnumerable<ExtensionCompilationReference> GetCompilationReferences(DependencyDescriptor dependency) { throw new NotImplementedException(); } public IEnumerable<string> GetVirtualPathDependencies(DependencyDescriptor dependency) { throw new NotImplementedException(); } #endregion } private ExtensionManager CreateExtensionManager(StubFolders extensionFolder, StubLoaders extensionLoader) { return new ExtensionManager(new[] { extensionFolder }, new[] { extensionLoader }, new StubCacheManager(), new StubParallelCacheContext(), new StubAsyncTokenProvider()); } [Test] public void AvailableExtensionsShouldFollowCatalogLocations() { _folders.Manifests.Add("foo", "Name: Foo"); _folders.Manifests.Add("bar", "Name: Bar"); _folders.Manifests.Add("frap", "Name: Frap"); _folders.Manifests.Add("quad", "Name: Quad"); var available = _manager.AvailableExtensions(); Assert.That(available.Count(), Is.EqualTo(4)); Assert.That(available, Has.Some.Property("Id").EqualTo("foo")); } [Test] public void ExtensionDescriptorsShouldHaveNameAndVersion() { _folders.Manifests.Add("Sample", @" Name: Sample Extension Version: 2.x "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("Sample")); Assert.That(descriptor.Name, Is.EqualTo("Sample Extension")); Assert.That(descriptor.Version, Is.EqualTo("2.x")); } [Test] public void ExtensionDescriptorsShouldBeParsedForMinimalModuleTxt() { _folders.Manifests.Add("SuperWiki", @" Name: SuperWiki Version: 1.0.3 OrchardVersion: 1 Features: SuperWiki: Description: My super wiki module for Orchard. "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Version, Is.EqualTo("1.0.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Features.Count(), Is.EqualTo(1)); Assert.That(descriptor.Features.First().Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Extension.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Description, Is.EqualTo("My super wiki module for Orchard.")); } [Test] public void ExtensionDescriptorsShouldBeParsedForMinimalModuleTxtWithSimpleFormat() { _folders.Manifests.Add("SuperWiki", @" Name: SuperWiki Version: 1.0.3 OrchardVersion: 1 Description: My super wiki module for Orchard. "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Version, Is.EqualTo("1.0.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Features.Count(), Is.EqualTo(1)); Assert.That(descriptor.Features.First().Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Extension.Id, Is.EqualTo("SuperWiki")); Assert.That(descriptor.Features.First().Description, Is.EqualTo("My super wiki module for Orchard.")); } [Test] public void ExtensionDescriptorsShouldBeParsedForCompleteModuleTxt() { _folders.Manifests.Add("MyCompany.AnotherWiki", @" Name: AnotherWiki Author: Coder Notaprogrammer Website: http://anotherwiki.codeplex.com Version: 1.2.3 OrchardVersion: 1 Features: AnotherWiki: Description: My super wiki module for Orchard. Dependencies: Versioning, Search Category: Content types AnotherWiki Editor: Description: A rich editor for wiki contents. Dependencies: TinyMCE, AnotherWiki Category: Input methods AnotherWiki DistributionList: Description: Sends e-mail alerts when wiki contents gets published. Dependencies: AnotherWiki, Email Subscriptions Category: Email AnotherWiki Captcha: Description: Kills spam. Or makes it zombie-like. Dependencies: AnotherWiki, reCaptcha Category: Spam "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("MyCompany.AnotherWiki")); Assert.That(descriptor.Name, Is.EqualTo("AnotherWiki")); Assert.That(descriptor.Author, Is.EqualTo("Coder Notaprogrammer")); Assert.That(descriptor.WebSite, Is.EqualTo("http://anotherwiki.codeplex.com")); Assert.That(descriptor.Version, Is.EqualTo("1.2.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Features.Count(), Is.EqualTo(5)); foreach (var featureDescriptor in descriptor.Features) { switch (featureDescriptor.Id) { case "AnotherWiki": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("My super wiki module for Orchard.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Content types")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("Versioning")); Assert.That(featureDescriptor.Dependencies.Contains("Search")); break; case "AnotherWiki Editor": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("A rich editor for wiki contents.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Input methods")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("TinyMCE")); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); break; case "AnotherWiki DistributionList": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Sends e-mail alerts when wiki contents gets published.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Email")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("Email Subscriptions")); break; case "AnotherWiki Captcha": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Kills spam. Or makes it zombie-like.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Spam")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("reCaptcha")); break; // default feature. case "MyCompany.AnotherWiki": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); break; default: Assert.Fail("Features not parsed correctly"); break; } } } [Test] public void ExtensionDescriptorsShouldBeParsedForCompleteModuleTxtWithSimpleFormat() { _folders.Manifests.Add("AnotherWiki", @" Name: AnotherWiki Author: Coder Notaprogrammer Website: http://anotherwiki.codeplex.com Version: 1.2.3 OrchardVersion: 1 Description: Module Description FeatureDescription: My super wiki module for Orchard. Dependencies: Versioning, Search Category: Content types Features: AnotherWiki Editor: Description: A rich editor for wiki contents. Dependencies: TinyMCE, AnotherWiki Category: Input methods AnotherWiki DistributionList: Description: Sends e-mail alerts when wiki contents gets published. Dependencies: AnotherWiki, Email Subscriptions Category: Email AnotherWiki Captcha: Description: Kills spam. Or makes it zombie-like. Dependencies: AnotherWiki, reCaptcha Category: Spam "); var descriptor = _manager.AvailableExtensions().Single(); Assert.That(descriptor.Id, Is.EqualTo("AnotherWiki")); Assert.That(descriptor.Name, Is.EqualTo("AnotherWiki")); Assert.That(descriptor.Author, Is.EqualTo("Coder Notaprogrammer")); Assert.That(descriptor.WebSite, Is.EqualTo("http://anotherwiki.codeplex.com")); Assert.That(descriptor.Version, Is.EqualTo("1.2.3")); Assert.That(descriptor.OrchardVersion, Is.EqualTo("1")); Assert.That(descriptor.Description, Is.EqualTo("Module Description")); Assert.That(descriptor.Features.Count(), Is.EqualTo(4)); foreach (var featureDescriptor in descriptor.Features) { switch (featureDescriptor.Id) { case "AnotherWiki": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("My super wiki module for Orchard.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Content types")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("Versioning")); Assert.That(featureDescriptor.Dependencies.Contains("Search")); break; case "AnotherWiki Editor": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("A rich editor for wiki contents.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Input methods")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("TinyMCE")); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); break; case "AnotherWiki DistributionList": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Sends e-mail alerts when wiki contents gets published.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Email")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("Email Subscriptions")); break; case "AnotherWiki Captcha": Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor)); Assert.That(featureDescriptor.Description, Is.EqualTo("Kills spam. Or makes it zombie-like.")); Assert.That(featureDescriptor.Category, Is.EqualTo("Spam")); Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2)); Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki")); Assert.That(featureDescriptor.Dependencies.Contains("reCaptcha")); break; default: Assert.Fail("Features not parsed correctly"); break; } } } [Test] public void ExtensionManagerShouldLoadFeatures() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(DefaultExtensionTypes.Module); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features); var features = extensionManager.LoadFeatures(testFeature); var types = features.SelectMany(x => x.ExportedTypes); Assert.That(types.Count(), Is.Not.EqualTo(0)); } [Test] public void ExtensionManagerFeaturesContainNonAbstractClasses() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(DefaultExtensionTypes.Module); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features); var features = extensionManager.LoadFeatures(testFeature); var types = features.SelectMany(x => x.ExportedTypes); foreach (var type in types) { Assert.That(type.IsClass); Assert.That(!type.IsAbstract); } } [Test] public void ExtensionManagerTestFeatureAttribute() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(DefaultExtensionTypes.Module); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestFeature"); foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) { foreach (var type in feature.ExportedTypes) { foreach (OrchardFeatureAttribute featureAttribute in type.GetCustomAttributes(typeof(OrchardFeatureAttribute), false)) { Assert.That(featureAttribute.FeatureName, Is.EqualTo("TestFeature")); } } } } [Test] public void ExtensionManagerLoadFeatureReturnsTypesFromSpecificFeaturesWithFeatureAttribute() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(DefaultExtensionTypes.Module); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testFeature = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestFeature"); foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) { foreach (var type in feature.ExportedTypes) { Assert.That(type == typeof(Phi)); } } } [Test] public void ExtensionManagerLoadFeatureDoesNotReturnTypesFromNonMatchingFeatures() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(DefaultExtensionTypes.Module); extensionFolder.Manifests.Add("TestModule", @" Name: TestModule Version: 1.0.3 OrchardVersion: 1 Features: TestModule: Description: My test module for Orchard. TestFeature: Description: Contains the Phi type. "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var testModule = extensionManager.AvailableExtensions() .SelectMany(x => x.Features) .Single(x => x.Id == "TestModule"); foreach (var feature in extensionManager.LoadFeatures(new[] { testModule })) { foreach (var type in feature.ExportedTypes) { Assert.That(type != typeof(Phi)); Assert.That((type == typeof(Alpha) || (type == typeof(Beta)))); } } } [Test] public void ModuleNameIsIntroducedAsFeatureImplicitly() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(DefaultExtensionTypes.Module); extensionFolder.Manifests.Add("Minimalistic", @" Name: Minimalistic Version: 1.0.3 OrchardVersion: 1 "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var minimalisticModule = extensionManager.AvailableExtensions().Single(x => x.Id == "Minimalistic"); Assert.That(minimalisticModule.Features.Count(), Is.EqualTo(1)); Assert.That(minimalisticModule.Features.Single().Id, Is.EqualTo("Minimalistic")); } [Test] public void ThemeNameIsIntroducedAsFeatureImplicitly() { var extensionLoader = new StubLoaders(); var extensionFolder = new StubFolders(DefaultExtensionTypes.Theme); extensionFolder.Manifests.Add("Minimalistic", @" Name: Minimalistic Version: 1.0.3 OrchardVersion: 1 "); IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader); var minimalisticModule = extensionManager.AvailableExtensions().Single(x => x.Id == "Minimalistic"); Assert.That(minimalisticModule.Features.Count(), Is.EqualTo(1)); Assert.That(minimalisticModule.Features.Single().Id, Is.EqualTo("Minimalistic")); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Pooling; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets.Catch.Judgements; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.Objects.Drawables; using osu.Game.Rulesets.Catch.Skinning; using osu.Game.Rulesets.Judgements; using osu.Game.Skinning; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.UI { public class Catcher : SkinReloadableDrawable { /// <summary> /// The default colour used to tint hyper-dash fruit, along with the moving catcher, its trail /// and end glow/after-image during a hyper-dash. /// </summary> public static readonly Color4 DEFAULT_HYPER_DASH_COLOUR = Color4.Red; /// <summary> /// The duration between transitioning to hyper-dash state. /// </summary> public const double HYPER_DASH_TRANSITION_DURATION = 180; /// <summary> /// Whether we are hyper-dashing or not. /// </summary> public bool HyperDashing => hyperDashModifier != 1; /// <summary> /// Whether <see cref="DrawablePalpableCatchHitObject"/> fruit should appear on the plate. /// </summary> public bool CatchFruitOnPlate { get; set; } = true; /// <summary> /// The relative space to cover in 1 millisecond. based on 1 game pixel per millisecond as in osu-stable. /// </summary> public const double BASE_SPEED = 1.0; /// <summary> /// The current speed of the catcher. /// </summary> public double Speed => (Dashing ? 1 : 0.5) * BASE_SPEED * hyperDashModifier; /// <summary> /// The amount by which caught fruit should be offset from the plate surface to make them look visually "caught". /// </summary> public const float CAUGHT_FRUIT_VERTICAL_OFFSET = -5; /// <summary> /// The amount by which caught fruit should be scaled down to fit on the plate. /// </summary> private const float caught_fruit_scale_adjust = 0.5f; [NotNull] private readonly Container trailsTarget; private CatcherTrailDisplay trails; /// <summary> /// Contains caught objects on the plate. /// </summary> private readonly Container<CaughtObject> caughtObjectContainer; /// <summary> /// Contains objects dropped from the plate. /// </summary> [Resolved] private DroppedObjectContainer droppedObjectTarget { get; set; } public CatcherAnimationState CurrentState { get => body.AnimationState.Value; private set => body.AnimationState.Value = value; } /// <summary> /// The width of the catcher which can receive fruit. Equivalent to "catchMargin" in osu-stable. /// </summary> public const float ALLOWED_CATCH_RANGE = 0.8f; private bool dashing; public bool Dashing { get => dashing; set { if (value == dashing) return; dashing = value; updateTrailVisibility(); } } public Direction VisualDirection { get => Scale.X > 0 ? Direction.Right : Direction.Left; set => Scale = new Vector2((value == Direction.Right ? 1 : -1) * Math.Abs(Scale.X), Scale.Y); } /// <summary> /// Width of the area that can be used to attempt catches during gameplay. /// </summary> private readonly float catchWidth; private readonly SkinnableCatcher body; private Color4 hyperDashColour = DEFAULT_HYPER_DASH_COLOUR; private Color4 hyperDashEndGlowColour = DEFAULT_HYPER_DASH_COLOUR; private double hyperDashModifier = 1; private int hyperDashDirection; private float hyperDashTargetPosition; private Bindable<bool> hitLighting; private readonly HitExplosionContainer hitExplosionContainer; private readonly DrawablePool<CaughtFruit> caughtFruitPool; private readonly DrawablePool<CaughtBanana> caughtBananaPool; private readonly DrawablePool<CaughtDroplet> caughtDropletPool; public Catcher([NotNull] Container trailsTarget, BeatmapDifficulty difficulty = null) { this.trailsTarget = trailsTarget; Origin = Anchor.TopCentre; Size = new Vector2(CatcherArea.CATCHER_SIZE); if (difficulty != null) Scale = calculateScale(difficulty); catchWidth = CalculateCatchWidth(Scale); InternalChildren = new Drawable[] { caughtFruitPool = new DrawablePool<CaughtFruit>(50), caughtBananaPool = new DrawablePool<CaughtBanana>(100), // less capacity is needed compared to fruit because droplet is not stacked caughtDropletPool = new DrawablePool<CaughtDroplet>(25), caughtObjectContainer = new Container<CaughtObject> { Anchor = Anchor.TopCentre, Origin = Anchor.BottomCentre, }, body = new SkinnableCatcher(), hitExplosionContainer = new HitExplosionContainer { Anchor = Anchor.TopCentre, Origin = Anchor.BottomCentre, }, }; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) { hitLighting = config.GetBindable<bool>(OsuSetting.HitLighting); trails = new CatcherTrailDisplay(this); } protected override void LoadComplete() { base.LoadComplete(); // don't add in above load as we may potentially modify a parent in an unsafe manner. trailsTarget.Add(trails); } /// <summary> /// Creates proxied content to be displayed beneath hitobjects. /// </summary> public Drawable CreateProxiedContent() => caughtObjectContainer.CreateProxy(); /// <summary> /// Calculates the scale of the catcher based off the provided beatmap difficulty. /// </summary> private static Vector2 calculateScale(BeatmapDifficulty difficulty) => new Vector2(1.0f - 0.7f * (difficulty.CircleSize - 5) / 5); /// <summary> /// Calculates the width of the area used for attempting catches in gameplay. /// </summary> /// <param name="scale">The scale of the catcher.</param> public static float CalculateCatchWidth(Vector2 scale) => CatcherArea.CATCHER_SIZE * Math.Abs(scale.X) * ALLOWED_CATCH_RANGE; /// <summary> /// Calculates the width of the area used for attempting catches in gameplay. /// </summary> /// <param name="difficulty">The beatmap difficulty.</param> public static float CalculateCatchWidth(BeatmapDifficulty difficulty) => CalculateCatchWidth(calculateScale(difficulty)); /// <summary> /// Determine if this catcher can catch a <see cref="CatchHitObject"/> in the current position. /// </summary> public bool CanCatch(CatchHitObject hitObject) { if (!(hitObject is PalpableCatchHitObject fruit)) return false; var halfCatchWidth = catchWidth * 0.5f; // this stuff wil disappear once we move fruit to non-relative coordinate space in the future. var catchObjectPosition = fruit.EffectiveX; var catcherPosition = Position.X; return catchObjectPosition >= catcherPosition - halfCatchWidth && catchObjectPosition <= catcherPosition + halfCatchWidth; } public void OnNewResult(DrawableCatchHitObject drawableObject, JudgementResult result) { var catchResult = (CatchJudgementResult)result; catchResult.CatcherAnimationState = CurrentState; catchResult.CatcherHyperDash = HyperDashing; if (!(drawableObject is DrawablePalpableCatchHitObject palpableObject)) return; var hitObject = palpableObject.HitObject; if (result.IsHit) { var positionInStack = computePositionInStack(new Vector2(palpableObject.X - X, 0), palpableObject.DisplaySize.X); if (CatchFruitOnPlate) placeCaughtObject(palpableObject, positionInStack); if (hitLighting.Value) addLighting(hitObject, positionInStack.X, drawableObject.AccentColour.Value); } // droplet doesn't affect the catcher state if (hitObject is TinyDroplet) return; if (result.IsHit && hitObject.HyperDash) { var target = hitObject.HyperDashTarget; var timeDifference = target.StartTime - hitObject.StartTime; double positionDifference = target.EffectiveX - X; var velocity = positionDifference / Math.Max(1.0, timeDifference - 1000.0 / 60.0); SetHyperDashState(Math.Abs(velocity), target.EffectiveX); } else SetHyperDashState(); if (result.IsHit) CurrentState = hitObject.Kiai ? CatcherAnimationState.Kiai : CatcherAnimationState.Idle; else if (!(hitObject is Banana)) CurrentState = CatcherAnimationState.Fail; } public void OnRevertResult(DrawableCatchHitObject drawableObject, JudgementResult result) { var catchResult = (CatchJudgementResult)result; CurrentState = catchResult.CatcherAnimationState; if (HyperDashing != catchResult.CatcherHyperDash) { if (catchResult.CatcherHyperDash) SetHyperDashState(2); else SetHyperDashState(); } caughtObjectContainer.RemoveAll(d => d.HitObject == drawableObject.HitObject); droppedObjectTarget.RemoveAll(d => d.HitObject == drawableObject.HitObject); } /// <summary> /// Set hyper-dash state. /// </summary> /// <param name="modifier">The speed multiplier. If this is less or equals to 1, this catcher will be non-hyper-dashing state.</param> /// <param name="targetPosition">When this catcher crosses this position, this catcher ends hyper-dashing.</param> public void SetHyperDashState(double modifier = 1, float targetPosition = -1) { var wasHyperDashing = HyperDashing; if (modifier <= 1 || X == targetPosition) { hyperDashModifier = 1; hyperDashDirection = 0; if (wasHyperDashing) runHyperDashStateTransition(false); } else { hyperDashModifier = modifier; hyperDashDirection = Math.Sign(targetPosition - X); hyperDashTargetPosition = targetPosition; if (!wasHyperDashing) { trails.DisplayEndGlow(); runHyperDashStateTransition(true); } } } /// <summary> /// Drop any fruit off the plate. /// </summary> public void Drop() => clearPlate(DroppedObjectAnimation.Drop); /// <summary> /// Explode all fruit off the plate. /// </summary> public void Explode() => clearPlate(DroppedObjectAnimation.Explode); private void runHyperDashStateTransition(bool hyperDashing) { updateTrailVisibility(); this.FadeColour(hyperDashing ? hyperDashColour : Color4.White, HYPER_DASH_TRANSITION_DURATION, Easing.OutQuint); } private void updateTrailVisibility() => trails.DisplayTrail = Dashing || HyperDashing; protected override void SkinChanged(ISkinSource skin) { base.SkinChanged(skin); hyperDashColour = skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDash)?.Value ?? DEFAULT_HYPER_DASH_COLOUR; hyperDashEndGlowColour = skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDashAfterImage)?.Value ?? hyperDashColour; trails.HyperDashTrailsColour = hyperDashColour; trails.EndGlowSpritesColour = hyperDashEndGlowColour; runHyperDashStateTransition(HyperDashing); } protected override void Update() { base.Update(); // Correct overshooting. if ((hyperDashDirection > 0 && hyperDashTargetPosition < X) || (hyperDashDirection < 0 && hyperDashTargetPosition > X)) { X = hyperDashTargetPosition; SetHyperDashState(); } } private void placeCaughtObject(DrawablePalpableCatchHitObject drawableObject, Vector2 position) { var caughtObject = getCaughtObject(drawableObject.HitObject); if (caughtObject == null) return; caughtObject.CopyStateFrom(drawableObject); caughtObject.Anchor = Anchor.TopCentre; caughtObject.Position = position; caughtObject.Scale *= caught_fruit_scale_adjust; caughtObjectContainer.Add(caughtObject); if (!caughtObject.StaysOnPlate) removeFromPlate(caughtObject, DroppedObjectAnimation.Explode); } private Vector2 computePositionInStack(Vector2 position, float displayRadius) { // this is taken from osu-stable (lenience should be 10 * 10 at standard scale). const float lenience_adjust = 10 / CatchHitObject.OBJECT_RADIUS; float adjustedRadius = displayRadius * lenience_adjust; float checkDistance = MathF.Pow(adjustedRadius, 2); // offset fruit vertically to better place "above" the plate. position.Y += CAUGHT_FRUIT_VERTICAL_OFFSET; while (caughtObjectContainer.Any(f => Vector2Extensions.DistanceSquared(f.Position, position) < checkDistance)) { position.X += RNG.NextSingle(-adjustedRadius, adjustedRadius); position.Y -= RNG.NextSingle(0, 5); } return position; } private void addLighting(CatchHitObject hitObject, float x, Color4 colour) => hitExplosionContainer.Add(new HitExplosionEntry(Time.Current, x, hitObject.Scale, colour, hitObject.RandomSeed)); private CaughtObject getCaughtObject(PalpableCatchHitObject source) { switch (source) { case Fruit _: return caughtFruitPool.Get(); case Banana _: return caughtBananaPool.Get(); case Droplet _: return caughtDropletPool.Get(); default: return null; } } private CaughtObject getDroppedObject(CaughtObject caughtObject) { var droppedObject = getCaughtObject(caughtObject.HitObject); droppedObject.CopyStateFrom(caughtObject); droppedObject.Anchor = Anchor.TopLeft; droppedObject.Position = caughtObjectContainer.ToSpaceOfOtherDrawable(caughtObject.DrawPosition, droppedObjectTarget); return droppedObject; } private void clearPlate(DroppedObjectAnimation animation) { var droppedObjects = caughtObjectContainer.Children.Select(getDroppedObject).ToArray(); caughtObjectContainer.Clear(false); droppedObjectTarget.AddRange(droppedObjects); foreach (var droppedObject in droppedObjects) applyDropAnimation(droppedObject, animation); } private void removeFromPlate(CaughtObject caughtObject, DroppedObjectAnimation animation) { var droppedObject = getDroppedObject(caughtObject); caughtObjectContainer.Remove(caughtObject); droppedObjectTarget.Add(droppedObject); applyDropAnimation(droppedObject, animation); } private void applyDropAnimation(Drawable d, DroppedObjectAnimation animation) { switch (animation) { case DroppedObjectAnimation.Drop: d.MoveToY(d.Y + 75, 750, Easing.InSine); d.FadeOut(750); break; case DroppedObjectAnimation.Explode: var originalX = droppedObjectTarget.ToSpaceOfOtherDrawable(d.DrawPosition, caughtObjectContainer).X * Scale.X; d.MoveToY(d.Y - 50, 250, Easing.OutSine).Then().MoveToY(d.Y + 50, 500, Easing.InSine); d.MoveToX(d.X + originalX * 6, 1000); d.FadeOut(750); break; } d.Expire(); } private enum DroppedObjectAnimation { Drop, Explode } } }
using System; using System.Collections; using System.Text; /* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace com.google.zxing.common { /// <summary> /// <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p> /// /// @author Sean Owen /// </summary> public sealed class BitArray { private int[] bits; private int size; public BitArray() { this.size = 0; this.bits = new int[1]; } public BitArray(int size) { this.size = size; this.bits = makeArray(size); } public int Size { get { return size; } } public int SizeInBytes { get { return (size + 7) >> 3; } } private void ensureCapacity(int size) { if (size > bits.Length << 5) { int[] newBits = makeArray(size); Array.Copy(bits, 0, newBits, 0, bits.Length); this.bits = newBits; } } /// <param name="i"> bit to get </param> /// <returns> true iff bit i is set </returns> public bool get(int i) { return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; } /// <summary> /// Sets bit i. /// </summary> /// <param name="i"> bit to set </param> public void set(int i) { bits[i >> 5] |= 1 << (i & 0x1F); } /// <summary> /// Flips bit i. /// </summary> /// <param name="i"> bit to set </param> public void flip(int i) { bits[i >> 5] ^= 1 << (i & 0x1F); } /// <param name="from"> first bit to check </param> /// <returns> index of first bit that is set, starting from the given index, or size if none are set /// at or beyond this given index </returns> /// <seealso cref= #getNextUnset(int) </seealso> public int getNextSet(int from) { if (from >= size) { return size; } int bitsOffset = from >> 5; int currentBits = bits[bitsOffset]; // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1); while (currentBits == 0) { if (++bitsOffset == bits.Length) { return size; } currentBits = bits[bitsOffset]; } //int result = (bitsOffset << 5) + int.numberOfTrailingZeros(currentBits); int result = (bitsOffset << 5) + currentBits.NumberOfTrailingZeros(); return result > size ? size : result; } /// <seealso cref= #getNextSet(int) </seealso> public int getNextUnset(int from) { if (from >= size) { return size; } int bitsOffset = from >> 5; int currentBits = ~bits[bitsOffset]; // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1); while (currentBits == 0) { if (++bitsOffset == bits.Length) { return size; } currentBits = ~bits[bitsOffset]; } //int result = (bitsOffset << 5) + int.numberOfTrailingZeros(currentBits); int result = (bitsOffset << 5) + currentBits.NumberOfTrailingZeros(); return result > size ? size : result; } /// <summary> /// Sets a block of 32 bits, starting at bit i. /// </summary> /// <param name="i"> first bit to set </param> /// <param name="newBits"> the new value of the next 32 bits. Note again that the least-significant bit /// corresponds to bit i, the next-least-significant to i+1, and so on. </param> public void setBulk(int i, int newBits) { bits[i >> 5] = newBits; } /// <summary> /// Sets a range of bits. /// </summary> /// <param name="start"> start of range, inclusive. </param> /// <param name="end"> end of range, exclusive </param> public void setRange(int start, int end) { if (end < start) { throw new System.ArgumentException(); } if (end == start) { return; } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } bits[i] |= mask; } } /// <summary> /// Clears all bits (sets to false). /// </summary> public void clear() { int max = bits.Length; for (int i = 0; i < max; i++) { bits[i] = 0; } } /// <summary> /// Efficient method to check if a range of bits is set, or not set. /// </summary> /// <param name="start"> start of range, inclusive. </param> /// <param name="end"> end of range, exclusive </param> /// <param name="value"> if true, checks that bits in range are set, otherwise checks that they are not set </param> /// <returns> true iff all bits are set or not set in range, according to value argument </returns> /// <exception cref="IllegalArgumentException"> if end is less than or equal to start </exception> public bool isRange(int start, int end, bool value) { if (end < start) { throw new System.ArgumentException(); } if (end == start) { return true; // empty range matches } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) != (value ? mask : 0)) { return false; } } return true; } public void appendBit(bool bit) { ensureCapacity(size + 1); if (bit) { bits[size >> 5] |= 1 << (size & 0x1F); } size++; } /// <summary> /// Appends the least-significant bits, from value, in order from most-significant to /// least-significant. For example, appending 6 bits from 0x000001E will append the bits /// 0, 1, 1, 1, 1, 0 in that order. /// </summary> public void appendBits(int value, int numBits) { if (numBits < 0 || numBits > 32) { throw new System.ArgumentException("Num bits must be between 0 and 32"); } ensureCapacity(size + numBits); for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) { appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1); } } public void appendBitArray(BitArray other) { int otherSize = other.size; ensureCapacity(size + otherSize); for (int i = 0; i < otherSize; i++) { appendBit(other.get(i)); } } public void xor(BitArray other) { if (bits.Length != other.bits.Length) { throw new System.ArgumentException("Sizes don't match"); } for (int i = 0; i < bits.Length; i++) { // The last byte could be incomplete (i.e. not have 8 bits in // it) but there is no problem since 0 XOR 0 == 0. bits[i] ^= other.bits[i]; } } /// /// <param name="bitOffset"> first bit to start writing </param> /// <param name="array"> array to write into. Bytes are written most-significant byte first. This is the opposite /// of the internal representation, which is exposed by <seealso cref="#getBitArray()"/> </param> /// <param name="offset"> position in array to start writing </param> /// <param name="numBytes"> how many bytes to write </param> public void toBytes(int bitOffset, sbyte[] array, int offset, int numBytes) { for (int i = 0; i < numBytes; i++) { int theByte = 0; for (int j = 0; j < 8; j++) { if (get(bitOffset)) { theByte |= 1 << (7 - j); } bitOffset++; } array[offset + i] = (sbyte) theByte; } } /// <returns> underlying array of ints. The first element holds the first 32 bits, and the least /// significant bit is bit 0. </returns> public int[] BitArrayBits { get { return bits; } } /// <summary> /// Reverses all bits in the array. /// </summary> public void reverse() { int[] newBits = new int[bits.Length]; int size = this.size; for (int i = 0; i < size; i++) { if (get(size - i - 1)) { newBits[i >> 5] |= 1 << (i & 0x1F); } } bits = newBits; } private static int[] makeArray(int size) { return new int[(size + 31) >> 5]; } public override string ToString() { StringBuilder result = new StringBuilder(size); for (int i = 0; i < size; i++) { if ((i & 0x07) == 0) { result.Append(' '); } result.Append(get(i) ? 'X' : '.'); } return result.ToString(); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows.Automation; using EnvDTE; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Python; using TestUtilities.UI; namespace PythonToolsUITests { [TestClass] public class ObjectBrowserTest { private class NodeInfo { public NodeInfo(string name, string description, string[] members = null) { Name = name; Description = description; Members = (members != null) ? new Collection<string>(members) : new Collection<string>(); } public string Name { get; private set; } public string Description { get; private set; } public Collection<string> Members { get; private set; } } private static void AssertNodes(ObjectBrowser objectBrowser, params NodeInfo[] expectedNodes) { AssertNodes(objectBrowser, true, expectedNodes); } private static void AssertNodes(ObjectBrowser objectBrowser, bool expand, params NodeInfo[] expectedNodes) { for (int i = 0; i < expectedNodes.Length; ++i) { // Check node name for (int j = 0; j < 100; j++) { if (i < objectBrowser.TypeBrowserPane.Nodes.Count) { break; } System.Threading.Thread.Sleep(250); } string str = objectBrowser.TypeBrowserPane.Nodes[i].Value.Trim(); Console.WriteLine("Found node: {0}", str); Assert.AreEqual(expectedNodes[i].Name, str, ""); objectBrowser.TypeBrowserPane.Nodes[i].Select(); if (expand) { try { objectBrowser.TypeBrowserPane.Nodes[i].ExpandCollapse(); } catch (InvalidOperationException) { } } System.Threading.Thread.Sleep(1000); // Check detailed node description. str = objectBrowser.DetailPane.Value.Trim(); if(expectedNodes[i].Description != str) { for (int j = 0; j < str.Length; j++) { Console.WriteLine("{0} {1}", (int)str[j], (int)expectedNodes[i].Description[j]); } } Assert.AreEqual(expectedNodes[i].Description, str, ""); // Check dependent nodes in member pane int nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; var expectedMembers = expectedNodes[i].Members; if (expectedMembers == null) { Assert.AreEqual(0, nodeCount, "Node Count: " + nodeCount.ToString()); } else { Assert.AreEqual(expectedMembers.Count, nodeCount, "Node Count: " + nodeCount.ToString()); for (int j = 0; j < expectedMembers.Count; ++j) { str = objectBrowser.TypeNavigatorPane.Nodes[j].Value.Trim(); Assert.AreEqual(expectedMembers[j], str, ""); } } } } [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserBasicTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Outlining.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); AssertNodes(objectBrowser, new NodeInfo("Outlining", "Outlining"), new NodeInfo("BadForStatement.py", "BadForStatement.py"), new NodeInfo("NestedFuncDef.py", "NestedFuncDef.py", new[] { "def f()" }), new NodeInfo("Program.py", "Program.py", new[] { "def f()", "i" })); app.Dte.Solution.Close(false); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserSearchTextTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\ObjectBrowser.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); // Initially, we should have only the top-level collapsed node for the project int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); // Sanity-check the starting view with all nodes expanded. var expectedNodesBeforeSearch = new[] { new NodeInfo("ObjectBrowser", "ObjectBrowser"), new NodeInfo("Program.py", "Program.py", new[] { "def frob()" }), new NodeInfo("class Fob", "class Fob"), new NodeInfo("class FobOarBaz", "class FobOarBaz", new[] { "def frob(self)" }), new NodeInfo("class Oar", "class Oar", new[] { "def oar(self)" }), }; AssertNodes(objectBrowser, expectedNodesBeforeSearch); // Do the search and check results objectBrowser.SearchText.SetValue("oar"); System.Threading.Thread.Sleep(1000); objectBrowser.SearchButton.Click(); System.Threading.Thread.Sleep(1000); var expectedNodesAfterSearch = new[] { new NodeInfo("oar", "def oar(self)\rdeclared in Oar"), new NodeInfo("Oar", "class Oar", new[] { "def oar(self)" }), new NodeInfo("FobOarBaz", "class FobOarBaz", new[] { "def frob(self)" }), }; AssertNodes(objectBrowser, expectedNodesAfterSearch); // Clear the search and check that we get back to the starting view. objectBrowser.ClearSearchButton.Click(); System.Threading.Thread.Sleep(1000); AssertNodes(objectBrowser, false, expectedNodesBeforeSearch); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserExpandTypeBrowserTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Inheritance.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[0].Value; Assert.AreEqual("Inheritance", str, ""); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString()); str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserCommentsTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Inheritance.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].Select(); nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; Assert.AreEqual(4, nodeCount, "Node Count: " + nodeCount.ToString()); str = objectBrowser.TypeNavigatorPane.Nodes[0].Value; Assert.AreEqual("member", str.Trim(), ""); str = objectBrowser.TypeNavigatorPane.Nodes[1].Value; Assert.AreEqual("members", str.Trim(), ""); str = objectBrowser.TypeNavigatorPane.Nodes[2].Value; Assert.AreEqual("s", str.Trim(), ""); str = objectBrowser.TypeNavigatorPane.Nodes[3].Value; Assert.AreEqual("t", str.Trim(), ""); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[2].Select(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node Count: " + nodeCount.ToString()); str = objectBrowser.TypeNavigatorPane.Nodes[0].Value; Assert.IsTrue(str.Trim().StartsWith("def __init__(self"), str); str = objectBrowser.TypeNavigatorPane.Nodes[1].Value; Assert.AreEqual("def tell(self)", str.Trim(), ""); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("SchoolMember"), str); Assert.IsTrue(str.Trim().Contains("Represents any school member."), str); objectBrowser.TypeNavigatorPane.Nodes[1].Select(); System.Threading.Thread.Sleep(1000); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("def tell(self)"), str); Assert.IsTrue(str.Trim().Contains("Tell my detail."), str); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserInheritanceRelationshipTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Inheritance.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].Select(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeNavigatorPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node Count: " + nodeCount.ToString()); str = objectBrowser.TypeNavigatorPane.Nodes[0].Value; Assert.IsTrue(str.Trim().StartsWith("__init__ (alias of def "), str); str = objectBrowser.TypeNavigatorPane.Nodes[1].Value; Assert.AreEqual("def tell(self)", str.Trim(), ""); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("Student(SchoolMember)"), str); Assert.IsTrue(str.Trim().Contains("Represents a student."), str); objectBrowser.TypeNavigatorPane.Nodes[1].Select(); System.Threading.Thread.Sleep(1000); str = objectBrowser.DetailPane.Value; Assert.IsTrue(str.Trim().Contains("def tell(self)"), str); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserNavigationTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[4].Select(); System.Threading.Thread.Sleep(1000); app.ExecuteCommand("Edit.GoToDefinition"); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveDocument.Name; Assert.AreEqual("Program.py", str, ""); int lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(14, lineNo, "Line number: " + lineNo.ToString()); app.OpenObjectBrowser(); objectBrowser.TypeBrowserPane.Nodes[2].Select(); System.Threading.Thread.Sleep(1000); app.ExecuteCommand("Edit.GoToDefinition"); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveDocument.Name; Assert.AreEqual("MyModule.py", str, ""); lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(1, lineNo, "Line number: " + lineNo.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserContextMenuBasicTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); Assert.AreEqual("Copy", menu.Items[0].Value.Trim(), ""); Assert.AreEqual("View Namespaces", menu.Items[1].Value.Trim(), ""); Assert.AreEqual("View Containers", menu.Items[2].Value.Trim(), ""); Assert.AreEqual("Sort Alphabetically", menu.Items[3].Value.Trim(), ""); Assert.AreEqual("Sort By Object Type", menu.Items[4].Value.Trim(), ""); Assert.AreEqual("Sort By Object Access", menu.Items[5].Value.Trim(), ""); Assert.AreEqual("Group By Object Type", menu.Items[6].Value.Trim(), ""); Keyboard.PressAndRelease(System.Windows.Input.Key.Escape); objectBrowser.TypeBrowserPane.Nodes[2].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); itemCount = menu.Items.Count; Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString()); Assert.AreEqual("Go To Definition", menu.Items[0].Value.Trim(), ""); Assert.AreEqual("Go To Declaration", menu.Items[1].Value.Trim(), ""); Assert.AreEqual("Go To Reference", menu.Items[2].Value.Trim(), ""); Assert.AreEqual("Browse Definition", menu.Items[3].Value.Trim(), ""); Assert.AreEqual("Find All References", menu.Items[4].Value.Trim(), ""); Assert.AreEqual("Filter To Type", menu.Items[5].Value.Trim(), ""); Assert.AreEqual("Copy", menu.Items[6].Value.Trim(), ""); Assert.AreEqual("View Namespaces", menu.Items[7].Value.Trim(), ""); Assert.AreEqual("View Containers", menu.Items[8].Value.Trim(), ""); Assert.AreEqual("Sort Alphabetically", menu.Items[9].Value.Trim(), ""); Assert.AreEqual("Sort By Object Type", menu.Items[10].Value.Trim(), ""); Assert.AreEqual("Sort By Object Access", menu.Items[11].Value.Trim(), ""); Assert.AreEqual("Group By Object Type", menu.Items[12].Value.Trim(), ""); Keyboard.PressAndRelease(System.Windows.Input.Key.Escape); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserTypeBrowserViewTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); menu.Items[1].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(2, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); Assert.IsTrue(menu.Items[1].ToggleStatus); menu.Items[2].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserTypeBrowserSortTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[1].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); menu.Items[6].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(4, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(5, nodeCount, "Node count: " + nodeCount.ToString()); Assert.AreEqual("Namespaces", objectBrowser.TypeBrowserPane.Nodes[3].Value, ""); Assert.AreEqual("Namespaces", objectBrowser.TypeBrowserPane.Nodes[1].Value, ""); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[0].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); itemCount = menu.Items.Count; Assert.AreEqual(7, itemCount, "Item count: " + itemCount.ToString()); Assert.IsTrue(menu.Items[6].ToggleStatus); menu.Items[3].Check(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(4, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[3].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("class SchoolMember\n", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[3].Value; Assert.AreEqual("Program.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[4].Value; Assert.AreEqual("class Student(MyModule.SchoolMember)\n", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[5].Value; Assert.AreEqual("class Teacher(MyModule.SchoolMember)\n", str, ""); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserNavigateVarContextMenuTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; objectBrowser.EnsureLoaded(); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[4].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString()); menu.Items[0].Check(); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveDocument.Name; Assert.AreEqual("Program.py", str, ""); int lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(14, lineNo, "Line number: " + lineNo.ToString()); app.OpenObjectBrowser(); objectBrowser.TypeBrowserPane.Nodes[5].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); menu.Items[0].Check(); System.Threading.Thread.Sleep(1000); lineNo = ((TextSelection)app.Dte.ActiveDocument.Selection).ActivePoint.Line; Assert.AreEqual(3, lineNo, "Line number: " + lineNo.ToString()); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ObjectBrowserFindAllReferencesTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\MultiModule.sln"); System.Threading.Thread.Sleep(1000); app.OpenObjectBrowser(); var objectBrowser = app.ObjectBrowser; System.Threading.Thread.Sleep(1000); int nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(1, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[0].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(3, nodeCount, "Node count: " + nodeCount.ToString()); string str = objectBrowser.TypeBrowserPane.Nodes[1].Value; Assert.AreEqual("MyModule.py", str, ""); str = objectBrowser.TypeBrowserPane.Nodes[2].Value; Assert.AreEqual("Program.py", str, ""); objectBrowser.TypeBrowserPane.Nodes[2].ExpandCollapse(); System.Threading.Thread.Sleep(1000); objectBrowser.TypeBrowserPane.Nodes[1].ExpandCollapse(); System.Threading.Thread.Sleep(1000); nodeCount = objectBrowser.TypeBrowserPane.Nodes.Count; Assert.AreEqual(6, nodeCount, "Node count: " + nodeCount.ToString()); objectBrowser.TypeBrowserPane.Nodes[4].ShowContextMenu(); System.Threading.Thread.Sleep(1000); Condition con = new PropertyCondition( AutomationElement.ClassNameProperty, "ContextMenu" ); AutomationElement el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); Menu menu = new Menu(el); int itemCount = menu.Items.Count; Assert.AreEqual(13, itemCount, "Item count: " + itemCount.ToString()); menu.Items[4].Check(); System.Threading.Thread.Sleep(1000); //this needs to be updated for bug #4840 str = app.Dte.ActiveWindow.Caption; Assert.IsTrue(str.Contains("2 matches found"), str); objectBrowser.TypeBrowserPane.Nodes[2].ShowContextMenu(); System.Threading.Thread.Sleep(1000); el = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, con); Assert.IsNotNull(el); menu = new Menu(el); menu.Items[4].Check(); System.Threading.Thread.Sleep(1000); str = app.Dte.ActiveWindow.Caption; Assert.IsTrue(str.Contains("2 matches found"), str); } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void NavigateTo() { using (var app = new VisualStudioApp()) { app.OpenProject(@"TestData\Navigation.sln"); using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "Class"; Assert.AreEqual(4, dialog.WaitForNumberOfResults(4)); } using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "cls"; Assert.AreEqual(4, dialog.WaitForNumberOfResults(4)); } using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "func"; Assert.AreEqual(8, dialog.WaitForNumberOfResults(8)); } using (var dialog = app.OpenNavigateTo()) { dialog.SearchTerm = "fn"; Assert.AreEqual(8, dialog.WaitForNumberOfResults(8)); } } } [TestMethod, Priority(1)] [HostType("VSTestHost"), TestCategory("Installed")] public void ResourceViewIsDisabledTest() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\Outlining.sln"); System.Threading.Thread.Sleep(1000); app.OpenResourceView(); var resourceView = app.ResourceView; Assert.IsNotNull(resourceView); System.Threading.Thread.Sleep(1000); Assert.IsNull(resourceView.TypeBrowserPane); } } } }
using System; using System.Linq; using Baseline; using LamarCodeGeneration; using LamarCodeGeneration.Frames; using Marten.Internal.Storage; using Marten.Linq; using Marten.Linq.SqlGeneration; using Marten.Schema; using Marten.Services; using Marten.Storage; namespace Marten.Internal.CodeGeneration { internal class DocumentStorageBuilder { private readonly Func<DocumentOperations, GeneratedType> _selectorTypeSource; private readonly Type _baseType; private readonly string _typeName; private readonly DocumentMapping _mapping; public DocumentStorageBuilder(DocumentMapping mapping, StorageStyle style, Func<DocumentOperations, GeneratedType> selectorTypeSource) { _mapping = mapping; _selectorTypeSource = selectorTypeSource; _typeName = $"{style}{mapping.DocumentType.Name.Sanitize()}DocumentStorage"; _baseType = determineOpenDocumentStorageType(style).MakeGenericType(mapping.DocumentType, mapping.IdType); } private Type determineOpenDocumentStorageType(StorageStyle style) { switch (style) { case StorageStyle.Lightweight: return typeof(LightweightDocumentStorage<,>); case StorageStyle.QueryOnly: return typeof(QueryOnlyDocumentStorage<,>); case StorageStyle.IdentityMap: return typeof(IdentityMapDocumentStorage<,>); case StorageStyle.DirtyTracking: return typeof(DirtyCheckedDocumentStorage<,>); } throw new NotSupportedException(); } public GeneratedType Build(GeneratedAssembly assembly, DocumentOperations operations) { var selectorType = _selectorTypeSource(operations); return buildDocumentStorageType(assembly, operations, _typeName, _baseType, selectorType); } private GeneratedType buildDocumentStorageType(GeneratedAssembly assembly, DocumentOperations operations, string typeName, Type baseType, GeneratedType selectorType) { var type = assembly.AddType(typeName, baseType); writeIdentityMethod(type); buildStorageOperationMethods(operations, type); type.MethodFor(nameof(ISelectClause.BuildSelector)) .Frames.Code($"return new Marten.Generated.{selectorType.TypeName}({{0}}, {{1}});", Use.Type<IMartenSession>(), Use.Type<DocumentMapping>()); buildLoaderCommands(type); writeNotImplementedStubs(type); return type; } private void writeIdentityMethod(GeneratedType type) { var identity = type.MethodFor("Identity"); identity.Frames.Code($"return {{0}}.{_mapping.IdMember.Name};", identity.Arguments[0]); var assign = type.MethodFor("AssignIdentity"); _mapping.IdStrategy.GenerateCode(assign, _mapping); } private static void writeNotImplementedStubs(GeneratedType type) { var missing = type.Methods.Where(x => !x.Frames.Any()).Select(x => x.MethodName); if (missing.Any()) { throw new Exception("Missing methods: " + missing.Join(", ")); } foreach (var method in type.Methods) { if (!method.Frames.Any()) { method.Frames.ThrowNotImplementedException(); } } } private void buildLoaderCommands(GeneratedType type) { var load = type.MethodFor("BuildLoadCommand"); var loadByArray = type.MethodFor("BuildLoadManyCommand"); if (_mapping.TenancyStyle == TenancyStyle.Conjoined) { load.Frames.Code( "return new NpgsqlCommand(_loaderSql).With(\"id\", id).With(TenantIdArgument.ArgName, tenant.TenantId);"); loadByArray.Frames.Code( "return new NpgsqlCommand(_loadArraySql).With(\"ids\", ids).With(TenantIdArgument.ArgName, tenant.TenantId);"); } else { load.Frames.Code("return new NpgsqlCommand(_loaderSql).With(\"id\", id);"); loadByArray.Frames.Code("return new NpgsqlCommand(_loadArraySql).With(\"ids\", ids);"); } } private void buildStorageOperationMethods(DocumentOperations operations, GeneratedType type) { if (_mapping.UseOptimisticConcurrency) { buildConditionalOperationBasedOnConcurrencyChecks(type, operations, "Upsert"); buildOperationMethod(type, operations, "Insert"); buildOperationMethod(type, operations, "Overwrite"); buildConditionalOperationBasedOnConcurrencyChecks(type, operations, "Update"); } else { buildOperationMethod(type, operations, "Upsert"); buildOperationMethod(type, operations, "Insert"); buildOperationMethod(type, operations, "Update"); } if (_mapping.UseOptimisticConcurrency) { buildOperationMethod(type, operations, "Overwrite"); } else { type.MethodFor("Overwrite").Frames.ThrowNotSupportedException(); } } private void buildConditionalOperationBasedOnConcurrencyChecks(GeneratedType type, DocumentOperations operations, string methodName) { var operationType = (GeneratedType)typeof(DocumentOperations).GetProperty(methodName).GetValue(operations); var overwriteType = operations.Overwrite; var method = type.MethodFor(methodName); method.Frames.Code($"BLOCK:if (session.{nameof(IDocumentSession.Concurrency)} == {{0}})", ConcurrencyChecks.Disabled); writeReturnOfOperation(method, overwriteType); method.Frames.Code("END"); method.Frames.Code("BLOCK:else"); writeReturnOfOperation(method, operationType); method.Frames.Code("END"); } private void buildOperationMethod(GeneratedType type, DocumentOperations operations, string methodName) { var operationType = (GeneratedType)typeof(DocumentOperations).GetProperty(methodName).GetValue(operations); var method = type.MethodFor(methodName); writeReturnOfOperation(method, operationType); } private void writeReturnOfOperation(GeneratedMethod method, GeneratedType operationType) { var tenantDeclaration = ""; if (_mapping.TenancyStyle == TenancyStyle.Conjoined) { tenantDeclaration = ", tenant"; } if (_mapping.IsHierarchy()) { method.Frames .Code($@" return new Marten.Generated.{operationType.TypeName} ( {{0}}, Identity({{0}}), {{1}}.Versions.ForType<{_mapping.DocumentType.FullNameInCode()}, {_mapping.IdType.FullNameInCode()}>(), {{2}} {tenantDeclaration} );" , new Use(_mapping.DocumentType), Use.Type<IMartenSession>(), Use.Type<DocumentMapping>()); } else { method.Frames .Code($@" return new Marten.Generated.{operationType.TypeName} ( {{0}}, Identity({{0}}), {{1}}.Versions.ForType<{_mapping.DocumentType.FullNameInCode()}, {_mapping.IdType.FullNameInCode()}>(), {{2}} {tenantDeclaration} );" , new Use(_mapping.DocumentType), Use.Type<IMartenSession>(), Use.Type<DocumentMapping>()); } } } }
// Copyright (C) 2014 - 2016 Stephan Bouchard - All Rights Reserved // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms // Release 1.0.54 using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; namespace TMPro { [ExecuteInEditMode] [DisallowMultipleComponent] [RequireComponent(typeof(TextContainer))] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [AddComponentMenu("Mesh/TextMeshPro - Text")] [SelectionBase] public partial class TextMeshPro : TMP_Text, ILayoutElement { // Public Properties and Serializable Properties /// <summary> /// Determines where word wrap will occur. /// </summary> [Obsolete("The length of the line is now controlled by the size of the text container and margins.")] public float lineLength { get { return m_lineLength; } set { Debug.Log("lineLength set called."); } } #pragma warning disable 0649 [SerializeField] private float m_lineLength; /// <summary> /// Determines the anchor position of the text object. /// </summary> [Obsolete("The length of the line is now controlled by the size of the text container and margins.")] public TMP_Compatibility.AnchorPositions anchor { get { return m_anchor; } set { m_anchor = value; } } [SerializeField] private TMP_Compatibility.AnchorPositions m_anchor = TMP_Compatibility.AnchorPositions.None; /// <summary> /// The margins of the text object. /// </summary> public override Vector4 margin { get { return m_margin; } set { if (m_margin == value) return; m_margin = value; this.textContainer.margins = m_margin; ComputeMarginSize(); m_havePropertiesChanged = true; SetVerticesDirty(); } } /// <summary> /// Sets the Renderer's sorting Layer ID /// </summary> public int sortingLayerID { get { return m_renderer.sortingLayerID; } set { m_renderer.sortingLayerID = value; } } /// <summary> /// Sets the Renderer's sorting order within the assigned layer. /// </summary> public int sortingOrder { get { return m_renderer.sortingOrder; } set { m_renderer.sortingOrder = value; } } /// <summary> /// Determines if the size of the text container will be adjusted to fit the text object when it is first created. /// </summary> public override bool autoSizeTextContainer { get { return m_autoSizeTextContainer; } set { if (m_autoSizeTextContainer == value) return; m_autoSizeTextContainer = value; if (m_autoSizeTextContainer) { TMP_UpdateManager.RegisterTextElementForLayoutRebuild(this); SetLayoutDirty(); } } } private bool m_autoSizeTextContainer; /// <summary> /// Returns a reference to the Text Container /// </summary> public TextContainer textContainer { get { if (m_textContainer == null) m_textContainer = GetComponent<TextContainer>(); return m_textContainer; } } /// <summary> /// Returns a reference to the Transform /// </summary> public new Transform transform { get { if (m_transform == null) m_transform = GetComponent<Transform>(); return m_transform; } } #pragma warning disable 0108 /// <summary> /// Returns the rendered assigned to the text object. /// </summary> public Renderer renderer { get { if (m_renderer == null) m_renderer = GetComponent<Renderer>(); return m_renderer; } } /// <summary> /// Returns the mesh assigned to the text object. /// </summary> public override Mesh mesh { get { if (m_mesh == null) { m_mesh = new Mesh(); m_mesh.hideFlags = HideFlags.HideAndDontSave; this.meshFilter.mesh = m_mesh; } return m_mesh; } } /// <summary> /// Returns the Mesh Filter of the text object. /// </summary> public MeshFilter meshFilter { get { if (m_meshFilter == null) m_meshFilter = GetComponent<MeshFilter>(); return m_meshFilter; } } // MASKING RELATED PROPERTIES /// <summary> /// Sets the mask type /// </summary> public MaskingTypes maskType { get { return m_maskType; } set { m_maskType = value; SetMask(m_maskType); } } /// <summary> /// Function used to set the mask type and coordinates in World Space /// </summary> /// <param name="type"></param> /// <param name="maskCoords"></param> public void SetMask(MaskingTypes type, Vector4 maskCoords) { SetMask(type); SetMaskCoordinates(maskCoords); } /// <summary> /// Function used to set the mask type, coordinates and softness /// </summary> /// <param name="type"></param> /// <param name="maskCoords"></param> /// <param name="softnessX"></param> /// <param name="softnessY"></param> public void SetMask(MaskingTypes type, Vector4 maskCoords, float softnessX, float softnessY) { SetMask(type); SetMaskCoordinates(maskCoords, softnessX, softnessY); } /// <summary> /// Schedule rebuilding of the text geometry. /// </summary> public override void SetVerticesDirty() { //Debug.Log("SetVerticesDirty()"); if (m_verticesAlreadyDirty || this == null || !this.IsActive()) return; TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this); m_verticesAlreadyDirty = true; } /// <summary> /// /// </summary> public override void SetLayoutDirty() { if (m_layoutAlreadyDirty || this == null || !this.IsActive()) return; //TMP_UpdateManager.RegisterTextElementForLayoutRebuild(this); m_layoutAlreadyDirty = true; //LayoutRebuilder.MarkLayoutForRebuild(this.rectTransform); m_isLayoutDirty = true; } /// <summary> /// Schedule updating of the material used by the text object. /// </summary> public override void SetMaterialDirty() { //Debug.Log("SetMaterialDirty()"); //if (!this.IsActive()) // return; //m_isMaterialDirty = true; UpdateMaterial(); //TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this); } /// <summary> /// /// </summary> public override void SetAllDirty() { SetLayoutDirty(); SetVerticesDirty(); SetMaterialDirty(); } /// <summary> /// /// </summary> /// <param name="update"></param> public override void Rebuild(CanvasUpdate update) { if (this == null) return; if (update == CanvasUpdate.Prelayout) { if (m_autoSizeTextContainer) { CalculateLayoutInputHorizontal(); if (m_textContainer.isDefaultWidth) { m_textContainer.width = m_preferredWidth; } CalculateLayoutInputVertical(); if (m_textContainer.isDefaultHeight) { m_textContainer.height = m_preferredHeight; } } } else if (update == CanvasUpdate.PreRender) { this.OnPreRenderObject(); m_verticesAlreadyDirty = false; m_layoutAlreadyDirty = false; if (!m_isMaterialDirty) return; UpdateMaterial(); m_isMaterialDirty = false; } } /// <summary> /// /// </summary> protected override void UpdateMaterial() { //Debug.Log("*** UpdateMaterial() ***"); //if (!this.IsActive()) // return; if (m_renderer == null) m_renderer = this.renderer; m_renderer.sharedMaterial = m_sharedMaterial; } /// <summary> /// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script. /// </summary> public override void UpdateMeshPadding() { m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold); m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial); m_havePropertiesChanged = true; checkPaddingRequired = false; // Update sub text objects for (int i = 1; i < m_textInfo.materialCount; i++) m_subTextObjects[i].UpdateMeshPadding(m_enableExtraPadding, m_isUsingBold); } /// <summary> /// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately. /// </summary> public override void ForceMeshUpdate() { //Debug.Log("ForceMeshUpdate() called."); m_havePropertiesChanged = true; OnPreRenderObject(); } /// <summary> /// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately. /// </summary> /// <param name="ignoreInactive">If set to true, the text object will be regenerated regardless of is active state.</param> public override void ForceMeshUpdate(bool ignoreInactive) { m_havePropertiesChanged = true; m_ignoreActiveState = true; OnPreRenderObject(); } /// <summary> /// Function used to evaluate the length of a text string. /// </summary> /// <param name="text"></param> /// <returns></returns> public override TMP_TextInfo GetTextInfo(string text) { StringToCharArray(text, ref m_char_buffer); SetArraySizes(m_char_buffer); m_renderMode = TextRenderFlags.DontRender; ComputeMarginSize(); GenerateTextMesh(); m_renderMode = TextRenderFlags.Render; return this.textInfo; } /// <summary> /// Function to force the regeneration of the text object. /// </summary> /// <param name="flags"> Flags to control which portions of the geometry gets uploaded.</param> //public override void ForceMeshUpdate(TMP_VertexDataUpdateFlags flags) { } /// <summary> /// Function to update the geometry of the main and sub text objects. /// </summary> /// <param name="mesh"></param> /// <param name="index"></param> public override void UpdateGeometry(Mesh mesh, int index) { mesh.RecalculateBounds(); } /// <summary> /// Function to upload the updated vertex data and renderer. /// </summary> public override void UpdateVertexData(TMP_VertexDataUpdateFlags flags) { int materialCount = m_textInfo.materialCount; for (int i = 0; i < materialCount; i++) { Mesh mesh; if (i == 0) mesh = m_mesh; else mesh = m_subTextObjects[i].mesh; //mesh.MarkDynamic(); if ((flags & TMP_VertexDataUpdateFlags.Vertices) == TMP_VertexDataUpdateFlags.Vertices) mesh.vertices = m_textInfo.meshInfo[i].vertices; if ((flags & TMP_VertexDataUpdateFlags.Uv0) == TMP_VertexDataUpdateFlags.Uv0) mesh.uv = m_textInfo.meshInfo[i].uvs0; if ((flags & TMP_VertexDataUpdateFlags.Uv2) == TMP_VertexDataUpdateFlags.Uv2) mesh.uv2 = m_textInfo.meshInfo[i].uvs2; //if ((flags & TMP_VertexDataUpdateFlags.Uv4) == TMP_VertexDataUpdateFlags.Uv4) // mesh.uv4 = m_textInfo.meshInfo[i].uvs4; if ((flags & TMP_VertexDataUpdateFlags.Colors32) == TMP_VertexDataUpdateFlags.Colors32) mesh.colors32 = m_textInfo.meshInfo[i].colors32; mesh.RecalculateBounds(); } } /// <summary> /// Function to upload the updated vertex data and renderer. /// </summary> public override void UpdateVertexData() { int materialCount = m_textInfo.materialCount; for (int i = 0; i < materialCount; i++) { Mesh mesh; if (i == 0) mesh = m_mesh; else mesh = m_subTextObjects[i].mesh; //mesh.MarkDynamic(); mesh.vertices = m_textInfo.meshInfo[i].vertices; mesh.uv = m_textInfo.meshInfo[i].uvs0; mesh.uv2 = m_textInfo.meshInfo[i].uvs2; //mesh.uv4 = m_textInfo.meshInfo[i].uvs4; mesh.colors32 = m_textInfo.meshInfo[i].colors32; mesh.RecalculateBounds(); } } public void UpdateFontAsset() { LoadFontAsset(); } private bool m_currentAutoSizeMode; public void CalculateLayoutInputHorizontal() { //Debug.Log("*** CalculateLayoutInputHorizontal() ***"); if (!this.gameObject.activeInHierarchy) return; //IsRectTransformDriven = true; m_currentAutoSizeMode = m_enableAutoSizing; if (m_isCalculateSizeRequired || m_rectTransform.hasChanged) { //Debug.Log("Calculating Layout Horizontal"); //m_LayoutPhase = AutoLayoutPhase.Horizontal; //m_isRebuildingLayout = true; m_minWidth = 0; m_flexibleWidth = 0; //m_renderMode = TextRenderFlags.GetPreferredSizes; // Set Text to not Render and exit early once we have new width values. if (m_enableAutoSizing) { m_fontSize = m_fontSizeMax; } // Set Margins to Infinity m_marginWidth = k_LargePositiveFloat; m_marginHeight = k_LargePositiveFloat; if (m_isInputParsingRequired || m_isTextTruncated) ParseInputText(); GenerateTextMesh(); m_renderMode = TextRenderFlags.Render; //m_preferredWidth = (int)m_preferredWidth + 1f; ComputeMarginSize(); //Debug.Log("Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect); m_isLayoutDirty = true; } } public void CalculateLayoutInputVertical() { //Debug.Log("*** CalculateLayoutInputVertical() ***"); // Check if object is active if (!this.gameObject.activeInHierarchy) // || IsRectTransformDriven == false) return; //IsRectTransformDriven = true; if (m_isCalculateSizeRequired || m_rectTransform.hasChanged) { //Debug.Log("Calculating Layout InputVertical"); //m_LayoutPhase = AutoLayoutPhase.Vertical; //m_isRebuildingLayout = true; m_minHeight = 0; m_flexibleHeight = 0; //m_renderMode = TextRenderFlags.GetPreferredSizes; if (m_enableAutoSizing) { m_currentAutoSizeMode = true; m_enableAutoSizing = false; } m_marginHeight = k_LargePositiveFloat; GenerateTextMesh(); m_enableAutoSizing = m_currentAutoSizeMode; m_renderMode = TextRenderFlags.Render; //m_preferredHeight = (int)m_preferredHeight + 1f; ComputeMarginSize(); //Debug.Log("Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect); m_isLayoutDirty = true; } m_isCalculateSizeRequired = false; } } }
#region Namespaces using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Data.OleDb; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; #endregion namespace Epi.Data.Office.Forms { /// <summary> /// Connection string dialog for a database that already exists /// </summary> public partial class Access2007ExistingFileDialog : System.Windows.Forms.Form, IConnectionStringGui { private bool shouldIgnoreNonExistance; #region Constructors /// <summary> /// Constructor /// </summary> public Access2007ExistingFileDialog() { InitializeComponent(); } #endregion #region Protected Methods /// <summary> /// Ok click for UI inheritance /// </summary> protected void OnOkClick() { if (!shouldIgnoreNonExistance) { if (!File.Exists(this.txtFileName.Text)) { MessageBox.Show("Invalid file name."); return; } } //this.connectionString = AccessDatabase.BuildConnectionString(this.txtFileName.Text, this.txtPassword.Text); //this.dbConnectionStringBuilder.FileName = this.txtFileName.Text; if (this.txtFileName.Text.EndsWith(".accdb", true, System.Globalization.CultureInfo.InvariantCulture)) { this.dbConnectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0"; } this.dbConnectionStringBuilder.DataSource = this.txtFileName.Text; if (this.UsesPassword) { this.dbConnectionStringBuilder.ConnectionString = this.dbConnectionStringBuilder.ConnectionString + ";Jet OLEDB:Database Password=" + this.txtPassword.Text; } this.DialogResult = DialogResult.OK; this.Close(); } /// <summary> /// Occurs when the file name has changed /// </summary> protected virtual void OnFileNameChanged() { btnOK.Enabled = !string.IsNullOrEmpty(txtFileName.Text); } /// <summary> /// Occurs when the Cancel button is clicked /// </summary> protected virtual void OnCancelClick() { this.dbConnectionStringBuilder.ConnectionString = string.Empty; this.DialogResult = DialogResult.Cancel; this.Close(); } /// <summary> /// Occurs when the Browse button is clicked /// </summary> protected virtual void OnBrowseClick() { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Microsoft Access 2007 Files (*.accdb)|*.accdb"; if (shouldIgnoreNonExistance) { dialog.CheckFileExists = false; } DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { txtFileName.Text = dialog.FileName; } } #endregion #region IConnectionStringBuilder public virtual void SetDatabaseName(string databaseName) { } public virtual void SetServerName(string serverName) { } public virtual void SetUserName(string userName) { } public virtual void SetPassword(string password) { } /// <summary> /// Gets the connection string's description /// </summary> public string ConnectionStringDescription { get { return "MS Access File: " + txtFileName.Text; } } public bool ShouldIgnoreNonExistance { set { this.shouldIgnoreNonExistance = value; } } private OleDbConnectionStringBuilder dbConnectionStringBuilder = new OleDbConnectionStringBuilder(); /// <summary> /// Gets or sets the DbConnectionStringBuilder object /// </summary> public DbConnectionStringBuilder DbConnectionStringBuilder { get { return dbConnectionStringBuilder; } set { dbConnectionStringBuilder = (OleDbConnectionStringBuilder)value; } } /// <summary> /// Sets the preferred database name /// </summary> public string PreferredDatabaseName { get { return dbConnectionStringBuilder.DataSource; } } /// <summary> /// Gets whether or not the user entered a password /// </summary> public bool UsesPassword { get { if (this.txtPassword.Text.Length > 0) { return true; } else { return false; } } } #endregion #region Event Handlers private void btnOK_Click(object sender, EventArgs e) { this.OnOkClick(); } private void btnCancel_Click(object sender, EventArgs e) { this.OnCancelClick(); } private void txtFileName_TextChanged(object sender, EventArgs e) { this.OnFileNameChanged(); } private void btnBrowse_Click(object sender, EventArgs e) { this.OnBrowseClick(); } #endregion } }
using System; using UnityEngine; using System.Collections; /// <summary> /// /// Implements an RTS-style camera. /// /// For KEYBOARD control, also add "Components/Camera-Control/RtsCamera-Keyboard" (RtsCameraKeys.cs) /// For MOUSE control, also add "Components/Camera-Control/RtsCamera-Mouse" (RtsCameraMouse.cs) /// /// </summary> [AddComponentMenu("Camera-Control/RtsCamera")] [RequireComponent(typeof(RtsCameraMouse))] [RequireComponent(typeof(RtsCameraKeys))] public class RtsCamera : MonoBehaviour { #region NOTES /* * ---------------------------------------------- * Options for height calculation: * * 1) Set GetTerrainHeight function (from another script) to provide x/z height lookup: * * _rtsCamera.GetTerrainHeight = MyGetTerrainHeightFunction; * ... * private float MyGetTerrainHeightFunction(float x, float z) * { * return ...; * } * * 2) Set "TerrainHeightViaPhysics = true;" * * 3) For a "simple plain" style terrain (flat), set "LookAtHeightOffset" to base terrain height * * See demo code for examples. * * ---------------------------------------------- * To "Auto Follow" a target: * * _rtsCamera.Follow(myGameObjectOrTransform) * * See demo code for examples. * * ---------------------------------------------- * To be notified when Auto-Follow target changes (or is cleared): * * _rtsCamera.OnBeginFollow = MyBeginFollowCallback; * _rtsCamera.OnEndFollow = MyEndFollowCallback; * * void OnBeginFollow(Transform followTransform) { ... } * void OnEndFollow(Transform followTransform) { ... } * * See demo code for examples. * * ---------------------------------------------- * To force the camera to follow "behind" (with optional degree offset): * * _rtsCamera.FollowBehind = true; * _rtsCamera.FollowRotationOffset = 90; // optional * * See demo code for examples. * * ---------------------------------------------- * For target visibility checking via Physics: * * _rtsCamera.TargetVisbilityViaPhysics = true; * _rtsCamera.TargetVisibilityIgnoreLayerMask = {your layer masks that should block camera}; * * See demo code for examples. * */ #endregion public Vector3 LookAt; // Desired lookat position public float Distance; // Desired distance (units, ie Meters) public float Rotation; // Desired rotation (degrees) public float Tilt; // Desired tilt (degrees) public bool Smoothing; // Should the camera "slide" between positions and targets? public float MoveDampening; // How "smooth" should the camera moves be? Note: Smaller numbers are smoother public float ZoomDampening; // How "smooth" should the camera zooms be? Note: Smaller numbers are smoother public float RotationDampening; // How "smooth" should the camera rotations be? Note: Smaller numbers are smoother public float TiltDampening; // How "smooth" should the camera tilts be? Note: Smaller numbers are smoother public Vector3 MinBounds; // Minimum x,y,z world position for camera target public Vector3 MaxBounds; // Maximum x,y,z world position for camera target public float MinDistance; // Minimum distance of camera from target public float MaxDistance; // Maximum distance of camera from target public float MinTilt; // Minimum tilt (degrees) public float MaxTilt; // Maximum tilt (degrees) public Func<float, float, float> GetTerrainHeight; // Function taking x,z position and returning height (y). public bool TerrainHeightViaPhysics; // If set, camera will automatically raycast against terrain (using TerrainPhysicsLayerMask) to determine height public LayerMask TerrainPhysicsLayerMask; // Layer mask indicating which layers the camera should ray cast against for height detection public float LookAtHeightOffset; // Y coordinate of camera target. Only used if TerrainHeightViaPhysics and GetTerrainHeight are not set. public bool TargetVisbilityViaPhysics; // If set, camera will raycast from target out in order to avoid objects being between target and camera public LayerMask TargetVisibilityIgnoreLayerMask; // Layer mask to ignore when raycasting to determine camera visbility public bool FollowBehind; // If set, keyboard and mouse rotation will be disabled when Following a target public float FollowRotationOffset; // Offset (degrees from zero) when forcing follow behind target public Action<Transform> OnBeginFollow; // "Callback" for when automatic target following begins public Action<Transform> OnEndFollow; // "Callback" for when automatic target following ends public bool ShowDebugCameraTarget; // If set, "small green sphere" will be shown indicating camera target position (even when Following) // // PRIVATE VARIABLES // private Vector3 _initialLookAt; private float _initialDistance; private float _initialRotation; private float _initialTilt; private float _currDistance; // actual distance private float _currRotation; // actual rotation private float _currTilt; // actual tilt private Vector3 _moveVector; private GameObject _target; private MeshRenderer _targetRenderer; private Transform _followTarget; private bool _lastDebugCamera = false; // // Unity METHODS // #region UNITY_METHODS protected void Reset() { Smoothing = true; LookAtHeightOffset = 0f; TerrainHeightViaPhysics = false; TerrainPhysicsLayerMask = ~0; // "Everything" by default! GetTerrainHeight = null; TargetVisbilityViaPhysics = false; TargetVisibilityIgnoreLayerMask = 0; // "Nothing" by default! LookAt = new Vector3(0, -180, 0); MoveDampening = 5f; MinBounds = new Vector3(-100, -100, -100); MaxBounds = new Vector3(100, 100, 100); Distance = 16f; MinDistance = 8f; MaxDistance = 32f; ZoomDampening = 5f; Rotation = 0f; RotationDampening = 5f; Tilt = 45f; MinTilt = 30f; MaxTilt = 85f; TiltDampening = 5f; FollowBehind = false; FollowRotationOffset = 0; } protected void Start() { if (rigidbody) { // don't allow camera to rotate rigidbody.freezeRotation = true; } // // store initial values so that we can reset them using ResetToInitialValues method // _initialLookAt = LookAt; _initialDistance = Distance; _initialRotation = Rotation; _initialTilt = Tilt; // // set our current values to the desired values so that we don't "slide in" // _currDistance = Distance; _currRotation = Rotation; _currTilt = Tilt; // // create a target sphere, hidden by default // CreateTarget(); } protected void Update() { // // show or hide camera target (mainly for debugging purposes) // if (_lastDebugCamera != ShowDebugCameraTarget) { if (_targetRenderer != null) { _targetRenderer.enabled = ShowDebugCameraTarget; _lastDebugCamera = ShowDebugCameraTarget; } } } protected void LateUpdate() { // // update desired target position // if (IsFollowing) { LookAt = _followTarget.position; } else { _moveVector.y = 0; LookAt += Quaternion.Euler(0, Rotation, 0) * _moveVector; LookAt.y = GetHeightAt(LookAt.x, LookAt.z); } LookAt.y += LookAtHeightOffset; // // clamp values // Tilt = Mathf.Clamp(Tilt, MinTilt, MaxTilt); Distance = Mathf.Clamp(Distance, MinDistance, MaxDistance); LookAt = new Vector3(Mathf.Clamp(LookAt.x, MinBounds.x, MaxBounds.x), Mathf.Clamp(LookAt.y, MinBounds.y, MaxBounds.y), Mathf.Clamp(LookAt.z, MinBounds.z, MaxBounds.z)); // // move from "desired" to "target" values // if (Smoothing) { _currRotation = Mathf.LerpAngle(_currRotation, Rotation, Time.deltaTime * RotationDampening); _currDistance = Mathf.Lerp(_currDistance, Distance, Time.deltaTime * ZoomDampening); _currTilt = Mathf.LerpAngle(_currTilt, Tilt, Time.deltaTime * TiltDampening); _target.transform.position = Vector3.Lerp(_target.transform.position, LookAt, Time.deltaTime * MoveDampening); } else { _currRotation = Rotation; _currDistance = Distance; _currTilt = Tilt; _target.transform.position = LookAt; } _moveVector = Vector3.zero; // // if we're following AND forcing behind, override the rotation to point to target (with offset) // if (IsFollowing && FollowBehind) { ForceFollowBehind(); } // // optionally, we'll check to make sure the target is visible // Note: we only do this when following so that we don't "jar" when moving manually // if (IsFollowing && TargetVisbilityViaPhysics && DistanceToTargetIsLessThan(1f)) { EnsureTargetIsVisible(); } // // recalculate the actual position of the camera based on the above // UpdateCamera(); } #endregion // // PUBLIC METHODS // #region PUBLIC_METHODS /// <summary> /// Current transform of camera target (NOTE: should not be set directly) /// </summary> public Transform CameraTarget { get { return _target.transform; } } /// <summary> /// True if the current camera auto-follow target is set. Else, false. /// </summary> public bool IsFollowing { get { return FollowTarget != null; } } /// <summary> /// Current auto-follow target /// </summary> public Transform FollowTarget { get { return _followTarget; } } /// <summary> /// Reset camera to initial (startup) position, distance, rotation, tilt, etc. /// </summary> /// <param name="includePosition">If true, position will be reset as well. If false, only distance/rotation/tilt.</param> /// <param name="snap">If true, camera will snap instantly to the position. If false, camera will slide smoothly back to initial values.</param> public void ResetToInitialValues(bool includePosition, bool snap = false) { if (includePosition) LookAt = _initialLookAt; Distance = _initialDistance; Rotation = _initialRotation; Tilt = _initialTilt; if (snap) { _currDistance = Distance; _currRotation = Rotation; _currTilt = Tilt; _target.transform.position = LookAt; } } /// <summary> /// Manually set target position (snap or slide). /// </summary> /// <param name="toPosition">Vector3 position</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void JumpTo(Vector3 toPosition, bool snap = false) { EndFollow(); LookAt = toPosition; if (snap) { _target.transform.position = toPosition; } } /// <summary> /// Manually set target position (snap or slide). /// </summary> /// <param name="toTransform">Transform to which the camera target will be moved</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void JumpTo(Transform toTransform, bool snap = false) { JumpTo(toTransform.position, snap); } /// <summary> /// Manually set target position (snap or slide). /// </summary> /// <param name="toGameObject">GameObject to which the camera target will be moved</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void JumpTo(GameObject toGameObject, bool snap = false) { JumpTo(toGameObject.transform.position, snap); } /// <summary> /// Set current auto-follow target (snap or slide). /// </summary> /// <param name="followTarget">Transform which the camera should follow</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void Follow(Transform followTarget, bool snap = false) { if (_followTarget != null) { if (OnEndFollow != null) { OnEndFollow(_followTarget); } } _followTarget = followTarget; if (_followTarget != null) { if (snap) { LookAt = _followTarget.position; } if (OnBeginFollow != null) { OnBeginFollow(_followTarget); } } } /// <summary> /// Set current auto-follow target (snap or slide). /// </summary> /// <param name="followTarget">GameObject which the camera should follow</param> /// <param name="snap">If true, camera will "snap" to the position, else will "slide"</param> public void Follow(GameObject followTarget, bool snap = false) { Follow(followTarget.transform); } /// <summary> /// Break auto-follow. Camera will now be manually controlled by player input. /// </summary> public void EndFollow() { Follow((Transform)null, false); } /// <summary> /// Adds movement to the camera (world coordinates). /// </summary> /// <param name="dx">World coordinate X distance to move</param> /// <param name="dy">World coordinate Y distance to move</param> /// <param name="dz">World coordinate Z distance to move</param> public void AddToPosition(float dx, float dy, float dz) { _moveVector += new Vector3(dx, dy, dz); } #endregion // // PRIVATE METHODS // #region PRIVATE_METHODS /// <summary> /// If "GetTerrainHeight" function set, will call to obtain desired camera height (y position). /// Else, if TerrainHeightViaPhysics is true, will use Physics.RayCast to determine camera height. /// Else, will assume flat terrain and will return "0" (which will later be offset by LookAtHeightOffset) /// </summary> /// <param name="x"></param> /// <param name="z"></param> /// <returns></returns> private float GetHeightAt(float x, float z) { // // priority 1: use supplied function to get height at point // if (GetTerrainHeight != null) { return GetTerrainHeight(x, z); } // // priority 2: use physics ray casting to get height at point // if (TerrainHeightViaPhysics) { var y = MaxBounds.y; var maxDist = MaxBounds.y - MinBounds.y + 1f; RaycastHit hitInfo; if (Physics.Raycast(new Vector3(x, y, z), new Vector3(0, -1, 0), out hitInfo, maxDist, TerrainPhysicsLayerMask)) { return hitInfo.point.y; } return 0; // no hit! } // // assume flat terrain // return 0; } /// <summary> /// Update the camera position and rotation based on calculated values /// </summary> private void UpdateCamera() { var rotation = Quaternion.Euler(_currTilt, _currRotation, 0); var v = new Vector3(0.0f, 0.0f, -_currDistance); var position = rotation * v + _target.transform.position; if (camera.orthographic) { camera.orthographicSize = _currDistance; } // update position and rotation of camera transform.rotation = rotation; transform.position = position; } /// <summary> /// Creates the camera's target, initially not visible. /// </summary> private void CreateTarget() { _target = GameObject.CreatePrimitive(PrimitiveType.Sphere); _target.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); _target.renderer.material.color = Color.green; var targetCollider = _target.GetComponent<Collider>(); if (targetCollider != null) { targetCollider.enabled = false; } _targetRenderer = _target.GetComponent<MeshRenderer>(); _targetRenderer.enabled = false; _target.name = "CameraTarget"; _target.transform.position = LookAt; } private bool DistanceToTargetIsLessThan(float sqrDistance) { if (!IsFollowing) return true; // our distance is technically zero var p1 = _target.transform.position; var p2 = _followTarget.position; p1.y = p2.y = 0; // ignore height offset var v = p1 - p2; var vd = v.sqrMagnitude; // use sqr for performance return vd < sqrDistance; } private void EnsureTargetIsVisible() { var direction = (transform.position - _target.transform.position); direction.Normalize(); var distance = Distance; RaycastHit hitInfo; if (Physics.Raycast(_target.transform.position, direction, out hitInfo, distance, ~TargetVisibilityIgnoreLayerMask)) { if (hitInfo.transform != _target) // don't collide with outself! { _currDistance = hitInfo.distance - 0.1f; } } } private void ForceFollowBehind() { var v = _followTarget.transform.forward * -1; var angle = Vector3.Angle(Vector3.forward, v); var sign = (Vector3.Dot(v, Vector3.right) > 0.0f) ? 1.0f : -1.0f; _currRotation = Rotation = 180f + (sign * angle) + FollowRotationOffset; } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.CompilerServices; using System.IO; using System.Text; using Xunit; public class File_Exists_str { public static String s_strDtTmVer = "2009/02/18"; public static String s_strClassMethod = "File.Exists(String)"; public static String s_strTFName = "FileExists_str.cs"; public static String s_strTFPath = Directory.GetCurrentDirectory(); [Fact] public static void runTest() { int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { String filName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName()); if (File.Exists(filName)) File.Delete(filName); // [] Exception for null argument strLoc = "Loc_t987b"; iCountTestcases++; try { if (File.Exists(null)) { iCountErrors++; printerr("Error_49939! Expected exception not thrown"); } } catch (ArgumentNullException) { } catch (Exception exc) { iCountErrors++; printerr("Error_6019b! Incorrect exception thrown, exc==" + exc.ToString()); } // [] ArgumentException for empty path strLoc = "Loc_199gb"; iCountTestcases++; try { if (File.Exists(String.Empty)) { iCountErrors++; printerr("Error_109tg! Expected exception not thrown"); } if (File.Exists("\0")) { iCountErrors++; printerr("Error_123af! Expected exception not thrown"); } } catch (Exception exc) { iCountErrors++; printerr("Error_6t69b! Incorrect exception thrown, exc==" + exc.ToString()); } // [] Current Directory strLoc = "Loc_276t8"; iCountTestcases++; if (File.Exists(".")) { iCountErrors++; printerr("Error_95428! Incorrect return value"); } iCountTestcases++; if (File.Exists(Directory.GetCurrentDirectory())) { iCountErrors++; printerr("Error_97t67! Incorrect return value"); } // [] Parent Directory strLoc = "Loc_y7t03"; iCountTestcases++; if (File.Exists("..")) { iCountErrors++; printerr("Error_290bb! Incorrect return value"); } /* Scenario disabled when porting because it modifies global process state and can not be run in parallel with other tests #if !TEST_WINRT // SetCurrentDirectory is not allowed in AppX String tmpDir = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory("C:\\"); iCountTestcases++; if (File.Exists("..")) { iCountErrors++; printerr("Error_t987y! Incorrect return value"); } Directory.SetCurrentDirectory(tmpDir); #endif */ // network path scenario moved to RemoteIOTests.cs // [] Non-existent directories strLoc = "Loc_t993c"; iCountTestcases++; if (File.Exists("Da drar vi til fjells")) { iCountErrors++; printerr("Error_6895b! Incorrect return value"); } // [] Path too long strLoc = "Loc_t899t"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < IOInputs.MaxPath + 1; i++) sb.Append(i); iCountTestcases++; try { if (File.Exists(sb.ToString())) { iCountErrors++; printerr("Error_20937! Expected exception not thrown"); } } catch (PathTooLongException) { } catch (Exception exc) { iCountErrors++; printerr("Error_7159s! Incorrect exception thrown, exc==" + exc.ToString()); } // [] File that does exist strLoc = "Loc_2y78g"; string shortFilName = Path.GetFileName(filName); #if !TEST_WINRT // Current dir is not writable new FileStream(shortFilName, FileMode.Create).Dispose(); iCountTestcases++; if (!File.Exists(shortFilName)) { iCountErrors++; printerr("Error_9t821! Returned false for existing file"); } File.Delete(shortFilName); #endif string fullFilName = Path.Combine(TestInfo.CurrentDirectory, shortFilName); new FileStream(fullFilName, FileMode.Create).Dispose(); iCountTestcases++; if (!File.Exists(fullFilName)) { iCountErrors++; printerr("Error_9198v! Returned false for existing file"); } File.Delete(fullFilName); iCountTestcases++; if (File.Exists(fullFilName)) { iCountErrors++; printerr("Errro_197bb! Returned true for deleted file"); } // [] Filename with spaces strLoc = "Loc_298g7"; String tmp = filName + " " + Path.GetFileName(filName); new FileStream(tmp, FileMode.Create).Dispose(); iCountTestcases++; if (!File.Exists(tmp)) { iCountErrors++; printerr("Error_01y8v! Returned incorrect value"); } File.Delete(tmp); // [] Wildcards in filename should return false strLoc = "Loc_398vy8"; iCountTestcases++; try { if (File.Exists("*")) { iCountErrors++; printerr("Error_4979c! File with wildcard exist"); } } catch (Exception exc) { iCountErrors++; printerr("Error_498u9! Unexpected exception thrown, exc==" + exc.ToString()); } if (File.Exists(filName)) File.Delete(filName); } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics if (iCountErrors != 0) { Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString()); } Assert.Equal(0, iCountErrors); } public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err); } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace CommandLineProcessor { /// <summary> /// Utility function wrapping executing command lines. /// </summary> static class Processor { /// <summary> /// Convert the features of an ICommandLineTool to a command line. /// This may feature some prefixed commands. /// </summary> /// <param name="tool">The ICommandLine tool to convert.</param> /// <returns>Stringified version of the tool.</returns> public static string StringifyTool( Bam.Core.ICommandLineTool tool) { var linearized = new System.Text.StringBuilder(); linearized.Append(tool.Executable.ToStringQuoteIfNecessary()); if (tool.InitialArguments != null) { foreach (var arg in tool.InitialArguments) { linearized.Append($" {arg.ToString()}"); } } return linearized.ToString(); } /// <summary> /// Convert the terminating arguments of an ICommandLineTool to a string. /// </summary> /// <param name="tool">The ICommandLineTool to convert.</param> /// <returns>Stringified terminating arguments</returns> public static string TerminatingArgs( Bam.Core.ICommandLineTool tool) { var linearized = new System.Text.StringBuilder(); if (null != tool.TerminatingArguments) { foreach (var arg in tool.TerminatingArguments) { linearized.Append($" {arg.ToString()}"); } } return linearized.ToString(); } /// <summary> /// Execute an arbitrary executable with arguments. /// </summary> /// <param name="context">The context that the command is running in.</param> /// <param name="executablePath">Absolute path to the executable to run.</param> /// <param name="successfulExitCodes">Array of exit codes that the executable can return for success.</param> /// <param name="commandLineArguments">Array of arguments to pass to the executable.</param> public static void Execute( Bam.Core.ExecutionContext context, string executablePath, Bam.Core.Array<int> successfulExitCodes, Bam.Core.TokenizedStringArray commandLineArguments) { var arguments = new Bam.Core.StringArray(); foreach (var arg in commandLineArguments) { arguments.Add(arg.ToString()); } Execute(context, executablePath, successfulExitCodes, commandLineArguments: arguments); } /// <summary> /// Execute an arbitrary command line executable with arguments. /// </summary> /// <param name="context">The context that the command is running in.</param> /// <param name="executablePath">Absolute path to the executable to run.</param> /// <param name="successfulExitCodes">Array of exit codes that the executable can return for success.</param> /// <param name="commandLineArguments">Optional: Array of arguments to pass to the executable. Default to null.</param> /// <param name="workingDirectory">Optional: Working directory that the executable is run in. Default to null.</param> /// <param name="inheritedEnvironmentVariables">Optional: Array of environment variable keys to inherit from the parent environment. Default to null.</param> /// <param name="addedEnvironmentVariables">Optional: Dictionary of environment variable name=value to add to this executable's environment. Default to null.</param> /// <param name="useResponseFileOption">Optional: the switch for using response files, if all the arguments are to be written to this file first, and then used directly in the tool. Default to null.</param> public static void Execute( Bam.Core.ExecutionContext context, string executablePath, Bam.Core.Array<int> successfulExitCodes, Bam.Core.StringArray commandLineArguments = null, string workingDirectory = null, Bam.Core.StringArray inheritedEnvironmentVariables = null, System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray> addedEnvironmentVariables = null, string useResponseFileOption = null) { var processStartInfo = new System.Diagnostics.ProcessStartInfo(); processStartInfo.FileName = executablePath; processStartInfo.ErrorDialog = true; if (null != workingDirectory) { processStartInfo.WorkingDirectory = workingDirectory; } var cachedEnvVars = new System.Collections.Generic.Dictionary<string, string>(); // first get the inherited environment variables from the system environment if (null != inheritedEnvironmentVariables) { if (inheritedEnvironmentVariables.Count == 1 && inheritedEnvironmentVariables[0].Equals("*", System.StringComparison.Ordinal)) { foreach (System.Collections.DictionaryEntry envVar in processStartInfo.EnvironmentVariables) { cachedEnvVars.Add(envVar.Key as string, envVar.Value as string); } } else if (inheritedEnvironmentVariables.Count == 1 && System.Int32.TryParse(inheritedEnvironmentVariables[0], out int envVarCount) && envVarCount < 0) { envVarCount += processStartInfo.EnvironmentVariables.Count; foreach (var envVar in processStartInfo.EnvironmentVariables.Cast<System.Collections.DictionaryEntry>().OrderBy(item => item.Key)) { cachedEnvVars.Add(envVar.Key as string, envVar.Value as string); --envVarCount; if (0 == envVarCount) { break; } } } else { foreach (var envVar in inheritedEnvironmentVariables) { if (!processStartInfo.EnvironmentVariables.ContainsKey(envVar)) { Bam.Core.Log.Info($"Environment variable '{envVar}' does not exist"); continue; } cachedEnvVars.Add(envVar, processStartInfo.EnvironmentVariables[envVar]); } } } processStartInfo.EnvironmentVariables.Clear(); foreach (var envVar in cachedEnvVars) { processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value; } if (null != addedEnvironmentVariables) { foreach (var envVar in addedEnvironmentVariables) { processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value.ToString(System.IO.Path.PathSeparator); } } processStartInfo.UseShellExecute = false; // to redirect IO streams processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; processStartInfo.RedirectStandardInput = true; var arguments = commandLineArguments != null ? commandLineArguments.ToString(' ') : string.Empty; string responseFilePath = null; if (Bam.Core.OSUtilities.IsWindowsHosting) { //TODO: should this include the length of the executable path too? if (arguments.Length >= 32767) { if (null == useResponseFileOption) { throw new Bam.Core.Exception( $"Command line is {arguments.Length} characters long, but response files are not supported by the tool {executablePath}" ); } responseFilePath = Bam.Core.IOWrapper.CreateTemporaryFile(); using (System.IO.StreamWriter writer = new System.IO.StreamWriter(responseFilePath)) { Bam.Core.Log.DebugMessage($"Written response file {responseFilePath} containing:\n{arguments}"); // escape any back slashes writer.WriteLine(arguments.Replace(@"\", @"\\")); } arguments = $"{useResponseFileOption}{responseFilePath}"; } } processStartInfo.Arguments = arguments; Bam.Core.Log.Detail($"{processStartInfo.FileName} {processStartInfo.Arguments}"); // useful debugging of the command line processor Bam.Core.Log.DebugMessage($"Working directory: '{processStartInfo.WorkingDirectory}'"); if (processStartInfo.EnvironmentVariables.Count > 0) { Bam.Core.Log.DebugMessage("Environment variables:"); foreach (var envVar in processStartInfo.EnvironmentVariables.Cast<System.Collections.DictionaryEntry>().OrderBy(item => item.Key)) { Bam.Core.Log.DebugMessage($"\t{envVar.Key} = {envVar.Value}"); } } System.Diagnostics.Process process = null; int exitCode = -1; try { process = new System.Diagnostics.Process(); process.StartInfo = processStartInfo; process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(context.OutputDataReceived); process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(context.ErrorDataReceived); process.Start(); process.StandardInput.Close(); } catch (System.ComponentModel.Win32Exception ex) { throw new Bam.Core.Exception($"'{ex.Message}': process filename '{processStartInfo.FileName}'"); } if (null != process) { process.BeginOutputReadLine(); process.BeginErrorReadLine(); // TODO: need to poll for an external cancel op? // poll for the process to exit, as some processes seem to get stuck (hdiutil attach, for example) while (!process.HasExited) { process.WaitForExit(2000); } // this additional WaitForExit appears to be needed in order to finish reading the output and error streams asynchronously // without it, output is missing from a Native build when executed in many threads process.WaitForExit(); exitCode = process.ExitCode; //Bam.Core.Log.DebugMessage($"Tool exit code: {exitCode}"); process.Close(); } // delete once the process has finished, or never started if (null != responseFilePath) { System.IO.File.Delete(responseFilePath); } if (!successfulExitCodes.Contains(exitCode)) { var message = new System.Text.StringBuilder(); message.AppendLine($"Command failed: {processStartInfo.FileName} {processStartInfo.Arguments}"); if (null != responseFilePath) { message.AppendLine("Response file contained:"); message.AppendLine(arguments); } message.AppendLine($"Command exit code: {exitCode}"); throw new Bam.Core.Exception(message.ToString()); } } /// <summary> /// Execute an ICommandLineTool. /// </summary> /// <param name="module">Module that the command line tool is running for.</param> /// <param name="context">Context in which the command line tool is running.</param> /// <param name="tool">Tool to run.</param> /// <param name="commandLine">Single string of arguments to pass.</param> /// <param name="workingDirectory">Optional working directory in which to run the command line tool. Default to null.</param> public static void Execute( Bam.Core.Module module, Bam.Core.ExecutionContext context, Bam.Core.ICommandLineTool tool, Bam.Core.StringArray commandLine, string workingDirectory = null) { if (null == tool) { throw new Bam.Core.Exception( $"Command line tool passed with module '{module.ToString()}' is invalid" ); } var commandLineArgs = new Bam.Core.StringArray(); if (null != tool.InitialArguments) { foreach (var arg in tool.InitialArguments) { commandLineArgs.Add(arg.ToString()); } } commandLineArgs.AddRange(commandLine); if (null != tool.TerminatingArguments) { foreach (var arg in tool.TerminatingArguments) { commandLineArgs.Add(arg.ToString()); } } Execute( context, tool.Executable.ToString(), tool.SuccessfulExitCodes, commandLineArgs, workingDirectory: module.WorkingDirectory?.ToString(), inheritedEnvironmentVariables: tool.InheritedEnvironmentVariables, addedEnvironmentVariables: tool.EnvironmentVariables, useResponseFileOption: tool.UseResponseFileOption); } } }
/* * 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.Net; using System.Reflection; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Client; namespace OpenSim.Tests.Common.Mock { public class TestClient : IClientAPI, IClientCore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Mock testing variables public List<ImageDataPacket> sentdatapkt = new List<ImageDataPacket>(); public List<ImagePacketPacket> sentpktpkt = new List<ImagePacketPacket>(); EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing"); // TODO: This is a really nasty (and temporary) means of telling the test client which scene to invoke setup // methods on when a teleport is requested public Scene TeleportTargetScene; private TestClient TeleportSceneClient; private IScene m_scene; // disable warning: public events, part of the public API #pragma warning disable 67 public event Action<IClientAPI> OnLogout; public event ObjectPermissions OnObjectPermissions; public event MoneyTransferRequest OnMoneyTransferRequest; public event ParcelBuy OnParcelBuy; public event Action<IClientAPI> OnConnectionClosed; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event DeRezObject OnDeRezObject; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall1 OnRequestWearables; public event GenericCall1 OnCompleteMovementToRegion; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event ViewerEffectEventHandler OnViewerEffect; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event ObjectSelect OnObjectSelect; public event ObjectRequest OnObjectRequest; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event LinkInventoryItem OnLinkInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event GenericMessage OnGenericMessage; public event UUIDNameRequest OnNameFromUUIDRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event ObjectDeselect OnObjectDeselect; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event EstateChangeInfo OnEstateChangeInfo; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event GrantUserFriendRights OnGrantUserRights; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event AgentSit OnUndo; public event AgentSit OnRedo; public event LandUndo OnLandUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event UpdateVector OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; public event FindAgentUpdate OnFindAgent; public event TrackAgentUpdate OnTrackAgent; public event NewUserReport OnUserReport; public event SaveStateHandler OnSaveState; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest; public event FreezeUserUpdate OnParcelFreezeUser; public event EjectUserUpdate OnParcelEjectUser; public event ParcelBuyPass OnParcelBuyPass; public event ParcelGodMark OnParcelGodMark; public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event SimWideDeletesDelegate OnSimWideDeletes; public event SendPostcard OnSendPostcard; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event GodlikeMessage onGodlikeMessage; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate; #pragma warning restore 67 /// <value> /// This agent's UUID /// </value> private UUID m_agentId; /// <value> /// The last caps seed url that this client was given. /// </value> public string CapsSeedUrl; private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2); public virtual Vector3 StartPos { get { return startPos; } set { } } public virtual UUID AgentId { get { return m_agentId; } } public UUID SessionId { get { return UUID.Zero; } } public UUID SecureSessionId { get { return UUID.Zero; } } public virtual string FirstName { get { return m_firstName; } } private string m_firstName; public virtual string LastName { get { return m_lastName; } } private string m_lastName; public virtual String Name { get { return FirstName + " " + LastName; } } public bool IsActive { get { return true; } set { } } public bool IsLoggingOut { get { return false; } set { } } public UUID ActiveGroupId { get { return UUID.Zero; } } public string ActiveGroupName { get { return String.Empty; } } public ulong ActiveGroupPowers { get { return 0; } } public bool IsGroupMember(UUID groupID) { return false; } public ulong GetGroupPowers(UUID groupID) { return 0; } public virtual int NextAnimationSequenceNumber { get { return 1; } } public IScene Scene { get { return m_scene; } } public bool SendLogoutPacketWhenClosing { set { } } private uint m_circuitCode; public uint CircuitCode { get { return m_circuitCode; } set { m_circuitCode = value; } } public IPEndPoint RemoteEndPoint { get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); } } /// <summary> /// Constructor /// </summary> /// <param name="agentData"></param> /// <param name="scene"></param> public TestClient(AgentCircuitData agentData, IScene scene) { m_agentId = agentData.AgentID; m_firstName = agentData.firstname; m_lastName = agentData.lastname; m_circuitCode = agentData.circuitcode; m_scene = scene; CapsSeedUrl = agentData.CapsPath; } /// <summary> /// Attempt a teleport to the given region. /// </summary> /// <param name="regionHandle"></param> /// <param name="position"></param> /// <param name="lookAt"></param> public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt) { OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16); } public void CompleteMovement() { OnCompleteMovementToRegion(this); } public virtual void ActivateGesture(UUID assetId, UUID gestureId) { } public virtual void SendWearables(AvatarWearable[] wearables, int serial) { } public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public virtual void Kick(string message) { } public virtual void SendStartPingCheck(byte seq) { } public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public virtual void SendKillObject(ulong regionHandle, uint localID) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public virtual void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public virtual void SendChatMessage(byte[] message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public void SendInstantMessage(GridInstantMessage im) { } public void SendGenericMessage(string method, List<string> message) { } public void SendGenericMessage(string method, List<byte[]> message) { } public virtual void SendLayerData(float[] map) { } public virtual void SendLayerData(int px, int py, float[] map) { } public virtual void SendLayerData(int px, int py, float[] map, bool track) { } public virtual void SendWindData(Vector2[] windSpeeds) { } public virtual void SendCloudData(float[] cloudCover) { } public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public virtual AgentCircuitData RequestClientInfo() { AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = AgentId; agentData.SessionID = UUID.Zero; agentData.SecureSessionID = UUID.Zero; agentData.circuitcode = m_circuitCode; agentData.child = false; agentData.firstname = m_firstName; agentData.lastname = m_lastName; ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>(); if (capsModule != null) { agentData.CapsPath = capsModule.GetCapsPath(m_agentId); agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId)); } return agentData; } public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { m_log.DebugFormat("[TEST CLIENT]: Processing inform client of neighbour"); // In response to this message, we are going to make a teleport to the scene we've previous been told // about by test code (this needs to be improved). AgentCircuitData newAgent = RequestClientInfo(); // Stage 2: add the new client as a child agent to the scene TeleportSceneClient = new TestClient(newAgent, TeleportTargetScene); TeleportTargetScene.AddNewClient(TeleportSceneClient); } public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { m_log.DebugFormat("[TEST CLIENT]: Received SendRegionTeleport"); CapsSeedUrl = capsURL; TeleportSceneClient.CompleteMovement(); //TeleportTargetScene.AgentCrossing(newAgent.AgentID, new Vector3(90, 90, 90), false); } public virtual void SendTeleportFailed(string reason) { m_log.DebugFormat("[TEST CLIENT]: Teleport failed with reason {0}", reason); } public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { // This is supposed to send a packet to the client telling it's ready to start region crossing. // Instead I will just signal I'm ready, mimicking the communication behavior. // It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs. // Arthur V. wh.Set(); } public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public virtual void SendTeleportStart(uint flags) { } public void SendTeleportProgress(uint flags, string message) { } public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { } public virtual void SendPayPrice(UUID objectID, int[] payPrice) { } public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public void SendAvatarDataImmediate(ISceneEntity avatar) { } public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } public void ReprioritizeUpdates() { } public void FlushPrimUpdates() { } public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems) { } public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID) { } public virtual void SendRemoveInventoryItem(UUID itemID) { } public virtual void SendBulkUpdateInventory(InventoryNodeBase node) { } public UUID GetDefaultAnimation(string name) { return UUID.Zero; } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data) { } public virtual void SendAbortXferPacket(ulong xferID) { } public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public virtual void SendNameReply(UUID profileId, string firstname, string lastname) { } public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendAlertMessage(string message) { } public void SendAgentAlertMessage(string message, bool modal) { } public void SendSystemAlertMessage(string message) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { } public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(this); } } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { ImageDataPacket im = new ImageDataPacket(); im.Header.Reliable = false; im.ImageID.Packets = numParts; im.ImageID.ID = ImageUUID; if (ImageSize > 0) im.ImageID.Size = ImageSize; im.ImageData.Data = ImageData; im.ImageID.Codec = imageCodec; im.Header.Zerocoded = true; sentdatapkt.Add(im); } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { ImagePacketPacket im = new ImagePacketPacket(); im.Header.Reliable = false; im.ImageID.Packet = partNumber; im.ImageID.ID = imageUuid; im.ImageData.Data = imageData; sentpktpkt.Add(im); } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { } public void SendObjectPropertiesReply(ISceneEntity entity) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } public bool AddMoney(int debit) { return false; } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SetDebugPacketLevel(int newDebug) { } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close() { m_scene.RemoveClient(AgentId); } public void Start() { } public void Stop() { } public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message) { } public void SendLogoutPacket() { } public void Terminate() { } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { return null; } public void SetClientInfo(ClientInfo info) { } public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties (UUID objectID) { } public void SendRegionHandle (UUID regoinID, ulong handle) { } public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return string.Empty; } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void KillEndDone() { } public void SendEventInfoReply (EventData info) { } public void SendOfferCallingCard (UUID destID, UUID transactionID) { } public void SendAcceptCallingCard (UUID transactionID) { } public void SendDeclineCallingCard (UUID transactionID) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendTerminateFriend(UUID exFriendID) { } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { //throw new NotImplementedException(); return false; } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void RefreshGroupMembership() { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } public bool TryGet<T>(out T iface) { iface = default(T); return false; } public T Get<T>() { return default(T); } public void Disconnect(string reason) { } public void Disconnect() { } public void SendRebakeAvatarTextures(UUID textureID) { } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes) { } public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) { } public void SendChangeUserRights(UUID agentID, UUID friendID, int rights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) { } public void StopFlying(ISceneEntity presence) { } public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Iso9660 { using System; using System.Globalization; using System.IO; using System.Text; internal static class IsoUtilities { public const int SectorSize = 2048; public static uint ToUInt32FromBoth(byte[] data, int offset) { return Utilities.ToUInt32LittleEndian(data, offset); } public static ushort ToUInt16FromBoth(byte[] data, int offset) { return Utilities.ToUInt16LittleEndian(data, offset); } internal static void ToBothFromUInt32(byte[] buffer, int offset, uint value) { Utilities.WriteBytesLittleEndian(value, buffer, offset); Utilities.WriteBytesBigEndian(value, buffer, offset + 4); } internal static void ToBothFromUInt16(byte[] buffer, int offset, ushort value) { Utilities.WriteBytesLittleEndian(value, buffer, offset); Utilities.WriteBytesBigEndian(value, buffer, offset + 2); } internal static void ToBytesFromUInt32(byte[] buffer, int offset, uint value) { Utilities.WriteBytesLittleEndian(value, buffer, offset); } internal static void ToBytesFromUInt16(byte[] buffer, int offset, ushort value) { Utilities.WriteBytesLittleEndian(value, buffer, offset); } internal static void WriteAChars(byte[] buffer, int offset, int numBytes, string str) { // Validate string if (!IsValidAString(str)) { throw new IOException("Attempt to write string with invalid a-characters"); } ////WriteASCII(buffer, offset, numBytes, true, str); WriteString(buffer, offset, numBytes, true, str, Encoding.ASCII); } internal static void WriteDChars(byte[] buffer, int offset, int numBytes, string str) { // Validate string if (!IsValidDString(str)) { throw new IOException("Attempt to write string with invalid d-characters"); } ////WriteASCII(buffer, offset, numBytes, true, str); WriteString(buffer, offset, numBytes, true, str, Encoding.ASCII); } internal static void WriteA1Chars(byte[] buffer, int offset, int numBytes, string str, Encoding enc) { // Validate string if (!IsValidAString(str)) { throw new IOException("Attempt to write string with invalid a-characters"); } WriteString(buffer, offset, numBytes, true, str, enc); } internal static void WriteD1Chars(byte[] buffer, int offset, int numBytes, string str, Encoding enc) { // Validate string if (!IsValidDString(str)) { throw new IOException("Attempt to write string with invalid d-characters"); } WriteString(buffer, offset, numBytes, true, str, enc); } internal static string ReadChars(byte[] buffer, int offset, int numBytes, Encoding enc) { char[] chars; // Special handling for 'magic' names '\x00' and '\x01', which indicate root and parent, respectively if (numBytes == 1) { chars = new char[1]; chars[0] = (char)buffer[offset]; } else { Decoder decoder = enc.GetDecoder(); chars = new char[decoder.GetCharCount(buffer, offset, numBytes, false)]; decoder.GetChars(buffer, offset, numBytes, chars, 0, false); } return new string(chars).TrimEnd(' '); } #if false public static byte WriteFileName(byte[] buffer, int offset, int numBytes, string str, Encoding enc) { if (numBytes > 255 || numBytes < 0) { throw new ArgumentOutOfRangeException("numBytes", "Attempt to write overlength or underlength file name"); } // Validate string if (!isValidFileName(str)) { throw new IOException("Attempt to write string with invalid file name characters"); } return (byte)WriteString(buffer, offset, numBytes, false, str, enc); } public static byte WriteDirectoryName(byte[] buffer, int offset, int numBytes, string str, Encoding enc) { if (numBytes > 255 || numBytes < 0) { throw new ArgumentOutOfRangeException("numBytes", "Attempt to write overlength or underlength directory name"); } // Validate string if (!isValidDirectoryName(str)) { throw new IOException("Attempt to write string with invalid directory name characters"); } return (byte)WriteString(buffer, offset, numBytes, false, str, enc); } #endif internal static int WriteString(byte[] buffer, int offset, int numBytes, bool pad, string str, Encoding enc) { return WriteString(buffer, offset, numBytes, pad, str, enc, false); } internal static int WriteString(byte[] buffer, int offset, int numBytes, bool pad, string str, Encoding enc, bool canTruncate) { Encoder encoder = enc.GetEncoder(); string paddedString = pad ? str + new string(' ', numBytes) : str; // Assumption: never less than one byte per character int charsUsed; int bytesUsed; bool completed; encoder.Convert(paddedString.ToCharArray(), 0, paddedString.Length, buffer, offset, numBytes, false, out charsUsed, out bytesUsed, out completed); if (!canTruncate && charsUsed < str.Length) { throw new IOException("Failed to write entire string"); } return bytesUsed; } internal static bool IsValidAString(string str) { for (int i = 0; i < str.Length; ++i) { if (!( (str[i] >= ' ' && str[i] <= '\"') || (str[i] >= '%' && str[i] <= '/') || (str[i] >= ':' && str[i] <= '?') || (str[i] >= '0' && str[i] <= '9') || (str[i] >= 'A' && str[i] <= 'Z') || (str[i] == '_'))) { return false; } } return true; } internal static bool IsValidDString(string str) { for (int i = 0; i < str.Length; ++i) { if (!IsValidDChar(str[i])) { return false; } } return true; } internal static bool IsValidDChar(char ch) { return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch == '_'); } internal static bool IsValidFileName(string str) { for (int i = 0; i < str.Length; ++i) { if (!((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'A' && str[i] <= 'Z') || (str[i] == '_') || (str[i] == '.') || (str[i] == ';'))) { return false; } } return true; } internal static bool IsValidDirectoryName(string str) { if (str.Length == 1 && (str[0] == 0 || str[0] == 1)) { return true; } else { return IsValidDString(str); } } internal static string NormalizeFileName(string name) { string[] parts = SplitFileName(name); return parts[0] + '.' + parts[1] + ';' + parts[2]; } internal static string[] SplitFileName(string name) { string[] parts = new string[] { name, string.Empty, "1" }; if (name.Contains(".")) { int endOfFilePart = name.IndexOf('.'); parts[0] = name.Substring(0, endOfFilePart); if (name.Contains(";")) { int verSep = name.IndexOf(';', endOfFilePart + 1); parts[1] = name.Substring(endOfFilePart + 1, verSep - (endOfFilePart + 1)); parts[2] = name.Substring(verSep + 1); } else { parts[1] = name.Substring(endOfFilePart + 1); } } else { if (name.Contains(";")) { int verSep = name.IndexOf(';'); parts[0] = name.Substring(0, verSep); parts[2] = name.Substring(verSep + 1); } } ushort ver; if (!UInt16.TryParse(parts[2], out ver) || ver > 32767 || ver < 1) { ver = 1; } parts[2] = string.Format(CultureInfo.InvariantCulture, "{0}", ver); return parts; } /// <summary> /// Converts a DirectoryRecord time to UTC. /// </summary> /// <param name="data">Buffer containing the time data.</param> /// <param name="offset">Offset in buffer of the time data.</param> /// <returns>The time in UTC.</returns> internal static DateTime ToUTCDateTimeFromDirectoryTime(byte[] data, int offset) { try { DateTime relTime = new DateTime( 1900 + data[offset], data[offset + 1], data[offset + 2], data[offset + 3], data[offset + 4], data[offset + 5], DateTimeKind.Utc); return relTime - TimeSpan.FromMinutes(15 * (sbyte)data[offset + 6]); } catch (ArgumentOutOfRangeException) { // In case the ISO has a bad date encoded, we'll just fall back to using a fixed date return DateTime.MinValue; } } internal static void ToDirectoryTimeFromUTC(byte[] data, int offset, DateTime dateTime) { if (dateTime == DateTime.MinValue) { Array.Clear(data, offset, 7); } else { if (dateTime.Year < 1900) { throw new IOException("Year is out of range"); } data[offset] = (byte)(dateTime.Year - 1900); data[offset + 1] = (byte)dateTime.Month; data[offset + 2] = (byte)dateTime.Day; data[offset + 3] = (byte)dateTime.Hour; data[offset + 4] = (byte)dateTime.Minute; data[offset + 5] = (byte)dateTime.Second; data[offset + 6] = 0; } } internal static DateTime ToDateTimeFromVolumeDescriptorTime(byte[] data, int offset) { bool allNull = true; for (int i = 0; i < 16; ++i) { if (data[offset + i] != (byte)'0' && data[offset + i] != 0) { allNull = false; break; } } if (allNull) { return DateTime.MinValue; } string strForm = Encoding.ASCII.GetString(data, offset, 16); // Work around bugs in burning software that may use zero bytes (rather than '0' characters) strForm = strForm.Replace('\0', '0'); int year = SafeParseInt(1, 9999, strForm.Substring(0, 4)); int month = SafeParseInt(1, 12, strForm.Substring(4, 2)); int day = SafeParseInt(1, 31, strForm.Substring(6, 2)); int hour = SafeParseInt(0, 23, strForm.Substring(8, 2)); int min = SafeParseInt(0, 59, strForm.Substring(10, 2)); int sec = SafeParseInt(0, 59, strForm.Substring(12, 2)); int hundredths = SafeParseInt(0, 99, strForm.Substring(14, 2)); try { DateTime time = new DateTime(year, month, day, hour, min, sec, hundredths * 10, DateTimeKind.Utc); return time - TimeSpan.FromMinutes(15 * (sbyte)data[offset + 16]); } catch (ArgumentOutOfRangeException) { return DateTime.MinValue; } } internal static void ToVolumeDescriptorTimeFromUTC(byte[] buffer, int offset, DateTime dateTime) { if (dateTime == DateTime.MinValue) { for (int i = offset; i < offset + 16; ++i) { buffer[i] = (byte)'0'; } buffer[offset + 16] = 0; return; } string strForm = dateTime.ToString("yyyyMMddHHmmssff", CultureInfo.InvariantCulture); Utilities.StringToBytes(strForm, buffer, offset, 16); buffer[offset + 16] = 0; } internal static void EncodingToBytes(Encoding enc, byte[] data, int offset) { Array.Clear(data, offset, 32); if (enc == Encoding.ASCII) { // Nothing to do } else if (enc == Encoding.BigEndianUnicode) { data[offset + 0] = 0x25; data[offset + 1] = 0x2F; data[offset + 2] = 0x45; } else { throw new ArgumentException("Unrecognized character encoding"); } } internal static Encoding EncodingFromBytes(byte[] data, int offset) { Encoding enc = Encoding.ASCII; if (data[offset + 0] == 0x25 && data[offset + 1] == 0x2F && (data[offset + 2] == 0x40 || data[offset + 2] == 0x43 || data[offset + 2] == 0x45)) { // I.e. this is a joliet disc! enc = Encoding.BigEndianUnicode; } return enc; } internal static bool IsSpecialDirectory(DirectoryRecord r) { return r.FileIdentifier == "\0" || r.FileIdentifier == "\x01"; } private static int SafeParseInt(int minVal, int maxVal, string str) { int val; if (!int.TryParse(str, out val)) { return minVal; } if (val < minVal) { return minVal; } else if (val > maxVal) { return maxVal; } else { return val; } } } }
// 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; /// <summary> /// Sinh(System.Double) /// </summary> public class MathSinh { public static int Main(string[] args) { MathSinh test = new MathSinh(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Sinh(System.Double)."); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the result when radian is 0."); try { Double d = Math.Sinh(0); if (!MathTestLib.DoubleIsWithinEpsilon(d, 0)) { TestLibrary.TestFramework.LogError("P01.1", "The result is error when radian is 0!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the result when radian is Math.PI/2."); try { Double d = Math.Sinh(Math.PI / 2); if (!MathTestLib.DoubleIsWithinEpsilon(d ,2.3012989023072947)) { TestLibrary.TestFramework.LogError("P02.1", "The result is error when radian is Math.PI/2!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the result when radian is -Math.PI/2."); try { Double d = Math.Sinh(-Math.PI / 2); if (!MathTestLib.DoubleIsWithinEpsilon(d ,-2.3012989023072947)) { TestLibrary.TestFramework.LogError("P03.1", "The result is error when radian is -Math.PI/2!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the result when radian is Math.PI/6."); try { Double d = Math.Sinh(Math.PI / 6); if (!MathTestLib.DoubleIsWithinEpsilon(d,0.54785347388803973)) { TestLibrary.TestFramework.LogError("P04.1", "The result is error when radian is Math.PI/6!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the result when radian is -Math.PI/6."); try { Double d = Math.Sinh(-Math.PI / 6); if (!MathTestLib.DoubleIsWithinEpsilon(d ,-0.54785347388803973)) { TestLibrary.TestFramework.LogError("P05.1", "The result is error when radian is -Math.PI/6!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the result is PositiveInfinity when radian is PositiveInfinity."); try { Double d = Math.Sinh(Double.PositiveInfinity); if (d.CompareTo(Double.PositiveInfinity) != 0) { TestLibrary.TestFramework.LogError("P06.1", "The result is error when radian is PositiveInfinity!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the result is NegativeInfinity when radian is NegativeInfinity."); try { Double d = Math.Sinh(Double.NegativeInfinity); if (d.CompareTo(Double.NegativeInfinity) != 0) { TestLibrary.TestFramework.LogError("P07.1", "The result is error when radian is NegativeInfinity!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest8: Verify the result is NaN when radian is NaN."); try { Double d = Math.Sinh(Double.NaN); if (d.CompareTo(Double.NaN) != 0) { TestLibrary.TestFramework.LogError("P08.1", "The result is error when radian is NaN!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P08.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
// // IMailSpool.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2014 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using MimeKit; namespace MailKit { /// <summary> /// An interface for retreiving messages from a spool. /// </summary> /// <remarks> /// An interface for retreiving messages from a spool. /// </remarks> public interface IMailSpool : IMailService, IEnumerable<MimeMessage> { /// <summary> /// Get whether or not the service supports referencing messages by UIDs. /// </summary> /// <remarks> /// <para>Not all servers support referencing messages by UID, so this property should /// be checked before using <see cref="GetMessageUid(int, CancellationToken)"/> /// and <see cref="GetMessageUids(CancellationToken)"/>.</para> /// <para>If the server does not support UIDs, then all methods that take UID arguments /// along with <see cref="GetMessageUid(int, CancellationToken)"/> and /// <see cref="GetMessageUids(CancellationToken)"/> will fail.</para> /// </remarks> /// <value><c>true</c> if supports uids; otherwise, <c>false</c>.</value> bool SupportsUids { get; } /// <summary> /// Get the number of messages available in the message spool. /// </summary> /// <remarks> /// Gets the number of messages available in the message spool. /// </remarks> /// <returns>The number of available messages.</returns> /// <param name="cancellationToken">The cancellation token.</param> int GetMessageCount (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the number of messages available in the message spool. /// </summary> /// <remarks> /// Asynchronously gets the number of messages available in the message spool. /// </remarks> /// <returns>The number of available messages.</returns> /// <param name="cancellationToken">The cancellation token.</param> Task<int> GetMessageCountAsync (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the UID of the message at the specified index. /// </summary> /// <remarks> /// Not all servers support UIDs, so you should first check /// the <see cref="SupportsUids"/> property. /// </remarks> /// <returns>The message UID.</returns> /// <param name="index">The message index.</param> /// <param name="cancellationToken">The cancellation token.</param> string GetMessageUid (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the UID of the message at the specified index. /// </summary> /// <remarks> /// Not all servers support UIDs, so you should first check /// the <see cref="SupportsUids"/> property. /// </remarks> /// <returns>The message UID.</returns> /// <param name="index">The message index.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<string> GetMessageUidAsync (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the full list of available message UIDs. /// </summary> /// <remarks> /// Not all servers support UIDs, so you should first check /// the <see cref="SupportsUids"/> property. /// </remarks> /// <returns>The message UIDs.</returns> /// <param name="cancellationToken">The cancellation token.</param> IList<string> GetMessageUids (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the full list of available message UIDs. /// </summary> /// <remarks> /// Not all servers support UIDs, so you should first check /// the <see cref="SupportsUids"/> property. /// </remarks> /// <returns>The message UIDs.</returns> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<string>> GetMessageUidsAsync (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the size of the specified message, in bytes. /// </summary> /// <remarks> /// Gets the size of the specified message, in bytes. /// </remarks> /// <returns>The message size, in bytes.</returns> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> int GetMessageSize (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the size of the specified message, in bytes. /// </summary> /// <remarks> /// Asynchronously gets the size of the specified message, in bytes. /// </remarks> /// <returns>The message size, in bytes.</returns> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<int> GetMessageSizeAsync (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the size of the specified message, in bytes. /// </summary> /// <remarks> /// Gets the size of the specified message, in bytes. /// </remarks> /// <returns>The message size, in bytes.</returns> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> int GetMessageSize (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the size of the specified message, in bytes. /// </summary> /// <remarks> /// Asynchronously gets the size of the specified message, in bytes. /// </remarks> /// <returns>The message size, in bytes.</returns> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<int> GetMessageSizeAsync (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the sizes for all available messages, in bytes. /// </summary> /// <remarks> /// Gets the sizes for all available messages, in bytes. /// </remarks> /// <returns>The message sizes, in bytes.</returns> /// <param name="cancellationToken">The cancellation token.</param> IList<int> GetMessageSizes (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the sizes for all available messages, in bytes. /// </summary> /// <remarks> /// Asynchronously gets the sizes for all available messages, in bytes. /// </remarks> /// <returns>The message sizes, in bytes.</returns> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<int>> GetMessageSizesAsync (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the headers for the specified message. /// </summary> /// <remarks> /// Gets the headers for the specified message. /// </remarks> /// <returns>The message headers.</returns> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> HeaderList GetMessageHeaders (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the headers for the specified message. /// </summary> /// <remarks> /// Asynchronously gets the headers for the specified message. /// </remarks> /// <returns>The message headers.</returns> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<HeaderList> GetMessageHeadersAsync (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the headers for the specified message. /// </summary> /// <remarks> /// Gets the headers for the specified message. /// </remarks> /// <returns>The message headers.</returns> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> HeaderList GetMessageHeaders (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the headers for the specified message. /// </summary> /// <remarks> /// Asynchronously gets the headers for the specified message. /// </remarks> /// <returns>The message headers.</returns> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<HeaderList> GetMessageHeadersAsync (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the headers for the specified messages. /// </summary> /// <remarks> /// Gets the headers for the specified messages. /// </remarks> /// <returns>The headers for the specified messages.</returns> /// <param name="uids">The UIDs of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> IList<HeaderList> GetMessageHeaders (IList<string> uids, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the headers for the specified messages. /// </summary> /// <remarks> /// Asynchronously gets the headers for the specified messages. /// </remarks> /// <returns>The headers for the specified messages.</returns> /// <param name="uids">The UIDs of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<HeaderList>> GetMessageHeadersAsync (IList<string> uids, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the headers for the specified messages. /// </summary> /// <remarks> /// Gets the headers for the specified messages. /// </remarks> /// <returns>The headers for the specified messages.</returns> /// <param name="indexes">The indexes of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> IList<HeaderList> GetMessageHeaders (IList<int> indexes, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the headers for the specified messages. /// </summary> /// <remarks> /// Asynchronously gets the headers for the specified messages. /// </remarks> /// <returns>The headers for the specified messages.</returns> /// <param name="indexes">The indexes of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<HeaderList>> GetMessageHeadersAsync (IList<int> indexes, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the headers of the messages within the specified range. /// </summary> /// <remarks> /// Gets the headers of the messages within the specified range. /// </remarks> /// <returns>The headers of the messages within the specified range.</returns> /// <param name="startIndex">The index of the first message to get.</param> /// <param name="count">The number of messages to get.</param> /// <param name="cancellationToken">The cancellation token.</param> IList<HeaderList> GetMessageHeaders (int startIndex, int count, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the headers of the messages within the specified range. /// </summary> /// <remarks> /// Gets the headers of the messages within the specified range. /// </remarks> /// <returns>The headers of the messages within the specified range.</returns> /// <param name="startIndex">The index of the first message to get.</param> /// <param name="count">The number of messages to get.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<HeaderList>> GetMessageHeadersAsync (int startIndex, int count, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the message with the specified UID. /// </summary> /// <remarks> /// Gets the message with the specified UID. /// </remarks> /// <returns>The message.</returns> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> MimeMessage GetMessage (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the message with the specified UID. /// </summary> /// <remarks> /// Asynchronously gets the message with the specified UID. /// </remarks> /// <returns>The message.</returns> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<MimeMessage> GetMessageAsync (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the message at the specified index. /// </summary> /// <remarks> /// Gets the message at the specified index. /// </remarks> /// <returns>The message.</returns> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> MimeMessage GetMessage (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the message at the specified index. /// </summary> /// <remarks> /// Asynchronously gets the message at the specified index. /// </remarks> /// <returns>The message.</returns> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<MimeMessage> GetMessageAsync (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the messages with the specified UIDs. /// </summary> /// <remarks> /// Gets the messages with the specified UIDs. /// </remarks> /// <returns>The messages.</returns> /// <param name="uids">The UID of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> IList<MimeMessage> GetMessages (IList<string> uids, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the messages with the specified UIDs. /// </summary> /// <remarks> /// Asynchronously gets the messages with the specified UIDs. /// </remarks> /// <returns>The messages.</returns> /// <param name="uids">The UIDs of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<MimeMessage>> GetMessagesAsync (IList<string> uids, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the messages at the specified indexes. /// </summary> /// <remarks> /// Gets the messages at the specified indexes. /// </remarks> /// <returns>The messages.</returns> /// <param name="indexes">The indexes of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> IList<MimeMessage> GetMessages (IList<int> indexes, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the messages at the specified indexes. /// </summary> /// <remarks> /// Asynchronously gets the messages at the specified indexes. /// </remarks> /// <returns>The messages.</returns> /// <param name="indexes">The indexes of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<MimeMessage>> GetMessagesAsync (IList<int> indexes, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Get the messages within the specified range. /// </summary> /// <remarks> /// Gets the messages within the specified range. /// </remarks> /// <returns>The messages.</returns> /// <param name="startIndex">The index of the first message to get.</param> /// <param name="count">The number of messages to get.</param> /// <param name="cancellationToken">The cancellation token.</param> IList<MimeMessage> GetMessages (int startIndex, int count, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously get the messages within the specified range. /// </summary> /// <remarks> /// Asynchronously gets the messages within the specified range. /// </remarks> /// <returns>The messages.</returns> /// <param name="startIndex">The index of the first message to get.</param> /// <param name="count">The number of messages to get.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<IList<MimeMessage>> GetMessagesAsync (int startIndex, int count, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Mark the specified message for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> void DeleteMessage (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously mark the specified message for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="uid">The UID of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task DeleteMessageAsync (string uid, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Mark the specified message for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> void DeleteMessage (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously mark the specified message for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="index">The index of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> Task DeleteMessageAsync (int index, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Mark the specified messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <param name="uids">The UIDs of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> void DeleteMessages (IList<string> uids, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously mark the specified messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="uids">The UIDs of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> Task DeleteMessagesAsync (IList<string> uids, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Mark the specified messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <param name="indexes">The indexes of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> void DeleteMessages (IList<int> indexes, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously mark the specified messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="indexes">The indexes of the messages.</param> /// <param name="cancellationToken">The cancellation token.</param> Task DeleteMessagesAsync (IList<int> indexes, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Mark the specified range of messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <param name="startIndex">The index of the first message to mark for deletion.</param> /// <param name="count">The number of messages to mark for deletion.</param> /// <param name="cancellationToken">The cancellation token.</param> void DeleteMessages (int startIndex, int count, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously mark the specified range of messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="startIndex">The index of the first message to mark for deletion.</param> /// <param name="count">The number of messages to mark for deletion.</param> /// <param name="cancellationToken">The cancellation token.</param> Task DeleteMessagesAsync (int startIndex, int count, CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Mark all messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <param name="cancellationToken">The cancellation token.</param> void DeleteAllMessages (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously mark all messages for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="cancellationToken">The cancellation token.</param> Task DeleteAllMessagesAsync (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Reset the state of all messages marked for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <param name="cancellationToken">The cancellation token.</param> void Reset (CancellationToken cancellationToken = default (CancellationToken)); /// <summary> /// Asynchronously reset the state of all messages marked for deletion. /// </summary> /// <remarks> /// Messages marked for deletion are not actually deleted until the session /// is cleanly disconnected /// (see <see cref="IMailService.Disconnect(bool, CancellationToken)"/>). /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="cancellationToken">The cancellation token.</param> Task ResetAsync (CancellationToken cancellationToken = default (CancellationToken)); } }
using System; using System.Collections.Generic; using System.Text; namespace HTLib2 { public partial class Matlab { /// Matlab.PutSparseMatrix("H", H.GetMatrixSparse(), 3, 3); //public static void PutSparseMatrix<MATRIX>(string name, MatrixSparse<MATRIX> real, int elemColSize, int elemRowSize) //public static void PutSparseMatrix<MATRIX>(string name, IMatrixSparse<MATRIX> real, int elemColSize, int elemRowSize) // where MATRIX : Matrix public static void PutSparseMatrix(string name, IMatrixSparse<double> real, bool bUseFile=false) { /// http://www.mathworks.com/help/matlab/ref/sparse.html /// S = sparse(i,j,s,m,n) /// * create m-by-n sparse matrix /// * where S(i(k),j(k)) = s(k) /// * Vectors i, j, and s are all the same length. /// * Any elements of s that are zero are ignored. /// * Any elementsof s that have duplicate values of i and j are added together. if(bUseFile == false) { int m = real.ColSize; int n = real.RowSize; { List<int > i = new List<int >(); List<int > j = new List<int >(); List<double> s = new List<double>(); foreach(var c_r_val in real.EnumElements()) { int c = c_r_val.Item1; int r = c_r_val.Item2; double val = c_r_val.Item3; if(val == 0) continue; i.Add(c ); j.Add(r ); s.Add(val); } PutVector("htlib2_matlab_PutSparseMatrix.i", i.ToArray()); PutVector("htlib2_matlab_PutSparseMatrix.j", j.ToArray()); PutVector("htlib2_matlab_PutSparseMatrix.s", s.ToArray()); } PutValue("htlib2_matlab_PutSparseMatrix.m", m); PutValue("htlib2_matlab_PutSparseMatrix.n", n); Execute("htlib2_matlab_PutSparseMatrix = sparse(htlib2_matlab_PutSparseMatrix.i+1, htlib2_matlab_PutSparseMatrix.j+1, htlib2_matlab_PutSparseMatrix.s, htlib2_matlab_PutSparseMatrix.m, htlib2_matlab_PutSparseMatrix.n);"); Execute(name+" = htlib2_matlab_PutSparseMatrix;"); Execute("clear htlib2_matlab_PutSparseMatrix;"); } else { HDebug.Assert(bUseFile == true); string i_path = HFile.GetTempPath(_path_temporary, ".dat"); string j_path = HFile.GetTempPath(_path_temporary, ".dat"); string s_path = HFile.GetTempPath(_path_temporary, ".dat"); ulong count = 0; { System.IO.BinaryWriter i_writer = new System.IO.BinaryWriter(new System.IO.FileStream(i_path, System.IO.FileMode.CreateNew)); System.IO.BinaryWriter j_writer = new System.IO.BinaryWriter(new System.IO.FileStream(j_path, System.IO.FileMode.CreateNew)); System.IO.BinaryWriter s_writer = new System.IO.BinaryWriter(new System.IO.FileStream(s_path, System.IO.FileMode.CreateNew)); foreach (var c_r_val in real.EnumElements()) { double c = c_r_val.Item1; double r = c_r_val.Item2; double val = c_r_val.Item3; count ++; i_writer.Write(c ); j_writer.Write(r ); s_writer.Write(val); HDebug.Exception(count > 0); } i_writer.Flush(); i_writer.Close(); j_writer.Flush(); j_writer.Close(); s_writer.Flush(); s_writer.Close(); } { PutValue("htlib2_matlab_PutSparseMatrix.m", real.ColSize); PutValue("htlib2_matlab_PutSparseMatrix.n", real.RowSize); Execute("htlib2_matlab_PutSparseMatrix.ifid=fopen('" + i_path + "','r');"); Execute("htlib2_matlab_PutSparseMatrix.jfid=fopen('" + j_path + "','r');"); Execute("htlib2_matlab_PutSparseMatrix.sfid=fopen('" + s_path + "','r');"); // A = fread(fileID) reads all the data in the file into a vector of class double. By default, fread reads a file 1 byte at a time, interprets each byte as an 8-bit unsigned integer (uint8), and returns a double array. Execute("htlib2_matlab_PutSparseMatrix.imat=fread(htlib2_matlab_PutSparseMatrix.ifid, ["+count+"],'*double')';"); Execute("htlib2_matlab_PutSparseMatrix.jmat=fread(htlib2_matlab_PutSparseMatrix.jfid, ["+count+"],'*double')';"); Execute("htlib2_matlab_PutSparseMatrix.smat=fread(htlib2_matlab_PutSparseMatrix.sfid, ["+count+"],'*double')';"); Execute("fclose(htlib2_matlab_PutSparseMatrix.ifid);"); Execute("fclose(htlib2_matlab_PutSparseMatrix.jfid);"); Execute("fclose(htlib2_matlab_PutSparseMatrix.sfid);"); Execute("htlib2_matlab_PutSparseMatrix = sparse(htlib2_matlab_PutSparseMatrix.imat+1, htlib2_matlab_PutSparseMatrix.jmat+1, htlib2_matlab_PutSparseMatrix.smat, htlib2_matlab_PutSparseMatrix.m, htlib2_matlab_PutSparseMatrix.n);"); Execute(name + " = htlib2_matlab_PutSparseMatrix;"); Execute("clear htlib2_matlab_PutSparseMatrix;"); } HFile.Delete(i_path); HFile.Delete(j_path); HFile.Delete(s_path); } if(HDebug.IsDebuggerAttached) { Random rand = new Random(); for(int i=0; i<1000; i++) { int c = rand.NextInt(real.ColSize) + 1; int r = rand.NextInt(real.RowSize) + 1; double real_cr = real[c-1, r-1]; double matl_cr = Matlab.GetValue("full("+name+"("+c+","+r+"))"); HDebug.Assert(real_cr == matl_cr); //HDebug.Assert(Math.Abs(real_cr - matl_cr) < 1.0e-15); } } } public static void PutSparseMatrix(string name, IMatrixSparse<MatrixByArr> real, int elemColSize, int elemRowSize, string opt=null) { /// http://www.mathworks.com/help/matlab/ref/sparse.html /// S = sparse(i,j,s,m,n) /// * create m-by-n sparse matrix /// * where S(i(k),j(k)) = s(k) /// * Vectors i, j, and s are all the same length. /// * Any elements of s that are zero are ignored. /// * Any elementsof s that have duplicate values of i and j are added together. if(opt == null) { int m = real.ColSize * elemColSize; int n = real.RowSize * elemRowSize; //if(opt == null) { List<int > i = new List<int >(); List<int > j = new List<int >(); List<double> s = new List<double>(); foreach(var c_r_val in real.EnumElements()) { int c = c_r_val.Item1; int r = c_r_val.Item2; Matrix hesscr = c_r_val.Item3; HDebug.Assert(hesscr != null); HDebug.Assert(hesscr.ColSize == elemColSize, hesscr.RowSize == elemRowSize); for(int dc=0; dc<elemColSize; dc++) for(int dr=0; dr<elemRowSize; dr++) { i.Add(c*elemColSize+dc); j.Add(r*elemRowSize+dr); s.Add(hesscr[dc, dr]); } } //for(int ii=0; ii<i.Count; ii++) //{ // if(i[ii] == j[ii]) // HDebug.Assert(s[ii] != 0); //} PutVector("htlib2_matlab_PutSparseMatrix.i", i.ToArray()); PutVector("htlib2_matlab_PutSparseMatrix.j", j.ToArray()); PutVector("htlib2_matlab_PutSparseMatrix.s", s.ToArray()); } //else //{ // Execute("htlib2_matlab_PutSparseMatrix.i = [];"); // Execute("htlib2_matlab_PutSparseMatrix.j = [];"); // Execute("htlib2_matlab_PutSparseMatrix.s = [];"); // // int maxleng = 10_000_000; // Count = 134217728 (maximum) // List<int > i = new List<int >(maxleng); // List<int > j = new List<int >(maxleng); // List<double> s = new List<double>(maxleng); // foreach(var c_r_val in real.EnumElements()) // { // int c = c_r_val.Item1; // int r = c_r_val.Item2; // Matrix hesscr = c_r_val.Item3; // HDebug.Assert(hesscr != null); // HDebug.Assert(hesscr.ColSize == elemColSize, hesscr.RowSize == elemRowSize); // for(int dc=0; dc<elemColSize; dc++) // for(int dr=0; dr<elemRowSize; dr++) // { // if(i.Count == maxleng) // { // PutVector("htlib2_matlab_PutSparseMatrix.ix", i.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.jx", j.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.sx", s.ToArray()); // Execute("htlib2_matlab_PutSparseMatrix.i = [htlib2_matlab_PutSparseMatrix.i; htlib2_matlab_PutSparseMatrix.ix];"); // Execute("htlib2_matlab_PutSparseMatrix.j = [htlib2_matlab_PutSparseMatrix.j; htlib2_matlab_PutSparseMatrix.jx];"); // Execute("htlib2_matlab_PutSparseMatrix.s = [htlib2_matlab_PutSparseMatrix.s; htlib2_matlab_PutSparseMatrix.sx];"); // Execute("clear htlib2_matlab_PutSparseMatrix.ix;"); // Execute("clear htlib2_matlab_PutSparseMatrix.jx;"); // Execute("clear htlib2_matlab_PutSparseMatrix.sx;"); // i.Clear(); // j.Clear(); // s.Clear(); // } // i.Add(c*elemColSize+dc); // j.Add(r*elemRowSize+dr); // s.Add(hesscr[dc, dr]); // } // } // if(i.Count != 0) // { // PutVector("htlib2_matlab_PutSparseMatrix.ix", i.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.jx", j.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.sx", s.ToArray()); // Execute("htlib2_matlab_PutSparseMatrix.i = [htlib2_matlab_PutSparseMatrix.i; htlib2_matlab_PutSparseMatrix.ix];"); // Execute("htlib2_matlab_PutSparseMatrix.j = [htlib2_matlab_PutSparseMatrix.j; htlib2_matlab_PutSparseMatrix.jx];"); // Execute("htlib2_matlab_PutSparseMatrix.s = [htlib2_matlab_PutSparseMatrix.s; htlib2_matlab_PutSparseMatrix.sx];"); // Execute("htlib2_matlab_PutSparseMatrix.ix = [];"); // Execute("htlib2_matlab_PutSparseMatrix.jx = [];"); // Execute("htlib2_matlab_PutSparseMatrix.sx = [];"); // i.Clear(); // j.Clear(); // s.Clear(); // } // HDebug.Assert(i.Count == 0); // HDebug.Assert(j.Count == 0); // HDebug.Assert(s.Count == 0); //} PutValue("htlib2_matlab_PutSparseMatrix.m", m); PutValue("htlib2_matlab_PutSparseMatrix.n", n); Execute("htlib2_matlab_PutSparseMatrix = sparse(htlib2_matlab_PutSparseMatrix.i+1, htlib2_matlab_PutSparseMatrix.j+1, htlib2_matlab_PutSparseMatrix.s, htlib2_matlab_PutSparseMatrix.m, htlib2_matlab_PutSparseMatrix.n);"); Execute(name+" = htlib2_matlab_PutSparseMatrix;"); Execute("clear htlib2_matlab_PutSparseMatrix;"); } else if(opt == "use file") { string i_path = HFile.GetTempPath(_path_temporary, ".dat"); string j_path = HFile.GetTempPath(_path_temporary, ".dat"); string s_path = HFile.GetTempPath(_path_temporary, ".dat"); ulong count = 0; { System.IO.BinaryWriter i_writer = new System.IO.BinaryWriter(new System.IO.FileStream(i_path, System.IO.FileMode.CreateNew)); System.IO.BinaryWriter j_writer = new System.IO.BinaryWriter(new System.IO.FileStream(j_path, System.IO.FileMode.CreateNew)); System.IO.BinaryWriter s_writer = new System.IO.BinaryWriter(new System.IO.FileStream(s_path, System.IO.FileMode.CreateNew)); foreach (var c_r_val in real.EnumElements()) { int c = c_r_val.Item1; int r = c_r_val.Item2; Matrix hesscr = c_r_val.Item3; HDebug.Assert(hesscr != null); HDebug.Assert(hesscr.ColSize == elemColSize, hesscr.RowSize == elemRowSize); for (int dc = 0; dc < elemColSize; dc++) for (int dr = 0; dr < elemRowSize; dr++) { count ++; double i = (c * elemColSize + dc); double j = (r * elemRowSize + dr); double s = (hesscr[dc, dr]); i_writer.Write(i); j_writer.Write(j); s_writer.Write(s); HDebug.Exception(count > 0); } } i_writer.Flush(); i_writer.Close(); j_writer.Flush(); j_writer.Close(); s_writer.Flush(); s_writer.Close(); } { int m = real.ColSize * elemColSize; int n = real.RowSize * elemRowSize; PutValue("htlib2_matlab_PutSparseMatrix.m", m); PutValue("htlib2_matlab_PutSparseMatrix.n", n); Execute("htlib2_matlab_PutSparseMatrix.ifid=fopen('" + i_path + "','r');"); Execute("htlib2_matlab_PutSparseMatrix.jfid=fopen('" + j_path + "','r');"); Execute("htlib2_matlab_PutSparseMatrix.sfid=fopen('" + s_path + "','r');"); // A = fread(fileID) reads all the data in the file into a vector of class double. By default, fread reads a file 1 byte at a time, interprets each byte as an 8-bit unsigned integer (uint8), and returns a double array. Execute("htlib2_matlab_PutSparseMatrix.imat=fread(htlib2_matlab_PutSparseMatrix.ifid, ["+count+"],'*double')';"); Execute("htlib2_matlab_PutSparseMatrix.jmat=fread(htlib2_matlab_PutSparseMatrix.jfid, ["+count+"],'*double')';"); Execute("htlib2_matlab_PutSparseMatrix.smat=fread(htlib2_matlab_PutSparseMatrix.sfid, ["+count+"],'*double')';"); Execute("fclose(htlib2_matlab_PutSparseMatrix.ifid);"); Execute("fclose(htlib2_matlab_PutSparseMatrix.jfid);"); Execute("fclose(htlib2_matlab_PutSparseMatrix.sfid);"); Execute("htlib2_matlab_PutSparseMatrix = sparse(htlib2_matlab_PutSparseMatrix.imat+1, htlib2_matlab_PutSparseMatrix.jmat+1, htlib2_matlab_PutSparseMatrix.smat, htlib2_matlab_PutSparseMatrix.m, htlib2_matlab_PutSparseMatrix.n);"); Execute(name + " = htlib2_matlab_PutSparseMatrix;"); Execute("clear htlib2_matlab_PutSparseMatrix;"); } HFile.Delete(i_path); HFile.Delete(j_path); HFile.Delete(s_path); } } } }
/* Copyright 2018 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading.Tasks; using ArcGIS.Core.Data; using ArcGIS.Core.Geometry; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Editing; using ArcGIS.Desktop.Framework.Threading.Tasks; namespace SDKExamples.GeodatabaseSDK { /// <summary> /// Illustrates how to get the original value from a given field in a Row or Feature. /// </summary> /// /// <remarks> /// <para> /// While it is true classes that are derived from the <see cref="ArcGIS.Core.CoreObjectsBase"/> super class /// consumes native resources (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>), /// you can rest assured that the garbage collector will properly dispose of the unmanaged resources during /// finalization. However, there are certain workflows that require a <b>deterministic</b> finalization of the /// <see cref="ArcGIS.Core.Data.Geodatabase"/>. Consider the case of a file geodatabase that needs to be deleted /// on the fly at a particular moment. Because of the <b>indeterministic</b> nature of garbage collection, we can't /// count on the garbage collector to dispose of the Geodatabase object, thereby removing the <b>lock(s)</b> at the /// moment we want. To ensure a deterministic finalization of important native resources such as a /// <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>, you should declare /// and instantiate said objects in a <b>using</b> statement. Alternatively, you can achieve the same result by /// putting the object inside a try block and then calling Dispose() in a finally block. /// </para> /// <para> /// In general, you should always call Dispose() on the following types of objects: /// </para> /// <para> /// - Those that are derived from <see cref="ArcGIS.Core.Data.Datastore"/> (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/>). /// </para> /// <para> /// - Those that are derived from <see cref="ArcGIS.Core.Data.Dataset"/> (e.g., <see cref="ArcGIS.Core.Data.Table"/>). /// </para> /// <para> /// - <see cref="ArcGIS.Core.Data.RowCursor"/> and <see cref="ArcGIS.Core.Data.RowBuffer"/>. /// </para> /// <para> /// - <see cref="ArcGIS.Core.Data.Row"/> and <see cref="ArcGIS.Core.Data.Feature"/>. /// </para> /// <para> /// - <see cref="ArcGIS.Core.Data.Selection"/>. /// </para> /// <para> /// - <see cref="ArcGIS.Core.Data.VersionManager"/> and <see cref="ArcGIS.Core.Data.Version"/>. /// </para> /// </remarks> public class RowOriginalValue { /// <summary> /// In order to illustrate that Geodatabase calls have to be made on the MCT /// </summary> /// <returns></returns> public async Task MainMethodCode() { await QueuedTask.Run(async () => { await EnterpriseGeodabaseWorkFlow(); await FileGeodatabaseWorkFlow(); }); } private static async Task EnterpriseGeodabaseWorkFlow() { // Opening a Non-Versioned SQL Server instance. DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. Instance = @"testMachine\testInstance", // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. Database = "LocalGovernment", // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. User = "gdb", Password = "password", Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase((connectionProperties))) using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" }; using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false)) { TableDefinition tableDefinition = enterpriseTable.GetDefinition(); int assetNameIndex = tableDefinition.FindField("ASSETNA"); while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { // Will be same as row[assetNameIndex]. string originalValueBeforeChange = row.GetOriginalValue(assetNameIndex) as String; // In order to update the Map and/or the attribute table. // Has to be called before any changes are made to the row context.Invalidate(row); row[assetNameIndex] = "wMainOpenCut"; //Will be same as row[assetNameIndex]. string originalValueAfterChange = row.GetOriginalValue(assetNameIndex) as String; // After all the changes are done, persist it. row.Store(); // Has to be called after the store too context.Invalidate(row); // Will be "wMainOpenCut". string originalValueAfterStore = row.GetOriginalValue(assetNameIndex) as String; } } } }, enterpriseTable); bool editResult = editOperation.Execute(); // If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted. bool saveResult = await Project.Current.SaveEditsAsync(); } } //Illustrating creating a row in a File GDB private static async Task FileGeodatabaseWorkFlow() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (FeatureClass featureClass = fileGeodatabase.OpenDataset<FeatureClass>("PollingPlace")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter queryFilter = new QueryFilter { WhereClause = "FULLADD LIKE '///%Lily Cache Ln///%'" }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition(); int shapeFieldIndex = featureClassDefinition.FindField(featureClassDefinition.GetShapeField()); while (rowCursor.MoveNext()) { using (Feature feature = (Feature)rowCursor.Current) { MapPoint mapPoint = feature.GetShape() as MapPoint; // Will be the same as feature.GetShape(). Geometry originalValueBeforeChange = feature.GetOriginalValue(shapeFieldIndex) as Geometry; // In order to update the Map and/or the attribute table. // Has to be called before any changes are made to the row context.Invalidate(feature); MapPoint newShape = new MapPointBuilder(mapPoint.X + 10, mapPoint.Y, mapPoint.SpatialReference).ToGeometry(); feature.SetShape(newShape); // Will be the same as feature.GetShape(). Geometry originalValueAfterChange = feature.GetOriginalValue(shapeFieldIndex) as Geometry; feature.Store(); // Will be the same as newShape. Geometry originalValueAfterStore = feature.GetOriginalValue(shapeFieldIndex) as Geometry; // Has to be called after the store too context.Invalidate(feature); } } } }, featureClass); bool editResult = editOperation.Execute(); //This is required to persist the changes to the disk. bool saveResult = await Project.Current.SaveEditsAsync(); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.ServiceModel.Dispatcher; using System.Threading; sealed class ConnectionDemuxer : IDisposable { static AsyncCallback onSingletonPreambleComplete; ConnectionAcceptor acceptor; // we use this list to track readers that don't have a clear owner (so they don't get GC'ed) List<InitialServerConnectionReader> connectionReaders; bool isDisposed; ConnectionModeCallback onConnectionModeKnown; ConnectionModeCallback onCachedConnectionModeKnown; ConnectionClosedCallback onConnectionClosed; ServerSessionPreambleCallback onSessionPreambleKnown; ServerSingletonPreambleCallback onSingletonPreambleKnown; Action<object> reuseConnectionCallback; ServerSessionPreambleDemuxCallback serverSessionPreambleCallback; SingletonPreambleDemuxCallback singletonPreambleCallback; TransportSettingsCallback transportSettingsCallback; Action pooledConnectionDequeuedCallback; Action<Uri> viaDelegate; TimeSpan channelInitializationTimeout; TimeSpan idleTimeout; int maxPooledConnections; int pooledConnectionCount; public ConnectionDemuxer(IConnectionListener listener, int maxAccepts, int maxPendingConnections, TimeSpan channelInitializationTimeout, TimeSpan idleTimeout, int maxPooledConnections, TransportSettingsCallback transportSettingsCallback, SingletonPreambleDemuxCallback singletonPreambleCallback, ServerSessionPreambleDemuxCallback serverSessionPreambleCallback, ErrorCallback errorCallback) { this.connectionReaders = new List<InitialServerConnectionReader>(); this.acceptor = new ConnectionAcceptor(listener, maxAccepts, maxPendingConnections, OnConnectionAvailable, errorCallback); this.channelInitializationTimeout = channelInitializationTimeout; this.idleTimeout = idleTimeout; this.maxPooledConnections = maxPooledConnections; this.onConnectionClosed = new ConnectionClosedCallback(OnConnectionClosed); this.transportSettingsCallback = transportSettingsCallback; this.singletonPreambleCallback = singletonPreambleCallback; this.serverSessionPreambleCallback = serverSessionPreambleCallback; } object ThisLock { get { return this; } } public void Dispose() { lock (ThisLock) { if (isDisposed) return; isDisposed = true; } for (int i = 0; i < connectionReaders.Count; i++) { connectionReaders[i].Dispose(); } connectionReaders.Clear(); acceptor.Dispose(); } ConnectionModeReader SetupModeReader(IConnection connection, bool isCached) { ConnectionModeReader modeReader; if (isCached) { if (onCachedConnectionModeKnown == null) { onCachedConnectionModeKnown = new ConnectionModeCallback(OnCachedConnectionModeKnown); } modeReader = new ConnectionModeReader(connection, onCachedConnectionModeKnown, onConnectionClosed); } else { if (onConnectionModeKnown == null) { onConnectionModeKnown = new ConnectionModeCallback(OnConnectionModeKnown); } modeReader = new ConnectionModeReader(connection, onConnectionModeKnown, onConnectionClosed); } lock (ThisLock) { if (isDisposed) { modeReader.Dispose(); return null; } connectionReaders.Add(modeReader); return modeReader; } } public void ReuseConnection(IConnection connection, TimeSpan closeTimeout) { connection.ExceptionEventType = TraceEventType.Information; ConnectionModeReader modeReader = SetupModeReader(connection, true); if (modeReader != null) { if (reuseConnectionCallback == null) { reuseConnectionCallback = new Action<object>(ReuseConnectionCallback); } ActionItem.Schedule(reuseConnectionCallback, new ReuseConnectionState(modeReader, closeTimeout)); } } void ReuseConnectionCallback(object state) { ReuseConnectionState connectionState = (ReuseConnectionState)state; bool closeReader = false; lock (ThisLock) { if (this.pooledConnectionCount >= this.maxPooledConnections) { closeReader = true; } else { this.pooledConnectionCount++; } } if (closeReader) { if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ServerMaxPooledConnectionsQuotaReached, SR.GetString(SR.TraceCodeServerMaxPooledConnectionsQuotaReached, maxPooledConnections), new StringTraceRecord("MaxOutboundConnectionsPerEndpoint", maxPooledConnections.ToString(CultureInfo.InvariantCulture)), this, null); } if (TD.ServerMaxPooledConnectionsQuotaReachedIsEnabled()) { TD.ServerMaxPooledConnectionsQuotaReached(); } connectionState.ModeReader.CloseFromPool(connectionState.CloseTimeout); } else { if (this.pooledConnectionDequeuedCallback == null) { this.pooledConnectionDequeuedCallback = new Action(PooledConnectionDequeuedCallback); } connectionState.ModeReader.StartReading(this.idleTimeout, this.pooledConnectionDequeuedCallback); } } void PooledConnectionDequeuedCallback() { lock (ThisLock) { this.pooledConnectionCount--; Fx.Assert(this.pooledConnectionCount >= 0, "Connection Throttle should never be negative"); } } void OnConnectionAvailable(IConnection connection, Action connectionDequeuedCallback) { ConnectionModeReader modeReader = SetupModeReader(connection, false); if (modeReader != null) { // StartReading() will never throw non-fatal exceptions; // it propagates all exceptions into the onConnectionModeKnown callback, // which is where we need our robust handling modeReader.StartReading(this.channelInitializationTimeout, connectionDequeuedCallback); } else { connectionDequeuedCallback(); } } void OnCachedConnectionModeKnown(ConnectionModeReader modeReader) { OnConnectionModeKnownCore(modeReader, true); } void OnConnectionModeKnown(ConnectionModeReader modeReader) { OnConnectionModeKnownCore(modeReader, false); } void OnConnectionModeKnownCore(ConnectionModeReader modeReader, bool isCached) { lock (ThisLock) { if (isDisposed) return; this.connectionReaders.Remove(modeReader); } bool closeReader = true; try { FramingMode framingMode; try { framingMode = modeReader.GetConnectionMode(); } catch (CommunicationException exception) { TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } catch (TimeoutException exception) { if (!isCached) { exception = new TimeoutException(SR.GetString(SR.ChannelInitializationTimeout, this.channelInitializationTimeout), exception); System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(exception); } if (TD.ChannelInitializationTimeoutIsEnabled()) { TD.ChannelInitializationTimeout(SR.GetString(SR.ChannelInitializationTimeout, this.channelInitializationTimeout)); } TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } switch (framingMode) { case FramingMode.Duplex: OnDuplexConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; case FramingMode.Singleton: OnSingletonConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; default: { Exception inner = new InvalidDataException(SR.GetString( SR.FramingModeNotSupported, framingMode)); Exception exception = new ProtocolException(inner.Message, inner); FramingEncodingString.AddFaultString(exception, FramingEncodingString.UnsupportedModeFault); System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(exception); return; } } closeReader = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!ExceptionHandler.HandleTransportExceptionHelper(e)) { throw; } // containment -- the reader is aborted, no need for additional containment } finally { if (closeReader) { modeReader.Dispose(); } } } void OnConnectionClosed(InitialServerConnectionReader connectionReader) { lock (ThisLock) { if (isDisposed) return; connectionReaders.Remove(connectionReader); } } void OnSingletonConnection(IConnection connection, Action connectionDequeuedCallback, long streamPosition, int offset, int size, TimeSpan timeout) { if (onSingletonPreambleKnown == null) { onSingletonPreambleKnown = OnSingletonPreambleKnown; } ServerSingletonPreambleConnectionReader singletonPreambleReader = new ServerSingletonPreambleConnectionReader(connection, connectionDequeuedCallback, streamPosition, offset, size, transportSettingsCallback, onConnectionClosed, onSingletonPreambleKnown); lock (ThisLock) { if (isDisposed) { singletonPreambleReader.Dispose(); return; } connectionReaders.Add(singletonPreambleReader); } singletonPreambleReader.StartReading(viaDelegate, timeout); } void OnSingletonPreambleKnown(ServerSingletonPreambleConnectionReader serverSingletonPreambleReader) { lock (ThisLock) { if (isDisposed) { return; } connectionReaders.Remove(serverSingletonPreambleReader); } if (onSingletonPreambleComplete == null) { onSingletonPreambleComplete = Fx.ThunkCallback(new AsyncCallback(OnSingletonPreambleComplete)); } ISingletonChannelListener singletonChannelListener = singletonPreambleCallback(serverSingletonPreambleReader); Fx.Assert(singletonChannelListener != null, "singletonPreambleCallback must return a listener or send a Fault/throw"); // transfer ownership of the connection from the preamble reader to the message handler IAsyncResult result = BeginCompleteSingletonPreamble(serverSingletonPreambleReader, singletonChannelListener, onSingletonPreambleComplete, this); if (result.CompletedSynchronously) { EndCompleteSingletonPreamble(result); } } IAsyncResult BeginCompleteSingletonPreamble( ServerSingletonPreambleConnectionReader serverSingletonPreambleReader, ISingletonChannelListener singletonChannelListener, AsyncCallback callback, object state) { return new CompleteSingletonPreambleAndDispatchRequestAsyncResult(serverSingletonPreambleReader, singletonChannelListener, this, callback, state); } void EndCompleteSingletonPreamble(IAsyncResult result) { CompleteSingletonPreambleAndDispatchRequestAsyncResult.End(result); } static void OnSingletonPreambleComplete(IAsyncResult result) { if (result.CompletedSynchronously) { return; } ConnectionDemuxer thisPtr = (ConnectionDemuxer)result.AsyncState; try { thisPtr.EndCompleteSingletonPreamble(result); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } //should never actually hit this code - the async result will handle all exceptions, trace them, then abort the reader DiagnosticUtility.TraceHandledException(ex, TraceEventType.Warning); } } void OnSessionPreambleKnown(ServerSessionPreambleConnectionReader serverSessionPreambleReader) { lock (ThisLock) { if (isDisposed) { return; } connectionReaders.Remove(serverSessionPreambleReader); } TraceOnSessionPreambleKnown(serverSessionPreambleReader); serverSessionPreambleCallback(serverSessionPreambleReader, this); } static void TraceOnSessionPreambleKnown(ServerSessionPreambleConnectionReader serverSessionPreambleReader) { if (TD.SessionPreambleUnderstoodIsEnabled()) { TD.SessionPreambleUnderstood((serverSessionPreambleReader.Via != null) ? serverSessionPreambleReader.Via.ToString() : String.Empty); } } void OnDuplexConnection(IConnection connection, Action connectionDequeuedCallback, long streamPosition, int offset, int size, TimeSpan timeout) { if (onSessionPreambleKnown == null) { onSessionPreambleKnown = OnSessionPreambleKnown; } ServerSessionPreambleConnectionReader sessionPreambleReader = new ServerSessionPreambleConnectionReader( connection, connectionDequeuedCallback, streamPosition, offset, size, transportSettingsCallback, onConnectionClosed, onSessionPreambleKnown); lock (ThisLock) { if (isDisposed) { sessionPreambleReader.Dispose(); return; } connectionReaders.Add(sessionPreambleReader); } sessionPreambleReader.StartReading(viaDelegate, timeout); } public void StartDemuxing() { StartDemuxing(null); } public void StartDemuxing(Action<Uri> viaDelegate) { this.viaDelegate = viaDelegate; acceptor.StartAccepting(); } class CompleteSingletonPreambleAndDispatchRequestAsyncResult : AsyncResult { ServerSingletonPreambleConnectionReader serverSingletonPreambleReader; ISingletonChannelListener singletonChannelListener; ConnectionDemuxer demuxer; TimeoutHelper timeoutHelper; static AsyncCallback onPreambleComplete = Fx.ThunkCallback(new AsyncCallback(OnPreambleComplete)); public CompleteSingletonPreambleAndDispatchRequestAsyncResult( ServerSingletonPreambleConnectionReader serverSingletonPreambleReader, ISingletonChannelListener singletonChannelListener, ConnectionDemuxer demuxer, AsyncCallback callback, object state) : base(callback, state) { this.serverSingletonPreambleReader = serverSingletonPreambleReader; this.singletonChannelListener = singletonChannelListener; this.demuxer = demuxer; //if this throws, the calling code paths will abort the connection, so we only need to //call AbortConnection if BeginCompletePramble completes asynchronously. if (BeginCompletePreamble()) { Complete(true); } } public static void End(IAsyncResult result) { AsyncResult.End<CompleteSingletonPreambleAndDispatchRequestAsyncResult>(result); } bool BeginCompletePreamble() { this.timeoutHelper = new TimeoutHelper(this.singletonChannelListener.ReceiveTimeout); IAsyncResult result = this.serverSingletonPreambleReader.BeginCompletePreamble(this.timeoutHelper.RemainingTime(), onPreambleComplete, this); if (result.CompletedSynchronously) { return HandlePreambleComplete(result); } return false; } static void OnPreambleComplete(IAsyncResult result) { if (result.CompletedSynchronously) { return; } CompleteSingletonPreambleAndDispatchRequestAsyncResult thisPtr = (CompleteSingletonPreambleAndDispatchRequestAsyncResult)result.AsyncState; bool completeSelf = false; try { completeSelf = thisPtr.HandlePreambleComplete(result); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } //Don't complete this AsyncResult with this non-fatal exception. The calling code can't really do anything with it, //so just trace it (inside of AbortConnection), then ---- it. completeSelf = true; thisPtr.AbortConnection(ex); } if (completeSelf) { thisPtr.Complete(false); } } bool HandlePreambleComplete(IAsyncResult result) { IConnection upgradedConnection = this.serverSingletonPreambleReader.EndCompletePreamble(result); ServerSingletonConnectionReader singletonReader = new ServerSingletonConnectionReader(serverSingletonPreambleReader, upgradedConnection, this.demuxer); //singletonReader doesn't have async version of ReceiveRequest, so just call the [....] method for now. RequestContext requestContext = singletonReader.ReceiveRequest(this.timeoutHelper.RemainingTime()); singletonChannelListener.ReceiveRequest(requestContext, serverSingletonPreambleReader.ConnectionDequeuedCallback, true); return true; } void AbortConnection(Exception exception) { //this will trace the exception and abort the connection this.serverSingletonPreambleReader.Abort(exception); } } class ReuseConnectionState { ConnectionModeReader modeReader; TimeSpan closeTimeout; public ReuseConnectionState(ConnectionModeReader modeReader, TimeSpan closeTimeout) { this.modeReader = modeReader; this.closeTimeout = closeTimeout; } public ConnectionModeReader ModeReader { get { return this.modeReader; } } public TimeSpan CloseTimeout { get { return this.closeTimeout; } } } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using Common.Logging; using Commons.Collections; using NVelocity.App; using NVelocity.Exception; using NVelocity.Runtime; using NVelocity.Runtime.Resource.Loader; using Spring.Context.Support; using Spring.Core.IO; using Spring.Util; namespace Spring.Template.Velocity { /// <summary> /// Factory that configures a VelocityEngine. Can be used standalone, /// but typically you will use VelocityEngineFactoryObject /// for preparing a VelocityEngine as bean reference. /// /// <br/> /// The optional "ConfigLocation" property sets the location of the Velocity /// properties file, within the current application. Velocity properties can be /// overridden via "VelocityProperties", or even completely specified locally, /// avoiding the need for an external properties file. /// /// <br/> /// The "ResourceLoaderPath" property can be used to specify the Velocity /// resource loader path via Spring's IResource abstraction, possibly relative /// to the Spring application context. /// /// <br/> /// If "OverrideLogging" is true (the default), the VelocityEngine will be /// configured to log via Commons Logging, that is, using the Spring-provided /// CommonsLoggingLogSystem as log system. /// /// <br/> /// The simplest way to use this class is to specify a ResourceLoaderPath /// property. the VelocityEngine typically then does not need any further /// configuration. /// /// </summary> /// <see cref="CommonsLoggingLogSystem" /> /// <see cref="VelocityEngineFactoryObject" /> /// <see cref="CommonsLoggingLogSystem" /> /// <author>Erez Mazor</author> public class VelocityEngineFactory { /// <summary> /// Shared logger instance. /// </summary> protected static readonly ILog log = LogManager.GetLogger(typeof(VelocityEngineFactory)); private IResource configLocation; private IDictionary<string, object> velocityProperties = new Dictionary<string, object>(); private IList<string> resourceLoaderPaths = new List<string>(); private IResourceLoader resourceLoader = new ConfigurableResourceLoader(); private bool preferFileSystemAccess = true; private bool overrideLogging = true; /// <summary> /// Set the location of the Velocity config file. Alternatively, you can specify all properties locally. /// </summary> /// <see cref="VelocityProperties"/> /// <see cref="ResourceLoaderPath"/> public IResource ConfigLocation { set { configLocation = value; } } /// <summary> /// Set local NVelocity properties. /// </summary> /// <see cref="VelocityProperties"/> public IDictionary<string, object> VelocityProperties { set { velocityProperties = value; } } /// <summary> /// Single ResourceLoaderPath /// </summary> /// <see cref="ResourceLoaderPaths"/> public string ResourceLoaderPath { set { resourceLoaderPaths.Add(value); } } /// <summary> /// Set the Velocity resource loader path via a Spring resource location. /// Accepts multiple locations in Velocity's comma-separated path style. /// <br/> /// When populated via a String, standard URLs like "file:" and "assembly:" /// pseudo URLs are supported, as understood by IResourceLoader. Allows for /// relative paths when running in an ApplicationContext. /// <br/> /// Will define a path for the default Velocity resource loader with the name /// "file". If the specified resource cannot be resolved to a File, /// a generic SpringResourceLoader will be used under the name "spring", without /// modification detection. /// <br/> /// Take notice that resource caching will be enabled in any case. With the file /// resource loader, the last-modified timestamp will be checked on access to /// detect changes. With SpringResourceLoader, the resource will be throughout /// the life time of the application context (for example for class path resources). /// <br/> /// To specify a modification check interval for files, use Velocity's /// standard "file.resource.loader.modificationCheckInterval" property. By default, /// the file timestamp is checked on every access (which is surprisingly fast). /// Of course, this just applies when loading resources from the file system. /// <br/> /// To enforce the use of SpringResourceLoader, i.e. to not resolve a path /// as file system resource in any case, turn off the "preferFileSystemAccess" /// flag. See the latter's documentation for details. /// </summary> /// <see cref="ResourceLoader"/> /// <see cref="VelocityProperties"/> /// <see cref="PreferFileSystemAccess"/> /// <see cref="SpringResourceLoader"/> /// <see cref="FileResourceLoader"/> public IList<string> ResourceLoaderPaths { set { resourceLoaderPaths = value; } } /// <summary> /// Set the Spring ResourceLoader to use for loading Velocity template files. /// The default is DefaultResourceLoader. Will get overridden by the /// ApplicationContext if running in a context. /// /// </summary> /// <see cref="ConfigurableResourceLoader"/> /// <see cref="ContextRegistry"/> /// public IResourceLoader ResourceLoader { get { return resourceLoader; } set { resourceLoader = value; } } /// <summary> /// Set whether to prefer file system access for template loading. /// File system access enables hot detection of template changes. /// <br/> /// If this is enabled, VelocityEngineFactory will try to resolve the /// specified "resourceLoaderPath" as file system resource. /// <br/> /// Default is "true". Turn this off to always load via SpringResourceLoader /// (i.e. as stream, without hot detection of template changes), which might /// be necessary if some of your templates reside in a directory while /// others reside in assembly files. /// </summary> /// <see cref="ResourceLoaderPath"/> public bool PreferFileSystemAccess { get { return preferFileSystemAccess; } set { preferFileSystemAccess = value; } } /// <summary> /// Set whether Velocity should log via Commons Logging, i.e. whether Velocity's /// log system should be set to CommonsLoggingLogSystem. Default value is true /// </summary> /// <see cref="CommonsLoggingLogSystem"/> public bool OverrideLogging { get { return overrideLogging; } set { overrideLogging = value; } } /// <summary> /// Create and initialize the VelocityEngine instance and return it /// </summary> /// <returns>VelocityEngine</returns> /// <exception cref="VelocityException" /> /// <see cref="FillProperties" /> /// <see cref="InitVelocityResourceLoader" /> /// <see cref="PostProcessVelocityEngine" /> /// <see cref="VelocityEngine.Init()" /> public VelocityEngine CreateVelocityEngine() { ExtendedProperties extendedProperties = new ExtendedProperties(); VelocityEngine velocityEngine = NewVelocityEngine(); LoadDefaultProperties(extendedProperties); // Load config file if set. if (configLocation != null) { if (log.IsInfoEnabled) { log.Info(string.Format("Loading Velocity config from [{0}]", configLocation)); } FillProperties(extendedProperties, configLocation, false); } // merge local properties if set. if (velocityProperties.Count > 0) { foreach (KeyValuePair<string, object> pair in velocityProperties) { extendedProperties.SetProperty(pair.Key, pair.Value); } } // Set a resource loader path, if required. if (!preferFileSystemAccess && resourceLoaderPaths.Count == 0) { throw new ArgumentException("When using SpringResourceLoader you must provide a path using the ResourceLoaderPath property"); } if (resourceLoaderPaths.Count > 0) { InitVelocityResourceLoader(velocityEngine, extendedProperties, resourceLoaderPaths); } // Log via Commons Logging? if (overrideLogging) { velocityEngine.SetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLoggingLogSystem()); } PostProcessVelocityEngine(velocityEngine); try { velocityEngine.Init(extendedProperties); } catch (Exception ex) { throw new VelocityException(ex.ToString(), ex); } return velocityEngine; } /// <summary> /// This is to overcome an issue with the current NVelocity library, it seems the /// default runetime properties/directives (nvelocity.properties and directive.properties /// files) are not being properly located in the library at load time. A jira should /// be filed but for now we attempt to do this on our own. Particularly our /// concern here is with several required properties which I don't want /// to require users to re-defined. e.g.,: /// <br/> /// /// Pre-requisites:<br/> /// resource.manager.class=NVelocity.Runtime.Resource.ResourceManagerImpl <br/> /// directive.manager=NVelocity.Runtime.Directive.DirectiveManager <br/> /// runtime.introspector.uberspect=NVelocity.Util.Introspection.UberspectImpl <br/> /// </summary> private static void LoadDefaultProperties(ExtendedProperties extendedProperties) { IResource defaultRuntimeProperties = new AssemblyResource("assembly://NVelocity/NVelocity.Runtime.Defaults/nvelocity.properties"); IResource defaultRuntimeDirectives = new AssemblyResource("assembly://NVelocity/NVelocity.Runtime.Defaults/directive.properties"); FillProperties(extendedProperties, defaultRuntimeProperties, true); FillProperties(extendedProperties, defaultRuntimeDirectives, true); } /// <summary> /// Return a new VelocityEngine. Subclasses can override this for /// custom initialization, or for using a mock object for testing. <br/> /// Called by CreateVelocityEngine() /// </summary> /// <returns>VelocityEngine instance (non-configured)</returns> /// <see cref="CreateVelocityEngine"/> protected static VelocityEngine NewVelocityEngine() { return new VelocityEngine(); } /// <summary> /// Initialize a Velocity resource loader for the given VelocityEngine: /// either a standard Velocity FileResourceLoader or a SpringResourceLoader. /// <br/>Called by <code>CreateVelocityEngine()</code>. /// </summary> /// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param> /// <param name="extendedProperties"></param> /// <param name="paths">paths the path list to load Velocity resources from</param> /// <see cref="FileResourceLoader"/> /// <see cref="SpringResourceLoader"/> /// <see cref="InitSpringResourceLoader"/> /// <see cref="CreateVelocityEngine"/> protected void InitVelocityResourceLoader(VelocityEngine velocityEngine, ExtendedProperties extendedProperties, IList<string> paths) { if (PreferFileSystemAccess) { // Try to load via the file system, fall back to SpringResourceLoader // (for hot detection of template changes, if possible). IList<string> resolvedPaths = new List<string>(); try { foreach (string path in paths) { IResource resource = ResourceLoader.GetResource(path); resolvedPaths.Add(resource.File.FullName); } extendedProperties.SetProperty(RuntimeConstants.RESOURCE_LOADER, VelocityConstants.File); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, StringUtils.CollectionToCommaDelimitedString(resolvedPaths)); } catch (IOException ex) { if (log.IsDebugEnabled) { log.Error(string.Format("Cannot resolve resource loader path [{0}] to [File]: using SpringResourceLoader", StringUtils.CollectionToCommaDelimitedString(resolvedPaths)), ex); } InitSpringResourceLoader(velocityEngine, extendedProperties, StringUtils.CollectionToCommaDelimitedString(paths)); } } else { // Always load via SpringResourceLoader (without hot detection of template changes). if (log.IsDebugEnabled) { log.Debug("File system access not preferred: using SpringResourceLoader"); } InitSpringResourceLoader(velocityEngine, extendedProperties, StringUtils.CollectionToCommaDelimitedString(paths)); } } /// <summary> /// Initialize a SpringResourceLoader for the given VelocityEngine. /// <br/>Called by <code>InitVelocityResourceLoader</code>. /// /// <b>Important</b>: the NVeloctity ResourceLoaderFactory.getLoader /// method replaces ';' with ',' when attempting to construct our resource /// loader. The name on the SPRING_RESOURCE_LOADER_CLASS property /// has to be in the form of "ClassFullName; AssemblyName" in replacement /// of the tranditional "ClassFullName, AssemblyName" to work. /// </summary> /// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param> /// <param name="extendedProperties"></param> /// <param name="resourceLoaderPathString">resourceLoaderPath the path to load Velocity resources from</param> /// <see cref="SpringResourceLoader"/> /// <see cref="InitVelocityResourceLoader"/> protected void InitSpringResourceLoader(VelocityEngine velocityEngine, ExtendedProperties extendedProperties, string resourceLoaderPathString) { extendedProperties.SetProperty(RuntimeConstants.RESOURCE_LOADER, SpringResourceLoader.NAME); Type springResourceLoaderType = typeof(SpringResourceLoader); string springResourceLoaderTypeName = springResourceLoaderType.FullName + "; " + springResourceLoaderType.Assembly.GetName().Name; extendedProperties.SetProperty(SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, springResourceLoaderTypeName); velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER, ResourceLoader); velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPathString); } /// <summary> /// To be implemented by subclasses that want to to perform custom /// post-processing of the VelocityEngine after this FactoryObject /// performed its default configuration (but before VelocityEngine.init) /// <br/> /// Called by CreateVelocityEngine /// </summary> /// <param name="velocityEngine">velocityEngine the current VelocityEngine</param> /// <exception cref="IOException" /> /// <see cref="CreateVelocityEngine"/> /// <see cref="VelocityEngine.Init()"/> protected virtual void PostProcessVelocityEngine(VelocityEngine velocityEngine) { } /// <summary> /// Populates the velocity properties from the given resource /// </summary> /// <param name="extendedProperties">ExtendedProperties instance to populate</param> /// <param name="resource">The resource from which to load the properties</param> /// <param name="append">A flag indicated weather the properties loaded from the resource should be appended or replaced in the extendedProperties</param> private static void FillProperties(ExtendedProperties extendedProperties, IInputStreamSource resource, bool append) { try { if (append) { extendedProperties.Load(resource.InputStream); } else { ExtendedProperties overrides = new ExtendedProperties(); overrides.Load(resource.InputStream); foreach (DictionaryEntry entry in overrides) { extendedProperties.SetProperty(Convert.ToString(entry.Key), entry.Value); } } } finally { resource.InputStream.Close(); } } } }
// 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.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.Text; using System.Threading; using System.Threading.Tasks; using Thrift.Collections; using Thrift.Protocols; using Thrift.Transports; using Thrift.Transports.Client; namespace ThriftTest { public class TestClient { private class TestParams { public int numIterations = 1; public IPAddress host = IPAddress.Any; public int port = 9090; public int numThreads = 1; public string url; public string pipe; public bool buffered; public bool framed; public string protocol; public bool encrypted = false; internal void Parse( List<string> args) { for (var i = 0; i < args.Count; ++i) { if (args[i] == "-u") { url = args[++i]; } else if (args[i] == "-n") { numIterations = Convert.ToInt32(args[++i]); } else if (args[i].StartsWith("--pipe=")) { pipe = args[i].Substring(args[i].IndexOf("=") + 1); Console.WriteLine("Using named pipes transport"); } else if (args[i].StartsWith("--host=")) { // check there for ipaddress host = new IPAddress(Encoding.Unicode.GetBytes(args[i].Substring(args[i].IndexOf("=") + 1))); } else if (args[i].StartsWith("--port=")) { port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1)); } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { buffered = true; Console.WriteLine("Using buffered sockets"); } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { framed = true; Console.WriteLine("Using framed transport"); } else if (args[i] == "-t") { numThreads = Convert.ToInt32(args[++i]); } else if (args[i] == "--binary" || args[i] == "--protocol=binary") { protocol = "binary"; Console.WriteLine("Using binary protocol"); } else if (args[i] == "--compact" || args[i] == "--protocol=compact") { protocol = "compact"; Console.WriteLine("Using compact protocol"); } else if (args[i] == "--json" || args[i] == "--protocol=json") { protocol = "json"; Console.WriteLine("Using JSON protocol"); } else if (args[i] == "--ssl") { encrypted = true; Console.WriteLine("Using encrypted transport"); } else { //throw new ArgumentException(args[i]); } } } private static X509Certificate2 GetClientCert() { var clientCertName = "client.p12"; var possiblePaths = new List<string> { "../../../keys/", "../../keys/", "../keys/", "keys/", }; string existingPath = null; foreach (var possiblePath in possiblePaths) { var path = Path.GetFullPath(possiblePath + clientCertName); if (File.Exists(path)) { existingPath = path; break; } } if (string.IsNullOrEmpty(existingPath)) { throw new FileNotFoundException($"Cannot find file: {clientCertName}"); } var cert = new X509Certificate2(existingPath, "thrift"); return cert; } public TClientTransport CreateTransport() { if (url == null) { // endpoint transport TClientTransport trans = null; if (pipe != null) { trans = new TNamedPipeClientTransport(pipe); } else { if (encrypted) { var cert = GetClientCert(); if (cert == null || !cert.HasPrivateKey) { throw new InvalidOperationException("Certificate doesn't contain private key"); } trans = new TTlsSocketClientTransport(host, port, 0, cert, (sender, certificate, chain, errors) => true, null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12); } else { trans = new TSocketClientTransport(host, port); } } // layered transport if (buffered) { trans = new TBufferedClientTransport(trans); } if (framed) { trans = new TFramedClientTransport(trans); } return trans; } return new THttpClientTransport(new Uri(url), null); } public TProtocol CreateProtocol(TClientTransport transport) { if (protocol == "compact") { return new TCompactProtocol(transport); } if (protocol == "json") { return new TJsonProtocol(transport); } return new TBinaryProtocol(transport); } } private const int ErrorBaseTypes = 1; private const int ErrorStructs = 2; private const int ErrorContainers = 4; private const int ErrorExceptions = 8; private const int ErrorUnknown = 64; private class ClientTest { private readonly TClientTransport transport; private readonly ThriftTest.Client client; private readonly int numIterations; private bool done; public int ReturnCode { get; set; } public ClientTest(TestParams param) { transport = param.CreateTransport(); client = new ThriftTest.Client(param.CreateProtocol(transport)); numIterations = param.numIterations; } public void Execute() { var token = CancellationToken.None; if (done) { Console.WriteLine("Execute called more than once"); throw new InvalidOperationException(); } for (var i = 0; i < numIterations; i++) { try { if (!transport.IsOpen) { transport.OpenAsync(token).GetAwaiter().GetResult(); } } catch (TTransportException ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Connect failed: " + ex.Message); ReturnCode |= ErrorUnknown; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); continue; } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Connect failed: " + ex.Message); ReturnCode |= ErrorUnknown; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); continue; } try { ReturnCode |= ExecuteClientTestAsync(client).GetAwaiter().GetResult(); ; } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); ReturnCode |= ErrorUnknown; } } try { transport.Close(); } catch (Exception ex) { Console.WriteLine("Error while closing transport"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } done = true; } } internal static void PrintOptionsHelp() { Console.WriteLine("Client options:"); Console.WriteLine(" -u <URL>"); Console.WriteLine(" -t <# of threads to run> default = 1"); Console.WriteLine(" -n <# of iterations> per thread"); Console.WriteLine(" --pipe=<pipe name>"); Console.WriteLine(" --host=<IP address>"); Console.WriteLine(" --port=<port number>"); Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)"); Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)"); Console.WriteLine(" --ssl"); Console.WriteLine(); } public static int Execute(List<string> args) { try { var param = new TestParams(); try { param.Parse(args); } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Error while parsing arguments"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); return ErrorUnknown; } var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray(); //issue tests on separate threads simultaneously var threads = tests.Select(test => new Task(test.Execute)).ToArray(); var start = DateTime.Now; foreach (var t in threads) { t.Start(); } Task.WaitAll(threads); Console.WriteLine("Total time: " + (DateTime.Now - start)); Console.WriteLine(); return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2); } catch (Exception outerEx) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Unexpected error"); Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace); return ErrorUnknown; } } public static string BytesToHex(byte[] data) { return BitConverter.ToString(data).Replace("-", string.Empty); } public static byte[] PrepareTestData(bool randomDist) { var retval = new byte[0x100]; var initLen = Math.Min(0x100, retval.Length); // linear distribution, unless random is requested if (!randomDist) { for (var i = 0; i < initLen; ++i) { retval[i] = (byte)i; } return retval; } // random distribution for (var i = 0; i < initLen; ++i) { retval[i] = (byte)0; } var rnd = new Random(); for (var i = 1; i < initLen; ++i) { while (true) { var nextPos = rnd.Next() % initLen; if (retval[nextPos] == 0) { retval[nextPos] = (byte)i; break; } } } return retval; } public static async Task<int> ExecuteClientTestAsync(ThriftTest.Client client) { var token = CancellationToken.None; var returnCode = 0; Console.Write("testVoid()"); await client.testVoidAsync(token); Console.WriteLine(" = void"); Console.Write("testString(\"Test\")"); var s = await client.testStringAsync("Test", token); Console.WriteLine(" = \"" + s + "\""); if ("Test" != s) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(true)"); var t = await client.testBoolAsync((bool)true, token); Console.WriteLine(" = " + t); if (!t) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(false)"); var f = await client.testBoolAsync((bool)false, token); Console.WriteLine(" = " + f); if (f) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testByte(1)"); var i8 = await client.testByteAsync((sbyte)1, token); Console.WriteLine(" = " + i8); if (1 != i8) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI32(-1)"); var i32 = await client.testI32Async(-1, token); Console.WriteLine(" = " + i32); if (-1 != i32) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI64(-34359738368)"); var i64 = await client.testI64Async(-34359738368, token); Console.WriteLine(" = " + i64); if (-34359738368 != i64) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } // TODO: Validate received message Console.Write("testDouble(5.325098235)"); var dub = await client.testDoubleAsync(5.325098235, token); Console.WriteLine(" = " + dub); if (5.325098235 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testDouble(-0.000341012439638598279)"); dub = await client.testDoubleAsync(-0.000341012439638598279, token); Console.WriteLine(" = " + dub); if (-0.000341012439638598279 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } var binOut = PrepareTestData(true); Console.Write("testBinary(" + BytesToHex(binOut) + ")"); try { var binIn = await client.testBinaryAsync(binOut, token); Console.WriteLine(" = " + BytesToHex(binIn)); if (binIn.Length != binOut.Length) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } for (var ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) if (binIn[ofs] != binOut[ofs]) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } } catch (Thrift.TApplicationException ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } // binary equals? only with hashcode option enabled ... Console.WriteLine("Test CrazyNesting"); var one = new CrazyNesting(); var two = new CrazyNesting(); one.String_field = "crazy"; two.String_field = "crazy"; one.Binary_field = new byte[] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; if (typeof(CrazyNesting).GetMethod("Equals")?.DeclaringType == typeof(CrazyNesting)) { if (!one.Equals(two)) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorContainers; throw new Exception("CrazyNesting.Equals failed"); } } // TODO: Validate received message Console.Write("testStruct({\"Zero\", 1, -3, -5})"); var o = new Xtruct(); o.String_thing = "Zero"; o.Byte_thing = (sbyte)1; o.I32_thing = -3; o.I64_thing = -5; var i = await client.testStructAsync(o, token); Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}"); // TODO: Validate received message Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})"); var o2 = new Xtruct2(); o2.Byte_thing = (sbyte)1; o2.Struct_thing = o; o2.I32_thing = 5; var i2 = await client.testNestAsync(o2, token); i = i2.Struct_thing; Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}"); var mapout = new Dictionary<int, int>(); for (var j = 0; j < 5; j++) { mapout[j] = j - 10; } Console.Write("testMap({"); var first = true; foreach (var key in mapout.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapout[key]); } Console.Write("})"); var mapin = await client.testMapAsync(mapout, token); Console.Write(" = {"); first = true; foreach (var key in mapin.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapin[key]); } Console.WriteLine("}"); // TODO: Validate received message var listout = new List<int>(); for (var j = -2; j < 3; j++) { listout.Add(j); } Console.Write("testList({"); first = true; foreach (var j in listout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); var listin = await client.testListAsync(listout, token); Console.Write(" = {"); first = true; foreach (var j in listin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); //set // TODO: Validate received message var setout = new THashSet<int>(); for (var j = -2; j < 3; j++) { setout.Add(j); } Console.Write("testSet({"); first = true; foreach (int j in setout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); var setin = await client.testSetAsync(setout, token); Console.Write(" = {"); first = true; foreach (int j in setin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); Console.Write("testEnum(ONE)"); var ret = await client.testEnumAsync(Numberz.ONE, token); Console.WriteLine(" = " + ret); if (Numberz.ONE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(TWO)"); ret = await client.testEnumAsync(Numberz.TWO, token); Console.WriteLine(" = " + ret); if (Numberz.TWO != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(THREE)"); ret = await client.testEnumAsync(Numberz.THREE, token); Console.WriteLine(" = " + ret); if (Numberz.THREE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(FIVE)"); ret = await client.testEnumAsync(Numberz.FIVE, token); Console.WriteLine(" = " + ret); if (Numberz.FIVE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(EIGHT)"); ret = await client.testEnumAsync(Numberz.EIGHT, token); Console.WriteLine(" = " + ret); if (Numberz.EIGHT != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testTypedef(309858235082523)"); var uid = await client.testTypedefAsync(309858235082523L, token); Console.WriteLine(" = " + uid); if (309858235082523L != uid) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } // TODO: Validate received message Console.Write("testMapMap(1)"); var mm = await client.testMapMapAsync(1, token); Console.Write(" = {"); foreach (var key in mm.Keys) { Console.Write(key + " => {"); var m2 = mm[key]; foreach (var k2 in m2.Keys) { Console.Write(k2 + " => " + m2[k2] + ", "); } Console.Write("}, "); } Console.WriteLine("}"); // TODO: Validate received message var insane = new Insanity(); insane.UserMap = new Dictionary<Numberz, long>(); insane.UserMap[Numberz.FIVE] = 5000L; var truck = new Xtruct(); truck.String_thing = "Truck"; truck.Byte_thing = (sbyte)8; truck.I32_thing = 8; truck.I64_thing = 8; insane.Xtructs = new List<Xtruct>(); insane.Xtructs.Add(truck); Console.Write("testInsanity()"); var whoa = await client.testInsanityAsync(insane, token); Console.Write(" = {"); foreach (var key in whoa.Keys) { var val = whoa[key]; Console.Write(key + " => {"); foreach (var k2 in val.Keys) { var v2 = val[k2]; Console.Write(k2 + " => {"); var userMap = v2.UserMap; Console.Write("{"); if (userMap != null) { foreach (var k3 in userMap.Keys) { Console.Write(k3 + " => " + userMap[k3] + ", "); } } else { Console.Write("null"); } Console.Write("}, "); var xtructs = v2.Xtructs; Console.Write("{"); if (xtructs != null) { foreach (var x in xtructs) { Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, "); } } else { Console.Write("null"); } Console.Write("}"); Console.Write("}, "); } Console.Write("}, "); } Console.WriteLine("}"); sbyte arg0 = 1; var arg1 = 2; var arg2 = long.MaxValue; var multiDict = new Dictionary<short, string>(); multiDict[1] = "one"; var tmpMultiDict = new List<string>(); foreach (var pair in multiDict) tmpMultiDict.Add(pair.Key +" => "+ pair.Value); var arg4 = Numberz.FIVE; long arg5 = 5000000; Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + ",{" + string.Join(",", tmpMultiDict) + "}," + arg4 + "," + arg5 + ")"); var multiResponse = await client.testMultiAsync(arg0, arg1, arg2, multiDict, arg4, arg5, token); Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n"); try { Console.WriteLine("testException(\"Xception\")"); await client.testExceptionAsync("Xception", token); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"TException\")"); await client.testExceptionAsync("TException", token); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Thrift.TException) { // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"ok\")"); await client.testExceptionAsync("ok", token); // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception\", ...)"); await client.testMultiExceptionAsync("Xception", "ignore", token); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception2\", ...)"); await client.testMultiExceptionAsync("Xception2", "ignore", token); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception2 ex) { if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"success\", \"OK\")"); if ("OK" != (await client.testMultiExceptionAsync("success", "OK", token)).String_thing) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } var sw = new Stopwatch(); sw.Start(); Console.WriteLine("Test Oneway(1)"); await client.testOnewayAsync(1, token); sw.Stop(); if (sw.ElapsedMilliseconds > 1000) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("Test Calltime()"); var times = 50; sw.Reset(); sw.Start(); for (var k = 0; k < times; ++k) await client.testVoidAsync(token); sw.Stop(); Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times); return returnCode; } } }
// ----- // 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.Net; using System.Threading; using Matrix.Common.Core; using Matrix.Common.Core.Collections; using Matrix.Common.Sockets.Common; using Matrix.Common.Sockets.Core; using Matrix.Framework.MessageBus.Core; using Matrix.Framework.MessageBus.Net.Messages; namespace Matrix.Framework.MessageBus.Net { /// <summary> /// Extends the message bus to allow it to connect to a servering message bus. /// </summary> public class ClientMessageBus : global::Matrix.Framework.MessageBus.Core.MessageBus { SocketMessageClient _socketClient; int _pendingMessageId = 0; protected int PendingMessageId { get { return Interlocked.Increment(ref _pendingMessageId); } } public ClientAccessControl AccessControl { get; protected set; } HotSwapDictionary<Guid, ClientId> _originalServerClientsHotSwap = new HotSwapDictionary<Guid, ClientId>(); HotSwapDictionary<Guid, Type> _originalServerClientsTypesHotSwap = new HotSwapDictionary<Guid, Type>(); HotSwapDictionary<Guid, List<string>> _originalServerClientsSourcesTypesHotNamesSwap = new HotSwapDictionary<Guid, List<string>>(); public bool IsConnected { get { SocketMessageClient socketClient = _socketClient; if (socketClient == null) { return false; } return socketClient.IsConnected; } } public delegate void MessageUpdateDelegate(ClientMessageBus client, object message); public event MessageUpdateDelegate MessageUpdateEvent; /// <summary> /// Constructor. /// </summary> /// <param name="nameAppending">Additional part to the default named bus (name is {endpoint} + "MessageBus.Proxy" + {appending}).</param> /// <param name="accessControl">Control acces to remote server (user and pass if required), pass null for no login.</param> public ClientMessageBus(IPEndPoint endpoint, string nameAppendix, ClientAccessControl accessControl) : base(endpoint.ToString() + " MessageBus.Proxy " + nameAppendix) { AccessControl = accessControl; _socketClient = new SocketMessageClient(endpoint, base.Serializer); _socketClient.ConnectedEvent += new SocketCommunicator.HelperUpdateDelegate(_messageClient_ConnectedEvent); _socketClient.DisconnectedEvent += new SocketCommunicator.HelperUpdateDelegate(_messageClient_DisconnectedEvent); _socketClient.MessageReceivedEvent += new SocketCommunicator.MessageUpdateDelegate(_messageClient_MessageReceivedEvent); _socketClient.SendAsyncCompleteEvent += new SocketCommunicator.AsyncMessageSendDelegate(_messageClient_SendAsyncCompleteEvent); _socketClient.AutoReconnect = true; _socketClient.KeepAlive = true; base.ClientAddedEvent += new global::Matrix.Framework.MessageBus.Core.MessageBusClientUpdateDelegate(MessageBusNetClient_ClientAddedEvent); base.ClientRemovedEvent += new global::Matrix.Framework.MessageBus.Core.MessageBusClientRemovedDelegate(MessageBusNetClient_ClientRemovedEvent); ApplicationLifetimeHelper.ApplicationClosingEvent += new CommonHelper.DefaultDelegate(ApplicationLifetimeHelper_ApplicationClosingEvent); } void ApplicationLifetimeHelper_ApplicationClosingEvent() { ToServer(new StateUpdateMessage() { MessageId = PendingMessageId, State = StateUpdateMessage.StateEnum.Shutdown, RequestResponse = false }, null); Thread.Sleep(100); } public override void Dispose() { ApplicationLifetimeHelper.ApplicationClosingEvent -= new CommonHelper.DefaultDelegate(ApplicationLifetimeHelper_ApplicationClosingEvent); base.ClientAddedEvent -= new global::Matrix.Framework.MessageBus.Core.MessageBusClientUpdateDelegate(MessageBusNetClient_ClientAddedEvent); base.ClientRemovedEvent -= new global::Matrix.Framework.MessageBus.Core.MessageBusClientRemovedDelegate(MessageBusNetClient_ClientRemovedEvent); base.Dispose(); SocketMessageClient messageClient = _socketClient; _socketClient = null; if (messageClient != null) { messageClient.ConnectedEvent -= new SocketCommunicator.HelperUpdateDelegate(_messageClient_ConnectedEvent); messageClient.DisconnectedEvent -= new SocketCommunicator.HelperUpdateDelegate(_messageClient_DisconnectedEvent); messageClient.MessageReceivedEvent -= new SocketCommunicator.MessageUpdateDelegate(_messageClient_MessageReceivedEvent); messageClient.SendAsyncCompleteEvent -= new SocketCommunicator.AsyncMessageSendDelegate(_messageClient_SendAsyncCompleteEvent); messageClient.Dispose(); } } void MessageBusNetClient_ClientAddedEvent(global::Matrix.Framework.MessageBus.Core.IMessageBus messageBus, ClientId clientId) { SendClientsUpdate(); } void MessageBusNetClient_ClientRemovedEvent(global::Matrix.Framework.MessageBus.Core.IMessageBus messageBus, ClientId clientId, bool isPermanenet) { SendClientsUpdate(); } void _messageClient_SendAsyncCompleteEvent(SocketCommunicator helper, SocketCommunicator.AsyncMessageSendInfo info) { // Message sent to server. MessageUpdateDelegate del = MessageUpdateEvent; if (del != null) { del(this, info.Message); } } void _messageClient_MessageReceivedEvent(SocketCommunicator helper, object message) { if (message is EnvelopeMessage) { EnvelopeMessage envelopeMessage = (EnvelopeMessage)message; // Remove the remote message bus index association. envelopeMessage.Sender.LocalMessageBusIndex = ClientId.InvalidMessageBusClientIndex; foreach (ClientId id in envelopeMessage.Receivers) { // Decode the id. id.LocalMessageBusIndex = base.GetClientIndexByGuid(id.Guid); if (id.IsMessageBusIndexValid) { // Assign as a part of the local bus. id.MessageBus = this; if (DoSendToClient(envelopeMessage.Sender, id, envelopeMessage.Envelope, null) != SendToClientResultEnum.Success) { #if Matrix_Diagnostics InstanceMonitor.OperationError(string.Format("Failed to accept envelope message [{0}].", envelopeMessage.ToString())); #endif } } else { #if Matrix_Diagnostics InstanceMonitor.OperationError(string.Format("Failed to accept envelope message [{0}] due to unrecognized receiver id.", envelopeMessage.ToString())); #endif } } } else if (message is ClientsListMessage) {// Received client update from server. ClientsListMessage listMessage = (ClientsListMessage)message; int jef = 0; foreach(var client in listMessage.Ids) { Console.WriteLine("Incoming client id: "+client+" Source type: "+listMessage.SourcesTypes[jef]); jef++; } List<ClientId> existingIds = new List<ClientId>(); lock (_syncRoot) { existingIds.AddRange(_originalServerClientsHotSwap.Values); _originalServerClientsHotSwap.Clear(); _originalServerClientsTypesHotSwap.Clear(); _originalServerClientsSourcesTypesHotNamesSwap.Clear(); // Preprocess Ids, by assigning them new indeces and adding to the local message bus register. for (int i = 0; i < listMessage.Ids.Count; i++) { // Add an original copy to the list. _originalServerClientsHotSwap.Add(listMessage.Ids[i].Guid, listMessage.Ids[i]); _originalServerClientsTypesHotSwap.Add(listMessage.Ids[i].Guid, listMessage.Types[i]); _originalServerClientsSourcesTypesHotNamesSwap.Add(listMessage.Ids[i].Guid, listMessage.SourcesTypes[i]); // Add the client to a new spot. //_clientsHotSwap.Add(null); //int messageBusIndex = _clientsHotSwap.Count - 1; // This type of assignment will also work with multiple entries. // This performs an internal hotswap. //_guidToIndexHotSwap[id.Guid] = messageBusIndex; // Also add to this classes collection. //_localToRemoteId[messageBusIndex] = id; } } foreach (ClientId id in listMessage.Ids) { existingIds.Remove(id); RaiseClientAddedEvent(id); } // Raise for any that were removed. foreach (ClientId id in existingIds) { RaiseClientRemovedEvent(id, true); } } else if (message is RequestClientListUpdateMessage) { SendClientsUpdate(); } else if (message is ClientUpdateMessage) { ClientUpdateMessage updateMessage = (ClientUpdateMessage)message; if (_originalServerClientsHotSwap.ContainsKey(updateMessage.ClientId.Guid)) { RaiseClientUpdateEvent(updateMessage.ClientId); } else { #if Matrix_Diagnostics InstanceMonitor.OperationError(string.Format("Failed to raise update event for client [{0}], since client not found.", updateMessage.ClientId.ToString())); #endif } } else if (message is StateUpdateMessage) { RaiseCounterPartyUpdateEvent("Server", ((StateUpdateMessage)message).State.ToString()); } else { #if Matrix_Diagnostics InstanceMonitor.Warning(string.Format("Message [{0}] not recognized.", message.GetType().Name)); #endif } } void _messageClient_DisconnectedEvent(SocketCommunicator helper) { ICollection<ClientId> ids = _originalServerClientsHotSwap.Values; _originalServerClientsHotSwap.Clear(); //lock (_syncRoot) //{ // _localToRemoteId.Clear(); //} // Removing all server clients. foreach (ClientId id in ids) { // Notify of clients removal, with non permanent remove, since they may later be restored. RaiseClientRemovedEvent(id, false); } } void _messageClient_ConnectedEvent(SocketCommunicator helper) { // Send an update of the clients to server. if (_socketClient == helper) { SendAccessControlMessage(); SendClientsUpdate(); } } bool SendAccessControlMessage() { ClientAccessControl accessControl = AccessControl; if (accessControl == null) { return true; } return ToServer(accessControl.ObtainClientSideMessage(), null); } /// <summary> /// Helper, sends an update with all the local clients ids to the server. /// </summary> bool SendClientsUpdate() { ClientsListMessage message = new ClientsListMessage(); foreach (MessageBusClient client in Clients) { message.Ids.Add(client.Id); message.AddType(client.GetType(), client.OptionalSourceType); } return ToServer(message, null); } /// <summary> /// Helper, send message to server. /// </summary> bool ToServer(Message message, TimeSpan? requestConfirmTimeout) { SocketMessageClient messageClient = _socketClient; if (messageClient == null) { return false; } message.MessageId = PendingMessageId; return messageClient.SendAsync(message, requestConfirmTimeout) != SocketCommunicator.InvalidSendIndex; } public override List<ClientId> GetAllClientsIds() { List<ClientId> result = base.GetAllClientsIds(); foreach (KeyValuePair<Guid, ClientId> pair in _originalServerClientsHotSwap) { if (pair.Value != null) { result.Add(pair.Value); } } return result; } /// <summary> /// /// </summary> public override bool ContainsClient(ClientId clientId) { if (base.ContainsClient(clientId)) { return true; } // Check agains the guid, since the Id instance may be different (also with different message bus id). return _originalServerClientsHotSwap.ContainsKey(clientId.Guid); } protected override void client_UpdateEvent(MessageBusClient client) { base.client_UpdateEvent(client); // Also send this notification to server. ToServer(new ClientUpdateMessage() { ClientId = client.Id, MessageId = PendingMessageId, RequestResponse = false }, null); } /// <summary> /// /// </summary> /// <param name="requestConfirm">Only valid for remote clients, since all local calls are confirmed or denied by default.</param> protected override SendToClientResultEnum DoSendToClient(ClientId senderId, ClientId receiverId, Envelope envelope, TimeSpan? requestConfirmTimeout) { if (receiverId.IsMessageBusIndexValid && receiverId.MessageBus == this) {// Seems to be a local client Id. SendToClientResultEnum result = base.DoSendToClient(senderId, receiverId, envelope, requestConfirmTimeout); if (result != SendToClientResultEnum.ClientNotFound) { return result; } } // Receiver was not local in parrent, try remote. if (IsConnected == false) { return SendToClientResultEnum.Failure; } EnvelopeMessage message = new EnvelopeMessage() { Envelope = envelope, Receivers = new ClientId[] { receiverId }, Sender = senderId }; return ToServer(message, requestConfirmTimeout) ? SendToClientResultEnum.Success : SendToClientResultEnum.Failure; } /// <summary> /// This will transport the envelope to the server, if it can. /// </summary> protected override Outcomes DoSend(ClientId senderId, IEnumerable<ClientId> receiversIds, Envelope envelope, TimeSpan? requestConfirmTimeout, bool showErrorsDiagnostics) { bool result = true; foreach (ClientId id in receiversIds) { result = result && DoSendToClient(senderId, id, envelope, requestConfirmTimeout) == SendToClientResultEnum.Success; } return result ? Outcomes.Success : Outcomes.Failure; } public override Type GetClientType(ClientId clientId) { if (clientId.IsMessageBusIndexValid && clientId.MessageBus == this) {// Seems to be a local client Id. return base.GetClientType(clientId); } Type value; if (_originalServerClientsTypesHotSwap.TryGetValue(clientId.Guid, out value)) { return value; } return null; } public override List<string> GetClientSourceTypes(ClientId clientId) { if (clientId.IsMessageBusIndexValid && clientId.MessageBus == this) {// Seems to be a local client Id. return base.GetClientSourceTypes(clientId); } List<string> names; if (_originalServerClientsSourcesTypesHotNamesSwap.TryGetValue(clientId.Guid, out names)) { return names; } return null; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.IO; using System.Net.Http; using System.Runtime; using System.Xml; public static class ByteStreamMessage { public static Message CreateMessage(Stream stream) { if (stream == null) { throw FxTrace.Exception.ArgumentNull("stream"); } return CreateMessage(stream, XmlDictionaryReaderQuotas.Max, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } public static Message CreateMessage(ArraySegment<byte> buffer) { return CreateMessage(buffer, null); } public static Message CreateMessage(ArraySegment<byte> buffer, BufferManager bufferManager) { if (buffer.Array == null) { throw FxTrace.Exception.ArgumentNull("buffer.Array", SR.ArgumentPropertyShouldNotBeNullError("buffer.Array")); } ByteStreamBufferedMessageData data = new ByteStreamBufferedMessageData(buffer, bufferManager); return CreateMessage(data, XmlDictionaryReaderQuotas.Max, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } internal static Message CreateMessage(Stream stream, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { return new InternalByteStreamMessage(stream, quotas, moveBodyReaderToContent); } internal static Message CreateMessage(HttpRequestMessage httpRequestMessage, XmlDictionaryReaderQuotas quotas) { return new InternalByteStreamMessage(httpRequestMessage, quotas, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } internal static Message CreateMessage(HttpResponseMessage httpResponseMessage, XmlDictionaryReaderQuotas quotas) { return new InternalByteStreamMessage(httpResponseMessage, quotas, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } internal static Message CreateMessage(ByteStreamBufferedMessageData bufferedMessageData, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { return new InternalByteStreamMessage(bufferedMessageData, quotas, moveBodyReaderToContent); } internal static bool IsInternalByteStreamMessage(Message message) { Fx.Assert(message != null, "message should not be null"); return message is InternalByteStreamMessage; } class InternalByteStreamMessage : Message { BodyWriter bodyWriter; MessageHeaders headers; MessageProperties properties; XmlByteStreamReader reader; /// <summary> /// If set to true, OnGetReaderAtBodyContents() calls MoveToContent() on the reader before returning it. /// If set to false, the reader is positioned on None, just before the root element of the body message. /// </summary> /// <remarks> /// We use this flag to preserve compatibility between .net 4.0 (or previous) and .net 4.5 (or later). /// /// In .net 4.0: /// - WebMessageEncodingBindingElement uses a raw encoder, different than ByteStreamMessageEncoder. /// - ByteStreamMessageEncodingBindingElement uses the ByteStreamMessageEncoder. /// - When the WebMessageEncodingBindingElement is used, the Message.GetReaderAtBodyContents() method returns /// an XmlDictionaryReader positioned initially on content (the root element of the xml); that's because MoveToContent() is called /// on the reader before it's returned. /// - When the ByteStreamMessageEncodingBindingElement is used, the Message.GetReaderAtBodyContents() method returns an /// XmlDictionaryReader positioned initially on None (just before the root element). /// /// In .net 4.5: /// - Both WebMessageEncodingBindingElement and ByteStreamMessageEncodingBindingElement use the ByteStreamMessageEncoder. /// - So we need the ByteStreamMessageEncoder to call MoveToContent() when used by WebMessageEncodingBindingElement, and not do so /// when used by the ByteStreamMessageEncodingBindingElement. /// - Preserving the compatibility with 4.0 is important especially because 4.5 is an in-place upgrade of 4.0. /// /// See 252277 @ CSDMain for other info. /// </remarks> bool moveBodyReaderToContent; public InternalByteStreamMessage(ByteStreamBufferedMessageData bufferedMessageData, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = new BufferedBodyWriter(bufferedMessageData); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = new XmlBufferedByteStreamReader(bufferedMessageData, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public InternalByteStreamMessage(Stream stream, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write on the same stream. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = StreamedBodyWriter.Create(stream); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = XmlStreamedByteStreamReader.Create(stream, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public InternalByteStreamMessage(HttpRequestMessage httpRequestMessage, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { Fx.Assert(httpRequestMessage != null, "The 'httpRequestMessage' parameter should not be null."); // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write on the same stream. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = StreamedBodyWriter.Create(httpRequestMessage); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = XmlStreamedByteStreamReader.Create(httpRequestMessage, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public InternalByteStreamMessage(HttpResponseMessage httpResponseMessage, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { Fx.Assert(httpResponseMessage != null, "The 'httpResponseMessage' parameter should not be null."); // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write on the same stream. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = StreamedBodyWriter.Create(httpResponseMessage); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = XmlStreamedByteStreamReader.Create(httpResponseMessage, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } InternalByteStreamMessage(ByteStreamBufferedMessageData messageData, MessageHeaders headers, MessageProperties properties, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { this.headers = new MessageHeaders(headers); this.properties = new MessageProperties(properties); this.bodyWriter = new BufferedBodyWriter(messageData); this.reader = new XmlBufferedByteStreamReader(messageData, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public override MessageHeaders Headers { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return this.headers; } } public override bool IsEmpty { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return false; } } public override bool IsFault { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return false; } } public override MessageProperties Properties { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return this.properties; } } public override MessageVersion Version { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return MessageVersion.None; } } protected override void OnBodyToString(XmlDictionaryWriter writer) { if (this.bodyWriter.IsBuffered) { bodyWriter.WriteBodyContents(writer); } else { writer.WriteString(SR.MessageBodyIsStream); } } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } ex = e; } try { if (properties != null) { properties.Dispose(); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ex == null) { ex = e; } } try { if (reader != null) { reader.Close(); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ex == null) { ex = e; } } if (ex != null) { throw FxTrace.Exception.AsError(ex); } this.bodyWriter = null; } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { BufferedBodyWriter bufferedBodyWriter; if (this.bodyWriter.IsBuffered) { // Can hand this off in buffered case without making a new one. bufferedBodyWriter = (BufferedBodyWriter)this.bodyWriter; } else { bufferedBodyWriter = (BufferedBodyWriter)this.bodyWriter.CreateBufferedCopy(maxBufferSize); } // Protected by Message state to be called only once. this.bodyWriter = null; return new ByteStreamMessageBuffer(bufferedBodyWriter.MessageData, this.headers, this.properties, this.reader.Quotas, this.moveBodyReaderToContent); } protected override T OnGetBody<T>(XmlDictionaryReader reader) { Fx.Assert(reader is XmlByteStreamReader, "reader should be XmlByteStreamReader"); if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } Type typeT = typeof(T); if (typeof(Stream) == typeT) { Stream stream = (reader as XmlByteStreamReader).ToStream(); reader.Close(); return (T)(object)stream; } else if (typeof(byte[]) == typeT) { byte[] buffer = (reader as XmlByteStreamReader).ToByteArray(); reader.Close(); return (T)(object)buffer; } throw FxTrace.Exception.AsError( new NotSupportedException(SR.ByteStreamMessageGetTypeNotSupported(typeT.FullName))); } protected override XmlDictionaryReader OnGetReaderAtBodyContents() { XmlDictionaryReader r = this.reader; this.reader = null; if ((r != null) && this.moveBodyReaderToContent) { r.MoveToContent(); } return r; } protected override IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { WriteMessagePreamble(writer); return new OnWriteMessageAsyncResult(writer, this, callback, state); } protected override void OnEndWriteMessage(IAsyncResult result) { OnWriteMessageAsyncResult.End(result); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { this.bodyWriter.WriteBodyContents(writer); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return this.bodyWriter.BeginWriteBodyContents(writer, callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { this.bodyWriter.EndWriteBodyContents(result); } class OnWriteMessageAsyncResult : AsyncResult { InternalByteStreamMessage message; XmlDictionaryWriter writer; public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, InternalByteStreamMessage message, AsyncCallback callback, object state) : base(callback, state) { this.message = message; this.writer = writer; IAsyncResult result = this.message.OnBeginWriteBodyContents(this.writer, PrepareAsyncCompletion(HandleWriteBodyContents), this); bool completeSelf = SyncContinue(result); if (completeSelf) { this.Complete(true); } } static bool HandleWriteBodyContents(IAsyncResult result) { OnWriteMessageAsyncResult thisPtr = (OnWriteMessageAsyncResult)result.AsyncState; thisPtr.message.OnEndWriteBodyContents(result); thisPtr.message.WriteMessagePostamble(thisPtr.writer); return true; } public static void End(IAsyncResult result) { AsyncResult.End<OnWriteMessageAsyncResult>(result); } } class BufferedBodyWriter : BodyWriter { ByteStreamBufferedMessageData bufferedMessageData; public BufferedBodyWriter(ByteStreamBufferedMessageData bufferedMessageData) : base(true) { this.bufferedMessageData = bufferedMessageData; } internal ByteStreamBufferedMessageData MessageData { get { return bufferedMessageData; } } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { // Never called because when copying a Buffered message, we simply hand off the existing BodyWriter // to the new message. Fx.Assert(false, "This is never called"); return null; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty); writer.WriteBase64(this.bufferedMessageData.Buffer.Array, this.bufferedMessageData.Buffer.Offset, this.bufferedMessageData.Buffer.Count); writer.WriteEndElement(); } } abstract class StreamedBodyWriter : BodyWriter { private StreamedBodyWriter() : base(false) { } public static StreamedBodyWriter Create(Stream stream) { return new StreamBasedStreamedBodyWriter(stream); } public static StreamedBodyWriter Create(HttpRequestMessage httpRequestMessage) { return new HttpRequestMessageStreamedBodyWriter(httpRequestMessage); } public static StreamedBodyWriter Create(HttpResponseMessage httpResponseMessage) { return new HttpResponseMessageStreamedBodyWriter(httpResponseMessage); } // OnCreateBufferedCopy / OnWriteBodyContents can only be called once - protected by state on Message (either copied or written once) protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { using (BufferManagerOutputStream bufferedStream = new BufferManagerOutputStream(SR.MaxReceivedMessageSizeExceeded("{0}"), maxBufferSize)) { using (XmlDictionaryWriter writer = new XmlByteStreamWriter(bufferedStream, true)) { OnWriteBodyContents(writer); writer.Flush(); int size; byte[] bytesArray = bufferedStream.ToArray(out size); ByteStreamBufferedMessageData bufferedMessageData = new ByteStreamBufferedMessageData(new ArraySegment<byte>(bytesArray, 0, size)); return new BufferedBodyWriter(bufferedMessageData); } } } // OnCreateBufferedCopy / OnWriteBodyContents can only be called once - protected by state on Message (either copied or written once) protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty); writer.WriteValue(new ByteStreamStreamProvider(this.GetStream())); writer.WriteEndElement(); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return new WriteBodyContentsAsyncResult(writer, this.GetStream(), callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { WriteBodyContentsAsyncResult.End(result); } protected abstract Stream GetStream(); class ByteStreamStreamProvider : IStreamProvider { Stream stream; internal ByteStreamStreamProvider(Stream stream) { this.stream = stream; } public Stream GetStream() { return stream; } public void ReleaseStream(Stream stream) { //Noop } } class WriteBodyContentsAsyncResult : AsyncResult { XmlDictionaryWriter writer; public WriteBodyContentsAsyncResult(XmlDictionaryWriter writer, Stream stream, AsyncCallback callback, object state) : base(callback, state) { this.writer = writer; this.writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty); IAsyncResult result = this.writer.WriteValueAsync(new ByteStreamStreamProvider(stream)).AsAsyncResult(PrepareAsyncCompletion(HandleWriteBodyContents), this); bool completeSelf = SyncContinue(result); // Note: The current task implementation hard codes the "IAsyncResult.CompletedSynchronously" property to false, so this fast path will never // be hit, and we will always hop threads. CSDMain #210220 if (completeSelf) { this.Complete(true); } } static bool HandleWriteBodyContents(IAsyncResult result) { WriteBodyContentsAsyncResult thisPtr = (WriteBodyContentsAsyncResult)result.AsyncState; thisPtr.writer.WriteEndElement(); return true; } public static void End(IAsyncResult result) { AsyncResult.End<WriteBodyContentsAsyncResult>(result); } } class StreamBasedStreamedBodyWriter : StreamedBodyWriter { private Stream stream; public StreamBasedStreamedBodyWriter(Stream stream) { this.stream = stream; } protected override Stream GetStream() { return this.stream; } } class HttpRequestMessageStreamedBodyWriter : StreamedBodyWriter { private HttpRequestMessage httpRequestMessage; public HttpRequestMessageStreamedBodyWriter(HttpRequestMessage httpRequestMessage) { Fx.Assert(httpRequestMessage != null, "The 'httpRequestMessage' parameter should not be null."); this.httpRequestMessage = httpRequestMessage; } protected override Stream GetStream() { HttpContent content = this.httpRequestMessage.Content; if (content != null) { return content.ReadAsStreamAsync().Result; } return new MemoryStream(EmptyArray<byte>.Instance); } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { HttpContent content = this.httpRequestMessage.Content; if (content != null) { content.LoadIntoBufferAsync(maxBufferSize).Wait(); } return base.OnCreateBufferedCopy(maxBufferSize); } } class HttpResponseMessageStreamedBodyWriter : StreamedBodyWriter { private HttpResponseMessage httpResponseMessage; public HttpResponseMessageStreamedBodyWriter(HttpResponseMessage httpResponseMessage) { Fx.Assert(httpResponseMessage != null, "The 'httpResponseMessage' parameter should not be null."); this.httpResponseMessage = httpResponseMessage; } protected override Stream GetStream() { HttpContent content = this.httpResponseMessage.Content; if (content != null) { return content.ReadAsStreamAsync().Result; } return new MemoryStream(EmptyArray<byte>.Instance); } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { HttpContent content = this.httpResponseMessage.Content; if (content != null) { content.LoadIntoBufferAsync(maxBufferSize).Wait(); } return base.OnCreateBufferedCopy(maxBufferSize); } } } class ByteStreamMessageBuffer : MessageBuffer { bool closed; MessageHeaders headers; ByteStreamBufferedMessageData messageData; MessageProperties properties; XmlDictionaryReaderQuotas quotas; bool moveBodyReaderToContent; object thisLock = new object(); public ByteStreamMessageBuffer(ByteStreamBufferedMessageData messageData, MessageHeaders headers, MessageProperties properties, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) : base() { this.messageData = messageData; this.headers = new MessageHeaders(headers); this.properties = new MessageProperties(properties); this.quotas = new XmlDictionaryReaderQuotas(); quotas.CopyTo(this.quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; this.messageData.Open(); } public override int BufferSize { get { return this.messageData.Buffer.Count; } } object ThisLock { get { return this.thisLock; } } public override void Close() { lock (ThisLock) { if (!closed) { closed = true; this.headers = null; if (properties != null) { properties.Dispose(); properties = null; } this.messageData.Close(); this.messageData = null; this.quotas = null; } } } public override Message CreateMessage() { lock (ThisLock) { if (closed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return new InternalByteStreamMessage(this.messageData, this.headers, this.properties, this.quotas, this.moveBodyReaderToContent); } } } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Web.Routing { using System; using System.Net; using System.Web; using System.Linq; using System.Web.Hosting; using System.Web.Routing; using System.Web.WebPages; using Adxstudio.Xrm.AspNet.Cms; using Microsoft.Xrm.Client; using Adxstudio.Xrm.Cms; using Microsoft.Xrm.Portal; using Microsoft.Xrm.Portal.Web; using Microsoft.Xrm.Portal.Configuration; using Adxstudio.Xrm.Web; /// <summary> /// Handles requests to portal <see cref="Entity"/> objects. /// </summary> /// <seealso cref="PortalRoutingModule"/> public class PortalRouteHandler : Microsoft.Xrm.Portal.Web.Routing.PortalRouteHandler { private const string DefaultWebTemplate = "~/Pages/WebTemplate.aspx"; private const string WebTemplateWithoutValidation = "~/Pages/WebTemplateNoValidation.aspx"; private const string DisableValidationSiteSetting = "DisableValidationWebTemplate"; private readonly string[] _redirectedEntities = { "adx_webpage", "adx_communityforum", "adx_communityforumthread", "adx_blog", "adx_blogpost" }; /// <summary> /// Initialize class /// </summary> /// <param name="portalName"></param> public PortalRouteHandler(string portalName) : base(portalName) { } /// <summary> /// Provides the object that processes the request. /// </summary> /// <param name="requestContext">An object that encapsulates information about the request.</param> /// <returns></returns> public override IHttpHandler GetHttpHandler(RequestContext requestContext) { string routeUrl = string.Empty; try { Route route = (System.Web.Routing.Route)requestContext.RouteData.Route; routeUrl = route.Url; } catch { } ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, string.Format("GetHttpHandler route=[{0}] ", routeUrl)); // apply the current SiteMapNode to the OWIN environment var node = GetNode(requestContext); if (node != null) { requestContext.Set(node); } // Note: prior to this next call, PortalContext is null. var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName, requestContext); portal = OnPortalLoaded(requestContext, portal); if (portal == null) return null; AsyncTracking.TrackRequest(requestContext.HttpContext); var isInvalidNode = portal.Entity == null || portal.Path == null; // there's nothing else we can really do--we'll exit with a bare-bones 404. if (isInvalidNode) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "FindSiteMapNode failed to find a non-null CrmSiteMapNode. Responding with a basic 404."); RenderNotFound(requestContext); return null; } if (portal.StatusCode == HttpStatusCode.NotFound) { var response = requestContext.HttpContext.Response; response.StatusCode = (int)HttpStatusCode.NotFound; } else if (portal.StatusCode == HttpStatusCode.Forbidden) { var response = requestContext.HttpContext.Response; response.StatusCode = (int)HttpStatusCode.Forbidden; } IHttpHandler handler; if (TryCreateHandler(portal, out handler)) { return handler; } if (node?.Entity?.Attributes != null && node.Entity.Attributes.ContainsKey("adx_alloworigin")) { var allowOrigin = node.Entity["adx_alloworigin"] as string; Web.Extensions.SetAccessControlAllowOriginHeader(requestContext.HttpContext, allowOrigin); } // remove the querystring var rewritePath = portal.Path; var index = rewritePath.IndexOf("?"); var path = index > -1 ? rewritePath.Substring(0, index) : rewritePath; DisplayInfo displayInfo; if (string.Equals(path, DefaultWebTemplate, StringComparison.OrdinalIgnoreCase) && requestContext.HttpContext.GetSiteSetting<bool>(DisableValidationSiteSetting)) { path = WebTemplateWithoutValidation; } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Current path: {0}", path)); if (TryGetDisplayModeInfoForPath(path, requestContext.HttpContext, out displayInfo)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Found displayModeInfo={0} for path", displayInfo.DisplayMode.DisplayModeId)); return displayInfo.FilePath == null ? null : CreateHandlerFromVirtualPath(displayInfo.FilePath); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Unable to get DisplayModeInfo for adx_pagetemplate with rewrite path"); return path == null ? null : CreateHandlerFromVirtualPath(path); } protected override bool TryCreateHandler(IPortalContext portal, out IHttpHandler handler) { var routeHandlerProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<IPortalRouteHandlerProvider>(); return routeHandlerProvider.TryCreateHandler(portal, out handler); } protected override IPortalContext OnPortalLoaded(RequestContext requestContext, IPortalContext portal) { if (portal == null) throw new ArgumentNullException("portal"); if (portal.Entity != null && _redirectedEntities.Contains(portal.Entity.LogicalName)) { // Check if we need to follow any rules with regards to Language Code prefix in URL (only applies if multi-language is enabled) var contextLanguageInfo = requestContext.HttpContext.GetContextLanguageInfo(); if (contextLanguageInfo.IsCrmMultiLanguageEnabled) { bool needRedirect = requestContext.HttpContext.Request.HttpMethod == WebRequestMethods.Http.Get && ((ContextLanguageInfo.DisplayLanguageCodeInUrl != contextLanguageInfo.RequestUrlHasLanguageCode) || contextLanguageInfo.ContextLanguage.UsedAsFallback); if (needRedirect) { string redirectPath = contextLanguageInfo.FormatUrlWithLanguage(); ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "OnPortalLoaded redirecting(1)"); requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Redirect; requestContext.HttpContext.Response.RedirectLocation = redirectPath; requestContext.HttpContext.Response.End(); return null; } } } var isInvalidNode = (portal.Entity == null || portal.Path == null); // If the node is null, isn't a CrmSiteMapNode, has no rewrite path, or is a 404, try other options. if (isInvalidNode || portal.StatusCode == HttpStatusCode.NotFound) { var redirectProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<IRedirectProvider>(); var context = requestContext.HttpContext; var clientUrl = new UrlBuilder(context.Request.Url); // Try matching user-defined redirects, and URL history--in that order. var redirectMatch = redirectProvider.Match(portal.Website.Id, clientUrl); // If we have a successful match, redirect. if (redirectMatch.Success) { ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "OnPortalLoaded redirecting(2)"); context.Trace.Write(GetType().FullName, @"Redirecting path ""{0}"" to ""{1}""".FormatWith(clientUrl.Path, redirectMatch.Location)); context.Response.StatusCode = (int)redirectMatch.StatusCode; context.Response.RedirectLocation = redirectMatch.Location; context.Response.End(); return null; } } return base.OnPortalLoaded(requestContext, portal); } protected virtual bool TryGetDisplayModeInfoForPath(string path, HttpContextBase httpContext, out DisplayInfo displayInfo) { displayInfo = null; var displayModeProvider = DisplayModeProvider.Instance; if (displayModeProvider == null) { return false; } var displayModes = displayModeProvider.GetAvailableDisplayModesForContext(httpContext, null); foreach (var displayMode in displayModes) { displayInfo = displayMode.GetDisplayInfo(httpContext, path, VirtualPathExists); if (displayInfo != null) { return true; } } return false; } private bool VirtualPathExists(string virtualPath) { try { return HostingEnvironment.VirtualPathProvider.FileExists(virtualPath); } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Exception while checking existence of virtual path: {0}", e.ToString())); return false; } } internal static CrmSiteMapNode GetNode(RequestContext request) { if (request == null) return null; var path = request.RouteData.Values["path"] as string; path = FormatPath(path); ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, string.Format("path={0}", path)); var node = SiteMap.Provider.FindSiteMapNode(path) as CrmSiteMapNode; return node; } /// <summary> /// Formats a route path value so that it can be processed by the site map. /// Rules are: 1) if path is null or white space, then make it to be just a forward-slash. /// 2) else if path doesn't have a leading forward-slash, then insert leading forward-slash. /// 3) else just return path as is. /// </summary> /// <param name="rawPath">Raw route path value to format.</param> /// <returns>Route path value formatted so it can be processed by the site map.</returns> private static string FormatPath(string rawPath) { var forwardSlash = System.IO.Path.AltDirectorySeparatorChar.ToString(); return !string.IsNullOrWhiteSpace(rawPath) ? rawPath.StartsWith(forwardSlash) ? rawPath : forwardSlash + rawPath : forwardSlash; } } }
// 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.Text; using System.Diagnostics; using System.Collections.Generic; namespace System.Xml { internal partial class XmlWellFormedWriter : XmlWriter { // // Private types // class NamespaceResolverProxy : IXmlNamespaceResolver { private XmlWellFormedWriter _wfWriter; internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter) { _wfWriter = wfWriter; } IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { throw NotImplemented.ByDesign; } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return _wfWriter.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _wfWriter.LookupPrefix(namespaceName); } } partial struct ElementScope { internal int prevNSTop; internal string prefix; internal string localName; internal string namespaceUri; internal XmlSpace xmlSpace; internal string xmlLang; internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop) { this.prevNSTop = prevNSTop; this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.xmlSpace = (System.Xml.XmlSpace)(int)-1; this.xmlLang = null; } internal void WriteEndElement(XmlRawWriter rawWriter) { rawWriter.WriteEndElement(prefix, localName, namespaceUri); } internal void WriteFullEndElement(XmlRawWriter rawWriter) { rawWriter.WriteFullEndElement(prefix, localName, namespaceUri); } } enum NamespaceKind { Written, NeedToWrite, Implied, Special, } partial struct Namespace { internal string prefix; internal string namespaceUri; internal NamespaceKind kind; internal int prevNsIndex; internal void Set(string prefix, string namespaceUri, NamespaceKind kind) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.kind = kind; this.prevNsIndex = -1; } internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); if (null != rawWriter) { rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri); } else { if (prefix.Length == 0) { writer.WriteStartAttribute(string.Empty, XmlConst.NsXmlNs, XmlConst.ReservedNsXmlNs); } else { writer.WriteStartAttribute(XmlConst.NsXmlNs, prefix, XmlConst.ReservedNsXmlNs); } writer.WriteString(namespaceUri); writer.WriteEndAttribute(); } } } struct AttrName { internal string prefix; internal string namespaceUri; internal string localName; internal int prev; internal void Set(string prefix, string localName, string namespaceUri) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.prev = 0; } internal bool IsDuplicate(string prefix, string localName, string namespaceUri) { return ((this.localName == localName) && ((this.prefix == prefix) || (this.namespaceUri == namespaceUri))); } } enum SpecialAttribute { No = 0, DefaultXmlns, PrefixedXmlns, XmlSpace, XmlLang } partial class AttributeValueCache { enum ItemType { EntityRef, CharEntity, SurrogateCharEntity, Whitespace, String, StringChars, Raw, RawChars, ValueString, } class Item { internal ItemType type; internal object data; internal Item() { } internal void Set(ItemType type, object data) { this.type = type; this.data = data; } } class BufferChunk { internal char[] buffer; internal int index; internal int count; internal BufferChunk(char[] buffer, int index, int count) { this.buffer = buffer; this.index = index; this.count = count; } } private StringBuilder _stringValue = new StringBuilder(); private string _singleStringValue; // special-case for a single WriteString call private Item[] _items; private int _firstItem; private int _lastItem = -1; internal string StringValue { get { if (_singleStringValue != null) { return _singleStringValue; } else { return _stringValue.ToString(); } } } internal void WriteEntityRef(string name) { if (_singleStringValue != null) { StartComplexValue(); } switch (name) { case "lt": _stringValue.Append('<'); break; case "gt": _stringValue.Append('>'); break; case "quot": _stringValue.Append('"'); break; case "apos": _stringValue.Append('\''); break; case "amp": _stringValue.Append('&'); break; default: _stringValue.Append('&'); _stringValue.Append(name); _stringValue.Append(';'); break; } AddItem(ItemType.EntityRef, name); } internal void WriteCharEntity(char ch) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(ch); AddItem(ItemType.CharEntity, ch); } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(highChar); _stringValue.Append(lowChar); AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar }); } internal void WriteWhitespace(string ws) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(ws); AddItem(ItemType.Whitespace, ws); } internal void WriteString(string text) { if (_singleStringValue != null) { StartComplexValue(); } else { // special-case for a single WriteString if (_lastItem == -1) { _singleStringValue = text; return; } } _stringValue.Append(text); AddItem(ItemType.String, text); } internal void WriteChars(char[] buffer, int index, int count) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(buffer, index, count); AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(char[] buffer, int index, int count) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(buffer, index, count); AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(string data) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(data); AddItem(ItemType.Raw, data); } internal void WriteValue(string value) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(value); AddItem(ItemType.ValueString, value); } internal void Replay(XmlWriter writer) { if (_singleStringValue != null) { writer.WriteString(_singleStringValue); return; } BufferChunk bufChunk; for (int i = _firstItem; i <= _lastItem; i++) { Item item = _items[i]; switch (item.type) { case ItemType.EntityRef: writer.WriteEntityRef((string)item.data); break; case ItemType.CharEntity: writer.WriteCharEntity((char)item.data); break; case ItemType.SurrogateCharEntity: char[] chars = (char[])item.data; writer.WriteSurrogateCharEntity(chars[0], chars[1]); break; case ItemType.Whitespace: writer.WriteWhitespace((string)item.data); break; case ItemType.String: writer.WriteString((string)item.data); break; case ItemType.StringChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.Raw: writer.WriteRaw((string)item.data); break; case ItemType.RawChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.ValueString: writer.WriteValue((string)item.data); break; default: Debug.Fail("Unexpected ItemType value."); break; } } } // This method trims whitespaces from the beginning and the end of the string and cached writer events internal void Trim() { // if only one string value -> trim the write spaces directly if (_singleStringValue != null) { _singleStringValue = XmlConvertEx.TrimString(_singleStringValue); return; } // trim the string in StringBuilder string valBefore = _stringValue.ToString(); string valAfter = XmlConvertEx.TrimString(valBefore); if (valBefore != valAfter) { _stringValue = new StringBuilder(valAfter); } // trim the beginning of the recorded writer events XmlCharType xmlCharType = XmlCharType.Instance; int i = _firstItem; while (i == _firstItem && i <= _lastItem) { Item item = _items[i]; switch (item.type) { case ItemType.Whitespace: _firstItem++; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvertEx.TrimStringStart((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the firstItem index to exclude it from the Replay _firstItem++; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; int endIndex = bufChunk.index + bufChunk.count; while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index])) { bufChunk.index++; bufChunk.count--; } if (bufChunk.index == endIndex) { // no characters left -> move the firstItem index to exclude it from the Replay _firstItem++; } break; } i++; } // trim the end of the recorded writer events i = _lastItem; while (i == _lastItem && i >= _firstItem) { Item item = _items[i]; switch (item.type) { case ItemType.Whitespace: _lastItem--; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvertEx.TrimStringEnd((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the lastItem index to exclude it from the Replay _lastItem--; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1])) { bufChunk.count--; } if (bufChunk.count == 0) { // no characters left -> move the lastItem index to exclude it from the Replay _lastItem--; } break; } i--; } } internal void Clear() { _singleStringValue = null; _lastItem = -1; _firstItem = 0; _stringValue.Length = 0; } private void StartComplexValue() { Debug.Assert(_singleStringValue != null); Debug.Assert(_lastItem == -1); _stringValue.Append(_singleStringValue); AddItem(ItemType.String, _singleStringValue); _singleStringValue = null; } void AddItem(ItemType type, object data) { int newItemIndex = _lastItem + 1; if (_items == null) { _items = new Item[4]; } else if (_items.Length == newItemIndex) { Item[] newItems = new Item[newItemIndex * 2]; Array.Copy(_items, 0, newItems, 0, newItemIndex); _items = newItems; } if (_items[newItemIndex] == null) { _items[newItemIndex] = new Item(); } _items[newItemIndex].Set(type, data); _lastItem = newItemIndex; } } } }
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="KeywordPlanAdGroupKeywordServiceClient"/> instances.</summary> public sealed partial class KeywordPlanAdGroupKeywordServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="KeywordPlanAdGroupKeywordServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="KeywordPlanAdGroupKeywordServiceSettings"/>.</returns> public static KeywordPlanAdGroupKeywordServiceSettings GetDefault() => new KeywordPlanAdGroupKeywordServiceSettings(); /// <summary> /// Constructs a new <see cref="KeywordPlanAdGroupKeywordServiceSettings"/> object with default settings. /// </summary> public KeywordPlanAdGroupKeywordServiceSettings() { } private KeywordPlanAdGroupKeywordServiceSettings(KeywordPlanAdGroupKeywordServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetKeywordPlanAdGroupKeywordSettings = existing.GetKeywordPlanAdGroupKeywordSettings; MutateKeywordPlanAdGroupKeywordsSettings = existing.MutateKeywordPlanAdGroupKeywordsSettings; OnCopy(existing); } partial void OnCopy(KeywordPlanAdGroupKeywordServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordPlanAdGroupKeywordServiceClient.GetKeywordPlanAdGroupKeyword</c> and /// <c>KeywordPlanAdGroupKeywordServiceClient.GetKeywordPlanAdGroupKeywordAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetKeywordPlanAdGroupKeywordSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordPlanAdGroupKeywordServiceClient.MutateKeywordPlanAdGroupKeywords</c> and /// <c>KeywordPlanAdGroupKeywordServiceClient.MutateKeywordPlanAdGroupKeywordsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateKeywordPlanAdGroupKeywordsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="KeywordPlanAdGroupKeywordServiceSettings"/> object.</returns> public KeywordPlanAdGroupKeywordServiceSettings Clone() => new KeywordPlanAdGroupKeywordServiceSettings(this); } /// <summary> /// Builder class for <see cref="KeywordPlanAdGroupKeywordServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class KeywordPlanAdGroupKeywordServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanAdGroupKeywordServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public KeywordPlanAdGroupKeywordServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public KeywordPlanAdGroupKeywordServiceClientBuilder() { UseJwtAccessWithScopes = KeywordPlanAdGroupKeywordServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref KeywordPlanAdGroupKeywordServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanAdGroupKeywordServiceClient> task); /// <summary>Builds the resulting client.</summary> public override KeywordPlanAdGroupKeywordServiceClient Build() { KeywordPlanAdGroupKeywordServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<KeywordPlanAdGroupKeywordServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<KeywordPlanAdGroupKeywordServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private KeywordPlanAdGroupKeywordServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return KeywordPlanAdGroupKeywordServiceClient.Create(callInvoker, Settings); } private async stt::Task<KeywordPlanAdGroupKeywordServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return KeywordPlanAdGroupKeywordServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => KeywordPlanAdGroupKeywordServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordPlanAdGroupKeywordServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanAdGroupKeywordServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>KeywordPlanAdGroupKeywordService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad group keywords. KeywordPlanAdGroup is /// required to add ad group keywords. Positive and negative keywords are /// supported. A maximum of 10,000 positive keywords are allowed per keyword /// plan. A maximum of 1,000 negative keywords are allower per keyword plan. This /// includes campaign negative keywords and ad group negative keywords. /// </remarks> public abstract partial class KeywordPlanAdGroupKeywordServiceClient { /// <summary> /// The default endpoint for the KeywordPlanAdGroupKeywordService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default KeywordPlanAdGroupKeywordService scopes.</summary> /// <remarks> /// The default KeywordPlanAdGroupKeywordService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="KeywordPlanAdGroupKeywordServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupKeywordServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="KeywordPlanAdGroupKeywordServiceClient"/>.</returns> public static stt::Task<KeywordPlanAdGroupKeywordServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new KeywordPlanAdGroupKeywordServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="KeywordPlanAdGroupKeywordServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupKeywordServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="KeywordPlanAdGroupKeywordServiceClient"/>.</returns> public static KeywordPlanAdGroupKeywordServiceClient Create() => new KeywordPlanAdGroupKeywordServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="KeywordPlanAdGroupKeywordServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="KeywordPlanAdGroupKeywordServiceSettings"/>.</param> /// <returns>The created <see cref="KeywordPlanAdGroupKeywordServiceClient"/>.</returns> internal static KeywordPlanAdGroupKeywordServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanAdGroupKeywordServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient grpcClient = new KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient(callInvoker); return new KeywordPlanAdGroupKeywordServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC KeywordPlanAdGroupKeywordService client</summary> public virtual KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(GetKeywordPlanAdGroupKeywordRequest request, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupKeywordAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group keyword to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeyword(new GetKeywordPlanAdGroupKeywordRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group keyword to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeywordAsync(new GetKeywordPlanAdGroupKeywordRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group keyword to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(string resourceName, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupKeywordAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group keyword to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(gagvr::KeywordPlanAdGroupKeywordName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeyword(new GetKeywordPlanAdGroupKeywordRequest { ResourceNameAsKeywordPlanAdGroupKeywordName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group keyword to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(gagvr::KeywordPlanAdGroupKeywordName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeywordAsync(new GetKeywordPlanAdGroupKeywordRequest { ResourceNameAsKeywordPlanAdGroupKeywordName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group keyword to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(gagvr::KeywordPlanAdGroupKeywordName resourceName, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupKeywordAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateKeywordPlanAdGroupKeywordsResponse MutateKeywordPlanAdGroupKeywords(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(MutateKeywordPlanAdGroupKeywordsRequest request, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupKeywordsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad group keywords are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad group /// keywords. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateKeywordPlanAdGroupKeywordsResponse MutateKeywordPlanAdGroupKeywords(string customerId, scg::IEnumerable<KeywordPlanAdGroupKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroupKeywords(new MutateKeywordPlanAdGroupKeywordsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad group keywords are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad group /// keywords. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroupKeywordsAsync(new MutateKeywordPlanAdGroupKeywordsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad group keywords are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad group /// keywords. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupKeywordOperation> operations, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupKeywordsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>KeywordPlanAdGroupKeywordService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad group keywords. KeywordPlanAdGroup is /// required to add ad group keywords. Positive and negative keywords are /// supported. A maximum of 10,000 positive keywords are allowed per keyword /// plan. A maximum of 1,000 negative keywords are allower per keyword plan. This /// includes campaign negative keywords and ad group negative keywords. /// </remarks> public sealed partial class KeywordPlanAdGroupKeywordServiceClientImpl : KeywordPlanAdGroupKeywordServiceClient { private readonly gaxgrpc::ApiCall<GetKeywordPlanAdGroupKeywordRequest, gagvr::KeywordPlanAdGroupKeyword> _callGetKeywordPlanAdGroupKeyword; private readonly gaxgrpc::ApiCall<MutateKeywordPlanAdGroupKeywordsRequest, MutateKeywordPlanAdGroupKeywordsResponse> _callMutateKeywordPlanAdGroupKeywords; /// <summary> /// Constructs a client wrapper for the KeywordPlanAdGroupKeywordService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="KeywordPlanAdGroupKeywordServiceSettings"/> used within this client. /// </param> public KeywordPlanAdGroupKeywordServiceClientImpl(KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient grpcClient, KeywordPlanAdGroupKeywordServiceSettings settings) { GrpcClient = grpcClient; KeywordPlanAdGroupKeywordServiceSettings effectiveSettings = settings ?? KeywordPlanAdGroupKeywordServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetKeywordPlanAdGroupKeyword = clientHelper.BuildApiCall<GetKeywordPlanAdGroupKeywordRequest, gagvr::KeywordPlanAdGroupKeyword>(grpcClient.GetKeywordPlanAdGroupKeywordAsync, grpcClient.GetKeywordPlanAdGroupKeyword, effectiveSettings.GetKeywordPlanAdGroupKeywordSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetKeywordPlanAdGroupKeyword); Modify_GetKeywordPlanAdGroupKeywordApiCall(ref _callGetKeywordPlanAdGroupKeyword); _callMutateKeywordPlanAdGroupKeywords = clientHelper.BuildApiCall<MutateKeywordPlanAdGroupKeywordsRequest, MutateKeywordPlanAdGroupKeywordsResponse>(grpcClient.MutateKeywordPlanAdGroupKeywordsAsync, grpcClient.MutateKeywordPlanAdGroupKeywords, effectiveSettings.MutateKeywordPlanAdGroupKeywordsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateKeywordPlanAdGroupKeywords); Modify_MutateKeywordPlanAdGroupKeywordsApiCall(ref _callMutateKeywordPlanAdGroupKeywords); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetKeywordPlanAdGroupKeywordApiCall(ref gaxgrpc::ApiCall<GetKeywordPlanAdGroupKeywordRequest, gagvr::KeywordPlanAdGroupKeyword> call); partial void Modify_MutateKeywordPlanAdGroupKeywordsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanAdGroupKeywordsRequest, MutateKeywordPlanAdGroupKeywordsResponse> call); partial void OnConstruction(KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient grpcClient, KeywordPlanAdGroupKeywordServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC KeywordPlanAdGroupKeywordService client</summary> public override KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient GrpcClient { get; } partial void Modify_GetKeywordPlanAdGroupKeywordRequest(ref GetKeywordPlanAdGroupKeywordRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateKeywordPlanAdGroupKeywordsRequest(ref MutateKeywordPlanAdGroupKeywordsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordPlanAdGroupKeywordRequest(ref request, ref callSettings); return _callGetKeywordPlanAdGroupKeyword.Sync(request, callSettings); } /// <summary> /// Returns the requested Keyword Plan ad group keyword in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordPlanAdGroupKeywordRequest(ref request, ref callSettings); return _callGetKeywordPlanAdGroupKeyword.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateKeywordPlanAdGroupKeywordsResponse MutateKeywordPlanAdGroupKeywords(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupKeywordsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroupKeywords.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupKeywordsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroupKeywords.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Linq; #if CLR_35 using CobaltAHK.v35Compat; #endif namespace CobaltAHK { public abstract class Operator { protected Operator(string op, uint prec) { code = op; precedence = prec; set.Add(this); } public virtual bool Matches(string op) { return Code.ToUpper() == op.ToUpper(); } #region fields protected readonly string code; private readonly uint precedence; #endregion #region properties public string Code { get { return code; } } public uint Precedence { get { return precedence; } } #endregion protected static HashSet<Operator> set = new HashSet<Operator>(); internal static IEnumerable<Operator> Operators { get { return set; } } public static Operator GetOperator(string code) { return set.First(op => op.Matches(code)); } public static bool IsOperator(string code) { return set.Where(op => op.Matches(code)).Count() > 0; } #region instances [Obsolete] public static readonly Operator Deref = new UnaryOperator("%", 13, Position.undefined); // todo public static readonly Operator ObjectAccess = new BinaryOperator(".", 13, BinaryOperationType.Other, Whitespace.neither); public static readonly Operator New = new UnaryOperator("new", 12, Position.undefined); public static readonly Operator PrefixIncrement = new UnaryOperator("++", 12, Position.prefix); public static readonly Operator PostfixIncrement = new UnaryOperator("++", 12, Position.postfix); public static readonly Operator PrefixDecrement = new UnaryOperator("--", 12, Position.prefix); public static readonly Operator PostfixDecrement = new UnaryOperator("--", 12, Position.postfix); public static readonly Operator Power = new BinaryOperator("**", 11, BinaryOperationType.Arithmetic); public static readonly Operator UnaryMinus = new UnaryOperator("-", 10, Position.prefix); public static readonly Operator LogicalNot = new UnaryOperator("!", 10, Position.prefix); public static readonly Operator BitwiseNot = new UnaryOperator("~", 10, Position.prefix); public static readonly Operator Address = new UnaryOperator("&", 10, Position.prefix); public static readonly Operator Dereference = new UnaryOperator("*", 10, Position.prefix); public static readonly Operator Multiply = new BinaryOperator("*", 10, BinaryOperationType.Arithmetic, Whitespace.both_or_neither); public static readonly Operator TrueDivide = new BinaryOperator("/", 10, BinaryOperationType.Arithmetic); public static readonly Operator FloorDivide = new BinaryOperator("//", 10, BinaryOperationType.Arithmetic); public static readonly Operator Add = new BinaryOperator("+", 9, BinaryOperationType.Arithmetic, Whitespace.both_or_neither); public static readonly Operator Subtract = new BinaryOperator("-", 9, BinaryOperationType.Arithmetic, Whitespace.both_or_neither); public static readonly Operator BitShiftLeft = new BinaryOperator("<<", 9, BinaryOperationType.BitShift); public static readonly Operator BitShiftRight = new BinaryOperator(">>", 9, BinaryOperationType.BitShift); public static readonly Operator BitwiseAnd = new BinaryOperator("&", 8, BinaryOperationType.Bitwise, Whitespace.both_or_neither); public static readonly Operator BitwiseXor = new BinaryOperator("^", 8, BinaryOperationType.Bitwise); public static readonly Operator BitwiseOr = new BinaryOperator("|", 8, BinaryOperationType.Bitwise); public static readonly Operator Concatenate = new BinaryOperator(".", 7, BinaryOperationType.Other, Whitespace.both); public static readonly Operator RegexMatch = new BinaryOperator("~=", 7, BinaryOperationType.Comparison); public static readonly Operator Greater = new BinaryOperator(">", 6, BinaryOperationType.Comparison); public static readonly Operator Less = new BinaryOperator("<", 6, BinaryOperationType.Comparison); public static readonly Operator GreaterOrEqual = new BinaryOperator(">=", 6, BinaryOperationType.Comparison); public static readonly Operator LessOrEqual = new BinaryOperator("<=", 6, BinaryOperationType.Comparison); public static readonly Operator Equal = new BinaryOperator("=", 5, BinaryOperationType.Comparison); public static readonly Operator CaseEqual = new BinaryOperator("==", 5, BinaryOperationType.Comparison); public static readonly Operator NotEqual = new BinaryOperator("!=", 5, BinaryOperationType.Comparison); public static readonly Operator NotEqualAlt = new BinaryOperator("<>", 5, BinaryOperationType.Comparison); public static readonly Operator WordLogicalNot = new UnaryOperator("NOT", 4, Position.undefined); public static readonly Operator LogicalAnd = new BinaryOperator("&&", 3, BinaryOperationType.Logical); public static readonly Operator WordLogicalAnd = new BinaryOperator("AND", 3, BinaryOperationType.Logical); public static readonly Operator LogicalOr = new BinaryOperator("||", 3, BinaryOperationType.Logical); public static readonly Operator WordLogicalOr = new BinaryOperator("OR", 3, BinaryOperationType.Logical); public static readonly Operator Ternary = new TernaryOperator("?", ":", 2); // todo public static readonly Operator Assign = new BinaryOperator(":=", 1, BinaryOperationType.Assign); public static readonly Operator AddAssign = new BinaryOperator("+=", 1, BinaryOperationType.Assign|BinaryOperationType.Arithmetic); public static readonly Operator SubtractAssign = new BinaryOperator("-=", 1, BinaryOperationType.Assign|BinaryOperationType.Arithmetic); public static readonly Operator MultiplyAssign = new BinaryOperator("*=", 1, BinaryOperationType.Assign|BinaryOperationType.Arithmetic); public static readonly Operator TrueDivideAssign = new BinaryOperator("/=", 1, BinaryOperationType.Assign|BinaryOperationType.Arithmetic); public static readonly Operator FloorDivideAssign = new BinaryOperator("//=", 1, BinaryOperationType.Assign|BinaryOperationType.Arithmetic); public static readonly Operator ConcatenateAssign = new BinaryOperator(".=", 1, BinaryOperationType.Assign|BinaryOperationType.Other); public static readonly Operator BitwiseOrAssign = new BinaryOperator("|=", 1, BinaryOperationType.Assign|BinaryOperationType.Bitwise); public static readonly Operator BitwiseAndAssign = new BinaryOperator("&=", 1, BinaryOperationType.Assign|BinaryOperationType.Bitwise); public static readonly Operator BitwiseXorAssign = new BinaryOperator("^=", 1, BinaryOperationType.Assign|BinaryOperationType.Bitwise); public static readonly Operator BitShiftLeftAssign = new BinaryOperator("<<=", 1, BinaryOperationType.Assign|BinaryOperationType.BitShift); public static readonly Operator BitShiftRightAssign = new BinaryOperator(">>=", 1, BinaryOperationType.Assign|BinaryOperationType.BitShift); public static readonly Operator AltObjAccess = new BinaryOperator("[", 0, BinaryOperationType.Other, Whitespace.not_before); // todo: is precedence correct? e.g. `f . a[b]` => `(f . a)[b]` ? #endregion #region compound assignments private static readonly IDictionary<Operator, Operator> compoundAssigns = new Dictionary<Operator, Operator>() { { Operator.ConcatenateAssign, Operator.Concatenate }, { Operator.AddAssign, Operator.Add }, { Operator.SubtractAssign, Operator.Subtract }, { Operator.MultiplyAssign, Operator.Multiply }, { Operator.TrueDivideAssign, Operator.TrueDivide }, { Operator.FloorDivideAssign, Operator.FloorDivide }, { Operator.BitwiseOrAssign, Operator.BitwiseOr }, { Operator.BitwiseAndAssign, Operator.BitwiseAnd }, { Operator.BitwiseXorAssign, Operator.BitwiseXor }, { Operator.BitShiftLeftAssign, Operator.BitShiftLeft }, { Operator.BitShiftRightAssign, Operator.BitShiftRight } }; internal static bool IsCompoundAssignment(BinaryOperator op) { return op.Type.HasFlag(BinaryOperationType.Assign) && op.Type != BinaryOperationType.Assign; } internal static BinaryOperator CompoundGetUnderlyingOperator(BinaryOperator op) { return (BinaryOperator)compoundAssigns[op]; } #endregion } [Flags] public enum Whitespace { none = 0, before = 1, not_before = 2, after = 4, not_after = 8, both = before|after, neither = not_before|not_after, both_or_neither = 16 } public enum Position { undefined, prefix, postfix } internal class UnaryOperator : Operator { internal UnaryOperator(string op, uint prec, Position pos) : base(op, prec) { position = pos; } private Position position; public Position Position { get { return position; } } } internal class BinaryOperator : Operator { internal BinaryOperator(string op, uint prec, BinaryOperationType tp, Whitespace white) : base(op, prec) { type = tp; whitespace = white; } internal BinaryOperator(string op, uint prec, BinaryOperationType tp) : this(op, prec, tp, Whitespace.none) { } private readonly Whitespace whitespace = Whitespace.none; public Whitespace Whitespace { get { return whitespace; } } public bool Is(BinaryOperationType type) { return Type.HasFlag(type); } private readonly BinaryOperationType type; public BinaryOperationType Type { get { return type; } } } [Flags] public enum BinaryOperationType { None = 0, Numeric = 1, Comparison = 4, Bitwise = 8, BitShift = 16, Logical = 32, Other = 64, Assign = 128, Arithmetic = Numeric|2 } internal class TernaryOperator : Operator { internal TernaryOperator(string first, string second, uint prec) : base(first + second, prec) { this.first = first; this.second = second; } private readonly string first; private readonly string second; public override bool Matches(string op) { return op.ToUpper() == first || op.ToUpper() == second; } } }
//------------------------------------------------------------------------------ // <license file="NativeScript.cs"> // // The use and distribution terms for this software are contained in the file // named 'LICENSE', which can be found in the resources directory of this // distribution. // // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // </license> //------------------------------------------------------------------------------ using System; namespace EcmaScript.NET.Types { /// <summary> /// The JavaScript Script object. /// /// Note that the C version of the engine uses XDR as the format used /// by freeze and thaw. Since this depends on the internal format of /// structures in the C runtime, we cannot duplicate it. /// /// Since we cannot replace 'this' as a result of the compile method, /// will forward requests to execute to the nonnull 'script' field. /// /// </summary> class BuiltinScript : BaseFunction { /// <summary> Returns the name of this JavaScript class, "Script".</summary> override public string ClassName { get { return "Script"; } } override public int Length { get { return 0; } } override public int Arity { get { return 0; } } private static readonly object SCRIPT_TAG = new object (); internal static new void Init (IScriptable scope, bool zealed) { BuiltinScript obj = new BuiltinScript (null); obj.ExportAsJSClass (MAX_PROTOTYPE_ID, scope, zealed); } private BuiltinScript (IScript script) { this.script = script; } public override object Call (Context cx, IScriptable scope, IScriptable thisObj, object [] args) { if (script != null) { return script.Exec (cx, scope); } return Undefined.Value; } public override IScriptable Construct (Context cx, IScriptable scope, object [] args) { throw Context.ReportRuntimeErrorById ("msg.script.is.not.constructor"); } internal override string Decompile (int indent, int flags) { if (script is BuiltinFunction) { return ((BuiltinFunction)script).Decompile (indent, flags); } return base.Decompile (indent, flags); } protected internal override void InitPrototypeId (int id) { string s; int arity; switch (id) { case Id_constructor: arity = 1; s = "constructor"; break; case Id_toString: arity = 0; s = "toString"; break; case Id_exec: arity = 0; s = "exec"; break; case Id_compile: arity = 1; s = "compile"; break; default: throw new ArgumentException (Convert.ToString (id)); } InitPrototypeMethod (SCRIPT_TAG, id, s, arity); } public override object ExecIdCall (IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args) { if (!f.HasTag (SCRIPT_TAG)) { return base.ExecIdCall (f, cx, scope, thisObj, args); } int id = f.MethodId; switch (id) { case Id_constructor: { string source = (args.Length == 0) ? "" : ScriptConvert.ToString (args [0]); IScript script = compile (cx, source); BuiltinScript nscript = new BuiltinScript (script); ScriptRuntime.setObjectProtoAndParent (nscript, scope); return nscript; } case Id_toString: { BuiltinScript real = realThis (thisObj, f); IScript realScript = real.script; if (realScript == null) { return ""; } return cx.DecompileScript (realScript, 0); } case Id_exec: { throw Context.ReportRuntimeErrorById ("msg.cant.call.indirect", "exec"); } case Id_compile: { BuiltinScript real = realThis (thisObj, f); string source = ScriptConvert.ToString (args, 0); real.script = compile (cx, source); return real; } } throw new ArgumentException (Convert.ToString (id)); } private static BuiltinScript realThis (IScriptable thisObj, IdFunctionObject f) { if (!(thisObj is BuiltinScript)) throw IncompatibleCallError (f); return (BuiltinScript)thisObj; } private static IScript compile (Context cx, string source) { int [] linep = new int [] { 0 }; string filename = Context.GetSourcePositionFromStack (linep); if (filename == null) { filename = "<Script object>"; linep [0] = 1; } ErrorReporter reporter; reporter = DefaultErrorReporter.ForEval (cx.ErrorReporter); return cx.CompileString (source, null, reporter, filename, linep [0], (object)null); } protected internal override int FindPrototypeId (string s) { int id; #region Generated PrototypeId Switch L0: { id = 0; string X = null; L: switch (s.Length) { case 4: X = "exec"; id = Id_exec; break; case 7: X = "compile"; id = Id_compile; break; case 8: X = "toString"; id = Id_toString; break; case 11: X = "constructor"; id = Id_constructor; break; } if (X != null && X != s && !X.Equals (s)) id = 0; } EL0: #endregion return id; } #region PrototypeIds private const int Id_constructor = 1; private const int Id_toString = 2; private const int Id_compile = 3; private const int Id_exec = 4; private const int MAX_PROTOTYPE_ID = 4; #endregion private IScript script; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace PhoneBook.Core.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) { var 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); } var genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { var collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } var closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { var dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } var 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) { var genericArgs = type.GetGenericArguments(); var parameterValues = new object[genericArgs.Length]; var failedToCreateTuple = true; var objectGenerator = new ObjectGenerator(); for (var i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } var 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) { var genericArgs = keyValuePairType.GetGenericArguments(); var typeK = genericArgs[0]; var typeV = genericArgs[1]; var objectGenerator = new ObjectGenerator(); var keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); var valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } var result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { var type = arrayType.GetElementType(); var result = Array.CreateInstance(type, size); var areAllElementsNull = true; var objectGenerator = new ObjectGenerator(); for (var i = 0; i < size; i++) { var element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } return areAllElementsNull ? null : result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { var typeK = typeof(object); var typeV = typeof(object); if (dictionaryType.IsGenericType) { var genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } var result = Activator.CreateInstance(dictionaryType); var addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); var containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); var objectGenerator = new ObjectGenerator(); for (var i = 0; i < size; i++) { var newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } var containsKey = (bool) containsMethod.Invoke(result, new[] {newKey}); if (!containsKey) { var newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new[] {newKey, newValue}); } } return result; } private static object GenerateEnum(Type enumType) { var possibleValues = Enum.GetValues(enumType); return possibleValues.Length > 0 ? possibleValues.GetValue(0) : null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { var isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { var 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) return ((IEnumerable) list).AsQueryable(); var argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); var asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] {argumentType}); return asQueryableMethod.Invoke(null, new[] {list}); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { var type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); var result = Activator.CreateInstance(collectionType); var addMethod = collectionType.GetMethod("Add"); var areAllElementsNull = true; var objectGenerator = new ObjectGenerator(); for (var i = 0; i < size; i++) { var element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new[] {element}); areAllElementsNull &= element == null; } return areAllElementsNull ? null : result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { var type = nullableType.GetGenericArguments()[0]; var 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 { var 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) { var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); var objectGenerator = new ObjectGenerator(); foreach (var property in properties) { if (!property.CanWrite) continue; var propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); var objectGenerator = new ObjectGenerator(); foreach (var field in fields) { var fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); private long _index; [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(bool), 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 => index + 0.1}, {typeof(Guid), index => Guid.NewGuid()}, {typeof(short), index => (short) (index%short.MaxValue)}, {typeof(int), index => (int) (index%int.MaxValue)}, {typeof(long), index => index}, {typeof(object), index => new object()}, {typeof(sbyte), index => (sbyte) 64}, {typeof(float), index => (float) (index + 0.1)}, { typeof(string), index => string.Format(CultureInfo.CurrentCulture, "sample string {0}", index) }, { typeof(TimeSpan), index => TimeSpan.FromTicks(1234567) }, {typeof(ushort), index => (ushort) (index%ushort.MaxValue)}, {typeof(uint), index => (uint) (index%uint.MaxValue)}, {typeof(ulong), index => (ulong) index}, { typeof(Uri), index => 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); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestZInt32() { var test = new BooleanBinaryOpTest__TestZInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestZInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestZInt32 testClass) { var result = Avx.TestZ(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestZInt32 testClass) { fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx.TestZ( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestZInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public BooleanBinaryOpTest__TestZInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.TestZ( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.TestZ( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.TestZ( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int32>* pClsVar1 = &_clsVar1) fixed (Vector256<Int32>* pClsVar2 = &_clsVar2) { var result = Avx.TestZ( Avx.LoadVector256((Int32*)(pClsVar1)), Avx.LoadVector256((Int32*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestZInt32(); var result = Avx.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestZInt32(); fixed (Vector256<Int32>* pFld1 = &test._fld1) fixed (Vector256<Int32>* pFld2 = &test._fld2) { var result = Avx.TestZ( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx.TestZ( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.TestZ( Avx.LoadVector256((Int32*)(&test._fld1)), Avx.LoadVector256((Int32*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestZ)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using Newtonsoft.Json; using OrchardCore.DisplayManagement.Zones; namespace OrchardCore.DisplayManagement.Shapes { [DebuggerTypeProxy(typeof(ShapeDebugView))] public class Shape : Composite, IShape, IPositioned, IEnumerable<object> { private List<string> _classes; private Dictionary<string, string> _attributes; private readonly List<IPositioned> _items = new List<IPositioned>(); private bool _sorted = false; public ShapeMetadata Metadata { get; } = new ShapeMetadata(); public string Id { get; set; } public string TagName { get; set; } public IList<string> Classes => _classes ??= new List<string>(); public IDictionary<string, string> Attributes => _attributes ??= new Dictionary<string, string>(); public IEnumerable<dynamic> Items { get { if (!_sorted) { _items.Sort(FlatPositionComparer.Instance); _sorted = true; } return _items; } } public bool HasItems => _items.Count > 0; public string Position { get { return Metadata.Position; } set { Metadata.Position = value; } } public virtual Shape Add(object item, string position = null) { if (item == null) { return this; } if (position == null) { position = ""; } _sorted = false; if (item is IHtmlContent) { _items.Add(new PositionWrapper((IHtmlContent)item, position)); } else if (item is string) { _items.Add(new PositionWrapper((string)item, position)); } else { var shape = item as IPositioned; if (shape != null) { if (position != null) { shape.Position = position; } _items.Add(shape); } } return this; } public Shape AddRange(IEnumerable<object> items, string position = null) { foreach (var item in items) { Add(item, position); } return this; } public void Remove(string shapeName) { for (var i = _items.Count - 1; i >= 0; i--) { if (_items[i] is IShape shape && shape.Metadata.Name == shapeName) { _items.RemoveAt(i); return; } } } public IShape Named(string shapeName) { for (var i = 0; i < _items.Count; i++) { if (_items[i] is IShape shape && shape.Metadata.Name == shapeName) { return shape; } } return null; } public IShape NormalizedNamed(string shapeName) { for (var i = 0; i < _items.Count; i++) { if (_items[i] is IShape shape && shape.Metadata.Name?.Replace("__", "-") == shapeName) { return shape; } } return null; } IEnumerator<object> IEnumerable<object>.GetEnumerator() { if (!_sorted) { _items.Sort(FlatPositionComparer.Instance); _sorted = true; } return _items.GetEnumerator(); } public IEnumerator GetEnumerator() { if (!_sorted) { _items.Sort(FlatPositionComparer.Instance); _sorted = true; } return _items.GetEnumerator(); } public override bool TryConvert(ConvertBinder binder, out object result) { result = Items; if (binder.ReturnType == typeof(IEnumerable<object>) || binder.ReturnType == typeof(IEnumerable<dynamic>)) { return true; } return base.TryConvert(binder, out result); } public static TagBuilder GetTagBuilder(Shape shape, string defaultTagName = "span") { var tagName = defaultTagName; // We keep this for backward compatibility if (shape.Properties.TryGetValue("Tag", out var value) && value is string valueString) { tagName = valueString; } if (!String.IsNullOrEmpty(shape.TagName)) { tagName = shape.TagName; } return GetTagBuilder(tagName, shape.Id, shape.Classes, shape.Attributes); } public static TagBuilder GetTagBuilder(string tagName, string id, IEnumerable<string> classes, IDictionary<string, string> attributes) { var tagBuilder = new TagBuilder(tagName); if (attributes != null) { tagBuilder.MergeAttributes(attributes, false); } foreach (var cssClass in classes ?? Enumerable.Empty<string>()) { tagBuilder.AddCssClass(cssClass); } if (!String.IsNullOrWhiteSpace(id)) { tagBuilder.Attributes["id"] = id; } return tagBuilder; } public override bool TryGetMember(GetMemberBinder binder, out object result) { var name = binder.Name; if (!base.TryGetMember(binder, out result) || (null == result)) { // Try to get a Named shape result = Named(name); if (result == null) { result = NormalizedNamed(name.Replace("__", "-")); } } return true; } protected override bool TrySetMemberImpl(string name, object value) { // We set the Shape real properties for Razor if (name == "Id") { Id = value as string; return true; } if (name == "TagName") { TagName = value as string; return true; } if (name == "Attributes") { if (value is Dictionary<string, string> attributes) { foreach (var attribute in attributes) { Attributes.TryAdd(attribute.Key, attribute.Value); } } if (value is string stringValue) { attributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringValue); foreach (var attribute in attributes) { Attributes.TryAdd(attribute.Key, attribute.Value); } } } if (name == "Classes") { if (value is List<string> classes) { foreach (var item in classes) { Classes.Add(item); } } if (value is string stringValue) { var values = stringValue.Split(' ', StringSplitOptions.RemoveEmptyEntries); foreach (var item in values) { Classes.Add(item); } } } base.TrySetMemberImpl(name, value); return true; } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005AutoHideStrip : AutoHideStripBase { private class TabVS2005 : Tab { internal TabVS2005(IDockContent content) : base(content) { } private int m_tabX = 0; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth = 0; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } } private const int _ImageHeight = 16; private const int _ImageWidth = 16; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 2; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 0; private const int _TextGapRight = 0; private const int _TabGapTop = 3; private const int _TabGapLeft = 4; private const int _TabGapBetween = 10; #region Customizable Properties public Font TextFont { get { return DockPanel.Skin.AutoHideStripSkin.TextFont; } } private static StringFormat _stringFormatTabHorizontal; private StringFormat StringFormatTabHorizontal { get { if (_stringFormatTabHorizontal == null) { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; _stringFormatTabHorizontal.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabHorizontal; } } private static StringFormat _stringFormatTabVertical; private StringFormat StringFormatTabVertical { get { if (_stringFormatTabVertical == null) { _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; _stringFormatTabVertical.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabVertical; } } private static int ImageHeight { get { return _ImageHeight; } } private static int ImageWidth { get { return _ImageWidth; } } private static int ImageGapTop { get { return _ImageGapTop; } } private static int ImageGapLeft { get { return _ImageGapLeft; } } private static int ImageGapRight { get { return _ImageGapRight; } } private static int ImageGapBottom { get { return _ImageGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int TabGapTop { get { return _TabGapTop; } } private static int TabGapLeft { get { return _TabGapLeft; } } private static int TabGapBetween { get { return _TabGapBetween; } } private static Pen PenTabBorder { get { return SystemPens.GrayText; } } #endregion private static Matrix _matrixIdentity = new Matrix(); private static Matrix MatrixIdentity { get { return _matrixIdentity; } } private static DockState[] _dockStates; private static DockState[] DockStates { get { if (_dockStates == null) { _dockStates = new DockState[4]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } return _dockStates; } } private static GraphicsPath _graphicsPath; internal static GraphicsPath GraphicsPath { get { if (_graphicsPath == null) _graphicsPath = new GraphicsPath(); return _graphicsPath; } } public VS2005AutoHideStrip(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); BackColor = SystemColors.ControlLight; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; Color startColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor; Color endColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout(levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return; Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) DrawTab(g, tab); } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); int x = TabGapLeft + rectTabStrip.X; foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + TextGapLeft + TextGapRight; tab.TabX = x; tab.TabWidth = width; x += width; } x += TabGapBetween; } } private Rectangle RtlTransform(Rectangle rect, DockState dockState) { Rectangle rectTransformed; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) rectTransformed = rect; else rectTransformed = DrawHelper.RtlTransform(this, rect); return rectTransformed; } private GraphicsPath GetTabOutline(TabVS2005 tab, bool transformed, bool rtlTransform) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTab = GetTabRectangle(tab, transformed); if (rtlTransform) rectTab = RtlTransform(rectTab, dockState); bool upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide); DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab); return GraphicsPath; } private void DrawTab(Graphics g, TabVS2005 tab) { Rectangle rectTabOrigin = GetTabRectangle(tab); if (rectTabOrigin.IsEmpty) return; DockState dockState = tab.Content.DockHandler.DockState; IDockContent content = tab.Content; GraphicsPath path = GetTabOutline(tab, false, true); Color startColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.StartColor; Color endColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.EndColor; LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTabOrigin, startColor, endColor, gradientMode), path); g.DrawPath(PenTabBorder, path); // Set no rotate for drawing icon and text Matrix matrixRotate = g.Transform; g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTabOrigin; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right. Rectangle rectTransform = RtlTransform(rectImage, dockState); Point[] rotationPoints = { new Point(rectTransform.X + rectTransform.Width, rectTransform.Y), new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), new Point(rectTransform.X, rectTransform.Y) }; using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) { g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); } } else { // Draw the icon normally without any rotation. g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState)); } // Draw the text Rectangle rectText = rectTabOrigin; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); Color textColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.TextColor; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical); else g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal); // Set rotate back g.Transform = matrixRotate; } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; int topPanes = GetPanes(DockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; height = MeasureHeight(); if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) { x = 0; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) { x = Width - height; if (leftPanes != 0 && x < height) x = height; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockTopAutoHide && topPanes > 0) { x = leftPanes == 0 ? 0 : height; y = 0; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) { x = leftPanes == 0 ? 0 : height; y = Height - height; if (topPanes != 0 && y < height) y = height; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else return Rectangle.Empty; if (width == 0 || height == 0) { return Rectangle.Empty; } var rect = new Rectangle(x, y, width, height); return transformed ? GetTransformedRectangle(dockState, rect) : rect; } private Rectangle GetTabRectangle(TabVS2005 tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(TabVS2005 tab, bool transformed) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; int x = tab.TabX; int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); int width = tab.TabWidth; int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = (float)rect.X + (float)rect.Width / 2; pts[0].Y = (float)rect.Y + (float)rect.Height / 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); Matrix matrix = new Matrix(); matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); matrix.TransformPoints(pts); return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), (int)(pts[0].Y - (float)rect.Width / 2 + .5F), rect.Height, rect.Width); } protected override IDockContent HitTest(Point ptMouse) { foreach (DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(ptMouse)) continue; foreach (Pane pane in GetPanes(state)) { foreach (TabVS2005 tab in pane.AutoHideTabs) { GraphicsPath path = GetTabOutline(tab, true, true); if (path.IsVisible(ptMouse)) return tab.Content; } } } return null; } protected internal override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, TextFont.Height) + TabGapTop; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } protected override AutoHideStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } } }
// // System.IO.Stream.cs // // Authors: // Dietmar Maurer (dietmar@ximian.com) // Miguel de Icaza (miguel@ximian.com) // Gonzalo Paniagua Javier (gonzalo@ximian.com) // Marek Safar (marek.safar@gmail.com) // // (C) 2001, 2002 Ximian, Inc. http://www.ximian.com // (c) 2004 Novell, Inc. (http://www.novell.com) // Copyright 2011 Xamarin, Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Morph.IO { public abstract class Stream // : MarshalByRefObject, IDisposable { public static readonly Stream Null = new NullStream(); //Func<byte[], int, int, int> async_read; //Action<byte[], int, int> async_write; //AutoResetEvent async_event; protected Stream() { } //TICKET#54 public virtual bool CanRead { get { return true; } } //TICKET#54 public virtual bool CanSeek { get { return true; } } //TICKET#54 public virtual bool CanWrite { get { return true; } } public virtual bool CanTimeout { get { return false; } } //TICKET#54 public virtual int Length { get { return 0; } } //TICKET#54 public virtual int Position { get { return 0; } set { } } public void Dispose() { Close(); } //protected virtual void Dispose(bool disposing) //{ // if (async_event != null && disposing) // { // async_event.Close(); // async_event = null; // } //} public virtual void Close() { //Dispose(true); //GC.SuppressFinalize(this); } public static Stream Synchronized(Stream stream) { return new SynchronizedStream(stream); } //TICKET#54 public virtual void Flush() { } //TICKET#54 public virtual int Read(byte[] buffer, int offset, int count) { return 0; } //WAS: public abstract int Read([In, Out] byte[] buffer, int offset, int count); public virtual int ReadByte() { byte[] buffer = new byte[1]; if (Read(buffer, 0, 1) == 1) return buffer[0]; return -1; } //TICKET#54 //LONG NOT SUPPORTED public virtual int Seek(int offset, SeekOrigin origin) { return 0; } //TICKET#54 public virtual void SetLength(int value) { } //TICKET#54 public virtual void Write(byte[] buffer, int offset, int count) { } public virtual void WriteByte(byte value) { byte[] buffer = new byte[1]; buffer[0] = value; Write(buffer, 0, 1); } public void CopyTo (Stream destination) { CopyTo (destination, 16*1024); } public void CopyTo (Stream destination, int bufferSize) { if (destination == null) { //throw new ArgumentNullException ("destination"); } if (!CanRead) { //throw new NotSupportedException ("This stream does not support reading"); } if (!destination.CanWrite) { //throw new NotSupportedException ("This destination stream does not support writing"); } if (bufferSize <= 0) { //throw new ArgumentOutOfRangeException ("bufferSize"); } byte[] buffer = new byte [bufferSize]; int nread; while ((nread = Read (buffer, 0, bufferSize)) != 0) destination.Write (buffer, 0, nread); } } class NullStream : Stream { public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override int Length { get { return 0; } } public override int Position { get { return 0; } set { } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override int ReadByte() { return -1; } public override int Seek(int offset, SeekOrigin origin) { return 0; } public override void SetLength(int value) { } public override void Write(byte[] buffer, int offset, int count) { } public override void WriteByte(byte value) { } } class SynchronizedStream : Stream { Stream source; //object slock; internal SynchronizedStream(Stream source) { this.source = source; //slock = new object(); } public override bool CanRead { get { ////lock (slock) return source.CanRead; } } public override bool CanSeek { get { //lock (slock) return source.CanSeek; } } public override bool CanWrite { get { //lock (slock) return source.CanWrite; } } public override int Length { get { //lock (slock) return source.Length; } } public override int Position { get { //lock (slock) return source.Position; } set { //lock (slock) source.Position = value; } } public override void Flush() { //lock (slock) source.Flush(); } public override int Read(byte[] buffer, int offset, int count) { //lock (slock) return source.Read(buffer, offset, count); } public override int ReadByte() { //lock (slock) return source.ReadByte(); } public override int Seek(int offset, SeekOrigin origin) { //lock (slock) return source.Seek(offset, origin); } public override void SetLength(int value) { //lock (slock) source.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { //lock (slock) source.Write(buffer, offset, count); } public override void WriteByte(byte value) { //lock (slock) source.WriteByte(value); } } }
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Sprite/tk2dTiledSprite")] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] /// <summary> /// Sprite implementation that tiles a sprite to fill given dimensions. /// </summary> public class tk2dTiledSprite : tk2dBaseSprite { Mesh mesh; Vector2[] meshUvs; Vector3[] meshVertices; Color32[] meshColors; Vector3[] meshNormals = null; Vector4[] meshTangents = null; int[] meshIndices; [SerializeField] Vector2 _dimensions = new Vector2(50.0f, 50.0f); [SerializeField] Anchor _anchor = Anchor.LowerLeft; /// <summary> /// Gets or sets the dimensions. /// </summary> /// <value> /// Use this to change the dimensions of the sliced sprite in pixel units /// </value> public Vector2 dimensions { get { return _dimensions; } set { if (value != _dimensions) { _dimensions = value; UpdateVertices(); #if UNITY_EDITOR EditMode__CreateCollider(); #endif UpdateCollider(); } } } /// <summary> /// The anchor position for this tiled sprite /// </summary> public Anchor anchor { get { return _anchor; } set { if (value != _anchor) { _anchor = value; UpdateVertices(); #if UNITY_EDITOR EditMode__CreateCollider(); #endif UpdateCollider(); } } } [SerializeField] protected bool _createBoxCollider = false; /// <summary> /// Create a trimmed box collider for this sprite /// </summary> public bool CreateBoxCollider { get { return _createBoxCollider; } set { if (_createBoxCollider != value) { _createBoxCollider = value; UpdateCollider(); } } } #if UNITY_EDITOR void OnValidate() { MeshFilter meshFilter = GetComponent<MeshFilter>(); if (meshFilter != null) { meshFilter.sharedMesh = mesh; } } #endif new void Awake() { base.Awake(); // Create mesh, independently to everything else mesh = new Mesh(); #if !UNITY_3_5 mesh.MarkDynamic(); #endif mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; // This will not be set when instantiating in code // In that case, Build will need to be called if (Collection) { // reset spriteId if outside bounds // this is when the sprite collection data is corrupt if (_spriteId < 0 || _spriteId >= Collection.Count) _spriteId = 0; Build(); if (boxCollider == null) boxCollider = GetComponent<BoxCollider>(); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D == null) { boxCollider2D = GetComponent<BoxCollider2D>(); } #endif } } protected void OnDestroy() { if (mesh) { #if UNITY_EDITOR DestroyImmediate(mesh); #else Destroy(mesh); #endif } } new protected void SetColors(Color32[] dest) { int numVertices; int numIndices; tk2dSpriteGeomGen.GetTiledSpriteGeomDesc(out numVertices, out numIndices, CurrentSprite, dimensions); tk2dSpriteGeomGen.SetSpriteColors (dest, 0, numVertices, _color, collectionInst.premultipliedAlpha); } // Calculated center and extents Vector3 boundsCenter = Vector3.zero, boundsExtents = Vector3.zero; public override void Build() { var spriteDef = CurrentSprite; int numVertices; int numIndices; tk2dSpriteGeomGen.GetTiledSpriteGeomDesc(out numVertices, out numIndices, spriteDef, dimensions); if (meshUvs == null || meshUvs.Length != numVertices) { meshUvs = new Vector2[numVertices]; meshVertices = new Vector3[numVertices]; meshColors = new Color32[numVertices]; } if (meshIndices == null || meshIndices.Length != numIndices) { meshIndices = new int[numIndices]; } meshNormals = new Vector3[0]; meshTangents = new Vector4[0]; if (spriteDef.normals != null && spriteDef.normals.Length > 0) { meshNormals = new Vector3[numVertices]; } if (spriteDef.tangents != null && spriteDef.tangents.Length > 0) { meshTangents = new Vector4[numVertices]; } float colliderOffsetZ = ( boxCollider != null ) ? ( boxCollider.center.z ) : 0.0f; float colliderExtentZ = ( boxCollider != null ) ? ( boxCollider.size.z * 0.5f ) : 0.5f; tk2dSpriteGeomGen.SetTiledSpriteGeom(meshVertices, meshUvs, 0, out boundsCenter, out boundsExtents, spriteDef, _scale, dimensions, anchor, colliderOffsetZ, colliderExtentZ); tk2dSpriteGeomGen.SetTiledSpriteIndices(meshIndices, 0, 0, spriteDef, dimensions); if (meshNormals.Length > 0 || meshTangents.Length > 0) { Vector3 meshVertexMin = new Vector3(spriteDef.positions[0].x * dimensions.x * spriteDef.texelSize.x * scale.x, spriteDef.positions[0].y * dimensions.y * spriteDef.texelSize.y * scale.y); Vector3 meshVertexMax = new Vector3(spriteDef.positions[3].x * dimensions.x * spriteDef.texelSize.x * scale.x, spriteDef.positions[3].y * dimensions.y * spriteDef.texelSize.y * scale.y); tk2dSpriteGeomGen.SetSpriteVertexNormals(meshVertices, meshVertexMin, meshVertexMax, spriteDef.normals, spriteDef.tangents, meshNormals, meshTangents); } SetColors(meshColors); if (mesh == null) { mesh = new Mesh(); #if !UNITY_3_5 mesh.MarkDynamic(); #endif mesh.hideFlags = HideFlags.DontSave; } else { mesh.Clear(); } mesh.vertices = meshVertices; mesh.colors32 = meshColors; mesh.uv = meshUvs; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.triangles = meshIndices; mesh.RecalculateBounds(); mesh.bounds = AdjustedMeshBounds( mesh.bounds, renderLayer ); GetComponent<MeshFilter>().mesh = mesh; UpdateCollider(); UpdateMaterial(); } protected override void UpdateGeometry() { UpdateGeometryImpl(); } protected override void UpdateColors() { UpdateColorsImpl(); } protected override void UpdateVertices() { UpdateGeometryImpl(); } protected void UpdateColorsImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if (meshColors == null || meshColors.Length == 0) return; #endif if (meshColors == null || meshColors.Length == 0) { Build(); } else { SetColors(meshColors); mesh.colors32 = meshColors; } } protected void UpdateGeometryImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if (mesh == null) return; #endif Build(); } #region Collider protected override void UpdateCollider() { if (CreateBoxCollider) { if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) { if (boxCollider != null) { boxCollider.size = 2 * boundsExtents; boxCollider.center = boundsCenter; } } else if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) { #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D != null) { boxCollider2D.size = 2 * boundsExtents; #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9) boxCollider2D.center = boundsCenter; #else boxCollider2D.offset = boundsCenter; #endif } #endif } } } #if UNITY_EDITOR void OnDrawGizmos() { if (mesh != null) { Bounds b = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(b.center, b.extents * 2); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif protected override void CreateCollider() { UpdateCollider(); } #if UNITY_EDITOR public override void EditMode__CreateCollider() { if (CreateBoxCollider) { base.CreateSimpleBoxCollider(); } UpdateCollider(); } #endif #endregion protected override void UpdateMaterial() { Renderer renderer = GetComponent<Renderer>(); if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst) renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst; } protected override int GetCurrentVertexCount() { #if UNITY_EDITOR if (meshVertices == null) return 0; #endif return 16; } public override void ReshapeBounds(Vector3 dMin, Vector3 dMax) { // Identical to tk2dSlicedSprite.ReshapeBounds float minSizeClampTexelScale = 0.1f; // Can't shrink sprite smaller than this many texels // Irrespective of transform var sprite = CurrentSprite; Vector2 boundsSize = new Vector2(_dimensions.x * sprite.texelSize.x, _dimensions.y * sprite.texelSize.y); Vector3 oldSize = new Vector3(boundsSize.x * _scale.x, boundsSize.y * _scale.y); Vector3 oldMin = Vector3.zero; switch (_anchor) { case Anchor.LowerLeft: oldMin.Set(0,0,0); break; case Anchor.LowerCenter: oldMin.Set(0.5f,0,0); break; case Anchor.LowerRight: oldMin.Set(1,0,0); break; case Anchor.MiddleLeft: oldMin.Set(0,0.5f,0); break; case Anchor.MiddleCenter: oldMin.Set(0.5f,0.5f,0); break; case Anchor.MiddleRight: oldMin.Set(1,0.5f,0); break; case Anchor.UpperLeft: oldMin.Set(0,1,0); break; case Anchor.UpperCenter: oldMin.Set(0.5f,1,0); break; case Anchor.UpperRight: oldMin.Set(1,1,0); break; } oldMin = Vector3.Scale(oldMin, oldSize) * -1; Vector3 newScale = oldSize + dMax - dMin; newScale.x /= boundsSize.x; newScale.y /= boundsSize.y; // Clamp the minimum size to avoid having the pivot move when we scale from near-zero if (Mathf.Abs(boundsSize.x * newScale.x) < sprite.texelSize.x * minSizeClampTexelScale && Mathf.Abs(newScale.x) < Mathf.Abs(_scale.x)) { dMin.x = 0; newScale.x = _scale.x; } if (Mathf.Abs(boundsSize.y * newScale.y) < sprite.texelSize.y * minSizeClampTexelScale && Mathf.Abs(newScale.y) < Mathf.Abs(_scale.y)) { dMin.y = 0; newScale.y = _scale.y; } // Add our wanted local dMin offset, while negating the positional offset caused by scaling Vector2 scaleFactor = new Vector3(Mathf.Approximately(_scale.x, 0) ? 0 : (newScale.x / _scale.x), Mathf.Approximately(_scale.y, 0) ? 0 : (newScale.y / _scale.y)); Vector3 scaledMin = new Vector3(oldMin.x * scaleFactor.x, oldMin.y * scaleFactor.y); Vector3 offset = dMin + oldMin - scaledMin; offset.z = 0; transform.position = transform.TransformPoint(offset); dimensions = new Vector2(_dimensions.x * scaleFactor.x, _dimensions.y * scaleFactor.y); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using System.Globalization; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class PropertiesFunctionalTests : TestModule { public partial class PropertiesTests : XLinqTestCase { public static object Explicit(Type ret, XAttribute data) { switch (ret.Name) { case "Boolean": return (bool)data; case "Int32": return (int)data; case "UInt32": return (uint)data; case "Int64": return (long)data; case "UInt64": return (ulong)data; case "Single": return (float)data; case "Double": return (double)data; case "Decimal": return (decimal)data; case "DateTime": return (DateTime)data; case "DateTimeOffset": return (DateTimeOffset)data; case "TimeSpan": return (TimeSpan)data; case "Guid": return (Guid)data; case "Nullable`1": { switch (ret.ToString()) { case "System.Nullable`1[System.Boolean]": return (bool?)data; case "System.Nullable`1[System.Int32]": return (int?)data; case "System.Nullable`1[System.Int64]": return (long?)data; case "System.Nullable`1[System.UInt32]": return (uint?)data; case "System.Nullable`1[System.UInt64]": return (ulong?)data; case "System.Nullable`1[System.Single]": return (float?)data; case "System.Nullable`1[System.Double]": return (double?)data; case "System.Nullable`1[System.Decimal]": return (decimal?)data; case "System.Nullable`1[System.DateTime]": return (DateTime?)data; case "System.Nullable`1[System.DateTimeOffset]": return (DateTimeOffset?)data; case "System.Nullable`1[System.TimeSpan]": return (TimeSpan?)data; case "System.Nullable`1[System.Guid]": return (Guid?)data; default: throw new ArgumentOutOfRangeException(); } } default: throw new ArgumentOutOfRangeException(); } } public static object Explicit(Type ret, XElement data) { switch (ret.Name) { case "Boolean": return (bool)data; case "Int32": return (int)data; case "UInt32": return (uint)data; case "Int64": return (long)data; case "UInt64": return (ulong)data; case "Single": return (float)data; case "Double": return (double)data; case "Decimal": return (decimal)data; case "DateTime": return (DateTime)data; case "DateTimeOffset": return (DateTimeOffset)data; case "TimeSpan": return (TimeSpan)data; case "Guid": return (Guid)data; case "Nullable`1": { switch (ret.ToString()) { case "System.Nullable`1[System.Boolean]": return (bool?)data; case "System.Nullable`1[System.Int32]": return (int?)data; case "System.Nullable`1[System.Int64]": return (long?)data; case "System.Nullable`1[System.UInt32]": return (uint?)data; case "System.Nullable`1[System.UInt64]": return (ulong?)data; case "System.Nullable`1[System.Single]": return (float?)data; case "System.Nullable`1[System.Double]": return (double?)data; case "System.Nullable`1[System.Decimal]": return (decimal?)data; case "System.Nullable`1[System.DateTime]": return (DateTime?)data; case "System.Nullable`1[System.DateTimeOffset]": return (DateTimeOffset?)data; case "System.Nullable`1[System.TimeSpan]": return (TimeSpan?)data; case "System.Nullable`1[System.Guid]": return (Guid?)data; default: throw new ArgumentOutOfRangeException(); } } default: throw new ArgumentOutOfRangeException(); } } public enum ExplicitCastTestType { RoundTrip, XmlConvert } public enum NodeCreateType { Constructor, SetValue } //[TestCase(Name = "XElement - value conversion round trip (constructor)", Params = new object[] { typeof(XElement), ExplicitCastTestType.RoundTrip, NodeCreateType.Constructor })] //[TestCase(Name = "XAttribute - value conversion round trip (constructor)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.RoundTrip, NodeCreateType.Constructor })] //[TestCase(Name = "XElement - XmlConvert conformance (constructor)", Params = new object[] { typeof(XElement), ExplicitCastTestType.XmlConvert, NodeCreateType.Constructor })] //[TestCase(Name = "XAttribute - XmlConvert conformance (constructor)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.XmlConvert, NodeCreateType.Constructor })] //[TestCase(Name = "XElement - value conversion round trip (SetValue)", Params = new object[] { typeof(XElement), ExplicitCastTestType.RoundTrip, NodeCreateType.SetValue })] //[TestCase(Name = "XAttribute - value conversion round trip (SetValue)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.RoundTrip, NodeCreateType.SetValue })] //[TestCase(Name = "XElement - XmlConvert conformance (SetValue)", Params = new object[] { typeof(XElement), ExplicitCastTestType.XmlConvert, NodeCreateType.SetValue })] //[TestCase(Name = "XAttribute - XmlConvert conformance (SetValue)", Params = new object[] { typeof(XAttribute), ExplicitCastTestType.XmlConvert, NodeCreateType.SetValue })] public partial class XElement_Op_Eplicit : XLinqTestCase { private object[] _data = new object[] { // bool true, false, // Int32 (int) 1001, (int) 0, (int) (-321), int.MaxValue, int.MinValue, // UInt32 (uint) 1001, (uint) 0, uint.MaxValue, uint.MinValue, (long) 0, (long) (-641), long.MaxValue, long.MinValue, (ulong) 1001, (ulong) 0, ulong.MaxValue, ulong.MinValue, // float (float) 12.1, (float) (-12.1), (float) 0.0, float.Epsilon, float.NaN, float.PositiveInfinity, float.NegativeInfinity, float.MinValue, float.MaxValue, // double (double)12.1, (double)(-12.1), (double)0.0, double.Epsilon, double.NaN, double.PositiveInfinity, double.NegativeInfinity, double.MinValue, double.MaxValue, // decimal (decimal)12.1, (decimal)(-12.1), (decimal) 0.0, decimal.MinValue, decimal.MaxValue, decimal.MinusOne, decimal.One, decimal.Zero, //// DateTimeOffset DateTimeOffset.Now, DateTimeOffset.MaxValue, DateTimeOffset.MinValue, DateTimeOffset.UtcNow, new DateTimeOffset (DateTime.Today), new DateTimeOffset (1989,11,17,19,30,00,TimeSpan.FromHours(8)), new DateTimeOffset (1989,11,17,19,30,00,TimeSpan.FromHours(-8)), // timespan TimeSpan.MaxValue, TimeSpan.MinValue, TimeSpan.Zero, TimeSpan.FromHours (1.4), TimeSpan.FromMilliseconds (1.0), TimeSpan.FromMinutes (5.0), // Guid System.Guid.Empty, System.Guid.NewGuid(), System.Guid.NewGuid() }; public static Dictionary<Type, Type> typeMapper; static XElement_Op_Eplicit() { if (typeMapper == null) { typeMapper = new Dictionary<Type, Type>(); typeMapper.Add(typeof(bool), typeof(bool?)); typeMapper.Add(typeof(int), typeof(int?)); typeMapper.Add(typeof(long), typeof(long?)); typeMapper.Add(typeof(uint), typeof(uint?)); typeMapper.Add(typeof(ulong), typeof(ulong?)); typeMapper.Add(typeof(float), typeof(float?)); typeMapper.Add(typeof(double), typeof(double?)); typeMapper.Add(typeof(decimal), typeof(decimal?)); typeMapper.Add(typeof(DateTime), typeof(DateTime?)); typeMapper.Add(typeof(DateTimeOffset), typeof(DateTimeOffset?)); typeMapper.Add(typeof(TimeSpan), typeof(TimeSpan?)); typeMapper.Add(typeof(Guid), typeof(Guid?)); } } protected override void DetermineChildren() { base.DetermineChildren(); Type type = Params[0] as Type; ExplicitCastTestType testType = (ExplicitCastTestType)Params[1]; NodeCreateType createType = (NodeCreateType)Params[2]; // add normal types foreach (object o in _data) { string desc = o.GetType().ToString() + " : "; // On Arabic locale DateTime and DateTimeOffset types threw on serialization if the date was // too big for the Arabic calendar if (o is DateTime) desc += ((DateTime)o).ToString(CultureInfo.InvariantCulture); else if (o is DateTimeOffset) desc += ((DateTimeOffset)o).ToString(CultureInfo.InvariantCulture); else desc += o; AddChild(new ExplicitCastVariation(testType, createType, type, o, o.GetType(), this, desc)); } // add Nullable types check (not applicable for XmlConvert tests) if (testType == ExplicitCastTestType.RoundTrip) { foreach (object o in _data) { string desc = o.GetType().ToString() + " : "; // On Arabic locale DateTime and DateTimeOffset types threw on serialization if the date was // too big for the Arabic calendar if (o is DateTime) desc += ((DateTime)o).ToString(CultureInfo.InvariantCulture); else if (o is DateTimeOffset) desc += ((DateTimeOffset)o).ToString(CultureInfo.InvariantCulture); else desc += o; AddChild(new ExplicitCastVariation(testType, createType, type, o, typeMapper[o.GetType()], this, desc)); } } } //[Variation(Desc = "XElement.SetValue(null)", Param = null)] //[Variation(Desc = "XElement.SetValue(null)", Param = "")] //[Variation(Desc = "XElement.SetValue(null)", Param = "text")] //[Variation(Desc = "XElement.SetValue(null)", Param = typeof(XElement))] public void SetValueNull() { XElement el = new XElement("elem", Variation.Param is Type ? new XElement("X") : Variation.Param); try { el.SetValue(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Desc = "XAttribute.SetValue(null)")] public void SetValueNullAttr() { XAttribute a = new XAttribute("a", "A"); try { a.SetValue(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Desc = "Conversion to bool overloads (1,True,true)", Params = new object[] { true, new string[] { "1", "True", "true","TRUE", " TRue " } })] //[Variation(Desc = "Conversion to bool overloads (0,False,false)", Params = new object[] { false, new string[] { "0", "False", "false", "FALSE", " FalsE " } })] public void ConversionoBool() { Type type = Params[0] as Type; NodeCreateType nodeCreateType = (NodeCreateType)Params[2]; bool expV = (bool)CurrentChild.Params[0]; string[] strs = CurrentChild.Params[1] as string[]; object node = null; foreach (string data in strs) { switch (nodeCreateType) { case NodeCreateType.Constructor: if (type == typeof(XElement)) { node = new XElement(XName.Get("name"), data); } else if (type == typeof(XAttribute)) { node = new XAttribute(XName.Get("name"), data); } break; case NodeCreateType.SetValue: if (type == typeof(XElement)) { node = new XElement(XName.Get("name"), ""); ((XElement)node).SetValue(data); } else if (type == typeof(XAttribute)) { node = new XAttribute(XName.Get("name"), ""); ((XAttribute)node).SetValue(data); } break; default: TestLog.Compare(false, "test failed: wrong create type"); break; } object retData = type == typeof(XElement) ? (bool)(node as XElement) : (bool)(node as XAttribute); TestLog.Compare(retData.Equals(expV), "Data verification for string :: " + data); } } } public partial class ExplicitCastVariation : TestVariation { private object _data; private Type _nodeType; private Type _retType; private ExplicitCastTestType _testType; private NodeCreateType _nodeCreateType; private string _desc; public ExplicitCastVariation(ExplicitCastTestType testType, NodeCreateType nodeCreateType, Type nodeType, object data, Type retType, TestCase testCase, string desc) { _desc = desc; _data = data; _nodeType = nodeType; _testType = testType; _retType = retType; _nodeCreateType = nodeCreateType; } private XObject CreateContainer() { if (_nodeCreateType == NodeCreateType.Constructor) { if (_nodeType.Name.Equals("XElement")) { return new XElement(XName.Get("name"), _data); } if (_nodeType.Name.Equals("XAttribute")) { return new XAttribute(XName.Get("name"), _data); } } else if (_nodeCreateType == NodeCreateType.SetValue) { if (_nodeType.Name.Equals("XElement")) { var node = new XElement(XName.Get("name"), ""); node.SetValue(_data); return node; } if (_nodeType.Name.Equals("XAttribute")) { var node = new XAttribute(XName.Get("name"), ""); node.SetValue(_data); return node; } } throw new ArgumentOutOfRangeException("Unknown NodeCreateType: " + _nodeCreateType); } public override TestResult Execute() { var node = CreateContainer(); switch (_testType) { case ExplicitCastTestType.RoundTrip: if (_nodeType.Name.Equals("XElement")) { var retData = Explicit(_retType, (XElement)node); TestLog.Compare(retData, _data, "XElement (" + _retType + ")"); } else { var retData = Explicit(_retType, (XAttribute)node); TestLog.Compare(retData, _data, "XElement (" + _retType + ")"); } break; case ExplicitCastTestType.XmlConvert: string xmlConv = ""; switch (_data.GetType().Name) { case "Boolean": xmlConv = XmlConvert.ToString((bool)_data); break; case "Int32": xmlConv = XmlConvert.ToString((int)_data); break; case "UInt32": xmlConv = XmlConvert.ToString((uint)_data); break; case "Int64": xmlConv = XmlConvert.ToString((long)_data); break; case "UInt64": xmlConv = XmlConvert.ToString((ulong)_data); break; case "Single": xmlConv = XmlConvert.ToString((float)_data); break; case "Double": xmlConv = XmlConvert.ToString((double)_data); break; case "Decimal": xmlConv = XmlConvert.ToString((decimal)_data); break; case "DateTime": TestLog.Skip("DateTime Convert include +8:00"); break; case "DateTimeOffset": xmlConv = XmlConvert.ToString((DateTimeOffset)_data); break; case "TimeSpan": xmlConv = XmlConvert.ToString((TimeSpan)_data); break; case "Guid": xmlConv = XmlConvert.ToString((Guid)_data); break; default: TestLog.Skip("No XmlConvert.ToString (" + _data.GetType().Name + ")"); break; } string value = node is XElement ? ((XElement)node).Value : ((XAttribute)node).Value; TestLog.Compare(value == xmlConv, "XmlConvert verification"); break; default: TestLog.Compare(false, "Test failed: wrong test type"); break; } return TestResult.Passed; } } public partial class XElement_Op_Eplicit_Null : XLinqTestCase { protected override void DetermineChildren() { Type nodeType = Params[0] as Type; foreach (Type retType in XElement_Op_Eplicit.typeMapper.Values) { AddChild(new ExplicitCastNullVariation(nodeType, retType, false, this, retType.ToString())); } foreach (Type retType in XElement_Op_Eplicit.typeMapper.Keys) { AddChild(new ExplicitCastNullVariation(nodeType, retType, true, this, retType.ToString())); } } } public partial class ExplicitCastNullVariation : TestVariation { private Type _nodeType, _retType; private bool _shouldThrow; public ExplicitCastNullVariation(Type nodeType, Type retType, bool shouldThrow, TestCase tc, string desc) { this.Desc = desc; _nodeType = nodeType; _retType = retType; _shouldThrow = shouldThrow; } public override TestResult Execute() { try { object ret = null; if (_nodeType.Equals(typeof(XElement))) { XElement e = null; ret = Explicit(_retType, e); } else if (_nodeType.Equals(typeof(XAttribute))) { XAttribute a = null; ret = Explicit(_retType, a); } TestLog.Compare(!_shouldThrow, "The call should throw!"); TestLog.Compare(ret == null, "Return value should be null"); } catch (ArgumentNullException e) { TestLog.Compare(e is ArgumentNullException, "e.InnerException is ArgumentNullException"); TestLog.Compare(_shouldThrow, "shouldThrow"); } return TestResult.Passed; } } } } }
//------------------------------------------------------------------------------ // <copyright file="SoapSchemaExporter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System; using System.Collections; using System.Xml.Schema; using System.Xml; using System.ComponentModel; using System.Diagnostics; /// <include file='doc\SoapSchemaExporter.uex' path='docs/doc[@for="SoapSchemaExporter"]/*' /> /// <internalonly/> public class SoapSchemaExporter { internal const XmlSchemaForm elementFormDefault = XmlSchemaForm.Qualified; XmlSchemas schemas; Hashtable types = new Hashtable(); // StructMapping/EnumMapping -> XmlSchemaComplexType/XmlSchemaSimpleType bool exportedRoot; TypeScope scope; XmlDocument document; static XmlQualifiedName ArrayQName = new XmlQualifiedName(Soap.Array, Soap.Encoding); static XmlQualifiedName ArrayTypeQName = new XmlQualifiedName(Soap.ArrayType, Soap.Encoding); /// <include file='doc\SoapSchemaExporter.uex' path='docs/doc[@for="SoapSchemaExporter.SoapSchemaExporter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapSchemaExporter(XmlSchemas schemas) { this.schemas = schemas; } /// <include file='doc\SoapSchemaExporter.uex' path='docs/doc[@for="SoapSchemaExporter.ExportTypeMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) { CheckScope(xmlTypeMapping.Scope); ExportTypeMapping(xmlTypeMapping.Mapping, null); } /// <include file='doc\SoapSchemaExporter.uex' path='docs/doc[@for="SoapSchemaExporter.ExportMembersMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping) { ExportMembersMapping(xmlMembersMapping, false); } /// <include file='doc\SoapSchemaExporter.uex' path='docs/doc[@for="SoapSchemaExporter.ExportMembersMapping1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool exportEnclosingType) { CheckScope(xmlMembersMapping.Scope); MembersMapping membersMapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping; if (exportEnclosingType) { ExportTypeMapping(membersMapping, null); } else { foreach (MemberMapping memberMapping in membersMapping.Members) { if (memberMapping.Elements.Length > 0) ExportTypeMapping(memberMapping.Elements[0].Mapping, null); } } } void CheckScope(TypeScope scope) { if (this.scope == null) { this.scope = scope; } else if (this.scope != scope) { throw new InvalidOperationException(Res.GetString(Res.XmlMappingsScopeMismatch)); } } internal XmlDocument Document { get { if (document == null) document = new XmlDocument(); return document; } } void CheckForDuplicateType(string newTypeName, string newNamespace){ XmlSchema schema = schemas[newNamespace]; if (schema != null){ foreach (XmlSchemaObject o in schema.Items) { XmlSchemaType type = o as XmlSchemaType; if ( type != null && type.Name == newTypeName) throw new InvalidOperationException(Res.GetString(Res.XmlDuplicateTypeName, newTypeName, newNamespace)); } } } void AddSchemaItem(XmlSchemaObject item, string ns, string referencingNs) { if (!SchemaContainsItem(item, ns)) { XmlSchema schema = schemas[ns]; if (schema == null) { schema = new XmlSchema(); schema.TargetNamespace = ns == null || ns.Length == 0 ? null : ns; #pragma warning disable 429 // unreachable code detected: elementFormDefault is const so it will never be Unqualified schema.ElementFormDefault = elementFormDefault == XmlSchemaForm.Unqualified ? XmlSchemaForm.None : elementFormDefault; #pragma warning restore 429 schemas.Add(schema); } schema.Items.Add(item); } if (referencingNs != null) AddSchemaImport(ns, referencingNs); } void AddSchemaImport(string ns, string referencingNs) { if (referencingNs == null || ns == null) return; if (ns == referencingNs) return; XmlSchema schema = schemas[referencingNs]; if (schema == null) throw new InvalidOperationException(Res.GetString(Res.XmlMissingSchema, referencingNs)); if (ns != null && ns.Length > 0 && FindImport(schema, ns) == null) { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = ns; schema.Includes.Add(import); } } bool SchemaContainsItem(XmlSchemaObject item, string ns) { XmlSchema schema = schemas[ns]; if (schema != null) { return schema.Items.Contains(item); } return false; } XmlSchemaImport FindImport(XmlSchema schema, string ns) { foreach (object item in schema.Includes) { if (item is XmlSchemaImport) { XmlSchemaImport import = (XmlSchemaImport)item; if (import.Namespace == ns) { return import; } } } return null; } XmlQualifiedName ExportTypeMapping(TypeMapping mapping, string ns) { if (mapping is ArrayMapping) return ExportArrayMapping((ArrayMapping)mapping, ns); else if (mapping is EnumMapping) return ExportEnumMapping((EnumMapping)mapping, ns); else if (mapping is PrimitiveMapping) { PrimitiveMapping pm = (PrimitiveMapping)mapping; if (pm.TypeDesc.IsXsdType) { return ExportPrimitiveMapping(pm); } else { return ExportNonXsdPrimitiveMapping(pm, ns); } } else if (mapping is StructMapping) return ExportStructMapping((StructMapping)mapping, ns); else if (mapping is NullableMapping) return ExportTypeMapping(((NullableMapping)mapping).BaseMapping, ns); else if (mapping is MembersMapping) return ExportMembersMapping((MembersMapping)mapping, ns); else throw new ArgumentException(Res.GetString(Res.XmlInternalError), "mapping"); } XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, string ns) { XmlSchemaType type = mapping.TypeDesc.DataType; if (!SchemaContainsItem(type, UrtTypes.Namespace)) { AddSchemaItem(type, UrtTypes.Namespace, ns); } else { AddSchemaImport(UrtTypes.Namespace, ns); } return new XmlQualifiedName(mapping.TypeDesc.DataType.Name, UrtTypes.Namespace); } XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping) { return new XmlQualifiedName(mapping.TypeDesc.DataType.Name, XmlSchema.Namespace); } XmlQualifiedName ExportArrayMapping(ArrayMapping mapping, string ns) { // for the Rpc ArrayMapping different mappings could have the same schema type // we link all mappings corresponding to the same type together // loop through all mapping that will map to the same complexType, and export only one, // the obvious choice is the last one. while (mapping.Next != null) { mapping = mapping.Next; } XmlSchemaComplexType type = (XmlSchemaComplexType)types[mapping]; if (type == null) { CheckForDuplicateType(mapping.TypeName, mapping.Namespace); type = new XmlSchemaComplexType(); type.Name = mapping.TypeName; types.Add(mapping, type); // we need to add the type first, to make sure that the schema get created AddSchemaItem(type, mapping.Namespace, ns); AddSchemaImport(Soap.Encoding, mapping.Namespace); AddSchemaImport(Wsdl.Namespace, mapping.Namespace); XmlSchemaComplexContentRestriction restriction = new XmlSchemaComplexContentRestriction(); XmlQualifiedName qname = ExportTypeMapping(mapping.Elements[0].Mapping, mapping.Namespace); if (qname.IsEmpty) { // this is a root mapping qname = new XmlQualifiedName(Soap.UrType, XmlSchema.Namespace); } //<attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:float[]"/> XmlSchemaAttribute attr = new XmlSchemaAttribute(); attr.RefName = ArrayTypeQName; XmlAttribute attribute = new XmlAttribute("wsdl", Wsdl.ArrayType, Wsdl.Namespace, Document); attribute.Value = qname.Namespace + ":" + qname.Name + "[]"; attr.UnhandledAttributes = new XmlAttribute[] {attribute}; restriction.Attributes.Add(attr); restriction.BaseTypeName = ArrayQName; XmlSchemaComplexContent model = new XmlSchemaComplexContent(); model.Content = restriction; type.ContentModel = model; if (qname.Namespace != XmlSchema.Namespace) AddSchemaImport(qname.Namespace, mapping.Namespace); } else { AddSchemaImport(mapping.Namespace, ns); } return new XmlQualifiedName(mapping.TypeName, mapping.Namespace); } void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] accessors, bool repeats, bool valueTypeOptional, string ns) { if (accessors.Length == 0) return; if (accessors.Length == 1) { ExportElementAccessor(group, accessors[0], repeats, valueTypeOptional, ns); } else { XmlSchemaChoice choice = new XmlSchemaChoice(); choice.MaxOccurs = repeats ? decimal.MaxValue : 1; choice.MinOccurs = repeats ? 0 : 1; for (int i = 0; i < accessors.Length; i++) ExportElementAccessor(choice, accessors[i], false, valueTypeOptional, ns); if (choice.Items.Count > 0) group.Items.Add(choice); } } void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor accessor, bool repeats, bool valueTypeOptional, string ns) { XmlSchemaElement element = new XmlSchemaElement(); element.MinOccurs = repeats || valueTypeOptional ? 0 : 1; element.MaxOccurs = repeats ? decimal.MaxValue : 1; element.Name = accessor.Name; element.IsNillable = accessor.IsNullable || accessor.Mapping is NullableMapping; element.Form = XmlSchemaForm.Unqualified; element.SchemaTypeName = ExportTypeMapping(accessor.Mapping, accessor.Namespace); group.Items.Add(element); } XmlQualifiedName ExportRootMapping(StructMapping mapping) { if (!exportedRoot) { exportedRoot = true; ExportDerivedMappings(mapping); } return new XmlQualifiedName(Soap.UrType, XmlSchema.Namespace); } XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns) { if (mapping.TypeDesc.IsRoot) return ExportRootMapping(mapping); XmlSchemaComplexType type = (XmlSchemaComplexType)types[mapping]; if (type == null) { if (!mapping.IncludeInSchema) throw new InvalidOperationException(Res.GetString(Res.XmlSoapCannotIncludeInSchema, mapping.TypeDesc.Name)); CheckForDuplicateType(mapping.TypeName, mapping.Namespace); type = new XmlSchemaComplexType(); type.Name = mapping.TypeName; types.Add(mapping, type); AddSchemaItem(type, mapping.Namespace, ns); type.IsAbstract = mapping.TypeDesc.IsAbstract; if (mapping.BaseMapping != null && mapping.BaseMapping.IncludeInSchema) { XmlSchemaComplexContentExtension extension = new XmlSchemaComplexContentExtension(); extension.BaseTypeName = ExportStructMapping(mapping.BaseMapping, mapping.Namespace); XmlSchemaComplexContent model = new XmlSchemaComplexContent(); model.Content = extension; type.ContentModel = model; } ExportTypeMembers(type, mapping.Members, mapping.Namespace); ExportDerivedMappings(mapping); } else { AddSchemaImport(mapping.Namespace, ns); } return new XmlQualifiedName(type.Name, mapping.Namespace); } XmlQualifiedName ExportMembersMapping(MembersMapping mapping, string ns) { XmlSchemaComplexType type = (XmlSchemaComplexType)types[mapping]; if(type == null) { CheckForDuplicateType(mapping.TypeName, mapping.Namespace); type = new XmlSchemaComplexType(); type.Name = mapping.TypeName; types.Add(mapping, type); AddSchemaItem(type, mapping.Namespace, ns); ExportTypeMembers(type, mapping.Members, mapping.Namespace); } else { AddSchemaImport(mapping.Namespace, ns); } return new XmlQualifiedName(type.Name, mapping.Namespace); } void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] members, string ns) { XmlSchemaGroupBase seq = new XmlSchemaSequence(); for (int i = 0; i < members.Length; i++) { MemberMapping member = members[i]; if (member.Elements.Length > 0) { bool valueTypeOptional = member.CheckSpecified != SpecifiedAccessor.None || member.CheckShouldPersist || !member.TypeDesc.IsValueType; ExportElementAccessors(seq, member.Elements, false, valueTypeOptional, ns); } } if (seq.Items.Count > 0) { if (type.ContentModel != null) { if (type.ContentModel.Content is XmlSchemaComplexContentExtension) ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Particle = seq; else if (type.ContentModel.Content is XmlSchemaComplexContentRestriction) ((XmlSchemaComplexContentRestriction)type.ContentModel.Content).Particle = seq; else throw new InvalidOperationException(Res.GetString(Res.XmlInvalidContent, type.ContentModel.Content.GetType().Name)); } else { type.Particle = seq; } } } void ExportDerivedMappings(StructMapping mapping) { for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { if (derived.IncludeInSchema) ExportStructMapping(derived, mapping.TypeDesc.IsRoot ? null : mapping.Namespace); } } XmlQualifiedName ExportEnumMapping(EnumMapping mapping, string ns) { XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)types[mapping]; if (dataType == null) { CheckForDuplicateType(mapping.TypeName, mapping.Namespace); dataType = new XmlSchemaSimpleType(); dataType.Name = mapping.TypeName; types.Add(mapping, dataType); AddSchemaItem(dataType, mapping.Namespace, ns); XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace); for (int i = 0; i < mapping.Constants.Length; i++) { ConstantMapping constant = mapping.Constants[i]; XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = constant.XmlName; restriction.Facets.Add(enumeration); } if (!mapping.IsFlags) { dataType.Content = restriction; } else { XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList(); XmlSchemaSimpleType enumType = new XmlSchemaSimpleType(); enumType.Content = restriction; list.ItemType = enumType; dataType.Content = list; } } else { AddSchemaImport(mapping.Namespace, ns); } return new XmlQualifiedName(mapping.TypeName, mapping.Namespace); } } }
// // RadioTrackInfo.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2007 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.Threading; using System.Collections.Generic; using Mono.Unix; using Hyena; using Media.Playlists.Xspf; using Banshee.Base; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Playlists.Formats; namespace Banshee.Streaming { public class RadioTrackInfo : TrackInfo { #region Static Helper Methods public static RadioTrackInfo OpenPlay (string uri) { try { return OpenPlay (new SafeUri (uri)); } catch (Exception e) { Hyena.Log.Exception (e); return null; } } public static RadioTrackInfo OpenPlay (SafeUri uri) { RadioTrackInfo track = Open (uri); if (track != null) { track.Play (); } return track; } public static RadioTrackInfo Open (string uri) { return Open (new SafeUri (uri)); } public static RadioTrackInfo Open (SafeUri uri) { try { RadioTrackInfo radio_track = new RadioTrackInfo (uri); radio_track.ParsingPlaylistEvent += delegate { ThreadAssist.ProxyToMain (delegate { if (radio_track.PlaybackError != StreamPlaybackError.None) { Log.Error (Catalog.GetString ("Error opening stream"), Catalog.GetString ("Could not open stream or playlist"), true); radio_track = null; } }); }; return radio_track; } catch { Log.Error (Catalog.GetString ("Error opening stream"), Catalog.GetString("Problem parsing playlist"), true); return null; } } #endregion private Track track; private SafeUri single_location; private List<SafeUri> stream_uris = new List<SafeUri>(); private int stream_index = 0; private bool loaded = false; private bool parsing_playlist = false; private bool trying_to_play; private TrackInfo parent_track; public TrackInfo ParentTrack { get { return parent_track; } set { parent_track = value; } } public event EventHandler ParsingPlaylistEvent; protected RadioTrackInfo() { IsLive = true; } public RadioTrackInfo(Track track) : this() { TrackTitle = track.Title; ArtistName = track.Creator; this.track = track; } public RadioTrackInfo(SafeUri uri) : this() { this.single_location = uri; } public RadioTrackInfo (TrackInfo parentTrack) : this (parentTrack.Uri) { ArtistName = parentTrack.ArtistName; TrackTitle = parentTrack.TrackTitle; AlbumTitle = parentTrack.AlbumTitle; ParentTrack = parentTrack; } public void Play() { if (trying_to_play) { return; } trying_to_play = true; SavePlaybackError (StreamPlaybackError.None); if (loaded) { PlayCore (); } else { // Stop playing until we load this radio station and play it ServiceManager.PlayerEngine.Close (true); ServiceManager.PlayerEngine.TrackIntercept += OnTrackIntercept; // Tell the seek slider that we're connecting // TODO move all this playlist-downloading/parsing logic into PlayerEngine? ServiceManager.PlayerEngine.StartSynthesizeContacting (this); OnParsingPlaylistStarted (); ThreadPool.QueueUserWorkItem (delegate { try { LoadStreamUris (); } catch (Exception e) { trying_to_play = false; Log.Exception (this.ToString (), e); SavePlaybackError (StreamPlaybackError.Unknown); OnParsingPlaylistFinished (); ServiceManager.PlayerEngine.Close (); } }); } } public override StreamPlaybackError PlaybackError { get { return ParentTrack == null ? base.PlaybackError : ParentTrack.PlaybackError; } set { if (value != StreamPlaybackError.None) { ServiceManager.PlayerEngine.EndSynthesizeContacting (this, true); } if (ParentTrack == null) { base.PlaybackError = value; } else { ParentTrack.PlaybackError = value; } } } public new void SavePlaybackError (StreamPlaybackError value) { PlaybackError = value; Save (); if (ParentTrack != null) { ParentTrack.Save (); } } private void PlayCore () { ServiceManager.PlayerEngine.EndSynthesizeContacting (this, false); if(track != null) { TrackTitle = track.Title; ArtistName = track.Creator; } AlbumTitle = null; Duration = TimeSpan.Zero; lock(stream_uris) { if(stream_uris.Count > 0) { Uri = stream_uris[stream_index]; Log.Debug("Playing Radio Stream", Uri.AbsoluteUri); if (Uri.IsFile) { try { using (var file = StreamTagger.ProcessUri (Uri)) { StreamTagger.TrackInfoMerge (this, file, true); } } catch (Exception e) { Log.Warning (String.Format ("Failed to update metadata for {0}", this), e.GetType ().ToString (), false); } } ServiceManager.PlayerEngine.OpenPlay(this); } } trying_to_play = false; } public bool PlayNextStream() { if(stream_index < stream_uris.Count - 1) { stream_index++; Play(); return true; } ServiceManager.PlaybackController.StopWhenFinished = true; return false; } public bool PlayPreviousStream() { if (stream_index > 0) { stream_index--; Play(); return true; } ServiceManager.PlaybackController.StopWhenFinished = true; return false; } private void LoadStreamUris() { lock(stream_uris) { if(track != null) { foreach(Uri uri in track.Locations) { LoadStreamUri(uri.AbsoluteUri); } } else { LoadStreamUri(single_location.AbsoluteUri); } loaded = true; } ServiceManager.PlayerEngine.TrackIntercept -= OnTrackIntercept; OnParsingPlaylistFinished(); if (ServiceManager.PlayerEngine.CurrentTrack == this) { PlayCore(); } else { trying_to_play = false; } } private bool OnTrackIntercept (TrackInfo track) { if (track != this && track != ParentTrack) { ServiceManager.PlayerEngine.EndSynthesizeContacting (this, false); ServiceManager.PlayerEngine.TrackIntercept -= OnTrackIntercept; } return false; } private void LoadStreamUri(string uri) { try { PlaylistParser parser = new PlaylistParser(); if (parser.Parse(new SafeUri(uri))) { foreach(Dictionary<string, object> element in parser.Elements) { if(element.ContainsKey("uri")) { // mms can be a nested link string element_uri = element["uri"].ToString(); if(element_uri.StartsWith("mms:", StringComparison.CurrentCultureIgnoreCase)){ LoadStreamUri("http" + element_uri.Substring(element_uri.IndexOf(":"))); } stream_uris.Add(new SafeUri(((Uri)element["uri"]).AbsoluteUri)); } } } else { stream_uris.Add(new SafeUri(uri)); } Log.DebugFormat ("Parsed {0} URIs out of {1}", stream_uris.Count, this); } catch (System.Net.WebException e) { Hyena.Log.Exception (this.ToString (), e); SavePlaybackError (StreamPlaybackError.ResourceNotFound); } catch (Exception e) { Hyena.Log.Exception (this.ToString (), e); SavePlaybackError (StreamPlaybackError.Unknown); } } private void OnParsingPlaylistStarted() { parsing_playlist = true; OnParsingPlaylistEvent(); } private void OnParsingPlaylistFinished() { parsing_playlist = false; OnParsingPlaylistEvent(); } private void OnParsingPlaylistEvent() { EventHandler handler = ParsingPlaylistEvent; if(handler != null) { handler(this, EventArgs.Empty); } } public Track XspfTrack { get { return track; } } public bool ParsingPlaylist { get { return parsing_playlist; } } } }
using System; using System.Collections; using System.Collections.Generic; using Volante; namespace Volante.Impl { class Rtree<T> : PersistentCollection<T>, ISpatialIndex<T> where T : class, IPersistent { private int height; private int n; private RtreePage root; [NonSerialized()] private int updateCounter; internal Rtree() { } public override int Count { get { return n; } } public void Put(Rectangle r, T obj) { if (root == null) { root = new RtreePage(Database, obj, r); height = 1; } else { RtreePage p = root.insert(Database, r, obj, height); if (p != null) { root = new RtreePage(Database, root, p); height += 1; } } n += 1; updateCounter += 1; Modify(); } public void Remove(Rectangle r, T obj) { if (root == null) throw new DatabaseException(DatabaseException.ErrorCode.KEY_NOT_FOUND); ArrayList reinsertList = new ArrayList(); int reinsertLevel = root.remove(r, obj, height, reinsertList); if (reinsertLevel < 0) throw new DatabaseException(DatabaseException.ErrorCode.KEY_NOT_FOUND); for (int i = reinsertList.Count; --i >= 0; ) { RtreePage p = (RtreePage)reinsertList[i]; for (int j = 0, pn = p.n; j < pn; j++) { RtreePage q = root.insert(Database, p.b[j], p.branch[j], height - reinsertLevel); if (q != null) { // root splitted root = new RtreePage(Database, root, q); height += 1; } } reinsertLevel -= 1; p.Deallocate(); } if (root.n == 1 && height > 1) { RtreePage newRoot = (RtreePage)root.branch[0]; root.Deallocate(); root = newRoot; height -= 1; } n -= 1; updateCounter += 1; Modify(); } public T[] Get(Rectangle r) { ArrayList result = new ArrayList(); if (root != null) root.find(r, result, height); return (T[])result.ToArray(typeof(T)); } public Rectangle WrappingRectangle { get { return (root != null) ? root.cover() : new Rectangle(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue); } } public override void Clear() { if (root != null) { root.purge(height); root = null; } height = 0; n = 0; updateCounter += 1; Modify(); } public override void Deallocate() { Clear(); base.Deallocate(); } public IEnumerable<T> Overlaps(Rectangle r) { return new RtreeIterator(this, r); } public override IEnumerator<T> GetEnumerator() { return Overlaps(WrappingRectangle).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IDictionaryEnumerator GetDictionaryEnumerator(Rectangle r) { return new RtreeEntryIterator(this, r); } public IDictionaryEnumerator GetDictionaryEnumerator() { return GetDictionaryEnumerator(WrappingRectangle); } class RtreeIterator : IEnumerator<T>, IEnumerable<T> { internal RtreeIterator(Rtree<T> tree, Rectangle r) { counter = tree.updateCounter; height = tree.height; this.tree = tree; if (height == 0) return; this.r = r; pageStack = new RtreePage[height]; posStack = new int[height]; Reset(); } public IEnumerator<T> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } public void Reset() { hasNext = gotoFirstItem(0, tree.root); } public void Dispose() { } public bool MoveNext() { if (counter != tree.updateCounter) throw new InvalidOperationException("Tree was modified"); if (hasNext) { page = pageStack[height - 1]; pos = posStack[height - 1]; if (!gotoNextItem(height - 1)) hasNext = false; return true; } else { page = null; return false; } } public virtual T Current { get { if (page == null) throw new InvalidOperationException(); return (T)page.branch[pos]; } } object IEnumerator.Current { get { return Current; } } private bool gotoFirstItem(int sp, RtreePage pg) { for (int i = 0, n = pg.n; i < n; i++) { if (r.Intersects(pg.b[i])) { if (sp + 1 == height || gotoFirstItem(sp + 1, (RtreePage)pg.branch[i])) { pageStack[sp] = pg; posStack[sp] = i; return true; } } } return false; } private bool gotoNextItem(int sp) { RtreePage pg = pageStack[sp]; for (int i = posStack[sp], n = pg.n; ++i < n; ) { if (r.Intersects(pg.b[i])) { if (sp + 1 == height || gotoFirstItem(sp + 1, (RtreePage)pg.branch[i])) { pageStack[sp] = pg; posStack[sp] = i; return true; } } } pageStack[sp] = null; return (sp > 0) ? gotoNextItem(sp - 1) : false; } protected RtreePage[] pageStack; protected int[] posStack; protected int counter; protected int height; protected int pos; protected bool hasNext; protected RtreePage page; protected Rtree<T> tree; protected Rectangle r; } class RtreeEntryIterator : RtreeIterator, IDictionaryEnumerator { internal RtreeEntryIterator(Rtree<T> tree, Rectangle r) : base(tree, r) { } public new virtual object Current { get { return Entry; } } object IEnumerator.Current { get { return Current; } } public DictionaryEntry Entry { get { if (page == null) throw new InvalidOperationException(); return new DictionaryEntry(page.b[pos], page.branch[pos]); } } public object Key { get { if (page == null) throw new InvalidOperationException(); return page.b[pos]; } } public object Value { get { if (page == null) throw new InvalidOperationException(); return page.branch[pos]; } } } } }
/* * 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 NodaTime; using QuantConnect.Configuration; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Packets; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using QuantConnect.Util; using HistoryRequest = QuantConnect.Data.HistoryRequest; using Timer = System.Timers.Timer; using System.Threading; namespace QuantConnect.ToolBox.IQFeed { /// <summary> /// IQFeedDataQueueHandler is an implementation of IDataQueueHandler and IHistoryProvider /// </summary> public class IQFeedDataQueueHandler : HistoryProviderBase, IDataQueueHandler, IDataQueueUniverseProvider { private bool _isConnected; private readonly HashSet<Symbol> _symbols; private readonly Dictionary<Symbol, Symbol> _underlyings; private readonly object _sync = new object(); private IQFeedDataQueueUniverseProvider _symbolUniverse; //Socket connections: private AdminPort _adminPort; private Level1Port _level1Port; private HistoryPort _historyPort; private readonly IDataAggregator _aggregator = Composer.Instance.GetExportedValueByTypeName<IDataAggregator>( Config.Get("data-aggregator", "QuantConnect.Lean.Engine.DataFeeds.AggregationManager")); private readonly EventBasedDataQueueHandlerSubscriptionManager _subscriptionManager; /// <summary> /// Gets the total number of data points emitted by this history provider /// </summary> public override int DataPointCount { get; } = 0; /// <summary> /// IQFeedDataQueueHandler is an implementation of IDataQueueHandler: /// </summary> public IQFeedDataQueueHandler() { _symbols = new HashSet<Symbol>(); _underlyings = new Dictionary<Symbol, Symbol>(); _subscriptionManager = new EventBasedDataQueueHandlerSubscriptionManager(); _subscriptionManager.SubscribeImpl += (s, t) => { Subscribe(s); return true; }; _subscriptionManager.UnsubscribeImpl += (s, t) => { Unsubscribe(s); return true; }; if (!IsConnected) Connect(); } /// <summary> /// Subscribe to the specified configuration /// </summary> /// <param name="dataConfig">defines the parameters to subscribe to a data feed</param> /// <param name="newDataAvailableHandler">handler to be fired on new data available</param> /// <returns>The new enumerator for this subscription request</returns> public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler) { if (!CanSubscribe(dataConfig.Symbol)) { return null; } var enumerator = _aggregator.Add(dataConfig, newDataAvailableHandler); _subscriptionManager.Subscribe(dataConfig); return enumerator; } /// <summary> /// Adds the specified symbols to the subscription: new IQLevel1WatchItem("IBM", true) /// </summary> /// <param name="symbols">The symbols to be added keyed by SecurityType</param> public void Subscribe(IEnumerable<Symbol> symbols) { try { foreach (var symbol in symbols) { lock (_sync) { Log.Trace("IQFeed.Subscribe(): Subscribe Request: " + symbol.ToString()); if (_symbols.Add(symbol)) { // processing canonical option symbol to subscribe to underlying prices var subscribeSymbol = symbol; if (symbol.ID.SecurityType == SecurityType.Option && symbol.IsCanonical()) { subscribeSymbol = symbol.Underlying; _underlyings.Add(subscribeSymbol, symbol); } if (symbol.ID.SecurityType == SecurityType.Future && symbol.IsCanonical()) { // do nothing for now. Later might add continuous contract symbol. return; } var ticker = _symbolUniverse.GetBrokerageSymbol(subscribeSymbol); if (!string.IsNullOrEmpty(ticker)) { _level1Port.Subscribe(ticker); Log.Trace("IQFeed.Subscribe(): Subscribe Processed: {0} ({1})", symbol.Value, ticker); } else { Log.Error("IQFeed.Subscribe(): Symbol {0} was not found in IQFeed symbol universe", symbol.Value); } } } } } catch (Exception err) { Log.Error("IQFeed.Subscribe(): " + err.Message); } } /// <summary> /// Removes the specified configuration /// </summary> /// <param name="dataConfig">Subscription config to be removed</param> public void Unsubscribe(SubscriptionDataConfig dataConfig) { _subscriptionManager.Unsubscribe(dataConfig); _aggregator.Remove(dataConfig); } /// <summary> /// Sets the job we're subscribing for /// </summary> /// <param name="job">Job we're subscribing for</param> public void SetJob(LiveNodePacket job) { } /// <summary> /// Removes the specified symbols to the subscription /// </summary> /// <param name="symbols">The symbols to be removed keyed by SecurityType</param> public void Unsubscribe(IEnumerable<Symbol> symbols) { try { foreach (var symbol in symbols) { lock (_sync) { Log.Trace("IQFeed.Unsubscribe(): " + symbol.ToString()); _symbols.Remove(symbol); var subscribeSymbol = symbol; if (symbol.ID.SecurityType == SecurityType.Option && symbol.ID.StrikePrice == 0.0m) { subscribeSymbol = symbol.Underlying; _underlyings.Remove(subscribeSymbol); } var ticker = _symbolUniverse.GetBrokerageSymbol(subscribeSymbol); if (_level1Port.Contains(ticker)) { _level1Port.Unsubscribe(ticker); } } } } catch (Exception err) { Log.Error("IQFeed.Unsubscribe(): " + err.Message); } } /// <summary> /// Initializes this history provider to work for the specified job /// </summary> /// <param name="parameters">The initialization parameters</param> public override void Initialize(HistoryProviderInitializeParameters parameters) { } /// <summary> /// Gets the history for the requested securities /// </summary> /// <param name="requests">The historical data requests</param> /// <param name="sliceTimeZone">The time zone used when time stamping the slice instances</param> /// <returns>An enumerable of the slices of data covering the span specified in each request</returns> public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone) { foreach (var request in requests) { foreach (var slice in _historyPort.ProcessHistoryRequests(request)) { yield return slice; } } } /// <summary> /// Indicates the connection is live. /// </summary> public bool IsConnected => _isConnected; /// <summary> /// Connect to the IQ Feed using supplied username and password information. /// </summary> private void Connect() { try { // Launch the IQ Feed Application: Log.Trace("IQFeed.Connect(): Launching client..."); if (OS.IsWindows) { // IQConnect is only supported on Windows var connector = new IQConnect(Config.Get("iqfeed-productName"), "1.0"); connector.Launch(); } // Initialise one admin port Log.Trace("IQFeed.Connect(): Connecting to admin..."); _adminPort = new AdminPort(); _adminPort.Connect(); _adminPort.SetAutoconnect(); _adminPort.SetClientStats(false); _adminPort.SetClientName("Admin"); _adminPort.DisconnectedEvent += AdminPortOnDisconnectedEvent; _adminPort.ConnectedEvent += AdminPortOnConnectedEvent; _symbolUniverse = new IQFeedDataQueueUniverseProvider(); Log.Trace("IQFeed.Connect(): Connecting to L1 data..."); _level1Port = new Level1Port(_aggregator, _symbolUniverse); _level1Port.Connect(); _level1Port.SetClientName("Level1"); Log.Trace("IQFeed.Connect(): Connecting to Historical data..."); _historyPort = new HistoryPort(_symbolUniverse); _historyPort.Connect(); _historyPort.SetClientName("History"); _isConnected = true; } catch (Exception err) { Log.Error("IQFeed.Connect(): Error Connecting to IQFeed: " + err.Message); _isConnected = false; } } /// <summary> /// Disconnect from all ports we're subscribed to: /// </summary> /// <remarks> /// Not being used. IQ automatically disconnect on killing LEAN /// </remarks> private void Disconnect() { if (_adminPort != null) _adminPort.Disconnect(); if (_level1Port != null) _level1Port.Disconnect(); _isConnected = false; Log.Trace("IQFeed.Disconnect(): Disconnected"); } /// <summary> /// Returns true if this data provide can handle the specified symbol /// </summary> /// <param name="symbol">The symbol to be handled</param> /// <returns>True if this data provider can get data for the symbol, false otherwise</returns> private static bool CanSubscribe(Symbol symbol) { var market = symbol.ID.Market; var securityType = symbol.ID.SecurityType; if (symbol.Value.IndexOfInvariant("universe", true) != -1) return false; return (securityType == SecurityType.Equity && market == Market.USA) || (securityType == SecurityType.Forex && market == Market.FXCM) || (securityType == SecurityType.Option && market == Market.USA) || (securityType == SecurityType.Future); } /// <summary> /// Admin port is connected. /// </summary> private void AdminPortOnConnectedEvent(object sender, ConnectedEventArgs connectedEventArgs) { _isConnected = true; Log.Error("IQFeed.AdminPortOnConnectedEvent(): ADMIN PORT CONNECTED!"); } /// <summary> /// Admin port disconnected from the IQFeed server. /// </summary> private void AdminPortOnDisconnectedEvent(object sender, DisconnectedEventArgs disconnectedEventArgs) { _isConnected = false; Log.Error("IQFeed.AdminPortOnDisconnectedEvent(): ADMIN PORT DISCONNECTED!"); } /// <summary> /// Method returns a collection of Symbols that are available at the data source. /// </summary> /// <param name="lookupName">String representing the name to lookup</param> /// <param name="securityType">Expected security type of the returned symbols (if any)</param> /// <param name="includeExpired">Include expired contracts</param> /// <param name="securityCurrency">Expected security currency(if any)</param> /// <param name="securityExchange">Expected security exchange name(if any)</param> /// <returns>Symbol results</returns> public IEnumerable<Symbol> LookupSymbols(string lookupName, SecurityType securityType, bool includeExpired, string securityCurrency = null, string securityExchange = null) { return _symbolUniverse.LookupSymbols(lookupName, securityType, includeExpired, securityCurrency, securityExchange); } /// <summary> /// Method returns a collection of Symbols that are available at the data source. /// </summary> /// <param name="symbol">Symbol to lookup</param> /// <param name="includeExpired">Include expired contracts</param> /// <param name="securityCurrency">Expected security currency(if any)</param> /// <returns>Symbol results</returns> public IEnumerable<Symbol> LookupSymbols(Symbol symbol, bool includeExpired, string securityCurrency) { return LookupSymbols(symbol.ID.Symbol, symbol.SecurityType, includeExpired, securityCurrency); } /// <summary> /// Returns whether selection can take place or not. /// </summary> /// <returns>True if selection can take place</returns> public bool CanPerformSelection() { return _symbolUniverse.CanPerformSelection(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _symbolUniverse.DisposeSafely(); } } /// <summary> /// Admin class type /// </summary> public class AdminPort : IQAdminSocketClient { public AdminPort() : base(80) { } } /// <summary> /// Level 1 Data Request: /// </summary> public class Level1Port : IQLevel1Client { private int count; private DateTime start; private DateTime _feedTime; private Stopwatch _stopwatch = new Stopwatch(); private readonly Timer _timer; private readonly ConcurrentDictionary<string, double> _prices; private readonly ConcurrentDictionary<string, int> _openInterests; private readonly IQFeedDataQueueUniverseProvider _symbolUniverse; private readonly IDataAggregator _aggregator; private int _dataQueueCount; public DateTime FeedTime { get { if (_feedTime == new DateTime()) return DateTime.Now; return _feedTime.AddMilliseconds(_stopwatch.ElapsedMilliseconds); } set { _feedTime = value; _stopwatch = Stopwatch.StartNew(); } } public Level1Port(IDataAggregator aggregator, IQFeedDataQueueUniverseProvider symbolUniverse) : base(80) { start = DateTime.Now; _prices = new ConcurrentDictionary<string, double>(); _openInterests = new ConcurrentDictionary<string, int>(); _aggregator = aggregator; _symbolUniverse = symbolUniverse; Level1SummaryUpdateEvent += OnLevel1SummaryUpdateEvent; Level1TimerEvent += OnLevel1TimerEvent; Level1ServerDisconnectedEvent += OnLevel1ServerDisconnected; Level1ServerReconnectFailed += OnLevel1ServerReconnectFailed; Level1UnknownEvent += OnLevel1UnknownEvent; Level1FundamentalEvent += OnLevel1FundamentalEvent; _timer = new Timer(1000); _timer.Enabled = false; _timer.AutoReset = true; _timer.Elapsed += (sender, args) => { var ticksPerSecond = count / (DateTime.Now - start).TotalSeconds; int dataQueueCount = Interlocked.Exchange(ref _dataQueueCount, 0); if (ticksPerSecond > 1000 || dataQueueCount > 31) { Log.Trace($"IQFeed.OnSecond(): Ticks/sec: {ticksPerSecond.ToStringInvariant("0000.00")} " + $"Engine.Ticks.Count: {dataQueueCount} CPU%: {OS.CpuUsage.ToStringInvariant("0.0") + "%"}" ); } count = 0; start = DateTime.Now; }; _timer.Enabled = true; } private Symbol GetLeanSymbol(string ticker) { return _symbolUniverse.GetLeanSymbol(ticker, SecurityType.Base, null); } private void OnLevel1FundamentalEvent(object sender, Level1FundamentalEventArgs e) { // handle split data, they're only valid today, they'll show up around 4:45am EST if (e.SplitDate1.Date == DateTime.Today && DateTime.Now.TimeOfDay.TotalHours <= 8) // they will always be sent premarket { // get the last price, if it doesn't exist then we'll just issue the split claiming the price was zero // this should (ideally) never happen, but sending this without the price is much better then not sending // it at all double referencePrice; _prices.TryGetValue(e.Symbol, out referencePrice); var symbol = GetLeanSymbol(e.Symbol); var split = new Split(symbol, FeedTime, (decimal)referencePrice, (decimal)e.SplitFactor1, SplitType.SplitOccurred); Emit(split); } } /// <summary> /// Handle a new price update packet: /// </summary> private void OnLevel1SummaryUpdateEvent(object sender, Level1SummaryUpdateEventArgs e) { // if ticker is not found, unsubscribe if (e.NotFound) Unsubscribe(e.Symbol); // only update if we have a value if (e.Last == 0) return; // only accept trade and B/A updates if (e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.ExtendedTrade && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Trade && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Bid && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Ask) return; count++; var time = FeedTime; var last = (decimal)(e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.ExtendedTrade ? e.ExtendedTradingLast : e.Last); var symbol = GetLeanSymbol(e.Symbol); TickType tradeType; switch (symbol.ID.SecurityType) { // the feed time is in NYC/EDT, convert it into EST case SecurityType.Forex: time = FeedTime.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); // TypeOfUpdate always equal to UpdateType.Trade for FXCM, but the message contains B/A and last data tradeType = TickType.Quote; break; // for all other asset classes we leave it as is (NYC/EDT) default: time = FeedTime; tradeType = e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.Bid || e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.Ask ? TickType.Quote : TickType.Trade; break; } var tick = new Tick(time, symbol, last, (decimal)e.Bid, (decimal)e.Ask) { AskSize = e.AskSize, BidSize = e.BidSize, Quantity = e.IncrementalVolume, TickType = tradeType, DataType = MarketDataType.Tick }; Emit(tick); _prices[e.Symbol] = e.Last; if (symbol.ID.SecurityType == SecurityType.Option || symbol.ID.SecurityType == SecurityType.Future) { if (!_openInterests.ContainsKey(e.Symbol) || _openInterests[e.Symbol] != e.OpenInterest) { var oi = new OpenInterest(time, symbol, e.OpenInterest); Emit(oi); _openInterests[e.Symbol] = e.OpenInterest; } } } private void Emit(BaseData tick) { _aggregator.Update(tick); Interlocked.Increment(ref _dataQueueCount); } /// <summary> /// Set the interal clock time. /// </summary> private void OnLevel1TimerEvent(object sender, Level1TimerEventArgs e) { //If there was a bad tick and the time didn't set right, skip setting it here and just use our millisecond timer to set the time from last time it was set. if (e.DateTimeStamp != DateTime.MinValue) { FeedTime = e.DateTimeStamp; } } /// <summary> /// Server has disconnected, reconnect. /// </summary> private void OnLevel1ServerDisconnected(object sender, Level1ServerDisconnectedArgs e) { Log.Error("IQFeed.OnLevel1ServerDisconnected(): LEVEL 1 PORT DISCONNECTED! " + e.TextLine); } /// <summary> /// Server has disconnected, reconnect. /// </summary> private void OnLevel1ServerReconnectFailed(object sender, Level1ServerReconnectFailedArgs e) { Log.Error("IQFeed.OnLevel1ServerReconnectFailed(): LEVEL 1 PORT DISCONNECT! " + e.TextLine); } /// <summary> /// Got a message we don't know about, log it for posterity. /// </summary> private void OnLevel1UnknownEvent(object sender, Level1TextLineEventArgs e) { Log.Error("IQFeed.OnUnknownEvent(): " + e.TextLine); } } // this type is expected to be used for exactly one job at a time public class HistoryPort : IQLookupHistorySymbolClient { private bool _inProgress; private ConcurrentDictionary<string, HistoryRequest> _requestDataByRequestId; private ConcurrentDictionary<string, List<BaseData>> _currentRequest; private readonly string DataDirectory = Config.Get("data-directory", "../../../Data"); private readonly double MaxHistoryRequestMinutes = Config.GetDouble("max-history-minutes", 5); private readonly IQFeedDataQueueUniverseProvider _symbolUniverse; /// <summary> /// ... /// </summary> public HistoryPort(IQFeedDataQueueUniverseProvider symbolUniverse) : base(80) { _symbolUniverse = symbolUniverse; _requestDataByRequestId = new ConcurrentDictionary<string, HistoryRequest>(); _currentRequest = new ConcurrentDictionary<string, List<BaseData>>(); } /// <summary> /// ... /// </summary> public HistoryPort(IQFeedDataQueueUniverseProvider symbolUniverse, int maxDataPoints, int dataPointsPerSend) : this(symbolUniverse) { MaxDataPoints = maxDataPoints; DataPointsPerSend = dataPointsPerSend; } /// <summary> /// Populate request data /// </summary> public IEnumerable<Slice> ProcessHistoryRequests(HistoryRequest request) { // skipping universe and canonical symbols if (!CanHandle(request.Symbol) || (request.Symbol.ID.SecurityType == SecurityType.Option && request.Symbol.IsCanonical()) || (request.Symbol.ID.SecurityType == SecurityType.Future && request.Symbol.IsCanonical())) { yield break; } // Set this process status _inProgress = true; var ticker = _symbolUniverse.GetBrokerageSymbol(request.Symbol); var start = request.StartTimeUtc.ConvertFromUtc(TimeZones.NewYork); DateTime? end = request.EndTimeUtc.ConvertFromUtc(TimeZones.NewYork); var exchangeTz = request.ExchangeHours.TimeZone; // if we're within a minute of now, don't set the end time if (request.EndTimeUtc >= DateTime.UtcNow.AddMinutes(-1)) { end = null; } Log.Trace($"HistoryPort.ProcessHistoryJob(): Submitting request: {request.Symbol.SecurityType.ToStringInvariant()}-{ticker}: " + $"{request.Resolution.ToStringInvariant()} {start.ToStringInvariant()}->{(end ?? DateTime.UtcNow.AddMinutes(-1)).ToStringInvariant()}" ); int id; var reqid = string.Empty; switch (request.Resolution) { case Resolution.Tick: id = RequestTickData(ticker, start, end, true); reqid = CreateRequestID(LookupType.REQ_HST_TCK, id); break; case Resolution.Daily: id = RequestDailyData(ticker, start, end, true); reqid = CreateRequestID(LookupType.REQ_HST_DWM, id); break; default: var interval = new Interval(GetPeriodType(request.Resolution), 1); id = RequestIntervalData(ticker, interval, start, end, true); reqid = CreateRequestID(LookupType.REQ_HST_INT, id); break; } _requestDataByRequestId[reqid] = request; while (_inProgress) { continue; } // After all data arrive, we pass it to the algorithm through memory and write to a file foreach (var key in _currentRequest.Keys) { List<BaseData> tradeBars; if (_currentRequest.TryRemove(key, out tradeBars)) { foreach (var tradeBar in tradeBars) { // Returns IEnumerable<Slice> object yield return new Slice(tradeBar.EndTime, new[] { tradeBar }, tradeBar.EndTime.ConvertToUtc(exchangeTz)); } } } } /// <summary> /// Returns true if this data provide can handle the specified symbol /// </summary> /// <param name="symbol">The symbol to be handled</param> /// <returns>True if this data provider can get data for the symbol, false otherwise</returns> private bool CanHandle(Symbol symbol) { var market = symbol.ID.Market; var securityType = symbol.ID.SecurityType; return (securityType == SecurityType.Equity && market == Market.USA) || (securityType == SecurityType.Forex && market == Market.FXCM) || (securityType == SecurityType.Option && market == Market.USA) || (securityType == SecurityType.Future && IQFeedDataQueueUniverseProvider.FuturesExchanges.Values.Contains(market)); } /// <summary> /// Created new request ID for a given lookup type (tick, intraday bar, daily bar) /// </summary> /// <param name="lookupType">Lookup type: REQ_HST_TCK (tick), REQ_HST_DWM (daily) or REQ_HST_INT (intraday resolutions)</param> /// <param name="id">Sequential identifier</param> /// <returns></returns> private static string CreateRequestID(LookupType lookupType, int id) { return lookupType + id.ToStringInvariant("0000000"); } /// <summary> /// Method called when a new Lookup event is fired /// </summary> /// <param name="e">Received data</param> protected override void OnLookupEvent(LookupEventArgs e) { try { switch (e.Sequence) { case LookupSequence.MessageStart: _currentRequest.AddOrUpdate(e.Id, new List<BaseData>()); break; case LookupSequence.MessageDetail: List<BaseData> current; if (_currentRequest.TryGetValue(e.Id, out current)) { HandleMessageDetail(e, current); } break; case LookupSequence.MessageEnd: _inProgress = false; break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception err) { Log.Error(err); } } /// <summary> /// Put received data into current list of BaseData object /// </summary> /// <param name="e">Received data</param> /// <param name="current">Current list of BaseData object</param> private void HandleMessageDetail(LookupEventArgs e, List<BaseData> current) { var requestData = _requestDataByRequestId[e.Id]; var data = GetData(e, requestData); if (data != null && data.Time != DateTime.MinValue) { current.Add(data); } } /// <summary> /// Transform received data into BaseData object /// </summary> /// <param name="e">Received data</param> /// <param name="requestData">Request information</param> /// <returns>BaseData object</returns> private BaseData GetData(LookupEventArgs e, HistoryRequest requestData) { var isEquity = requestData.Symbol.SecurityType == SecurityType.Equity; try { switch (e.Type) { case LookupType.REQ_HST_TCK: var t = (LookupTickEventArgs)e; var time = isEquity ? t.DateTimeStamp : t.DateTimeStamp.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); return new Tick(time, requestData.Symbol, (decimal)t.Last, (decimal)t.Bid, (decimal)t.Ask) { Quantity = t.LastSize }; case LookupType.REQ_HST_INT: var i = (LookupIntervalEventArgs)e; if (i.DateTimeStamp == DateTime.MinValue) return null; var istartTime = i.DateTimeStamp - requestData.Resolution.ToTimeSpan(); if (!isEquity) istartTime = istartTime.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); return new TradeBar(istartTime, requestData.Symbol, (decimal)i.Open, (decimal)i.High, (decimal)i.Low, (decimal)i.Close, i.PeriodVolume); case LookupType.REQ_HST_DWM: var d = (LookupDayWeekMonthEventArgs)e; if (d.DateTimeStamp == DateTime.MinValue) return null; var dstartTime = d.DateTimeStamp.Date; if (!isEquity) dstartTime = dstartTime.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); return new TradeBar(dstartTime, requestData.Symbol, (decimal)d.Open, (decimal)d.High, (decimal)d.Low, (decimal)d.Close, d.PeriodVolume, requestData.Resolution.ToTimeSpan()); // we don't need to handle these other types case LookupType.REQ_SYM_SYM: case LookupType.REQ_SYM_SIC: case LookupType.REQ_SYM_NAC: case LookupType.REQ_TAB_MKT: case LookupType.REQ_TAB_SEC: case LookupType.REQ_TAB_MKC: case LookupType.REQ_TAB_SIC: case LookupType.REQ_TAB_NAC: default: return null; } } catch (Exception err) { Log.Error("Encountered error while processing request: " + e.Id); Log.Error(err); return null; } } private static PeriodType GetPeriodType(Resolution resolution) { switch (resolution) { case Resolution.Second: return PeriodType.Second; case Resolution.Minute: return PeriodType.Minute; case Resolution.Hour: return PeriodType.Hour; case Resolution.Tick: case Resolution.Daily: default: throw new ArgumentOutOfRangeException("resolution", resolution, null); } } } }
#region File Description //----------------------------------------------------------------------------- // Tank.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using XnaGraphicsDemo; using System; #endregion namespace SimpleAnimation { /// <summary> /// Helper class for drawing a tank model with animated wheels and turret. /// </summary> public class Tank { #region Fields // The XNA framework Model object that we are going to display. Model tankModel; // Shortcut references to the bones that we are going to animate. // We could just look these up inside the Draw method, but it is more // efficient to do the lookups while loading and cache the results. ModelBone leftBackWheelBone; ModelBone rightBackWheelBone; ModelBone leftFrontWheelBone; ModelBone rightFrontWheelBone; ModelBone leftSteerBone; ModelBone rightSteerBone; ModelBone turretBone; ModelBone cannonBone; ModelBone hatchBone; // Store the original transform matrix for each animating bone. Matrix leftBackWheelTransform; Matrix rightBackWheelTransform; Matrix leftFrontWheelTransform; Matrix rightFrontWheelTransform; Matrix leftSteerTransform; Matrix rightSteerTransform; Matrix turretTransform; Matrix cannonTransform; Matrix hatchTransform; // Array holding all the bone transform matrices for the entire model. // We could just allocate this locally inside the Draw method, but it // is more efficient to reuse a single array, as this avoids creating // unnecessary garbage. Matrix[] boneTransforms; // Current animation positions. float wheelRotationValue; float steerRotationValue; float turretRotationValue; float cannonRotationValue; float hatchRotationValue; #endregion #region Properties /// <summary> /// Gets or sets the wheel rotation amount. /// </summary> public float WheelRotation { get { return wheelRotationValue; } set { wheelRotationValue = value; } } /// <summary> /// Gets or sets the steering rotation amount. /// </summary> public float SteerRotation { get { return steerRotationValue; } set { steerRotationValue = value; } } /// <summary> /// Gets or sets the turret rotation amount. /// </summary> public float TurretRotation { get { return turretRotationValue; } set { turretRotationValue = value; } } /// <summary> /// Gets or sets the cannon rotation amount. /// </summary> public float CannonRotation { get { return cannonRotationValue; } set { cannonRotationValue = value; } } /// <summary> /// Gets or sets the entry hatch rotation amount. /// </summary> public float HatchRotation { get { return hatchRotationValue; } set { hatchRotationValue = value; } } #endregion /// <summary> /// Loads the tank model. /// </summary> public void Load(ContentManager content) { // Load the tank model from the ContentManager. tankModel = content.Load<Model>("tank"); // Look up shortcut references to the bones we are going to animate. leftBackWheelBone = tankModel.Bones["l_back_wheel_geo"]; rightBackWheelBone = tankModel.Bones["r_back_wheel_geo"]; leftFrontWheelBone = tankModel.Bones["l_front_wheel_geo"]; rightFrontWheelBone = tankModel.Bones["r_front_wheel_geo"]; leftSteerBone = tankModel.Bones["l_steer_geo"]; rightSteerBone = tankModel.Bones["r_steer_geo"]; turretBone = tankModel.Bones["turret_geo"]; cannonBone = tankModel.Bones["canon_geo"]; hatchBone = tankModel.Bones["hatch_geo"]; // Store the original transform matrix for each animating bone. leftBackWheelTransform = leftBackWheelBone.Transform; rightBackWheelTransform = rightBackWheelBone.Transform; leftFrontWheelTransform = leftFrontWheelBone.Transform; rightFrontWheelTransform = rightFrontWheelBone.Transform; leftSteerTransform = leftSteerBone.Transform; rightSteerTransform = rightSteerBone.Transform; turretTransform = turretBone.Transform; cannonTransform = cannonBone.Transform; hatchTransform = hatchBone.Transform; // Allocate the transform matrix array. boneTransforms = new Matrix[tankModel.Bones.Count]; } /// <summary> /// Animates the tank model. /// </summary> /// <param name="gameTime"></param> public void Animate(GameTime gameTime) { float time = (float)gameTime.TotalGameTime.TotalSeconds; SteerRotation = (float)Math.Sin(time * 0.75f) * 0.5f; TurretRotation = (float)Math.Sin(time * 0.333f) * 1.25f; CannonRotation = (float)Math.Sin(time * 0.25f) * 0.333f - 0.333f; HatchRotation = MathHelper.Clamp((float)Math.Sin(time * 2) * 2, -1, 0); } /// <summary> /// Draws the tank model, using the current animation settings. /// </summary> public void Draw(Matrix world, Matrix view, Matrix projection, LightingMode lightMode, bool textureEnable) { // Set the world matrix as the root transform of the model. tankModel.Root.Transform = world; // Calculate matrices based on the current animation position. Matrix wheelRotation = Matrix.CreateRotationX(wheelRotationValue); Matrix steerRotation = Matrix.CreateRotationY(steerRotationValue); Matrix turretRotation = Matrix.CreateRotationY(turretRotationValue); Matrix cannonRotation = Matrix.CreateRotationX(cannonRotationValue); Matrix hatchRotation = Matrix.CreateRotationX(hatchRotationValue); // Apply matrices to the relevant bones. leftBackWheelBone.Transform = wheelRotation * leftBackWheelTransform; rightBackWheelBone.Transform = wheelRotation * rightBackWheelTransform; leftFrontWheelBone.Transform = wheelRotation * leftFrontWheelTransform; rightFrontWheelBone.Transform = wheelRotation * rightFrontWheelTransform; leftSteerBone.Transform = steerRotation * leftSteerTransform; rightSteerBone.Transform = steerRotation * rightSteerTransform; turretBone.Transform = turretRotation * turretTransform; cannonBone.Transform = cannonRotation * cannonTransform; hatchBone.Transform = hatchRotation * hatchTransform; // Look up combined bone matrices for the entire model. tankModel.CopyAbsoluteBoneTransformsTo(boneTransforms); // Draw the model. foreach (ModelMesh mesh in tankModel.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = boneTransforms[mesh.ParentBone.Index]; effect.View = view; effect.Projection = projection; switch (lightMode) { case LightingMode.NoLighting: effect.LightingEnabled = false; break; case LightingMode.OneVertexLight: effect.EnableDefaultLighting(); effect.PreferPerPixelLighting = false; effect.DirectionalLight1.Enabled = false; effect.DirectionalLight2.Enabled = false; break; case LightingMode.ThreeVertexLights: effect.EnableDefaultLighting(); effect.PreferPerPixelLighting = false; break; case LightingMode.ThreePixelLights: effect.EnableDefaultLighting(); effect.PreferPerPixelLighting = true; break; } effect.SpecularColor = new Vector3(0.8f, 0.8f, 0.6f); effect.SpecularPower = 16; effect.TextureEnabled = textureEnable; } mesh.Draw(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Pathoschild.Stardew.Common; using Pathoschild.Stardew.Common.Patching; using Pathoschild.Stardew.HorseFluteAnywhere.Framework; using Pathoschild.Stardew.HorseFluteAnywhere.Patches; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewModdingAPI.Utilities; using StardewValley; using StardewValley.Buildings; using StardewValley.Characters; using SObject = StardewValley.Object; namespace Pathoschild.Stardew.HorseFluteAnywhere { /// <summary>The mod entry point.</summary> internal class ModEntry : Mod { /********* ** Fields *********/ /// <summary>The unique item ID for a horse flute.</summary> private const int HorseFluteId = 911; /// <summary>The horse flute to play when the summon key is pressed.</summary> private readonly Lazy<SObject> HorseFlute = new(() => new SObject(ModEntry.HorseFluteId, 1)); /// <summary>The mod configuration.</summary> private ModConfig Config; /// <summary>The summon key binding.</summary> private KeybindList SummonKey => this.Config.SummonHorseKey; /********* ** Public methods *********/ /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides methods for interacting with the mod directory, such as read/writing a config file or custom JSON files.</param> public override void Entry(IModHelper helper) { I18n.Init(helper.Translation); // load config this.UpdateConfig(); // add patches HarmonyPatcher.Apply(this, new UtilityPatcher(this.Monitor) ); // hook events helper.Events.GameLoop.GameLaunched += this.OnGameLaunched; helper.Events.Input.ButtonsChanged += this.OnButtonsChanged; helper.Events.Player.Warped += this.OnWarped; helper.Events.World.LocationListChanged += this.OnLocationListChanged; // hook commands helper.ConsoleCommands.Add("reset_horses", "Reset the name and ownership for every horse in the game, so you can rename or reclaim a broken horse.", (_, _) => this.ResetHorsesCommand()); } /********* ** Private methods *********/ /// <summary>The event called after the first game update, once all mods are loaded.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnGameLaunched(object sender, GameLaunchedEventArgs e) { // add Generic Mod Config Menu integration new GenericModConfigMenuIntegrationForHorseFluteAnywhere( getConfig: () => this.Config, reset: () => { this.Config = new ModConfig(); this.Helper.WriteConfig(this.Config); this.UpdateConfig(); }, saveAndApply: () => { this.Helper.WriteConfig(this.Config); this.UpdateConfig(); }, modRegistry: this.Helper.ModRegistry, monitor: this.Monitor, manifest: this.ModManifest ).Register(); } /// <summary>Raised after the player presses any buttons on the keyboard, controller, or mouse.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event data.</param> private void OnButtonsChanged(object sender, ButtonsChangedEventArgs e) { if (this.SummonKey.JustPressed() && this.CanPlayFlute(Game1.player)) { int[] warpRestrictions = Utility.GetHorseWarpRestrictionsForFarmer(Game1.player).ToArray(); if (warpRestrictions.Length == 1 && warpRestrictions[0] == 2 && this.TryFallbackSummonHorse()) { // GetHorseWarpRestrictionsForFarmer patch failed (usually on macOS), but we // were able to fallback to summoning the horse manually. } else this.HorseFlute.Value.performUseAction(Game1.currentLocation); this.Helper.Input.SuppressActiveKeybinds(this.SummonKey); } } /// <summary>The event called after the location list changes.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnLocationListChanged(object sender, LocationListChangedEventArgs e) { // rescue lost horses if (Context.IsMainPlayer) { foreach (GameLocation location in e.Removed) { foreach (Horse horse in this.GetHorsesIn(location).ToArray()) this.WarpHome(horse); } } } /// <summary>The event called after the player warps into a new location.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnWarped(object sender, WarpedEventArgs e) { if (!e.IsLocalPlayer || !this.IsRidingHorse(Game1.player)) return; // fix: warping onto a magic warp while mounted causes an infinite warp loop Vector2 tile = CommonHelper.GetPlayerTile(Game1.player); string touchAction = Game1.player.currentLocation.doesTileHaveProperty((int)tile.X, (int)tile.Y, "TouchAction", "Back"); if (touchAction != null && touchAction.StartsWith("MagicWarp ")) Game1.currentLocation.lastTouchActionLocation = tile; // fix: warping into an event may break the event (e.g. Mr Qi's event on mine level event for the 'Cryptic Note' quest) if (Game1.CurrentEvent != null) Game1.player.mount.dismount(); } /// <summary>Summon the horse manually if the <see cref="UtilityPatcher.After_GetHorseWarpRestrictionsForFarmer"/> patch isn't working for some reason.</summary> /// <remarks>On macOS, patches on <see cref="Utility.GetHorseWarpRestrictionsForFarmer"/> are never called for some unknown reason. Derived from <see cref="SObject.performUseAction"/> and <see cref="FarmerTeam.OnRequestHorseWarp"/>.</remarks> private bool TryFallbackSummonHorse() { // find horse Horse horse = Utility.findHorseForPlayer(Game1.player.UniqueMultiplayerID); if (horse == null) return false; // play flute this.Monitor.Log("Falling back to custom summon..."); Game1.player.faceDirection(Game1.down); Game1.soundBank.PlayCue("horse_flute"); Game1.player.FarmerSprite.animateOnce(new[] { new FarmerSprite.AnimationFrame(98, 400, true, false), new FarmerSprite.AnimationFrame(99, 200, true, false), new FarmerSprite.AnimationFrame(100, 200, true, false), new FarmerSprite.AnimationFrame(99, 200, true, false), new FarmerSprite.AnimationFrame(98, 400, true, false), new FarmerSprite.AnimationFrame(99, 200, true, false), }); Game1.player.freezePause = 1500; // summon horse DelayedAction.functionAfterDelay(() => { horse.mutex.RequestLock(() => { horse.mutex.ReleaseLock(); Multiplayer multiplayer = this.Helper.Reflection.GetField<Multiplayer>(typeof(Game1), "multiplayer").GetValue(); GameLocation location = horse.currentLocation; Vector2 tile_location = horse.getTileLocation(); for (int i = 0; i < 8; i++) { multiplayer.broadcastSprites(location, new TemporaryAnimatedSprite(10, new Vector2(tile_location.X + Utility.RandomFloat(-1, 1), tile_location.Y + Utility.RandomFloat(-1, 0)) * Game1.tileSize, Color.White, 8, false, 50f) { layerDepth = 1f, motion = new Vector2(Utility.RandomFloat(-0.5F, 0.5F), Utility.RandomFloat(-0.5F, 0.5F)) }); } location.playSoundAt("wand", horse.getTileLocation()); location = Game1.player.currentLocation; tile_location = Game1.player.getTileLocation(); location.playSoundAt("wand", tile_location); for (int i = 0; i < 8; i++) { multiplayer.broadcastSprites(location, new TemporaryAnimatedSprite(10, new Vector2(tile_location.X + Utility.RandomFloat(-1, 1), tile_location.Y + Utility.RandomFloat(-1, 0)) * Game1.tileSize, Color.White, 8, false, 50f) { layerDepth = 1f, motion = new Vector2(Utility.RandomFloat(-0.5F, 0.5F), Utility.RandomFloat(-0.5F, 0.5F)) }); } Game1.warpCharacter(horse, Game1.player.currentLocation, tile_location); int j = 0; for (int x = (int)tile_location.X + 3; x >= (int)tile_location.X - 3; x--) { multiplayer.broadcastSprites(location, new TemporaryAnimatedSprite(6, new Vector2(x, tile_location.Y) * Game1.tileSize, Color.White, 8, false, 50f) { layerDepth = 1f, delayBeforeAnimationStart = j * 25, motion = new Vector2(-.25f, 0) }); j++; } }); }, 1500); return true; } /// <summary>Reset all horse names and ownership, and log details to the SMAPI console.</summary> private void ResetHorsesCommand() { // validate if (!Context.IsWorldReady) { this.Monitor.Log("You must load a save to use this command.", LogLevel.Error); return; } if (!Context.IsMainPlayer) { this.Monitor.Log("You must be the main player to use this command.", LogLevel.Error); return; } // reset horse instances Farm farm = Game1.getFarm(); bool anyChanged = false; foreach (Stable stable in farm.buildings.OfType<Stable>()) { bool curChanged = false; // fetch info Horse horse = stable.getStableHorse(); bool isTractor = this.IsTractor(horse); bool hadName = !string.IsNullOrEmpty(horse?.Name); // fix stable if (stable.owner.Value != 0) { stable.owner.Value = 0; curChanged = true; } // fix horse if (horse != null) { if (horse.ownerId.Value != 0) { horse.ownerId.Value = 0; curChanged = true; } if (!isTractor && hadName) { horse.Name = ""; curChanged = true; } } // log if (curChanged) { string message = isTractor ? $"Reset tractor {(hadName ? $"'{horse.Name}'" : "with no name")}." : $"Reset horse '{(hadName ? $"'{horse.Name}'" : "with no name")}'. The next player who interacts with it will become the owner."; this.Monitor.Log(message, LogLevel.Info); } anyChanged |= curChanged; } // reset player horse names foreach (Farmer farmer in Game1.getAllFarmers()) { if (!string.IsNullOrEmpty(farmer.horseName.Value)) { farmer.horseName.Value = null; anyChanged = true; this.Monitor.Log($"Reset horse link for player '{farmer.Name}'.", LogLevel.Info); } } this.Monitor.Log(anyChanged ? "Done!" : "No horses found to reset.", LogLevel.Info); } /// <summary>Update the mod configuration.</summary> private void UpdateConfig() { this.Config = this.Helper.ReadConfig<ModConfig>(); } /// <summary>Get all horses in the given location.</summary> /// <param name="location">The location to scan.</param> private IEnumerable<Horse> GetHorsesIn(GameLocation location) { return location.characters .OfType<Horse>() .Where(p => !this.ShouldIgnore(p)); } /// <summary>Warp a horse back to its home.</summary> /// <param name="horse">The horse to warp.</param> private void WarpHome(Horse horse) { Farm farm = Game1.getFarm(); Stable stable = farm.buildings.OfType<Stable>().FirstOrDefault(p => p.HorseId == horse.HorseId); Game1.warpCharacter(horse, farm, Vector2.Zero); stable?.grabHorse(); } /// <summary>Get whether the player can play the flute.</summary> /// <param name="player">The player to check.</param> private bool CanPlayFlute(Farmer player) { return Context.IsPlayerFree && ( !this.Config.RequireHorseFlute || player.Items.Any(p => Utility.IsNormalObjectAtParentSheetIndex(p, ModEntry.HorseFluteId)) ); } /// <summary>Get whether a player is riding a non-ignored horse.</summary> /// <param name="player">The player to check.</param> private bool IsRidingHorse(Farmer player) { return player.mount != null && !this.ShouldIgnore(player.mount); } /// <summary>Get whether a horse should be ignored by the main horse logic.</summary> /// <param name="horse">The horse to check.</param> private bool ShouldIgnore(Horse horse) { return horse == null || this.IsTractor(horse) // Tractor Mod tractor || horse.GetType().FullName?.StartsWith("DeepWoodsMod.") == true; // Deep Woods unicorn } /// <summary>Get whether a horse is a tractor added by Tractor Mod, which manages the edge cases for tractor summoning automatically.</summary> /// <param name="horse">The horse to check.</param> private bool IsTractor(Horse horse) { return horse.modData?.TryGetValue("Pathoschild.TractorMod", out _) == true; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting.CSharp { public sealed class CSharpObjectFormatter : ObjectFormatter { public static readonly CSharpObjectFormatter Instance = new CSharpObjectFormatter(); private CSharpObjectFormatter() { } public override object VoidDisplayString { get { return "<void>"; } } public override string NullLiteral { get { return ObjectDisplay.NullLiteral; } } public override string FormatLiteral(bool value) { return ObjectDisplay.FormatLiteral(value); } public override string FormatLiteral(string value, bool quote, bool useHexadecimalNumbers = false) { var options = ObjectDisplayOptions.None; if (quote) { options |= ObjectDisplayOptions.UseQuotes; } if (useHexadecimalNumbers) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } return ObjectDisplay.FormatLiteral(value, options); } public override string FormatLiteral(char c, bool quote, bool includeCodePoints = false, bool useHexadecimalNumbers = false) { var options = ObjectDisplayOptions.None; if (quote) { options |= ObjectDisplayOptions.UseQuotes; } if (includeCodePoints) { options |= ObjectDisplayOptions.IncludeCodePoints; } if (useHexadecimalNumbers) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } return ObjectDisplay.FormatLiteral(c, options); } public override string FormatLiteral(sbyte value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(byte value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(short value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(ushort value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(int value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(uint value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(long value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(ulong value, bool useHexadecimalNumbers = false) { return ObjectDisplay.FormatLiteral(value, GetObjectDisplayOptions(useHexadecimalNumbers)); } public override string FormatLiteral(double value) { return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None); } public override string FormatLiteral(float value) { return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None); } public override string FormatLiteral(decimal value) { return ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None); } public override string FormatTypeName(Type type, ObjectFormattingOptions options) { return GetPrimitiveTypeName(type) ?? AppendComplexTypeName(new StringBuilder(), type, options).ToString(); } private static string GetPrimitiveTypeName(Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return "bool"; case TypeCode.Byte: return "byte"; case TypeCode.Char: return "char"; case TypeCode.Decimal: return "decimal"; case TypeCode.Double: return "double"; case TypeCode.Int16: return "short"; case TypeCode.Int32: return "int"; case TypeCode.Int64: return "long"; case TypeCode.SByte: return "sbyte"; case TypeCode.Single: return "float"; case TypeCode.String: return "string"; case TypeCode.UInt16: return "ushort"; case TypeCode.UInt32: return "uint"; case TypeCode.UInt64: return "ulong"; case TypeCode.Object: case TypeCode.Empty: case TypeCode.DBNull: case TypeCode.DateTime: default: if (type == typeof(object)) { return "object"; } return null; } } private StringBuilder AppendComplexTypeName(StringBuilder builder, Type type, ObjectFormattingOptions options) { if (type.IsArray) { builder.Append(FormatArrayTypeName(type, arrayOpt: null, options: options)); return builder; } // compiler generated (e.g. iterator/async) string stateMachineName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(type.Name, GeneratedNameKind.StateMachineType, out stateMachineName)) { builder.Append(stateMachineName); return builder; } if (type.IsGenericType) { // consolidated generic arguments (includes arguments of all declaring types): Type[] genericArguments = type.GetGenericArguments(); if (type.DeclaringType != null) { List<Type> nestedTypes = new List<Type>(); do { nestedTypes.Add(type); type = type.DeclaringType; } while (type != null); int typeArgumentIndex = 0; for (int i = nestedTypes.Count - 1; i >= 0; i--) { AppendTypeInstantiation(builder, nestedTypes[i], genericArguments, ref typeArgumentIndex, options); if (i > 0) { builder.Append('.'); } } } else { int typeArgumentIndex = 0; return AppendTypeInstantiation(builder, type, genericArguments, ref typeArgumentIndex, options); } } else if (type.DeclaringType != null) { builder.Append(type.Name.Replace('+', '.')); } else { builder.Append(type.Name); } return builder; } private StringBuilder AppendTypeInstantiation(StringBuilder builder, Type type, Type[] genericArguments, ref int genericArgIndex, ObjectFormattingOptions options) { // generic arguments of all the outer types and the current type; Type[] currentGenericArgs = type.GetGenericArguments(); int currentArgCount = currentGenericArgs.Length - genericArgIndex; if (currentArgCount > 0) { int backtick = type.Name.IndexOf('`'); if (backtick > 0) { builder.Append(type.Name.Substring(0, backtick)); } else { builder.Append(type.Name); } builder.Append('<'); for (int i = 0; i < currentArgCount; i++) { if (i > 0) { builder.Append(", "); } builder.Append(FormatTypeName(genericArguments[genericArgIndex++], options)); } builder.Append('>'); } else { builder.Append(type.Name); } return builder; } public override string FormatArrayTypeName(Array array, ObjectFormattingOptions options) { return FormatArrayTypeName(array.GetType(), array, options); } private string FormatArrayTypeName(Type arrayType, Array arrayOpt, ObjectFormattingOptions options) { StringBuilder sb = new StringBuilder(); // print the inner-most element type first: Type elementType = arrayType.GetElementType(); while (elementType.IsArray) { elementType = elementType.GetElementType(); } sb.Append(FormatTypeName(elementType, options)); // print all components of a jagged array: Type type = arrayType; do { if (arrayOpt != null) { sb.Append('['); int rank = type.GetArrayRank(); bool anyNonzeroLowerBound = false; for (int i = 0; i < rank; i++) { if (arrayOpt.GetLowerBound(i) > 0) { anyNonzeroLowerBound = true; break; } } for (int i = 0; i < rank; i++) { int lowerBound = arrayOpt.GetLowerBound(i); long length = arrayOpt.GetLongLength(i); if (i > 0) { sb.Append(", "); } if (anyNonzeroLowerBound) { AppendArrayBound(sb, lowerBound, options.UseHexadecimalNumbers); sb.Append(".."); AppendArrayBound(sb, length + lowerBound, options.UseHexadecimalNumbers); } else { AppendArrayBound(sb, length, options.UseHexadecimalNumbers); } } sb.Append(']'); arrayOpt = null; } else { AppendArrayRank(sb, type); } type = type.GetElementType(); } while (type.IsArray); return sb.ToString(); } private void AppendArrayBound(StringBuilder sb, long bound, bool useHexadecimalNumbers) { if (bound <= Int32.MaxValue) { sb.Append(FormatLiteral((int)bound, useHexadecimalNumbers)); } else { sb.Append(FormatLiteral(bound, useHexadecimalNumbers)); } } private static void AppendArrayRank(StringBuilder sb, Type arrayType) { sb.Append('['); int rank = arrayType.GetArrayRank(); if (rank > 1) { sb.Append(',', rank - 1); } sb.Append(']'); } public override string FormatMemberName(System.Reflection.MemberInfo member) { return member.Name; } public override bool IsHiddenMember(System.Reflection.MemberInfo member) { // Generated fields, e.g. "<property_name>k__BackingField" return GeneratedNames.IsGeneratedMemberName(member.Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Collections.Concurrent; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.MethodInfos; using Internal.Metadata.NativeFormat; using Internal.Reflection.Core.Execution; // // It is common practice for app code to compare Type objects using reference equality with the expectation that reference equality // is equivalent to semantic equality. To support this, all RuntimeTypeObject objects are interned using weak references. // // This assumption is baked into the codebase in these places: // // - RuntimeTypeInfo.Equals(object) implements itself as Object.ReferenceEquals(this, obj) // // - RuntimeTypeInfo.GetHashCode() is implemented in a flavor-specific manner (We can't use Object.GetHashCode() // because we don't want the hash value to change if a type is collected and resurrected later.) // // This assumption is actualized as follows: // // - RuntimeTypeInfo classes hide their constructor. The only way to instantiate a RuntimeTypeInfo // is through its public static factory method which ensures the interning and are collected in this one // file for easy auditing and to help ensure that they all operate in a consistent manner. // // - The TypeUnifier extension class provides a more friendly interface to the rest of the codebase. // namespace System.Reflection.Runtime.General { internal static class TypeUnifier { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetNamedType(this TypeDefinitionHandle typeDefinitionHandle, MetadataReader reader) { return typeDefinitionHandle.GetNamedType(reader, default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType) { return elementType.GetArrayType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank) { return elementType.GetMultiDimArrayType(rank, default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetByRefType(this RuntimeTypeInfo targetType) { return RuntimeByRefTypeInfo.GetByRefTypeInfo(targetType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType) { return targetType.GetPointerType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments) { return genericTypeDefinition.GetConstructedGenericType(genericTypeArguments, default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetTypeForRuntimeTypeHandle(this RuntimeTypeHandle typeHandle) { Type type = Type.GetTypeFromHandle(typeHandle); return type.CastToRuntimeTypeInfo(); } //====================================================================================================== // This next group services the Type.GetTypeFromHandle() path. Since we already have a RuntimeTypeHandle // in that case, we pass it in as an extra argument as an optimization (otherwise, the unifier will // waste cycles looking up the handle again from the mapping tables.) //====================================================================================================== [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetNamedType(this TypeDefinitionHandle typeDefinitionHandle, MetadataReader reader, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeNamedTypeInfo.GetRuntimeNamedTypeInfo(reader, typeDefinitionHandle, precomputedTypeHandle: precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: false, rank: 1, precomputedTypeHandle: precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: true, rank: rank, precomputedTypeHandle: precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimePointerTypeInfo.GetPointerTypeInfo(targetType, precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeConstructedGenericTypeInfo.GetRuntimeConstructedGenericTypeInfo(genericTypeDefinition, genericTypeArguments, precomputedTypeHandle); } } } namespace System.Reflection.Runtime.TypeInfos { //----------------------------------------------------------------------------------------------------------- // TypeInfos for type definitions (i.e. "Foo" and "Foo<>" but not "Foo<int>") //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeNamedTypeInfo : RuntimeTypeInfo { internal static RuntimeTypeInfo GetRuntimeNamedTypeInfo(MetadataReader metadataReader, TypeDefinitionHandle typeDefHandle, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle; if (typeHandle.IsNull()) { if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetNamedTypeForMetadata(metadataReader, typeDefHandle, out typeHandle)) typeHandle = default(RuntimeTypeHandle); } UnificationKey key = new UnificationKey(metadataReader, typeDefHandle, typeHandle); RuntimeNamedTypeInfo type = NamedTypeTable.Table.GetOrAdd(key); type.EstablishDebugName(); return type; } private sealed class NamedTypeTable : ConcurrentUnifierW<UnificationKey, RuntimeNamedTypeInfo> { protected sealed override RuntimeNamedTypeInfo Factory(UnificationKey key) { return new RuntimeNamedTypeInfo(key.Reader, key.TypeDefinitionHandle, key.TypeHandle); } public static readonly NamedTypeTable Table = new NamedTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for type definitions (i.e. "Foo" and "Foo<>" but not "Foo<int>") that aren't opted into metadata. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeNoMetadataNamedTypeInfo : RuntimeTypeInfo { internal static RuntimeNoMetadataNamedTypeInfo GetRuntimeNoMetadataNamedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { RuntimeNoMetadataNamedTypeInfo type; if (isGenericTypeDefinition) type = GenericNoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); else type = NoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); type.EstablishDebugName(); return type; } private sealed class NoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo> { protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false); } public static readonly NoMetadataNamedTypeTable Table = new NoMetadataNamedTypeTable(); } private sealed class GenericNoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo> { protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true); } public static readonly GenericNoMetadataNamedTypeTable Table = new GenericNoMetadataNamedTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos that represent type definitions (i.e. Foo or Foo<>) or constructed generic types (Foo<int>) // that can never be reflection-enabled due to the framework Reflection block. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeBlockedTypeInfo : RuntimeTypeInfo { internal static RuntimeBlockedTypeInfo GetRuntimeBlockedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { RuntimeBlockedTypeInfo type; if (isGenericTypeDefinition) type = GenericBlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); else type = BlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); type.EstablishDebugName(); return type; } private sealed class BlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo> { protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false); } public static readonly BlockedTypeTable Table = new BlockedTypeTable(); } private sealed class GenericBlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo> { protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true); } public static readonly GenericBlockedTypeTable Table = new GenericBlockedTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Sz and multi-dim Array types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeArrayTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimeArrayTypeInfo GetArrayTypeInfo(RuntimeTypeInfo elementType, bool multiDim, int rank, RuntimeTypeHandle precomputedTypeHandle) { Debug.Assert(multiDim || rank == 1); RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType, multiDim, rank) : precomputedTypeHandle; UnificationKey key = new UnificationKey(elementType, typeHandle); RuntimeArrayTypeInfo type; if (!multiDim) type = ArrayTypeTable.Table.GetOrAdd(key); else type = TypeTableForMultiDimArrayTypeTables.Table.GetOrAdd(rank).GetOrAdd(key); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType, bool multiDim, int rank) { Debug.Assert(multiDim || rank == 1); RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!multiDim) { if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetArrayTypeForElementType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); } else { if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetMultiDimArrayTypeForElementType(elementTypeHandle, rank, out typeHandle)) return default(RuntimeTypeHandle); } return typeHandle; } private sealed class ArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo> { protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key) { ValidateElementType(key.ElementType, key.TypeHandle, multiDim: false, rank: 1); return new RuntimeArrayTypeInfo(key, multiDim: false, rank: 1); } public static readonly ArrayTypeTable Table = new ArrayTypeTable(); } private sealed class MultiDimArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo> { public MultiDimArrayTypeTable(int rank) { _rank = rank; } protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key) { ValidateElementType(key.ElementType, key.TypeHandle, multiDim: true, rank: _rank); return new RuntimeArrayTypeInfo(key, multiDim: true, rank: _rank); } private readonly int _rank; } // // For the hopefully rare case of multidim arrays, we have a dictionary of dictionaries. // private sealed class TypeTableForMultiDimArrayTypeTables : ConcurrentUnifier<int, MultiDimArrayTypeTable> { protected sealed override MultiDimArrayTypeTable Factory(int rank) { Debug.Assert(rank > 0); return new MultiDimArrayTypeTable(rank); } public static readonly TypeTableForMultiDimArrayTypeTables Table = new TypeTableForMultiDimArrayTypeTables(); } private static void ValidateElementType(RuntimeTypeInfo elementType, RuntimeTypeHandle typeHandle, bool multiDim, int rank) { Debug.Assert(multiDim || rank == 1); if (elementType.IsByRef) throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); if (elementType.IsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. if (typeHandle.IsNull() && !elementType.ContainsGenericParameters) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingArrayTypeException(elementType.AsType(), multiDim, rank); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for ByRef types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeByRefTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimeByRefTypeInfo GetByRefTypeInfo(RuntimeTypeInfo elementType) { RuntimeTypeHandle typeHandle = default(RuntimeTypeHandle); RuntimeByRefTypeInfo type = ByRefTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle)); type.EstablishDebugName(); return type; } private sealed class ByRefTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeByRefTypeInfo> { protected sealed override RuntimeByRefTypeInfo Factory(UnificationKey key) { return new RuntimeByRefTypeInfo(key); } public static readonly ByRefTypeTable Table = new ByRefTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Pointer types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimePointerTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimePointerTypeInfo GetPointerTypeInfo(RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType) : precomputedTypeHandle; RuntimePointerTypeInfo type = PointerTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle)); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType) { RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetPointerTypeForTargetType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class PointerTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimePointerTypeInfo> { protected sealed override RuntimePointerTypeInfo Factory(UnificationKey key) { return new RuntimePointerTypeInfo(key); } public static readonly PointerTypeTable Table = new PointerTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Constructed generic types ("Foo<int>") //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeConstructedGenericTypeInfo : RuntimeTypeInfo, IKeyedItem<RuntimeConstructedGenericTypeInfo.UnificationKey> { internal static RuntimeConstructedGenericTypeInfo GetRuntimeConstructedGenericTypeInfo(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(genericTypeDefinition, genericTypeArguments) : precomputedTypeHandle; UnificationKey key = new UnificationKey(genericTypeDefinition, genericTypeArguments, typeHandle); RuntimeConstructedGenericTypeInfo typeInfo = ConstructedGenericTypeTable.Table.GetOrAdd(key); typeInfo.EstablishDebugName(); return typeInfo; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments) { RuntimeTypeHandle genericTypeDefinitionHandle = genericTypeDefinition.InternalTypeHandleIfAvailable; if (genericTypeDefinitionHandle.IsNull()) return default(RuntimeTypeHandle); if (ReflectionCoreExecution.ExecutionEnvironment.IsReflectionBlocked(genericTypeDefinitionHandle)) return default(RuntimeTypeHandle); int count = genericTypeArguments.Length; RuntimeTypeHandle[] genericTypeArgumentHandles = new RuntimeTypeHandle[count]; for (int i = 0; i < count; i++) { RuntimeTypeHandle genericTypeArgumentHandle = genericTypeArguments[i].InternalTypeHandleIfAvailable; if (genericTypeArgumentHandle.IsNull()) return default(RuntimeTypeHandle); genericTypeArgumentHandles[i] = genericTypeArgumentHandle; } RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class ConstructedGenericTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeConstructedGenericTypeInfo> { protected sealed override RuntimeConstructedGenericTypeInfo Factory(UnificationKey key) { bool atLeastOneOpenType = false; foreach (RuntimeTypeInfo genericTypeArgument in key.GenericTypeArguments) { if (genericTypeArgument.IsByRef || genericTypeArgument.IsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidTypeArgument, genericTypeArgument)); if (genericTypeArgument.ContainsGenericParameters) atLeastOneOpenType = true; } // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. if (key.TypeHandle.IsNull() && !atLeastOneOpenType) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingConstructedGenericTypeException(key.GenericTypeDefinition.AsType(), key.GenericTypeArguments.CloneTypeArray()); return new RuntimeConstructedGenericTypeInfo(key); } public static readonly ConstructedGenericTypeTable Table = new ConstructedGenericTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for generic parameters on types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeGenericParameterTypeInfoForTypes : RuntimeGenericParameterTypeInfo { // // For app-compat reasons, we need to make sure that only TypeInfo instance exists for a given semantic type. If you change this, you must change the way // RuntimeTypeInfo.Equals() is implemented. // internal static RuntimeGenericParameterTypeInfoForTypes GetRuntimeGenericParameterTypeInfoForTypes(RuntimeNamedTypeInfo typeOwner, GenericParameterHandle genericParameterHandle) { UnificationKey key = new UnificationKey(typeOwner.Reader, typeOwner.TypeDefinitionHandle, genericParameterHandle); RuntimeGenericParameterTypeInfoForTypes type = GenericParameterTypeForTypesTable.Table.GetOrAdd(key); type.EstablishDebugName(); return type; } private sealed class GenericParameterTypeForTypesTable : ConcurrentUnifierW<UnificationKey, RuntimeGenericParameterTypeInfoForTypes> { protected sealed override RuntimeGenericParameterTypeInfoForTypes Factory(UnificationKey key) { RuntimeTypeInfo typeOwner = key.TypeDefinitionHandle.GetNamedType(key.Reader); return new RuntimeGenericParameterTypeInfoForTypes(key.Reader, key.GenericParameterHandle, typeOwner); } public static readonly GenericParameterTypeForTypesTable Table = new GenericParameterTypeForTypesTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for generic parameters on methods. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeGenericParameterTypeInfoForMethods : RuntimeGenericParameterTypeInfo, IKeyedItem<RuntimeGenericParameterTypeInfoForMethods.UnificationKey> { // // For app-compat reasons, we need to make sure that only TypeInfo instance exists for a given semantic type. If you change this, you must change the way // RuntimeTypeInfo.Equals() is implemented. // internal static RuntimeGenericParameterTypeInfoForMethods GetRuntimeGenericParameterTypeInfoForMethods(RuntimeNamedMethodInfo methodOwner, MetadataReader reader, GenericParameterHandle genericParameterHandle) { UnificationKey key = new UnificationKey(methodOwner, reader, genericParameterHandle); RuntimeGenericParameterTypeInfoForMethods type = GenericParameterTypeForMethodsTable.Table.GetOrAdd(key); type.EstablishDebugName(); return type; } private sealed class GenericParameterTypeForMethodsTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeGenericParameterTypeInfoForMethods> { protected sealed override RuntimeGenericParameterTypeInfoForMethods Factory(UnificationKey key) { return new RuntimeGenericParameterTypeInfoForMethods(key.Reader, key.GenericParameterHandle, key.MethodOwner); } public static readonly GenericParameterTypeForMethodsTable Table = new GenericParameterTypeForMethodsTable(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using System.Collections.ObjectModel; using Microsoft.VisualStudio.OLE.Interop; using System.Runtime.InteropServices; using System.Threading; using MICore; namespace Microsoft.MIDebugEngine { internal class EngineCallback : ISampleEngineCallback, MICore.IDeviceAppLauncherEventCallback { // If we store the event callback in a normal IDebugEventCallback2 member, COM interop will attempt to call back to the main UI // thread the first time that we invoke the call back. To work around this, we will instead store the event call back in the // global interface table like we would if we implemented this code in native. private readonly uint _cookie; // NOTE: The GIT doesn't aggregate the free threaded marshaler, so we can't store it in an RCW // or the CLR will just call right back to the main thread to try and marshal it. private readonly IntPtr _pGIT; private readonly AD7Engine _engine; private Guid _IID_IDebugEventCallback2 = typeof(IDebugEventCallback2).GUID; private readonly object _cacheLock = new object(); private int _cachedEventCallbackThread; private IDebugEventCallback2 _cacheEventCallback; public EngineCallback(AD7Engine engine, IDebugEventCallback2 ad7Callback) { // Obtain the GIT from COM, and store the event callback in it Guid CLSID_StdGlobalInterfaceTable = new Guid("00000323-0000-0000-C000-000000000046"); Guid IID_IGlobalInterfaceTable = typeof(IGlobalInterfaceTable).GUID; const int CLSCTX_INPROC_SERVER = 0x1; _pGIT = NativeMethods.CoCreateInstance(ref CLSID_StdGlobalInterfaceTable, IntPtr.Zero, CLSCTX_INPROC_SERVER, ref IID_IGlobalInterfaceTable); var git = GetGlobalInterfaceTable(); git.RegisterInterfaceInGlobal(ad7Callback, ref _IID_IDebugEventCallback2, out _cookie); Marshal.ReleaseComObject(git); _engine = engine; } ~EngineCallback() { // NOTE: This object does NOT implement the dispose pattern. The reasons are -- // 1. The underlying thing we are disposing is the SDM's IDebugEventCallback2. We are not going to get // deterministic release of this without both implementing the dispose pattern on this object but also // switching to use Marshal.ReleaseComObject everywhere. Marshal.ReleaseComObject is difficult to get // right and there isn't a large need to deterministically release the SDM's event callback. // 2. There is some risk of deadlock if we tried to implement the dispose pattern because of the trickiness // of releasing cross-thread COM interfaces. We could avoid this by doing an async dispose, but then // we losing the primary benefit of dispose which is the deterministic release. if (_cookie != 0) { var git = GetGlobalInterfaceTable(); git.RevokeInterfaceFromGlobal(_cookie); Marshal.ReleaseComObject(git); } if (_pGIT != IntPtr.Zero) { Marshal.Release(_pGIT); } } public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread) { uint attributes; Guid riidEvent = new Guid(iidEvent); EngineUtils.RequireOk(eventObject.GetAttributes(out attributes)); var callback = GetEventCallback(); EngineUtils.RequireOk(callback.Event(_engine, null, program, thread, eventObject, ref riidEvent, attributes)); } private IGlobalInterfaceTable GetGlobalInterfaceTable() { Debug.Assert(_pGIT != IntPtr.Zero, "GetGlobalInterfaceTable called before the m_pGIT is initialized"); // NOTE: We want to use GetUniqueObjectForIUnknown since the GIT will exist in both the STA and the MTA, and we don't want // them to be the same rcw return (IGlobalInterfaceTable)Marshal.GetUniqueObjectForIUnknown(_pGIT); } private IDebugEventCallback2 GetEventCallback() { Debug.Assert(_cookie != 0, "GetEventCallback called before m_cookie is initialized"); // We send esentially all events from the same thread, so lets optimize the common case int currentThreadId = Thread.CurrentThread.ManagedThreadId; if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId) { lock (_cacheLock) { if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId) { return _cacheEventCallback; } } } var git = GetGlobalInterfaceTable(); IntPtr pCallback; git.GetInterfaceFromGlobal(_cookie, ref _IID_IDebugEventCallback2, out pCallback); Marshal.ReleaseComObject(git); var eventCallback = (IDebugEventCallback2)Marshal.GetObjectForIUnknown(pCallback); Marshal.Release(pCallback); lock (_cacheLock) { _cachedEventCallbackThread = currentThreadId; _cacheEventCallback = eventCallback; } return eventCallback; } public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread) { IDebugProgram2 program = _engine; if (!_engine.ProgramCreateEventSent) { // Any events before programe create shouldn't include the program program = null; } Send(eventObject, iidEvent, program, thread); } public void OnError(string message) { SendMessage(message, OutputMessage.Severity.Error, isAsync: true); } /// <summary> /// Sends an error to the user, blocking until the user dismisses the error /// </summary> /// <param name="message">string to display to the user</param> public void OnErrorImmediate(string message) { SendMessage(message, OutputMessage.Severity.Error, isAsync: false); } public void OnWarning(string message) { SendMessage(message, OutputMessage.Severity.Warning, isAsync: true); } public void OnModuleLoad(DebuggedModule debuggedModule) { // This will get called when the entrypoint breakpoint is fired because the engine sends a mod-load event // for the exe. if (_engine.DebuggedProcess != null) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); } AD7Module ad7Module = new AD7Module(debuggedModule, _engine.DebuggedProcess); AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */); debuggedModule.Client = ad7Module; // The sample engine does not support binding breakpoints as modules load since the primary exe is the only module // symbols are loaded for. A production debugger will need to bind breakpoints when a new module is loaded. Send(eventObject, AD7ModuleLoadEvent.IID, null); } public void OnModuleUnload(DebuggedModule debuggedModule) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); AD7Module ad7Module = (AD7Module)debuggedModule.Client; Debug.Assert(ad7Module != null); AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, false /* this is a module unload */); Send(eventObject, AD7ModuleLoadEvent.IID, null); } public void OnOutputString(string outputString) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); AD7OutputDebugStringEvent eventObject = new AD7OutputDebugStringEvent(outputString); Send(eventObject, AD7OutputDebugStringEvent.IID, null); } public void OnOutputMessage(OutputMessage outputMessage) { try { if (outputMessage.ErrorCode == 0) { var eventObject = new AD7MessageEvent(outputMessage, isAsync:true); Send(eventObject, AD7MessageEvent.IID, null); } else { var eventObject = new AD7ErrorEvent(outputMessage, isAsync:true); Send(eventObject, AD7ErrorEvent.IID, null); } } catch { // Since we are often trying to report an exception, if something goes wrong we don't want to take down the process, // so ignore the failure. } } public void OnProcessExit(uint exitCode) { AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode); try { Send(eventObject, AD7ProgramDestroyEvent.IID, null); } catch (InvalidOperationException) { // If debugging has already stopped, this can throw } } public void OnEntryPoint(DebuggedThread thread) { AD7EntryPointEvent eventObject = new AD7EntryPointEvent(); Send(eventObject, AD7EntryPointEvent.IID, (AD7Thread)thread.Client); } public void OnThreadExit(DebuggedThread debuggedThread, uint exitCode) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); AD7Thread ad7Thread = (AD7Thread)debuggedThread.Client; Debug.Assert(ad7Thread != null); AD7ThreadDestroyEvent eventObject = new AD7ThreadDestroyEvent(exitCode); Send(eventObject, AD7ThreadDestroyEvent.IID, ad7Thread); } public void OnThreadStart(DebuggedThread debuggedThread) { // This will get called when the entrypoint breakpoint is fired because the engine sends a thread start event // for the main thread of the application. if (_engine.DebuggedProcess != null) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); } AD7ThreadCreateEvent eventObject = new AD7ThreadCreateEvent(); Send(eventObject, AD7ThreadCreateEvent.IID, (IDebugThread2)debuggedThread.Client); } public void OnBreakpoint(DebuggedThread thread, ReadOnlyCollection<object> clients) { IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[clients.Count]; int i = 0; foreach (object objCurrentBreakpoint in clients) { boundBreakpoints[i] = (IDebugBoundBreakpoint2)objCurrentBreakpoint; i++; } // An engine that supports more advanced breakpoint features such as hit counts, conditions and filters // should notify each bound breakpoint that it has been hit and evaluate conditions here. // The sample engine does not support these features. AD7BoundBreakpointsEnum boundBreakpointsEnum = new AD7BoundBreakpointsEnum(boundBreakpoints); AD7BreakpointEvent eventObject = new AD7BreakpointEvent(boundBreakpointsEnum); AD7Thread ad7Thread = (AD7Thread)thread.Client; Send(eventObject, AD7BreakpointEvent.IID, ad7Thread); } // Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting. public void OnException(DebuggedThread thread, string name, string description, uint code, Guid? exceptionCategory = null, ExceptionBreakpointState state = ExceptionBreakpointState.None) { AD7ExceptionEvent eventObject = new AD7ExceptionEvent(name, description, code, exceptionCategory, state); AD7Thread ad7Thread = (AD7Thread)thread.Client; Send(eventObject, AD7ExceptionEvent.IID, ad7Thread); } public void OnExpressionEvaluationComplete(IVariableInformation var, IDebugProperty2 prop = null) { AD7ExpressionCompleteEvent eventObject = new AD7ExpressionCompleteEvent(var, prop); Send(eventObject, AD7ExpressionCompleteEvent.IID, var.Client); } public void OnStepComplete(DebuggedThread thread) { // Step complete is sent when a step has finished AD7StepCompleteEvent eventObject = new AD7StepCompleteEvent(); AD7Thread ad7Thread = (AD7Thread)thread.Client; Send(eventObject, AD7StepCompleteEvent.IID, ad7Thread); } public void OnAsyncBreakComplete(DebuggedThread thread) { // This will get called when the engine receives the breakpoint event that is created when the user // hits the pause button in vs. Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); AD7Thread ad7Thread = (AD7Thread)thread.Client; AD7AsyncBreakCompleteEvent eventObject = new AD7AsyncBreakCompleteEvent(); Send(eventObject, AD7AsyncBreakCompleteEvent.IID, ad7Thread); } public void OnLoadComplete(DebuggedThread thread) { AD7Thread ad7Thread = (AD7Thread)thread.Client; AD7LoadCompleteEvent eventObject = new AD7LoadCompleteEvent(); Send(eventObject, AD7LoadCompleteEvent.IID, ad7Thread); } public void OnProgramDestroy(uint exitCode) { AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode); Send(eventObject, AD7ProgramDestroyEvent.IID, null); } // Engines notify the debugger about the results of a symbol serach by sending an instance // of IDebugSymbolSearchEvent2 public void OnSymbolSearch(DebuggedModule module, string status, uint dwStatusFlags) { enum_MODULE_INFO_FLAGS statusFlags = (enum_MODULE_INFO_FLAGS)dwStatusFlags; string statusString = ((statusFlags & enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED) != 0 ? "Symbols Loaded - " : "No symbols loaded") + status; AD7Module ad7Module = new AD7Module(module, _engine.DebuggedProcess); AD7SymbolSearchEvent eventObject = new AD7SymbolSearchEvent(ad7Module, statusString, statusFlags); Send(eventObject, AD7SymbolSearchEvent.IID, null); } // Engines notify the debugger that a breakpoint has bound through the breakpoint bound event. public void OnBreakpointBound(object objBoundBreakpoint) { AD7BoundBreakpoint boundBreakpoint = (AD7BoundBreakpoint)objBoundBreakpoint; IDebugPendingBreakpoint2 pendingBreakpoint; ((IDebugBoundBreakpoint2)boundBreakpoint).GetPendingBreakpoint(out pendingBreakpoint); AD7BreakpointBoundEvent eventObject = new AD7BreakpointBoundEvent((AD7PendingBreakpoint)pendingBreakpoint, boundBreakpoint); Send(eventObject, AD7BreakpointBoundEvent.IID, null); } // Engines notify the SDM that a pending breakpoint failed to bind through the breakpoint error event public void OnBreakpointError(AD7ErrorBreakpoint bperr) { AD7BreakpointErrorEvent eventObject = new AD7BreakpointErrorEvent(bperr); Send(eventObject, AD7BreakpointErrorEvent.IID, null); } // Engines notify the SDM that a bound breakpoint change resulted in an error public void OnBreakpointUnbound(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason) { AD7BreakpointUnboundEvent eventObject = new AD7BreakpointUnboundEvent(bp, reason); Send(eventObject, AD7BreakpointUnboundEvent.IID, null); } public void OnCustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2) { var eventObject = new AD7CustomDebugEvent(guidVSService, sourceId, messageCode, parameter1, parameter2); Send(eventObject, AD7CustomDebugEvent.IID, null); } private void SendMessage(string message, OutputMessage.Severity severity, bool isAsync) { try { // IDebugErrorEvent2 is used to report error messages to the user when something goes wrong in the debug engine. // The sample engine doesn't take advantage of this. AD7MessageEvent eventObject = new AD7MessageEvent(new OutputMessage(message, enum_MESSAGETYPE.MT_MESSAGEBOX, severity), isAsync); Send(eventObject, AD7MessageEvent.IID, null); } catch { // Since we are often trying to report an exception, if something goes wrong we don't want to take down the process, // so ignore the failure. } } private static class NativeMethods { [DllImport("ole32.dll", ExactSpelling = true, PreserveSig = false)] public static extern IntPtr CoCreateInstance( [In] ref Guid clsid, IntPtr punkOuter, int context, [In] ref Guid iid); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Threading.Tasks; using System.Web.UI; using Microsoft.Data.Edm.Library.Expressions; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Microsoft.WindowsAzure.Storage.Table.Queryable; using Orleans.Runtime; namespace Orleans.AzureUtils { /// <summary> /// Utility class to encapsulate row-based access to Azure table storage. /// </summary> /// <remarks> /// These functions are mostly intended for internal usage by Orleans runtime, but due to certain assembly packaging constrants this class needs to have public visibility. /// </remarks> /// <typeparam name="T">Table data entry used by this table / manager.</typeparam> public class AzureTableDataManager<T> where T : class, ITableEntity, new() { /// <summary> Name of the table this instance is managing. </summary> public string TableName { get; private set; } /// <summary> Logger for this table manager instance. </summary> protected internal Logger Logger { get; private set; } /// <summary> Connection string for the Azure storage account used to host this table. </summary> protected string ConnectionString { get; set; } private CloudTable tableReference; private readonly CounterStatistic numServerBusy = CounterStatistic.FindOrCreate(StatisticNames.AZURE_SERVER_BUSY, true); /// <summary> /// Constructor /// </summary> /// <param name="tableName">Name of the table to be connected to.</param> /// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param> /// <param name="logger">Logger to use.</param> public AzureTableDataManager(string tableName, string storageConnectionString, Logger logger = null) { var loggerName = "AzureTableDataManager-" + typeof(T).Name; Logger = logger ?? LogManager.GetLogger(loggerName, LoggerType.Runtime); TableName = tableName; ConnectionString = storageConnectionString; AzureStorageUtils.ValidateTableName(tableName); } /// <summary> /// Connects to, or creates and initializes a new Azure table if it does not already exist. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task InitTableAsync() { const string operation = "InitTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didCreate = await Task<bool>.Factory.FromAsync( tableRef.BeginCreateIfNotExists, tableRef.EndCreateIfNotExists, null); Logger.Info(ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName); CloudTableClient tableOperationsClient = GetCloudTableOperationsClient(); tableReference = tableOperationsClient.GetTableReference(TableName); } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task DeleteTableAsync() { const string operation = "DeleteTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didDelete = await Task<bool>.Factory.FromAsync( tableRef.BeginDeleteIfExists, tableRef.EndDeleteIfExists, null); if (didDelete) { Logger.Info(ErrorCode.AzureTable_03, "Deleted Azure storage table {0}", TableName); } } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_04, "Could not delete storage table {0}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes all entities the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task ClearTableAsync() { IEnumerable<Tuple<T,string>> items = (await ReadAllTableEntriesAsync()).ToList(); List <Tuple<T,string>> batch = new List<Tuple<T, string>>(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); foreach (Tuple<T, string> item in items) { batch.Add(item); // delete and clear when we have a full batch if (batch.Count == AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { await DeleteTableEntriesAsync(batch); batch.Clear(); } } if (batch.Count != 0) { await DeleteTableEntriesAsync(batch); } } /// <summary> /// Create a new data entry in the Azure table (insert new, not update existing). /// Fails if the data already exists. /// </summary> /// <param name="data">Data to be inserted into the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> CreateTableEntryAsync(T data) { const string operation = "CreateTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("Creating {0} table entry: {1}", TableName, data); try { // WAS: // svc.AddObject(TableName, data); // SaveChangesOptions.None try { // Presumably FromAsync(BeginExecute, EndExecute) has a slightly better performance then CreateIfNotExistsAsync. var opResult = await Task<TableResult>.Factory.FromAsync( tableReference.BeginExecute, tableReference.EndExecute, TableOperation.Insert(data), null); return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a data entry in the Azure table: creates a new one if does not exists or overwrites (without eTag) an already existing version (the "update in place" semantincs). /// </summary> /// <param name="data">Data to be inserted or replaced in the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpsertTableEntryAsync(T data) { const string operation = "UpsertTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, null); // svc.UpdateObject(data); // SaveChangesOptions.ReplaceOnUpdate, var opResult = await Task<TableResult>.Factory.FromAsync( tableReference.BeginExecute, tableReference.EndExecute, TableOperation.InsertOrReplace(data), null); return opResult.Etag; } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_06, $"Intermediate error upserting entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Merges a data entry in the Azure table. /// </summary> /// <param name="data">Data to be merged in the table.</param> /// <param name="eTag">ETag to apply.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> internal async Task<string> MergeTableEntryAsync(T data, string eTag) { const string operation = "MergeTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, ANY_ETAG); // svc.UpdateObject(data); data.ETag = eTag; // Merge requires an ETag (which may be the '*' wildcard). var opResult = await Task<TableResult>.Factory.FromAsync( tableReference.BeginExecute, tableReference.EndExecute, TableOperation.Merge(data), null); return opResult.Etag; } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_07, $"Intermediate error merging entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Updates a data entry in the Azure table: updates an already existing data in the table, by using eTag. /// Fails if the data does not already exist or of eTag does not match. /// </summary> /// <param name="data">Data to be updated into the table.</param> /// /// <param name="dataEtag">ETag to use.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpdateTableEntryAsync(T data, string dataEtag) { const string operation = "UpdateTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("{0} table {1} entry {2}", operation, TableName, data); try { try { data.ETag = dataEtag; var opResult = await Task<TableResult>.Factory.FromAsync( tableReference.BeginExecute, tableReference.EndExecute, TableOperation.Replace(data), null); //The ETag of data is needed in further operations. return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes an already existing data in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="data">Data entry to be deleted from the table.</param> /// <param name="eTag">ETag to use.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntryAsync(T data, string eTag) { const string operation = "DeleteTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("{0} table {1} entry {2}", operation, TableName, data); try { data.ETag = eTag; try { // Presumably FromAsync(BeginExecute, EndExecute) has a slightly better performance then DeleteIfExistsAsync. await Task<TableResult>.Factory.FromAsync( tableReference.BeginExecute, tableReference.EndExecute, TableOperation.Delete(data), null); } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_08, $"Intermediate error deleting entry {data} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read a single table entry from the storage table. /// </summary> /// <param name="partitionKey">The partition key for the entry.</param> /// <param name="rowKey">The row key for the entry.</param> /// <returns>Value promise for tuple containing the data entry and its corresponding etag.</returns> public async Task<Tuple<T, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { const string operation = "ReadSingleTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("{0} table {1} partitionKey {2} rowKey = {3}", operation, TableName, partitionKey, rowKey); T retrievedResult = default(T); try { try { string queryString = TableQueryFilterBuilder.MatchPartitionKeyAndRowKeyFilter(partitionKey, rowKey); var query = new TableQuery<T>().Where(queryString); TableQuerySegment<T> segment = await Task.Factory .FromAsync<TableQuery<T>, TableContinuationToken, TableQuerySegment<T>>( tableReference.BeginExecuteQuerySegmented, tableReference.EndExecuteQuerySegmented<T>, query, null, null); retrievedResult = segment.Results.SingleOrDefault(); } catch (StorageException exception) { if (!AzureStorageUtils.TableStorageDataNotFound(exception)) throw; } //The ETag of data is needed in further operations. if (retrievedResult != null) return new Tuple<T, string>(retrievedResult, retrievedResult.ETag); if (Logger.IsVerbose) Logger.Verbose("Could not find table entry for PartitionKey={0} RowKey={1}", partitionKey, rowKey); return null; // No data } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read all entries in one partition of the storage table. /// NOTE: This could be an expensive and slow operation for large table partitions! /// </summary> /// <param name="partitionKey">The key for the partition to be searched.</param> /// <returns>Enumeration of all entries in the specified table partition.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesForPartitionAsync(string partitionKey) { Expression<Func<T, bool>> query = instance => instance.PartitionKey == partitionKey; return ReadTableEntriesAndEtagsAsync(query); } /// <summary> /// Read all entries in the table. /// NOTE: This could be a very expensive and slow operation for large tables! /// </summary> /// <returns>Enumeration of all entries in the table.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesAsync() { Expression<Func<T, bool>> query = _ => true; return ReadTableEntriesAndEtagsAsync(query); } /// <summary> /// Deletes a set of already existing data entries in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="collection">Data entries and their corresponding etags to be deleted from the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntriesAsync(IReadOnlyCollection<Tuple<T, string>> collection) { const string operation = "DeleteTableEntries"; var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("Deleting {0} table entries: {1}", TableName, Utils.EnumerableToString(collection)); if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk delete - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } try { var entityBatch = new TableBatchOperation(); foreach (var tuple in collection) { // WAS: // svc.AttachTo(TableName, tuple.Item1, tuple.Item2); // svc.DeleteObject(tuple.Item1); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, T item = tuple.Item1; item.ETag = tuple.Item2; entityBatch.Delete(item); } try { await Task<IList<TableResult>>.Factory.FromAsync( tableReference.BeginExecuteBatch, tableReference.EndExecuteBatch, entityBatch, null); } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_08, $"Intermediate error deleting entries {Utils.EnumerableToString(collection)} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read data entries and their corresponding eTags from the Azure table. /// </summary> /// <param name="predicate">Predicate function to use for querying the table and filtering the results.</param> /// <returns>Enumeration of entries in the table which match the query condition.</returns> public async Task<IEnumerable<Tuple<T, string>>> ReadTableEntriesAndEtagsAsync(Expression<Func<T, bool>> predicate) { const string operation = "ReadTableEntriesAndEtags"; var startTime = DateTime.UtcNow; try { TableQuery<T> cloudTableQuery = tableReference.CreateQuery<T>().Where(predicate).AsTableQuery(); try { Func<Task<List<T>>> executeQueryHandleContinuations = async () => { TableQuerySegment<T> querySegment = null; var list = new List<T>(); while (querySegment == null || querySegment.ContinuationToken != null) { querySegment = await cloudTableQuery.ExecuteSegmentedAsync(querySegment != null ? querySegment.ContinuationToken : null); list.AddRange(querySegment); } return list; }; IBackoffProvider backoff = new FixedBackoff(AzureTableDefaultPolicies.PauseBetweenTableOperationRetries); List<T> results = await AsyncExecutorWithRetries.ExecuteWithRetries( counter => executeQueryHandleContinuations(), AzureTableDefaultPolicies.MaxTableOperationRetries, (exc, counter) => AzureStorageUtils.AnalyzeReadException(exc.GetBaseException(), counter, TableName, Logger), AzureTableDefaultPolicies.TableOperationTimeout, backoff); // Data was read successfully if we got to here return results.Select(i => Tuple.Create(i, i.ETag)).ToList(); } catch (Exception exc) { // Out of retries... var errorMsg = $"Failed to read Azure storage table {TableName}: {exc.Message}"; if (!AzureStorageUtils.TableStorageDataNotFound(exc)) { Logger.Warn(ErrorCode.AzureTable_09, errorMsg, exc); } throw new OrleansException(errorMsg, exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a set of new data entries into the table. /// Fails if the data does already exists. /// </summary> /// <param name="collection">Data entries to be inserted into the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task BulkInsertTableEntries(IReadOnlyCollection<T> collection) { const string operation = "BulkInsertTableEntries"; if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk update - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("Bulk inserting {0} entries to {1} table", collection.Count, TableName); try { // WAS: // svc.AttachTo(TableName, entry); // svc.UpdateObject(entry); // SaveChangesOptions.None | SaveChangesOptions.Batch, // SaveChangesOptions.None == Insert-or-merge operation, SaveChangesOptions.Batch == Batch transaction // http://msdn.microsoft.com/en-us/library/hh452241.aspx var entityBatch = new TableBatchOperation(); foreach (T entry in collection) { entityBatch.Insert(entry); } try { // http://msdn.microsoft.com/en-us/library/hh452241.aspx await Task<IList<TableResult>>.Factory.FromAsync( tableReference.BeginExecuteBatch, tableReference.EndExecuteBatch, entityBatch, null); } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_37, $"Intermediate error bulk inserting {collection.Count} entries in the table {TableName}", exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } #region Internal functions internal async Task<Tuple<string, string>> InsertTwoTableEntriesConditionallyAsync(T data1, T data2, string data2Etag) { const string operation = "InsertTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("{0} into table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AddObject(TableName, data); // --- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); entityBatch.Add(TableOperation.Insert(data1)); data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); var opResults = await Task<IList<TableResult>>.Factory.FromAsync( tableReference.BeginExecuteBatch, tableReference.EndExecuteBatch, entityBatch, null); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } internal async Task<Tuple<string, string>> UpdateTwoTableEntriesConditionallyAsync(T data1, string data1Etag, T data2, string data2Etag) { const string operation = "UpdateTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsVerbose2) Logger.Verbose2("{0} table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AttachTo(TableName, data, dataEtag); // svc.UpdateObject(data); // ---- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); data1.ETag = data1Etag; entityBatch.Add(TableOperation.Replace(data1)); if (data2 != null && data2Etag != null) { data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); } var opResults = await Task<IList<TableResult>>.Factory.FromAsync( tableReference.BeginExecuteBatch, tableReference.EndExecuteBatch, entityBatch, null); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } // Utility methods private CloudTableClient GetCloudTableOperationsClient() { try { CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient operationsClient = storageAccount.CreateCloudTableClient(); operationsClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableOperationRetryPolicy; operationsClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableOperationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value operationsClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return operationsClient; } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_17, "Error creating CloudTableOperationsClient.", exc); throw; } } private CloudTableClient GetCloudTableCreationClient() { try { CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient creationClient = storageAccount.CreateCloudTableClient(); creationClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableCreationRetryPolicy; creationClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableCreationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value creationClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return creationClient; } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_18, "Error creating CloudTableCreationClient.", exc); throw; } } private void CheckAlertWriteError(string operation, object data1, string data2, Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if(AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus) && AzureStorageUtils.IsContentionError(httpStatusCode)) { // log at Verbose, since failure on conditional is not not an error. Will analyze and warn later, if required. if(Logger.IsVerbose) Logger.Verbose(ErrorCode.AzureTable_13, $"Intermediate Azure table write error {operation} to table {TableName} data1 {(data1 ?? "null")} data2 {(data2 ?? "null")}", exc); } else { Logger.Error(ErrorCode.AzureTable_14, $"Azure table access write error {operation} to table {TableName} entry {data1}", exc); } } private void CheckAlertSlowAccess(DateTime startOperation, string operation) { var timeSpan = DateTime.UtcNow - startOperation; if (timeSpan > AzureTableDefaultPolicies.TableOperationTimeout) { Logger.Warn(ErrorCode.AzureTable_15, "Slow access to Azure Table {0} for {1}, which took {2}.", TableName, operation, timeSpan); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Diagnostics.CodeAnalysis; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb { /// <summary> /// packet decoder /// </summary> public class SmbServerDecodePacket : CifsServerDecodePacket { /// <summary> /// server context /// </summary> private SmbServerContext context; /// <summary> /// server context /// </summary> public SmbServerContext Context { get { return context; } set { context = value; } } /// <summary> /// Constructor /// </summary> public SmbServerDecodePacket() : base() { } /// <summary> /// to decode stack packet from the received message bytes. /// </summary> /// <param name = "endPointIdentity">the endpoint from which the message bytes are received. </param> /// <param name = "messageBytes">the received message bytes to be decoded. </param> /// <param name = "consumedLength">the length of message bytes consumed by decoder. </param> /// <param name = "expectedLength">the length of message bytes the decoder expects to receive. </param> /// <returns>the stack packets decoded from the received message bytes. </returns> [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] public SmbPacket[] DecodePacket( object endPointIdentity, byte[] messageBytes, out int consumedLength, out int expectedLength) { // initialize the default values expectedLength = 0; consumedLength = 0; SmbPacket[] packets = null; byte[] packetBytes = null; // direct tcp transport management instance SmbDirectTcpPacket directTcp = new SmbDirectTcpPacket(null); // Netbios over Tcp if (endPointIdentity is int) { packetBytes = messageBytes; } // Direct Tcp else { // message bytes is invalid if (directTcp.IsPacketInvalid(messageBytes)) { return null; } // if the packet has continue packet, do not parse it. if (directTcp.HasContinuousPacket(messageBytes)) { return null; } // decode the data of packet packetBytes = directTcp.GetTcpData(messageBytes); } packets = DecodePacketFromBytesWithoutTransport( this.context.GetConnection(endPointIdentity), packetBytes, out consumedLength, out expectedLength); // decode the header of packet if (packets != null && packets.Length > 0) { packets[0].TransportHeader = CifsMessageUtils.ToStuct<TransportHeader>(messageBytes); } // for Direct Tcp, calculate the cosumedlength and plus the Tcp header length. if (!(endPointIdentity is int)) { // to consume the additional data consumedLength = Math.Max(consumedLength, directTcp.GetTcpPacketLength(messageBytes)); // update the consumed length with transport consumedLength += directTcp.TcpTransportHeaderSize; } return packets; } /// <summary> /// to decode stack packet from the received message bytes. /// the message bytes contains data without transport information /// </summary> /// <param name = "connection">the connection from which the message bytes are received. </param> /// <param name = "packetBytesWithoutTransport">the received message bytes to be decoded. </param> /// <param name = "consumedLength">the length of message bytes consumed by decoder. </param> /// <param name = "expectedLength">the length of message bytes the decoder expects to receive. </param> /// <returns>the stack packets decoded from the received message bytes. </returns> /// <exception cref="InvalidOperationException"> /// thrown when packet security signature is invalid. /// </exception> private SmbPacket[] DecodePacketFromBytesWithoutTransport( SmbServerConnection connection, byte[] packetBytesWithoutTransport, out int consumedLength, out int expectedLength) { expectedLength = 0; consumedLength = 0; SmbPacket[] packets = new SmbPacket[0]; int packetConsumedLength = 0; int packetExpectedLength = 0; // decode packets using cifs decorder. SmbPacket request = this.DecodeSmbRequestFromBytes( packetBytesWithoutTransport, out packetConsumedLength); // valid the signature if (request != null && request.SmbHeader.SecurityFeatures != 0 && connection.GssApi != null && connection.GssApi.SessionKey != null) { byte[] bytesToValid = ArrayUtility.SubArray(packetBytesWithoutTransport, 0); // the signature offset is 14. byte[] zeroSignature = new byte[sizeof(ulong)]; Array.Copy(zeroSignature, 0, bytesToValid, 14, zeroSignature.Length); // the signature offset is 14. zeroSignature = BitConverter.GetBytes((ulong)connection.ServerNextReceiveSequenceNumber); Array.Copy(zeroSignature, 0, bytesToValid, 14, zeroSignature.Length); byte[] signature = CifsMessageUtils.CreateSignature(bytesToValid, connection.GssApi.SessionKey); if (request.SmbHeader.SecurityFeatures != BitConverter.ToUInt64(signature, 0)) { throw new InvalidOperationException("packet security signature is invalid"); } } // Use the decoded packet to UpdateRoleContext if it is not null and ContextUpdate is enabled: if (request != null) { if (this.context.IsUpdateContext) { this.context.UpdateRoleContext(connection, request); } packets = new SmbPacket[] { request }; } // update the length after decode packet. consumedLength += packetConsumedLength; expectedLength += packetExpectedLength; return packets; } /// <summary> /// decode the batched request packet /// </summary> /// <param name="channel">the channel of bytes to read</param> /// <param name="smbBatchedRequest">the batched request</param> /// <returns>the consumed length of batched request packet</returns> protected override int DecodeBatchedRequest(Channel channel, SmbBatchedRequestPacket smbBatchedRequest) { // do not process batched request. return 0; } /// <summary> /// to new a Smb request packet in type of the Command in SmbHeader. /// </summary> /// <param name="messageBytes">bytes contains packet</param> /// <returns> /// the new request packet. /// the null means that the utility don't know how to create the request. /// </returns> protected override SmbPacket CreateSmbRequestPacket(byte[] messageBytes) { SmbPacket smbRequest = null; using (MemoryStream stream = new MemoryStream(messageBytes, true)) { using (Channel channel = new Channel(null, stream)) { // read smb header and new SmbPacket: if (channel.Stream.Position < channel.Stream.Length && messageBytes.Length >= CifsMessageUtils.GetSize<SmbHeader>(new SmbHeader())) { SmbHeader smbHeader = channel.Read<SmbHeader>(); smbRequest = FindTheTargetPacket(smbHeader, channel); } } } return smbRequest; } /// <summary> /// find the target packet. /// </summary> /// <param name="smbHeader">the header of smb packet</param> /// <param name="channel">the channel to access bytes</param> /// <returns>the target packet</returns> private static SmbPacket FindTheTargetPacket(SmbHeader smbHeader, Channel channel) { SmbPacket smbPacket = null; switch (smbHeader.Command) { case SmbCommand.SMB_COM_NEGOTIATE: smbPacket = new SmbNegotiateRequestPacket(); break; case SmbCommand.SMB_COM_SESSION_SETUP_ANDX: SmbHeader_Flags2_Values flags2 = (SmbHeader_Flags2_Values)smbHeader.Flags2; if ((flags2 & SmbHeader_Flags2_Values.SMB_FLAGS2_EXTENDED_SECURITY) == SmbHeader_Flags2_Values.SMB_FLAGS2_EXTENDED_SECURITY) { smbPacket = new Smb.SmbSessionSetupAndxRequestPacket(); } else { smbPacket = new Cifs.SmbSessionSetupAndxRequestPacket(); } break; case SmbCommand.SMB_COM_TREE_CONNECT_ANDX: smbPacket = new SmbTreeConnectAndxRequestPacket(); break; case SmbCommand.SMB_COM_NT_CREATE_ANDX: smbPacket = new SmbNtCreateAndxRequestPacket(); break; case SmbCommand.SMB_COM_OPEN_ANDX: smbPacket = new SmbOpenAndxRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_ANDX: smbPacket = new SmbWriteAndxRequestPacket(); break; case SmbCommand.SMB_COM_READ_ANDX: smbPacket = new SmbReadAndxRequestPacket(); break; case SmbCommand.SMB_COM_CLOSE: smbPacket = new SmbCloseRequestPacket(); break; case SmbCommand.SMB_COM_TREE_DISCONNECT: smbPacket = new SmbTreeDisconnectRequestPacket(); break; case SmbCommand.SMB_COM_LOGOFF_ANDX: smbPacket = new SmbLogoffAndxRequestPacket(); break; case SmbCommand.SMB_COM_TRANSACTION: SMB_COM_TRANSACTION_Request_SMB_Parameters transaction = channel.Read<SMB_COM_TRANSACTION_Request_SMB_Parameters>(); if (transaction.SetupCount == 0) { smbPacket = new SmbTransRapRequestPacket(); } else { smbPacket = FindTheTransactionPacket( transaction.SetupCount, (TransSubCommand)transaction.Setup[0]); } break; case SmbCommand.SMB_COM_TRANSACTION2: SMB_COM_TRANSACTION2_Request_SMB_Parameters transaction2 = channel.Read<SMB_COM_TRANSACTION2_Request_SMB_Parameters>(); smbPacket = FindTheTrans2Packet((Trans2SubCommand)transaction2.Subcommand); break; case SmbCommand.SMB_COM_NT_TRANSACT: SMB_COM_NT_TRANSACT_Request_SMB_Parameters ntTransactoin = channel.Read<SMB_COM_NT_TRANSACT_Request_SMB_Parameters>(); smbPacket = FindTheNtTransPacket(ntTransactoin.Function, CifsMessageUtils.ToBytesArray<ushort>(ntTransactoin.Setup)); break; default: break; } return smbPacket; } /// <summary> /// find the nt transaction packets /// </summary> /// <param name="command">the command of nt transaction</param> /// <param name="setup">the setup contains the sub command</param> /// <returns>the target nt transaction packet</returns> private static SmbPacket FindTheNtTransPacket(NtTransSubCommand command, byte[] setup) { SmbPacket smbPacket = null; switch (command) { case NtTransSubCommand.NT_TRANSACT_CREATE: smbPacket = new SmbNtTransactCreateRequestPacket(); break; case NtTransSubCommand.NT_TRANSACT_RENAME: smbPacket = new SmbNtTransRenameRequestPacket(); break; case NtTransSubCommand.NT_TRANSACT_IOCTL: NT_TRANSACT_IOCTL_SETUP subCommand = CifsMessageUtils.ToStuct<NT_TRANSACT_IOCTL_SETUP>(setup); switch ((NtTransFunctionCode)subCommand.FunctionCode) { case NtTransFunctionCode.FSCTL_SRV_ENUMERATE_SNAPSHOTS: smbPacket = new SmbNtTransFsctlSrvEnumerateSnapshotsRequestPacket(); break; case NtTransFunctionCode.FSCTL_SRV_REQUEST_RESUME_KEY: smbPacket = new SmbNtTransFsctlSrvRequestResumeKeyRequestPacket(); break; case NtTransFunctionCode.FSCTL_SRV_COPYCHUNK: smbPacket = new SmbNtTransFsctlSrvCopyChunkRequestPacket(); break; default: smbPacket = new SmbNtTransactIoctlRequestPacket(); break; } break; default: switch ((SmbNtTransSubCommand)command) { case SmbNtTransSubCommand.NT_TRANSACT_QUERY_QUOTA: smbPacket = new SmbNtTransQueryQuotaRequestPacket(); break; case SmbNtTransSubCommand.NT_TRANSACT_SET_QUOTA: smbPacket = new SmbNtTransSetQuotaRequestPacket(); break; } break; } return smbPacket; } /// <summary> /// find the transaction2 packet. /// </summary> /// <param name="command">the command of transaction2 packet.</param> /// <returns>the target transaction2 packet</returns> private static SmbPacket FindTheTrans2Packet(Trans2SubCommand command) { SmbPacket smbPacket = null; switch ((Trans2SubCommand)command) { case Trans2SubCommand.TRANS2_FIND_FIRST2: smbPacket = new SmbTrans2FindFirst2RequestPacket(); break; case Trans2SubCommand.TRANS2_FIND_NEXT2: smbPacket = new SmbTrans2FindNext2RequestPacket(); break; case Trans2SubCommand.TRANS2_QUERY_FS_INFORMATION: smbPacket = new SmbTrans2QueryFsInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_SET_FS_INFORMATION: smbPacket = new SmbTrans2SetFsInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_QUERY_PATH_INFORMATION: smbPacket = new SmbTrans2QueryPathInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_SET_PATH_INFORMATION: smbPacket = new SmbTrans2SetPathInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_QUERY_FILE_INFORMATION: smbPacket = new SmbTrans2QueryFileInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_SET_FILE_INFORMATION: smbPacket = new SmbTrans2SetFileInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_GET_DFS_REFERRAL: smbPacket = new SmbTrans2GetDfsReferralRequestPacket(); break; default: break; } return smbPacket; } /// <summary> /// find the transaction packet. /// </summary> /// <param name="setupCount">the count of setup</param> /// <param name="command">the command of transaction packet</param> /// <returns>the target transaction packet</returns> private static SmbPacket FindTheTransactionPacket(byte setupCount, TransSubCommand command) { if (setupCount == 0) { return new SmbTransRapRequestPacket(); } else if (setupCount == 3) { return new SmbTransMailslotWriteRequestPacket(); } SmbPacket smbPacket = null; switch ((TransSubCommand)command) { case TransSubCommand.TRANS_SET_NMPIPE_STATE: smbPacket = new SmbTransSetNmpipeStateRequestPacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_STATE: smbPacket = new SmbTransQueryNmpipeStateRequestPacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_INFO: smbPacket = new SmbTransQueryNmpipeInfoRequestPacket(); break; case TransSubCommand.TRANS_PEEK_NMPIPE: smbPacket = new SmbTransPeekNmpipeRequestPacket(); break; case TransSubCommand.TRANS_TRANSACT_NMPIPE: smbPacket = new SmbTransTransactNmpipeRequestPacket(); break; case TransSubCommand.TRANS_RAW_READ_NMPIPE: smbPacket = new SmbTransRawReadNmpipeRequestPacket(); break; case TransSubCommand.TRANS_READ_NMPIPE: smbPacket = new SmbTransReadNmpipeRequestPacket(); break; case TransSubCommand.TRANS_WRITE_NMPIPE: smbPacket = new SmbTransWriteNmpipeRequestPacket(); break; case TransSubCommand.TRANS_WAIT_NMPIPE: smbPacket = new SmbTransWaitNmpipeRequestPacket(); break; case TransSubCommand.TRANS_CALL_NMPIPE: smbPacket = new SmbTransCallNmpipeRequestPacket(); break; case TransSubCommand.TRANS_RAW_WRITE_NMPIPE: smbPacket = new SmbTransRawWriteNmpipeRequestPacket(); break; default: break; } return smbPacket; } } }
/* * Port of Snowball stemmers on C# * Original stemmers can be found on http://snowball.tartarus.org * Licence still BSD: http://snowball.tartarus.org/license.php * * Most of stemmers are ported from Java by Iveonik Systems ltd. (www.iveonik.com) */ using System; using System.Collections.Generic; using System.Text; namespace Iveonik.Stemmers { public class EnglishStemmer : StemmerOperations, IStemmer { private readonly static Among[] a_0 = { new Among ( "arsen", -1, -1,null ), new Among ( "commun", -1, -1, null ), new Among ( "gener", -1, -1, null ) }; private readonly static Among[] a_1 = { new Among ( "'", -1, 1, null), new Among ( "'s'", 0, 1, null), new Among ( "'s", -1, 1, null) }; private readonly static Among[] a_2 = { new Among ( "ied", -1, 2, null), new Among ( "s", -1, 3, null), new Among ( "ies", 1, 2, null), new Among ( "sses", 1, 1, null), new Among ( "ss", 1, -1, null), new Among ( "us", 1, -1, null) }; private readonly static Among[] a_3 = { new Among ( "", -1, 3, null), new Among ( "bb", 0, 2, null), new Among ( "dd", 0, 2, null), new Among ( "ff", 0, 2, null), new Among ( "gg", 0, 2, null), new Among ( "bl", 0, 1, null), new Among ( "mm", 0, 2, null), new Among ( "nn", 0, 2, null), new Among ( "pp", 0, 2, null), new Among ( "rr", 0, 2, null), new Among ( "at", 0, 1, null), new Among ( "tt", 0, 2, null), new Among ( "iz", 0, 1, null) }; private readonly static Among[] a_4 = { new Among ( "ed", -1, 2, null), new Among ( "eed", 0, 1, null), new Among ( "ing", -1, 2, null), new Among ( "edly", -1, 2, null), new Among ( "eedly", 3, 1, null), new Among ( "ingly", -1, 2, null) }; private readonly static Among[] a_5 = { new Among ( "anci", -1, 3, null), new Among ( "enci", -1, 2, null), new Among ( "ogi", -1, 13, null), new Among ( "li", -1, 16, null), new Among ( "bli", 3, 12, null), new Among ( "abli", 4, 4, null), new Among ( "alli", 3, 8, null), new Among ( "fulli", 3, 14, null), new Among ( "lessli", 3, 15, null), new Among ( "ousli", 3, 10, null), new Among ( "entli", 3, 5, null), new Among ( "aliti", -1, 8, null), new Among ( "biliti", -1, 12, null), new Among ( "iviti", -1, 11, null), new Among ( "tional", -1, 1, null), new Among ( "ational", 14, 7, null), new Among ( "alism", -1, 8, null), new Among ( "ation", -1, 7, null), new Among ( "ization", 17, 6, null), new Among ( "izer", -1, 6, null), new Among ( "ator", -1, 7, null), new Among ( "iveness", -1, 11, null), new Among ( "fulness", -1, 9, null), new Among ( "ousness", -1, 10, null) }; private readonly static Among[] a_6 = { new Among ( "icate", -1, 4, null), new Among ( "ative", -1, 6, null), new Among ( "alize", -1, 3, null), new Among ( "iciti", -1, 4, null), new Among ( "ical", -1, 4, null), new Among ( "tional", -1, 1, null), new Among ( "ational", 5, 2, null), new Among ( "ful", -1, 5, null), new Among ( "ness", -1, 5, null) }; private readonly static Among[] a_7 = { new Among ( "ic", -1, 1, null), new Among ( "ance", -1, 1, null), new Among ( "ence", -1, 1, null), new Among ( "able", -1, 1, null), new Among ( "ible", -1, 1, null), new Among ( "ate", -1, 1, null), new Among ( "ive", -1, 1, null), new Among ( "ize", -1, 1, null), new Among ( "iti", -1, 1, null), new Among ( "al", -1, 1, null), new Among ( "ism", -1, 1, null), new Among ( "ion", -1, 2, null), new Among ( "er", -1, 1, null), new Among ( "ous", -1, 1, null), new Among ( "ant", -1, 1, null), new Among ( "ent", -1, 1, null), new Among ( "ment", 15, 1, null), new Among ( "ement", 16, 1, null) }; private readonly static Among[] a_8 = { new Among ( "e", -1, 1, null), new Among ( "l", -1, 2, null) }; private readonly static Among[] a_9 = { new Among ( "succeed", -1, -1, null), new Among ( "proceed", -1, -1, null), new Among ( "exceed", -1, -1, null), new Among ( "canning", -1, -1, null), new Among ( "inning", -1, -1, null), new Among ( "earring", -1, -1, null), new Among ( "herring", -1, -1, null), new Among ( "outing", -1, -1, null) }; private readonly static Among[] a_10 = { new Among ( "andes", -1, -1, null), new Among ( "atlas", -1, -1, null), new Among ( "bias", -1, -1, null), new Among ( "cosmos", -1, -1, null), new Among ( "dying", -1, 3, null), new Among ( "early", -1, 9, null), new Among ( "gently", -1, 7, null), new Among ( "howe", -1, -1, null), new Among ( "idly", -1, 6, null), new Among ( "lying", -1, 4, null), new Among ( "news", -1, -1, null), new Among ( "only", -1, 10, null), new Among ( "singly", -1, 11, null), new Among ( "skies", -1, 2, null), new Among ( "skis", -1, 1, null), new Among ( "sky", -1, -1, null), new Among ( "tying", -1, 5, null), new Among ( "ugly", -1, 8, null) }; private static readonly char[] g_v = { (char)17, (char)65, (char)16, (char)1 }; private static readonly char[] g_v_WXY = { (char)1, (char)17, (char)65, (char)208, (char)1 }; private static readonly char[] g_valid_LI = { (char)55, (char)141, (char)2 }; private bool B_Y_found; private int I_p2; private int I_p1; private void copy_from(EnglishStemmer other) { B_Y_found = other.B_Y_found; I_p2 = other.I_p2; I_p1 = other.I_p1; copy_from(other); } private bool r_prelude() { bool returnn = false; bool subroot = false; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 25 // unset Y_found, line 26 B_Y_found = false; // do, line 27 v_1 = cursor; // lab0: do { // (, line 27 // [, line 27 bra = cursor; // literal, line 27 if (!(eq_s(1, "'"))) { break; } // ], line 27 ket = cursor; // delete, line 27 slice_del(); } while (false); cursor = v_1; // do, line 28 v_2 = cursor; do { // (, line 28 // [, line 28 bra = cursor; // literal, line 28 if (!(eq_s(1, "y"))) { break; } // ], line 28 ket = cursor; // <-, line 28 slice_from("Y"); // set Y_found, line 28 B_Y_found = true; } while (false); cursor = v_2; // do, line 29 v_3 = cursor; do { // repeat, line 29 replab3: while (true) { v_4 = cursor; do { // (, line 29 // goto, line 29 while (true) { v_5 = cursor; do { // (, line 29 if (!(in_grouping(g_v, 97, 121))) { break; } // [, line 29 bra = cursor; // literal, line 29 if (!(eq_s(1, "y"))) { break; } // ], line 29 ket = cursor; cursor = v_5; subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = v_5; if (cursor >= limit) { subroot = true; break; } cursor++; } returnn = true; if (subroot) { subroot = false; break; } // <-, line 29 slice_from("Y"); // set Y_found, line 29 B_Y_found = true; if (returnn) { goto replab3; } } while (false); cursor = v_4; break; } } while (false); cursor = v_3; return true; } private bool r_mark_regions() { bool subroot = false; int v_1; int v_2; // (, line 32 I_p1 = limit; I_p2 = limit; // do, line 35 v_1 = cursor; do { // (, line 35 // or, line 41 do { v_2 = cursor; do { // among, line 36 if (find_among(a_0, 3) == 0) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = v_2; // (, line 41 // gopast, line 41 while (true) { do { if (!(in_grouping(g_v, 97, 121))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } if (cursor >= limit) { goto breaklab0; } cursor++; } // gopast, line 41 while (true) { do { if (!(out_grouping(g_v, 97, 121))) { break; } // break golab5; subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } if (cursor >= limit) { goto breaklab0; } cursor++; } } while (false); // setmark p1, line 42 I_p1 = cursor; // gopast, line 43 while (true) { do { if (!(in_grouping(g_v, 97, 121))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } if (cursor >= limit) { goto breaklab0; } cursor++; } // gopast, line 43 while (true) { do { if (!(out_grouping(g_v, 97, 121))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } if (cursor >= limit) { goto breaklab0; } cursor++; } // setmark p2, line 43 I_p2 = cursor; } while (false); breaklab0: cursor = v_1; return true; } private bool r_shortv() { bool subroot = false; int v_1; // (, line 49 // or, line 51 // lab0: do { v_1 = limit - cursor; do { // (, line 50 if (!(out_grouping_b(g_v_WXY, 89, 121))) { break; } if (!(in_grouping_b(g_v, 97, 121))) { break; } if (!(out_grouping_b(g_v, 97, 121))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = limit - v_1; // (, line 52 if (!(out_grouping_b(g_v, 97, 121))) { return false; } if (!(in_grouping_b(g_v, 97, 121))) { return false; } // atlimit, line 52 if (cursor > limit_backward) { return false; } } while (false); return true; } private bool r_R1() { if (!(I_p1 <= cursor)) { return false; } return true; } private bool r_R2() { if (!(I_p2 <= cursor)) { return false; } return true; } private bool r_Step_1a() { bool subroot = false; int among_var; int v_1; int v_2; // (, line 58 // try, line 59 v_1 = limit - cursor; do { // (, line 59 // [, line 60 ket = cursor; // substring, line 60 among_var = find_among_b(a_1, 3); if (among_var == 0) { cursor = limit - v_1; break; } // ], line 60 bra = cursor; switch (among_var) { case 0: cursor = limit - v_1; subroot = true; break; case 1: // (, line 62 // delete, line 62 slice_del(); break; } if (subroot) { subroot = false; break; } } while (false); // [, line 65 ket = cursor; // substring, line 65 among_var = find_among_b(a_2, 6); if (among_var == 0) { return false; } // ], line 65 bra = cursor; switch (among_var) { case 0: return false; case 1: // (, line 66 // <-, line 66 slice_from("ss"); break; case 2: // (, line 68 // or, line 68 // lab1: do { v_2 = limit - cursor; do { // (, line 68 // hop, line 68 { int c = cursor - 2; if (limit_backward > c || c > limit) { break; } cursor = c; } // <-, line 68 slice_from("i"); subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = limit - v_2; // <-, line 68 slice_from("ie"); } while (false); break; case 3: // (, line 69 // next, line 69 if (cursor <= limit_backward) { return false; } cursor--; // gopast, line 69 while (true) { do { if (!(in_grouping_b(g_v, 97, 121))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } if (cursor <= limit_backward) { return false; } cursor--; } // delete, line 69 slice_del(); break; } return true; } private bool r_Step_1b() { bool subroot = false; int among_var; int v_1; int v_3; int v_4; // (, line 74 // [, line 75 ket = cursor; // substring, line 75 among_var = find_among_b(a_4, 6); if (among_var == 0) { return false; } // ], line 75 bra = cursor; switch (among_var) { case 0: return false; case 1: // (, line 77 // call R1, line 77 if (!r_R1()) { return false; } // <-, line 77 slice_from("ee"); break; case 2: // (, line 79 // test, line 80 v_1 = limit - cursor; // gopast, line 80 while (true) { do { if (!(in_grouping_b(g_v, 97, 121))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } if (cursor <= limit_backward) { return false; } cursor--; } cursor = limit - v_1; // delete, line 80 slice_del(); // test, line 81 v_3 = limit - cursor; // substring, line 81 among_var = find_among_b(a_3, 13); if (among_var == 0) { return false; } cursor = limit - v_3; switch (among_var) { case 0: return false; case 1: // (, line 83 // <+, line 83 { int c = cursor; insert(cursor, cursor, "e"); cursor = c; } break; case 2: // (, line 86 // [, line 86 ket = cursor; // next, line 86 if (cursor <= limit_backward) { return false; } cursor--; // ], line 86 bra = cursor; // delete, line 86 slice_del(); break; case 3: // (, line 87 // atmark, line 87 if (cursor != I_p1) { return false; } // test, line 87 v_4 = limit - cursor; // call shortv, line 87 if (!r_shortv()) { return false; } cursor = limit - v_4; // <+, line 87 { int c = cursor; insert(cursor, cursor, "e"); cursor = c; } break; } break; } return true; } private bool r_Step_1c() { bool returnn = false; bool subroot = false; int v_1; int v_2; // (, line 93 // [, line 94 ket = cursor; // or, line 94 // lab0: do { v_1 = limit - cursor; do { // literal, line 94 if (!(eq_s_b(1, "y"))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = limit - v_1; // literal, line 94 if (!(eq_s_b(1, "Y"))) { return false; } } while (false); // ], line 94 bra = cursor; if (!(out_grouping_b(g_v, 97, 121))) { return false; } // not, line 95 { v_2 = limit - cursor; do { returnn = true; // atlimit, line 95 if (cursor > limit_backward) { break; } if (returnn) { return false; } } while (false); cursor = limit - v_2; } // <-, line 96 slice_from("i"); return true; } private bool r_Step_2() { int among_var; // (, line 99 // [, line 100 ket = cursor; // substring, line 100 among_var = find_among_b(a_5, 24); if (among_var == 0) { return false; } // ], line 100 bra = cursor; // call R1, line 100 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 101 // <-, line 101 slice_from("tion"); break; case 2: // (, line 102 // <-, line 102 slice_from("ence"); break; case 3: // (, line 103 // <-, line 103 slice_from("ance"); break; case 4: // (, line 104 // <-, line 104 slice_from("able"); break; case 5: // (, line 105 // <-, line 105 slice_from("ent"); break; case 6: // (, line 107 // <-, line 107 slice_from("ize"); break; case 7: // (, line 109 // <-, line 109 slice_from("ate"); break; case 8: // (, line 111 // <-, line 111 slice_from("al"); break; case 9: // (, line 112 // <-, line 112 slice_from("ful"); break; case 10: // (, line 114 // <-, line 114 slice_from("ous"); break; case 11: // (, line 116 // <-, line 116 slice_from("ive"); break; case 12: // (, line 118 // <-, line 118 slice_from("ble"); break; case 13: // (, line 119 // literal, line 119 if (!(eq_s_b(1, "l"))) { return false; } // <-, line 119 slice_from("og"); break; case 14: // (, line 120 // <-, line 120 slice_from("ful"); break; case 15: // (, line 121 // <-, line 121 slice_from("less"); break; case 16: // (, line 122 if (!(in_grouping_b(g_valid_LI, 99, 116))) { return false; } // delete, line 122 slice_del(); break; } return true; } private bool r_Step_3() { int among_var; // (, line 126 // [, line 127 ket = cursor; // substring, line 127 among_var = find_among_b(a_6, 9); if (among_var == 0) { return false; } // ], line 127 bra = cursor; // call R1, line 127 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 128 // <-, line 128 slice_from("tion"); break; case 2: // (, line 129 // <-, line 129 slice_from("ate"); break; case 3: // (, line 130 // <-, line 130 slice_from("al"); break; case 4: // (, line 132 // <-, line 132 slice_from("ic"); break; case 5: // (, line 134 // delete, line 134 slice_del(); break; case 6: // (, line 136 // call R2, line 136 if (!r_R2()) { return false; } // delete, line 136 slice_del(); break; } return true; } private bool r_Step_4() { bool subroot = false; int among_var; int v_1; // (, line 140 // [, line 141 ket = cursor; // substring, line 141 among_var = find_among_b(a_7, 18); if (among_var == 0) { return false; } // ], line 141 bra = cursor; // call R2, line 141 if (!r_R2()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 144 // delete, line 144 slice_del(); break; case 2: // (, line 145 // or, line 145 do { v_1 = limit - cursor; do { // literal, line 145 if (!(eq_s_b(1, "s"))) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = limit - v_1; // literal, line 145 if (!(eq_s_b(1, "t"))) { return false; } } while (false); // delete, line 145 slice_del(); break; } return true; } private bool r_Step_5() { bool returnn = false; bool subroot = false; int among_var; int v_1; int v_2; // (, line 149 // [, line 150 ket = cursor; // substring, line 150 among_var = find_among_b(a_8, 2); if (among_var == 0) { return false; } // ], line 150 bra = cursor; switch (among_var) { case 0: return false; case 1: // (, line 151 // or, line 151 do { v_1 = limit - cursor; do { // call R2, line 151 if (!r_R2()) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = limit - v_1; // (, line 151 // call R1, line 151 if (!r_R1()) { return false; } // not, line 151 { v_2 = limit - cursor; do { returnn = true; // call shortv, line 151 if (!r_shortv()) { break; } if (returnn) { return false; } } while (false); cursor = limit - v_2; } } while (false); // delete, line 151 slice_del(); break; case 2: // (, line 152 // call R2, line 152 if (!r_R2()) { return false; } // literal, line 152 if (!(eq_s_b(1, "l"))) { return false; } // delete, line 152 slice_del(); break; } return true; } private bool r_exception2() { // (, line 156 // [, line 158 ket = cursor; // substring, line 158 if (find_among_b(a_9, 8) == 0) { return false; } // ], line 158 bra = cursor; // atlimit, line 158 if (cursor > limit_backward) { return false; } return true; } private bool r_exception1() { int among_var; // (, line 168 // [, line 170 bra = cursor; // substring, line 170 among_var = find_among(a_10, 18); if (among_var == 0) { return false; } // ], line 170 ket = cursor; // atlimit, line 170 if (cursor < limit) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 174 // <-, line 174 slice_from("ski"); break; case 2: // (, line 175 // <-, line 175 slice_from("sky"); break; case 3: // (, line 176 // <-, line 176 slice_from("die"); break; case 4: // (, line 177 // <-, line 177 slice_from("lie"); break; case 5: // (, line 178 // <-, line 178 slice_from("tie"); break; case 6: // (, line 182 // <-, line 182 slice_from("idl"); break; case 7: // (, line 183 // <-, line 183 slice_from("gentl"); break; case 8: // (, line 184 // <-, line 184 slice_from("ugli"); break; case 9: // (, line 185 // <-, line 185 slice_from("earli"); break; case 10: // (, line 186 // <-, line 186 slice_from("onli"); break; case 11: // (, line 187 // <-, line 187 slice_from("singl"); break; } return true; } private bool r_postlude() { bool returnn = false; bool subroot = false; int v_1; int v_2; // (, line 203 // Boolean test Y_found, line 203 if (!(B_Y_found)) { return false; } // repeat, line 203 replab0: while (true) { v_1 = cursor; do { // (, line 203 // goto, line 203 while (true) { v_2 = cursor; do { // (, line 203 // [, line 203 bra = cursor; // literal, line 203 if (!(eq_s(1, "Y"))) { break; } // ], line 203 ket = cursor; cursor = v_2; subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = v_2; if (cursor >= limit) { subroot = true; break; } cursor++; } returnn = true; if (subroot) { subroot = false; break; } // <-, line 203 slice_from("y"); if (returnn) { goto replab0; } } while (false); cursor = v_1; break; } return true; } public bool CanStem() { bool returnn = true; bool subroot = false; int v_1; int v_2; int v_3; int v_4; int v_5; int v_6; int v_7; int v_8; int v_9; int v_10; int v_11; int v_12; int v_13; // (, line 205 // or, line 207 do { v_1 = cursor; do { // call exception1, line 207 if (!r_exception1()) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = v_1; do { // not, line 208 { v_2 = cursor; do { // hop, line 208 { int c = cursor + 3; if (0 > c || c > limit) { break; ; } cursor = c; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = v_2; } returnn = true; if (returnn) goto breaklab0; } while (false); cursor = v_1; // (, line 208 // do, line 209 v_3 = cursor; do { // call prelude, line 209 if (!r_prelude()) { break; } } while (false); cursor = v_3; // do, line 210 v_4 = cursor; do { // call mark_regions, line 210 if (!r_mark_regions()) { break; } } while (false); cursor = v_4; // backwards, line 211 limit_backward = cursor; cursor = limit; // (, line 211 // do, line 213 v_5 = limit - cursor; do { // call Step_1a, line 213 if (!r_Step_1a()) { break; } } while (false); cursor = limit - v_5; // or, line 215 do { v_6 = limit - cursor; do { // call exception2, line 215 if (!r_exception2()) { break; } subroot = true; if (subroot) break; } while (false); if (subroot) { subroot = false; break; } cursor = limit - v_6; // (, line 215 // do, line 217 v_7 = limit - cursor; do { // call Step_1b, line 217 if (!r_Step_1b()) { break; } } while (false); cursor = limit - v_7; // do, line 218 v_8 = limit - cursor; do { // call Step_1c, line 218 if (!r_Step_1c()) { break; } } while (false); cursor = limit - v_8; // do, line 220 v_9 = limit - cursor; do { // call Step_2, line 220 if (!r_Step_2()) { break; } } while (false); cursor = limit - v_9; // do, line 221 v_10 = limit - cursor; do { // call Step_3, line 221 if (!r_Step_3()) { break; } } while (false); cursor = limit - v_10; // do, line 222 v_11 = limit - cursor; do { // call Step_4, line 222 if (!r_Step_4()) { break; } } while (false); cursor = limit - v_11; // do, line 224 v_12 = limit - cursor; do { // call Step_5, line 224 if (!r_Step_5()) { break; } } while (false); cursor = limit - v_12; } while (false); cursor = limit_backward; // do, line 227 v_13 = cursor; do { // call postlude, line 227 if (!r_postlude()) { break; } } while (false); cursor = v_13; } while (false); breaklab0: return true; } public string Stem(string s) { this.setCurrent(s.ToLowerInvariant()); this.CanStem(); return this.getCurrent(); } } }
using UnityEngine; using System.Collections; using System; [Serializable] public class UFTAtlasEntry:ScriptableObject{ [SerializeField] public Texture2D texture; [SerializeField] public Rect canvasRect; [SerializeField] public string assetPath; [SerializeField] public string textureName; [SerializeField] public bool isTrimmed=false; public static int _idCounter; [SerializeField] public int? _id; public int? id { get { if (this._id==null){ _idCounter++; this._id=_idCounter; } return this._id; } } public Rect uvRect { get { float x = (float)canvasRect.x / (float) uftAtlas.atlasWidth; float width = (float)canvasRect.width / (float) uftAtlas.atlasWidth; float height= (float)canvasRect.height / (float) uftAtlas.atlasHeight; float y = 1-height - (float)canvasRect.y / (float) uftAtlas.atlasHeight; return new Rect(x,y,width,height); } } private UFTAtlas _uftAtlas; public UFTAtlas uftAtlas{ set{ this._uftAtlas=value; checkSize((int)uftAtlas.atlasWidth,(int)uftAtlas.atlasHeight); } get{ return this._uftAtlas; } } private bool isDragging=false; private Vector2 mouseStartPosition; public UFTTextureState textureState=UFTTextureState.passive; public long blinkTimeout=5000000; //interval in ticks There are 10,000 ticks in a millisecond public Color blinkColor1=Color.red; public Color blinkColor2=Color.yellow; private Color currentBlinkColor; private long? controlBlinkTime=null; public bool isSizeInvalid=false; private bool stopDragging = false; public void OnEnable(){ hideFlags = HideFlags.HideAndDontSave; UFTAtlasEditorEventManager.onAtlasSizeChanged+=onAtlasSizeChanged; } //i'm not sure about it, but i think we need to destroy texture on close if texture is clipped, because it doesn't store in assets public void OnDestroy() { if (isTrimmed){ DestroyImmediate(texture,true); } } public void OnGUI(){ if (Event.current.type == EventType.MouseUp || (isDragging && stopDragging)){ textureState=UFTTextureState.passive; if (isDragging){ isDragging = false; if (UFTAtlasEditorEventManager.onStopDragging!=null) UFTAtlasEditorEventManager.onStopDragging(this); if (UFTAtlasEditorEventManager.onAtlasChange!=null) UFTAtlasEditorEventManager.onAtlasChange(); } } else if (Event.current.type == EventType.MouseDown && canvasRect.Contains (Event.current.mousePosition)){ textureState=UFTTextureState.onDrag; isDragging = true; textureState=UFTTextureState.onDrag; mouseStartPosition=Event.current.mousePosition; if (UFTAtlasEditorEventManager.onStartDragging!=null) UFTAtlasEditorEventManager.onStartDragging(this); Event.current.Use(); stopDragging=false; } Color color=GUI.color; if (isDragging){ Vector2 currentOffset=Event.current.mousePosition-mouseStartPosition; if (Event.current.type == EventType.Repaint){ canvasRect.x+=currentOffset.x; canvasRect.y+=currentOffset.y; if (canvasRect.x < 0){ canvasRect.x=0; } if (canvasRect.y <0){ canvasRect.y=0; } if (canvasRect.xMax > (int)uftAtlas.atlasWidth){ canvasRect.x= (int)uftAtlas.atlasWidth-texture.width; } if (canvasRect.yMax > (int)uftAtlas.atlasHeight){ canvasRect.y= (int)uftAtlas.atlasHeight-texture.height; } mouseStartPosition=Event.current.mousePosition; } if (UFTAtlasEditorEventManager.onDragInProgress!=null) UFTAtlasEditorEventManager.onDragInProgress(); //if dragging lets color it to drag color border GUI.color=UFTTextureUtil.borderColorDict[UFTTextureState.onDrag]; // check is mouse under texture, if not, initialize dropping if (Event.current.type==EventType.Repaint && !canvasRect.Contains (Event.current.mousePosition)) stopDragging=true; } if (isSizeInvalid){ long currentTime=System.DateTime.Now.Ticks; if (controlBlinkTime==null){ controlBlinkTime=currentTime+blinkTimeout; currentBlinkColor=blinkColor1; } if (controlBlinkTime <= currentTime){ controlBlinkTime=currentTime+blinkTimeout; currentBlinkColor=(currentBlinkColor==blinkColor1)?blinkColor2:blinkColor1; } GUI.color=currentBlinkColor; if (UFTAtlasEditorEventManager.onNeedToRepaint!=null) UFTAtlasEditorEventManager.onNeedToRepaint(); } GUI.DrawTexture(canvasRect,texture,ScaleMode.ScaleToFit,true); //EditorGUI.DrawPreviewTexture(canvasRect,texture); if (isDragging || isSizeInvalid) GUI.color=color; } // this is event handler, it's called whenever atlas size is changed private void onAtlasSizeChanged(int width, int height){ checkSize (width, height); } //this function change status to size invalid if texture size is greater than width, or heigh public void checkSize (int width, int height) { if (texture==null) return; if (texture.width>width || texture.height>height){ isSizeInvalid=true; }else{ isSizeInvalid=false; } controlBlinkTime=null; } //return true if texture has been trimmed, or false if not public bool trimTexture () { Texture2D newTexture=UFTTextureUtil.trimTextureAlpha (texture); if (newTexture!=texture){ canvasRect.width=newTexture.width; canvasRect.height=newTexture.height; isTrimmed=true; texture=newTexture; if (UFTAtlasEditorEventManager.onTextureSizeChanged!=null) UFTAtlasEditorEventManager.onTextureSizeChanged(this); return true; } return false; } public void readPropertiesFromMetadata(UFTAtlasEntryMetadata metadata){ Texture2D texture= UFTTextureUtil.importTexture(metadata.assetPath); if (texture==null){ throw new TextureDoesNotExistsException(metadata.assetPath); } else { this.texture=texture; this.canvasRect=metadata.pixelRect; this.textureName=metadata.name; this.isTrimmed=metadata.isTrimmed; if (this.isTrimmed){ trimTexture(); } } } public UFTAtlasEntryMetadata getMetadata(){ return new UFTAtlasEntryMetadata(textureName,assetPath,canvasRect,uvRect,isTrimmed); } }
#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. Note: This code has been heavily modified for the Duality framework. */ #endregion using System; using System.Runtime.InteropServices; namespace Duality { /// <summary> /// Represents a 2D vector using two single-precision floating-point numbers. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Vector2 : IEquatable<Vector2> { /// <summary> /// Defines a unit-length Vector2 that points towards the X-axis. /// </summary> public static readonly Vector2 UnitX = new Vector2(1, 0); /// <summary> /// Defines a unit-length Vector2 that points towards the Y-axis. /// </summary> public static readonly Vector2 UnitY = new Vector2(0, 1); /// <summary> /// Defines a zero-length Vector2. /// </summary> public static readonly Vector2 Zero = new Vector2(0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector2 One = new Vector2(1, 1); /// <summary> /// The X component of the Vector2. /// </summary> public float X; /// <summary> /// The Y component of the Vector2. /// </summary> public float Y; /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2(float value) { X = value; Y = value; } /// <summary> /// Constructs a new Vector2. /// </summary> /// <param name="x">The x coordinate of the net Vector2.</param> /// <param name="y">The y coordinate of the net Vector2.</param> public Vector2(float x, float y) { X = x; Y = y; } /// <summary> /// Constructs a new vector from angle and length. /// </summary> /// <param name="angle"></param> /// <param name="length"></param> /// <returns></returns> public static Vector2 FromAngleLength(float angle, float length) { return new Vector2((float)Math.Sin(angle) * length, (float)Math.Cos(angle) * -length); } /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt(X * X + Y * Y); } } /// <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 float LengthSquared { get { return X * X + Y * Y; } } /// <summary> /// Returns the vectors angle /// </summary> public float Angle { get { return (float)((Math.Atan2(Y, X) + Math.PI * 2.5) % (Math.PI * 2)); } } /// <summary> /// Gets the perpendicular vector on the right side of this vector. /// </summary> public Vector2 PerpendicularRight { get { return new Vector2(-Y, X); } } /// <summary> /// Gets the perpendicular vector on the left side of this vector. /// </summary> public Vector2 PerpendicularLeft { get { return new Vector2(Y, -X); } } /// <summary> /// Returns a normalized version of this vector. /// </summary> public Vector2 Normalized { get { Vector2 n = this; n.Normalize(); return n; } } /// <summary> /// Gets or sets the value at the index of the Vector. /// </summary> public float this[int index] { get { if (index == 0) return X; else if (index == 1) return Y; throw new IndexOutOfRangeException("You tried to access this vector at index: " + index); } set { if (index == 0) X = value; else if (index == 1) Y = value; else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index); } } /// <summary> /// Scales the Vector2 to unit length. /// </summary> public void Normalize() { float scale = 1.0f / this.Length; X *= scale; Y *= scale; } /// <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 Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X + b.X, a.Y + b.Y); } /// <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 Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X - b.X, a.Y - b.Y); } /// <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 Vector2 vector, float scale, out Vector2 result) { result = new Vector2(vector.X * scale, vector.Y * scale); } /// <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 Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X * scale.X, vector.Y * scale.Y); } /// <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 Vector2 vector, float scale, out Vector2 result) { Multiply(ref vector, 1 / scale, out result); } /// <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 Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X / scale.X, vector.Y / scale.Y); } /// <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 Vector2 Min(Vector2 a, Vector2 b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; 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 Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; } /// <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 Vector2 Max(Vector2 a, Vector2 b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; 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 Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; } /// <summary> /// Calculate the dot (scalar) 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 float Dot(Vector2 left, Vector2 right) { return left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculate the dot (scalar) 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 Vector2 left, ref Vector2 right, out float result) { result = left.X * right.X + left.Y * right.Y; } /// <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 Vector2 Lerp(Vector2 a, Vector2 b, float blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; 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 Vector2 a, ref Vector2 b, float blend, out Vector2 result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <returns>Angle (in radians) between the vectors.</returns> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static float AngleBetween(Vector2 first, Vector2 second) { return (float)System.Math.Acos((Vector2.Dot(first, second)) / (first.Length * second.Length)); } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <param name="result">Angle (in radians) between the vectors.</param> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static void AngleBetween(ref Vector2 first, ref Vector2 second, out float result) { float temp; Vector2.Dot(ref first, ref second, out temp); result = (float)System.Math.Acos(temp / (first.Length * second.Length)); } /// <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 Vector2 Transform(Vector2 vec, Quaternion quat) { Vector2 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 Vector2 vec, ref Quaternion quat, out Vector2 result) { Quaternion v = new Quaternion(vec.X, vec.Y, 0, 0), i, t; Quaternion.Invert(ref quat, out i); Quaternion.Multiply(ref quat, ref v, out t); Quaternion.Multiply(ref t, ref i, out v); result = new Vector2(v.X, v.Y); } /// <summary> /// Transforms the vector /// </summary> /// <param name="vec"></param> /// <param name="mat"></param> /// <returns></returns> public static Vector2 Transform(Vector2 vec, Matrix4 mat) { Vector2 result; Transform(ref vec, ref mat, out result); return result; } /// <summary> /// Transforms the vector /// </summary> /// <param name="vec"></param> /// <param name="mat"></param> /// <param name="result"></param> /// <returns></returns> public static void Transform(ref Vector2 vec, ref Matrix4 mat, out Vector2 result) { Vector4 row0 = mat.Row0; Vector4 row1 = mat.Row1; Vector4 row3 = mat.Row3; result.X = vec.X * row0.X + vec.Y * row1.X + row3.X; result.Y = vec.X * row0.Y + vec.Y * row1.Y + row3.Y; } /// <summary> /// Adds the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of addition.</returns> public static Vector2 operator +(Vector2 left, Vector2 right) { left.X += right.X; left.Y += right.Y; return left; } /// <summary> /// Subtracts the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of subtraction.</returns> public static Vector2 operator -(Vector2 left, Vector2 right) { left.X -= right.X; left.Y -= right.Y; return left; } /// <summary> /// Negates the specified instance. /// </summary> /// <param name="vec">Operand.</param> /// <returns>Result of negation.</returns> public static Vector2 operator -(Vector2 vec) { vec.X = -vec.X; vec.Y = -vec.Y; return vec; } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(Vector2 vec, float scale) { vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="scale">Left operand.</param> /// <param name="vec">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(float scale, Vector2 vec) { vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scales the specified instance by a vector. /// </summary> /// <param name="vec">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(Vector2 vec, Vector2 scale) { vec.X *= scale.X; vec.Y *= scale.Y; return vec; } /// <summary> /// Divides the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand</param> /// <param name="scale">Right operand</param> /// <returns>Result of the division.</returns> public static Vector2 operator /(Vector2 vec, float scale) { float mult = 1.0f / scale; vec.X *= mult; vec.Y *= mult; return vec; } /// <summary> /// Divides the specified instance by a vector. /// </summary> /// <param name="vec">Left operand</param> /// <param name="scale">Right operand</param> /// <returns>Result of the division.</returns> public static Vector2 operator /(Vector2 vec, Vector2 scale) { vec.X /= scale.X; vec.Y /= scale.Y; return vec; } /// <summary> /// Compares the specified instances for equality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are equal; false otherwise.</returns> public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } /// <summary> /// Compares the specified instances for inequality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are not equal; false otherwise.</returns> public static bool operator !=(Vector2 left, Vector2 right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Vector2. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0:F}, {1:F})", X, Y); } /// <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(); } /// <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 Vector2)) return false; return this.Equals((Vector2)obj); } /// <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(Vector2 other) { return X == other.X && Y == other.Y; } } }
using SolidEdgeSpy.Extensions; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Linq; using System.Text; namespace SolidEdgeSpy.InteropServices { public class ComTypeInfo { protected ComTypeLibrary _comTypeLibrary; protected ITypeInfo _typeInfo; protected IntPtr _pTypeAttr; protected System.Runtime.InteropServices.ComTypes.TYPEATTR _typeAttr; protected string _name = String.Empty; protected string _description = String.Empty; protected int _helpContext = 0; protected string _helpFile = String.Empty; protected List<ComMemberInfo> _members = null; protected List<ComImplementedTypeInfo> _implementedTypes = null; public ComTypeInfo(ComTypeLibrary comTypeLibrary, ITypeInfo typeInfo, IntPtr pTypeAttr) { _comTypeLibrary = comTypeLibrary; _typeInfo = typeInfo; _pTypeAttr = pTypeAttr; _typeAttr = _pTypeAttr.ToStructure<System.Runtime.InteropServices.ComTypes.TYPEATTR>(); _typeInfo.GetDocumentation(-1, out _name, out _description, out _helpContext, out _helpFile); } public ComImplementedTypeInfo[] ImplementedTypes { get { if (_implementedTypes == null) { _implementedTypes = new List<ComImplementedTypeInfo>(); for (int i = 0; i< _typeAttr.cImplTypes; i++) { System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS flags = default(System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS); _typeInfo.GetImplTypeFlags(i, out flags); ITypeInfo refTypeInfo = null; int href = 0; _typeInfo.GetRefTypeOfImplType(i, out href); _typeInfo.GetRefTypeInfo(href, out refTypeInfo); ComTypeInfo comTypeInfo = ComTypeManager.Instance.FromITypeInfo(refTypeInfo); _implementedTypes.Add(new ComImplementedTypeInfo(comTypeInfo, flags)); } } return _implementedTypes.ToArray(); } } public ComMemberInfo[] Members { get { if (_members == null) LoadMembers(); return _members.ToArray(); } } public ComFunctionInfo[] Methods { get { return Members.OfType<ComFunctionInfo>().Where(function => function.InvokeKind == System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_FUNC).ToArray(); } } public ComPropertyInfo[] Properties { get { List<ComPropertyInfo> list = new List<ComPropertyInfo>(); Dictionary<string, List<ComFunctionInfo>> dictionary = new Dictionary<string, List<ComFunctionInfo>>(); ComFunctionInfo[] functions = Members.OfType<ComFunctionInfo>().Where( x => x.InvokeKind != System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_FUNC).ToArray(); foreach (ComFunctionInfo function in functions) { if (!dictionary.ContainsKey(function.Name)) { dictionary.Add(function.Name, new List<ComFunctionInfo>()); } dictionary[function.Name].Add(function); } var enumerator = dictionary.GetEnumerator(); while (enumerator.MoveNext()) { list.Add(new ComPropertyInfo(this, enumerator.Current.Value.ToArray())); } return list.ToArray(); } } public ComVariableInfo[] Variables { get { return Members.OfType<ComVariableInfo>().ToArray(); } } public ComFunctionInfo[] GetMethods(bool includeInherited) { List<ComFunctionInfo> list = new List<ComFunctionInfo>(); list.AddRange(Methods); if (includeInherited) { list.AddRange(GetInheritedMethods(this)); } list.Sort(delegate(ComFunctionInfo a, ComFunctionInfo b) { return a.Name.CompareTo(b.Name); }); return list.GroupBy(x => x.Name).Select(s => s.First()).ToArray(); } public ComPropertyInfo[] GetProperties(bool includeInherited) { List<ComPropertyInfo> list = new List<ComPropertyInfo>(); list.AddRange(Properties); if (includeInherited) { list.AddRange(GetInheriteProperties(this)); } list.Sort(delegate(ComPropertyInfo a, ComPropertyInfo b) { return a.Name.CompareTo(b.Name); }); return list.GroupBy(x => x.Name).Select(s => s.First()).ToArray(); } private ComFunctionInfo[] GetInheritedMethods(ComTypeInfo comTypeInfo) { List<ComFunctionInfo> list = new List<ComFunctionInfo>(); for (int i = 0; i < comTypeInfo.ImplementedTypes.Length; i++) { ComImplementedTypeInfo comImplementedTypeInfo = comTypeInfo.ImplementedTypes[i]; if (comImplementedTypeInfo.IsSource == false) { foreach (ComFunctionInfo comFunctionInfo in comImplementedTypeInfo.ComTypeInfo.Methods) { if (list.FirstOrDefault(x => x.Name.Equals(comFunctionInfo.Name)) == null) { list.Add(comFunctionInfo); } } list.AddRange(GetInheritedMethods(comImplementedTypeInfo.ComTypeInfo)); } } list.Sort(delegate(ComFunctionInfo a, ComFunctionInfo b) { return a.Name.CompareTo(b.Name); }); return list.ToArray(); } private ComPropertyInfo[] GetInheriteProperties(ComTypeInfo comTypeInfo) { List<ComPropertyInfo> list = new List<ComPropertyInfo>(); for (int i = 0; i < comTypeInfo.ImplementedTypes.Length; i++) { ComImplementedTypeInfo comImplementedTypeInfo = comTypeInfo.ImplementedTypes[i]; if (comImplementedTypeInfo.IsSource == false) { foreach (ComPropertyInfo comPropertyInfo in comImplementedTypeInfo.ComTypeInfo.Properties) { if (list.FirstOrDefault(x => x.Name.Equals(comPropertyInfo.Name)) == null) { list.Add(comPropertyInfo); } } list.AddRange(GetInheriteProperties(comImplementedTypeInfo.ComTypeInfo)); } } list.Sort(delegate(ComPropertyInfo a, ComPropertyInfo b) { return a.Name.CompareTo(b.Name); }); return list.ToArray(); } public bool IsAlias { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_ALIAS; } } public bool IsCoClass { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_COCLASS; } } public bool IsDispatch { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_DISPATCH; } } public bool IsEnum { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_ENUM; } } public bool IsInterface { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_INTERFACE; } } public bool IsMax { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_MAX; } } public bool IsModule { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_MODULE; } } public bool IsRecord { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_RECORD; } } public bool IsUnion { get { return _typeAttr.typekind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_UNION; } } public bool IsAppObject { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FAPPOBJECT); } } public bool IsCanCreate { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FCANCREATE); } } public bool IsLicensed { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FLICENSED); } } public bool IsPredeclid { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FPREDECLID); } } public bool IsHidden { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FHIDDEN); } } public bool IsControl { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FCONTROL); } } public bool IsDual { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FDUAL); } } public bool IsNonExtensible { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FNONEXTENSIBLE); } } public bool IsOleAutomation { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FOLEAUTOMATION); } } public bool IsRestricted { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FRESTRICTED); } } public bool IsAggregatable { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FAGGREGATABLE); } } public bool IsReplaceable { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FREPLACEABLE); } } public bool IsDispatchable { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FDISPATCHABLE); } } public bool IsReverseBind { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FREVERSEBIND); } } public bool IsProxy { get { return _typeAttr.wTypeFlags.IsSet(System.Runtime.InteropServices.ComTypes.TYPEFLAGS.TYPEFLAG_FPROXY); } } private void LoadMembers() { _members = new List<ComMemberInfo>(); for (short i = 0; i < _typeAttr.cFuncs; i++) { IntPtr pFuncDesc = IntPtr.Zero; _typeInfo.GetFuncDesc(i, out pFuncDesc); ComFunctionInfo comFunctionInfo = new ComFunctionInfo(this, pFuncDesc); _members.Add(comFunctionInfo); } /* Note that these are not always enum constants. Some properties show up as VARDESC's. */ for (short i = 0; i < _typeAttr.cVars; i++) { System.Runtime.InteropServices.ComTypes.VARDESC varDesc; IntPtr p = IntPtr.Zero; _typeInfo.GetVarDesc(i, out p); object constantValue = null; try { varDesc = p.ToStructure<System.Runtime.InteropServices.ComTypes.VARDESC>(); if (varDesc.varkind == VARKIND.VAR_CONST) { constantValue = Marshal.GetObjectForNativeVariant(varDesc.desc.lpvarValue); } } finally { _typeInfo.ReleaseVarDesc(p); } ComVariableInfo comVariableInfo = new ComVariableInfo(this, varDesc, constantValue); _members.Add(comVariableInfo); } _members.Sort(delegate(ComMemberInfo a, ComMemberInfo b) { return a.Name.CompareTo(b.Name); }); } //private void LoadFunctions() //{ // _functions = new List<ComFunctionInfo>(); // for (short i = 0; i < _typeAttr.cFuncs; i++) // { // System.Runtime.InteropServices.ComTypes.FUNCDESC funcDesc = _typeInfo.GetFuncDesc(i); // ComFunctionInfo comMethodInfo = new ComFunctionInfo(this, funcDesc); // _functions.Add(comMethodInfo); // } // _functions.Sort(delegate(ComFunctionInfo a, ComFunctionInfo b) // { // return a.Name.CompareTo(b.Name); // }); //} //private void LoadVariables() //{ // _variables = new List<ComVariableInfo>(); // /* Note that these are not always enum constants. Some properties show up as VARDESC's. */ // for (short i = 0; i < _typeAttr.cVars; i++) // { // System.Runtime.InteropServices.ComTypes.VARDESC varDesc; // IntPtr p = IntPtr.Zero; // _typeInfo.GetVarDesc(i, out p); // object constantValue = null; // try // { // varDesc = p.ToVARDESC(); // if (varDesc.varkind == VARKIND.VAR_CONST) // { // constantValue = Marshal.GetObjectForNativeVariant(varDesc.desc.lpvarValue); // } // } // finally // { // _typeInfo.ReleaseTypeAttr(p); // } // ComVariableInfo comVariableInfo = new ComVariableInfo(this, varDesc, constantValue); // _variables.Add(comVariableInfo); // } // _variables.Sort(delegate(ComVariableInfo a, ComVariableInfo b) // { // return a.Name.CompareTo(b.Name); // }); //} public ComTypeLibrary ComTypeLibrary { get { return _comTypeLibrary; } } public string Name { get { return _name; } } public string FullName { get { return String.Format("{0}.{1}", _comTypeLibrary.Name, _name); } } public string Description { get { return _description; } } public ITypeInfo GetITypeInfo() { return _typeInfo; } public Guid Guid { get { return _typeAttr.guid; } } public Version Version { get { return new Version(_typeAttr.wMajorVerNum, _typeAttr.wMinorVerNum); } } public bool IsCollection { get { var newEnum = Members.OfType<ComFunctionInfo>().Where(x => x.DispId == NativeMethods.DISPID_NEWENUM).FirstOrDefault(); return newEnum == null ? false : true; } } public override string ToString() { return FullName; } } public class ComAliasInfo : ComTypeInfo { public ComAliasInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } public class ComCoClassInfo : ComTypeInfo { List<ComFunctionInfo> _events = null; public ComCoClassInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } public ComFunctionInfo[] Events { get { if (_events == null) { _events = new List<ComFunctionInfo>(); for (int i = 0; i < ImplementedTypes.Length; i++) { ComImplementedTypeInfo comImplementedTypeInfo = ImplementedTypes[i]; if (comImplementedTypeInfo.IsSource) { foreach (ComFunctionInfo comFunctionInfo in comImplementedTypeInfo.ComTypeInfo.Methods) { if (comFunctionInfo.IsRestricted == false) { if (_events.FirstOrDefault(x => x.Name.Equals(comFunctionInfo.Name)) == null) { _events.Add(comFunctionInfo); } } } } } _events.Sort(delegate(ComFunctionInfo a, ComFunctionInfo b) { return a.Name.CompareTo(b.Name); }); } return _events.ToArray(); } } } public class ComDispatchInfo : ComTypeInfo { public ComDispatchInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } public class ComEnumInfo : ComTypeInfo { public ComEnumInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } public class ComInterfaceInfo : ComTypeInfo { public ComInterfaceInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } public class ComMaxInfo : ComTypeInfo { public ComMaxInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } public class ComModuleInfo : ComTypeInfo { public ComModuleInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } public class ComRecordInfo : ComTypeInfo { public ComRecordInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } public class ComUnionInfo : ComTypeInfo { public ComUnionInfo(ComTypeLibrary parent, ITypeInfo typeInfo, IntPtr pTypeAttr) : base(parent, typeInfo, pTypeAttr) { } } }
using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor.Experimental.Rendering.LowendMobile { public static class SupportedUpgradeParams { static public UpgradeParams diffuseOpaque = new UpgradeParams() { blendMode = UpgradeBlendMode.Opaque, specularSource = SpecularSource.NoSpecular, glosinessSource = GlossinessSource.BaseAlpha, reflectionSource = ReflectionSource.NoReflection }; static public UpgradeParams specularOpaque = new UpgradeParams() { blendMode = UpgradeBlendMode.Opaque, specularSource = SpecularSource.SpecularTextureAndColor, glosinessSource = GlossinessSource.BaseAlpha, reflectionSource = ReflectionSource.NoReflection }; static public UpgradeParams diffuseAlpha = new UpgradeParams() { blendMode = UpgradeBlendMode.Alpha, specularSource = SpecularSource.NoSpecular, glosinessSource = GlossinessSource.SpecularAlpha, reflectionSource = ReflectionSource.NoReflection }; static public UpgradeParams specularAlpha = new UpgradeParams() { blendMode = UpgradeBlendMode.Alpha, specularSource = SpecularSource.SpecularTextureAndColor, glosinessSource = GlossinessSource.SpecularAlpha, reflectionSource = ReflectionSource.NoReflection }; static public UpgradeParams diffuseAlphaCutout = new UpgradeParams() { blendMode = UpgradeBlendMode.Cutout, specularSource = SpecularSource.NoSpecular, glosinessSource = GlossinessSource.SpecularAlpha, reflectionSource = ReflectionSource.NoReflection }; static public UpgradeParams specularAlphaCutout = new UpgradeParams() { blendMode = UpgradeBlendMode.Cutout, specularSource = SpecularSource.SpecularTextureAndColor, glosinessSource = GlossinessSource.SpecularAlpha, reflectionSource = ReflectionSource.NoReflection }; static public UpgradeParams diffuseCubemap = new UpgradeParams() { blendMode = UpgradeBlendMode.Opaque, specularSource = SpecularSource.NoSpecular, glosinessSource = GlossinessSource.BaseAlpha, reflectionSource = ReflectionSource.Cubemap }; static public UpgradeParams specularCubemap = new UpgradeParams() { blendMode = UpgradeBlendMode.Opaque, specularSource = SpecularSource.SpecularTextureAndColor, glosinessSource = GlossinessSource.BaseAlpha, reflectionSource = ReflectionSource.Cubemap }; static public UpgradeParams diffuseCubemapAlpha = new UpgradeParams() { blendMode = UpgradeBlendMode.Alpha, specularSource = SpecularSource.NoSpecular, glosinessSource = GlossinessSource.BaseAlpha, reflectionSource = ReflectionSource.Cubemap }; static public UpgradeParams specularCubemapAlpha = new UpgradeParams() { blendMode = UpgradeBlendMode.Alpha, specularSource = SpecularSource.SpecularTextureAndColor, glosinessSource = GlossinessSource.BaseAlpha, reflectionSource = ReflectionSource.Cubemap }; } public class LegacyBlinnPhongUpgrader : MaterialUpgrader { public LegacyBlinnPhongUpgrader(string oldShaderName, UpgradeParams upgradeParams) { RenameShader(oldShaderName, "ScriptableRenderPipeline/LowEndMobile/NonPBR", UpdateMaterialKeywords); SetFloat("_Mode", (float)upgradeParams.blendMode); SetFloat("_SpecSource", (float)upgradeParams.specularSource); SetFloat("_GlossinessSource", (float)upgradeParams.glosinessSource); SetFloat("_ReflectionSource", (float)upgradeParams.reflectionSource); if (oldShaderName.Contains("Legacy Shaders/Self-Illumin")) { RenameTexture("_MainTex", "_EmissionMap"); RemoveTexture("_MainTex"); SetColor("_EmissionColor", Color.white); } } public static void UpdateMaterialKeywords(Material material) { UpdateMaterialBlendMode(material); UpdateMaterialSpecularSource(material); UpdateMaterialReflectionSource(material); SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap")); SetKeyword(material, "_CUBEMAP_REFLECTION", material.GetTexture("_Cube")); SetKeyword(material, "_EMISSION_MAP", material.GetTexture("_EmissionMap")); } private static void UpdateMaterialBlendMode(Material material) { UpgradeBlendMode mode = (UpgradeBlendMode)material.GetFloat("_Mode"); switch (mode) { case UpgradeBlendMode.Opaque: material.SetOverrideTag("RenderType", ""); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); SetKeyword(material, "_ALPHATEST_ON", false); SetKeyword(material, "_ALPHABLEND_ON", false); material.renderQueue = -1; break; case UpgradeBlendMode.Cutout: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); SetKeyword(material, "_ALPHATEST_ON", true); SetKeyword(material, "_ALPHABLEND_ON", false); material.renderQueue = (int)RenderQueue.AlphaTest; break; case UpgradeBlendMode.Alpha: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); SetKeyword(material, "_ALPHATEST_ON", false); SetKeyword(material, "_ALPHABLEND_ON", true); material.renderQueue = (int)RenderQueue.Transparent; break; } } private static void UpdateMaterialSpecularSource(Material material) { SpecularSource specSource = (SpecularSource)material.GetFloat("_SpecSource"); if (specSource == SpecularSource.NoSpecular) { SetKeyword(material, "_SPECGLOSSMAP", false); SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false); SetKeyword(material, "_SPECULAR_COLOR", false); } else if (specSource == SpecularSource.SpecularTextureAndColor && material.GetTexture("_SpecGlossMap")) { GlossinessSource glossSource = (GlossinessSource)material.GetFloat("_GlossinessSource"); if (glossSource == GlossinessSource.BaseAlpha) { SetKeyword(material, "_SPECGLOSSMAP", false); SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", true); } else { SetKeyword(material, "_SPECGLOSSMAP", true); SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false); } SetKeyword(material, "_SPECULAR_COLOR", false); } else { SetKeyword(material, "_SPECGLOSSMAP", false); SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false); SetKeyword(material, "_SPECULAR_COLOR", true); } } private static void UpdateMaterialReflectionSource(Material material) { ReflectionSource reflectionSource = (ReflectionSource)material.GetFloat("_ReflectionSource"); if (reflectionSource == ReflectionSource.NoReflection) { SetKeyword(material, "_CUBEMAP_REFLECTION", false); } else if (reflectionSource == ReflectionSource.Cubemap && material.GetTexture("_Cube")) { SetKeyword(material, "_CUBEMAP_REFLECTION", true); } else if (reflectionSource == ReflectionSource.ReflectionProbe) { Debug.LogWarning("Reflection probe not implemented yet"); SetKeyword(material, "_CUBEMAP_REFLECTION", false); } else { SetKeyword(material, "_CUBEMAP_REFLECTION", false); } } private static void SetKeyword(Material material, string keyword, bool enable) { if (enable) material.EnableKeyword(keyword); else material.DisableKeyword(keyword); } } public class ParticlesMultiplyUpgrader : MaterialUpgrader { public ParticlesMultiplyUpgrader(string oldShaderName) { RenameShader(oldShaderName, "ScriptableRenderPipeline/LowEndMobile/Particles/Multiply"); } } public class ParticlesAdditiveUpgrader : MaterialUpgrader { public ParticlesAdditiveUpgrader(string oldShaderName) { RenameShader(oldShaderName, "ScriptableRenderPipeline/LowEndMobile/Particles/Additive"); } } public class StandardUpgrader : MaterialUpgrader { public StandardUpgrader(string oldShaderName) { RenameShader(oldShaderName, "ScriptableRenderPipeline/LowEndMobile/NonPBR"); } } public class TerrainUpgrader : MaterialUpgrader { public TerrainUpgrader(string oldShaderName) { RenameShader(oldShaderName, "ScriptableRenderPipeline/LowEndMobile/NonPBR"); SetFloat("_Shininess", 1.0f); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// RecordingResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Video.V1 { public class RecordingResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Processing = new StatusEnum("processing"); public static readonly StatusEnum Completed = new StatusEnum("completed"); public static readonly StatusEnum Deleted = new StatusEnum("deleted"); public static readonly StatusEnum Failed = new StatusEnum("failed"); } public sealed class TypeEnum : StringEnum { private TypeEnum(string value) : base(value) {} public TypeEnum() {} public static implicit operator TypeEnum(string value) { return new TypeEnum(value); } public static readonly TypeEnum Audio = new TypeEnum("audio"); public static readonly TypeEnum Video = new TypeEnum("video"); public static readonly TypeEnum Data = new TypeEnum("data"); } public sealed class FormatEnum : StringEnum { private FormatEnum(string value) : base(value) {} public FormatEnum() {} public static implicit operator FormatEnum(string value) { return new FormatEnum(value); } public static readonly FormatEnum Mka = new FormatEnum("mka"); public static readonly FormatEnum Mkv = new FormatEnum("mkv"); } public sealed class CodecEnum : StringEnum { private CodecEnum(string value) : base(value) {} public CodecEnum() {} public static implicit operator CodecEnum(string value) { return new CodecEnum(value); } public static readonly CodecEnum Vp8 = new CodecEnum("VP8"); public static readonly CodecEnum H264 = new CodecEnum("H264"); public static readonly CodecEnum Opus = new CodecEnum("OPUS"); public static readonly CodecEnum Pcmu = new CodecEnum("PCMU"); } private static Request BuildFetchRequest(FetchRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Video, "/v1/Recordings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Returns a single Recording resource identified by a Recording SID. /// </summary> /// <param name="options"> Fetch Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Fetch(FetchRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Returns a single Recording resource identified by a Recording SID. /// </summary> /// <param name="options"> Fetch Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> FetchAsync(FetchRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Returns a single Recording resource identified by a Recording SID. /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchRecordingOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Returns a single Recording resource identified by a Recording SID. /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchRecordingOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Video, "/v1/Recordings", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// List of all Track recordings. /// </summary> /// <param name="options"> Read Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static ResourceSet<RecordingResource> Read(ReadRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<RecordingResource>.FromJson("recordings", response.Content); return new ResourceSet<RecordingResource>(page, options, client); } #if !NET35 /// <summary> /// List of all Track recordings. /// </summary> /// <param name="options"> Read Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<ResourceSet<RecordingResource>> ReadAsync(ReadRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<RecordingResource>.FromJson("recordings", response.Content); return new ResourceSet<RecordingResource>(page, options, client); } #endif /// <summary> /// List of all Track recordings. /// </summary> /// <param name="status"> Read only the recordings that have this status </param> /// <param name="sourceSid"> Read only the recordings that have this source_sid </param> /// <param name="groupingSid"> Read only recordings that have this grouping_sid </param> /// <param name="dateCreatedAfter"> Read only recordings that started on or after this [ISO /// 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone </param> /// <param name="dateCreatedBefore"> Read only recordings that started before this [ISO /// 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone </param> /// <param name="mediaType"> Read only recordings that have this media type </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static ResourceSet<RecordingResource> Read(RecordingResource.StatusEnum status = null, string sourceSid = null, List<string> groupingSid = null, DateTime? dateCreatedAfter = null, DateTime? dateCreatedBefore = null, RecordingResource.TypeEnum mediaType = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRecordingOptions(){Status = status, SourceSid = sourceSid, GroupingSid = groupingSid, DateCreatedAfter = dateCreatedAfter, DateCreatedBefore = dateCreatedBefore, MediaType = mediaType, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// List of all Track recordings. /// </summary> /// <param name="status"> Read only the recordings that have this status </param> /// <param name="sourceSid"> Read only the recordings that have this source_sid </param> /// <param name="groupingSid"> Read only recordings that have this grouping_sid </param> /// <param name="dateCreatedAfter"> Read only recordings that started on or after this [ISO /// 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone </param> /// <param name="dateCreatedBefore"> Read only recordings that started before this [ISO /// 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone </param> /// <param name="mediaType"> Read only recordings that have this media type </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<ResourceSet<RecordingResource>> ReadAsync(RecordingResource.StatusEnum status = null, string sourceSid = null, List<string> groupingSid = null, DateTime? dateCreatedAfter = null, DateTime? dateCreatedBefore = null, RecordingResource.TypeEnum mediaType = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRecordingOptions(){Status = status, SourceSid = sourceSid, GroupingSid = groupingSid, DateCreatedAfter = dateCreatedAfter, DateCreatedBefore = dateCreatedBefore, MediaType = mediaType, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<RecordingResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<RecordingResource> NextPage(Page<RecordingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Video) ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<RecordingResource> PreviousPage(Page<RecordingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Video) ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } private static Request BuildDeleteRequest(DeleteRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Video, "/v1/Recordings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a Recording resource identified by a Recording SID. /// </summary> /// <param name="options"> Delete Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static bool Delete(DeleteRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a Recording resource identified by a Recording SID. /// </summary> /// <param name="options"> Delete Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a Recording resource identified by a Recording SID. /// </summary> /// <param name="pathSid"> The SID that identifies the resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static bool Delete(string pathSid, ITwilioRestClient client = null) { var options = new DeleteRecordingOptions(pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a Recording resource identified by a Recording SID. /// </summary> /// <param name="pathSid"> The SID that identifies the resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null) { var options = new DeleteRecordingOptions(pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a RecordingResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> RecordingResource object represented by the provided JSON </returns> public static RecordingResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<RecordingResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The status of the recording /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.StatusEnum Status { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the recording source /// </summary> [JsonProperty("source_sid")] public string SourceSid { get; private set; } /// <summary> /// The size of the recorded track, in bytes /// </summary> [JsonProperty("size")] public long? Size { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The recording's media type /// </summary> [JsonProperty("type")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.TypeEnum Type { get; private set; } /// <summary> /// The duration of the recording in seconds /// </summary> [JsonProperty("duration")] public int? Duration { get; private set; } /// <summary> /// The file format for the recording /// </summary> [JsonProperty("container_format")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.FormatEnum ContainerFormat { get; private set; } /// <summary> /// The codec used to encode the track /// </summary> [JsonProperty("codec")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.CodecEnum Codec { get; private set; } /// <summary> /// A list of SIDs related to the recording /// </summary> [JsonProperty("grouping_sids")] public object GroupingSids { get; private set; } /// <summary> /// The name that was given to the source track of the recording /// </summary> [JsonProperty("track_name")] public string TrackName { get; private set; } /// <summary> /// The number of milliseconds between a point in time that is common to all rooms in a group and when the source room of the recording started /// </summary> [JsonProperty("offset")] public long? Offset { get; private set; } /// <summary> /// The URL of the media file associated with the recording when stored externally /// </summary> [JsonProperty("media_external_location")] public Uri MediaExternalLocation { get; private set; } /// <summary> /// The URLs of related resources /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private RecordingResource() { } } }
//----------------------------------------------------------------------- // <copyright file="LogRecordStreamReader.cs" company="Microsoft"> // Copyright 2013 Microsoft 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. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Analytics { using Microsoft.WindowsAzure.Storage.Core; using System; using System.IO; using System.Text; using System.Net; using System.Globalization; /// <summary> /// Reads log record information from a stream. /// </summary> internal class LogRecordStreamReader : IDisposable { /// <summary> /// A delimiter that exists between fields in a log. /// </summary> public const char FieldDelimiter = ';'; /// <summary> /// A delimiter that exists between logs. /// </summary> public const char RecordDelimiter = '\n'; /// <summary> /// The quote character. /// </summary> public const char QuoteChar = '\"'; private Encoding encoding; private StreamReader reader; private long position; private bool isFirstFieldInRecord; /// <summary> /// Initializes a new instance of the <see cref="LogRecordStreamReader"/> class using the specified stream and buffer size. /// </summary> /// <param name="stream">The <see cref="System.IO.Stream"/> object to read from.</param> /// <param name="bufferSize">An integer indicating the size of the buffer.</param> public LogRecordStreamReader(Stream stream, int bufferSize) { this.encoding = new UTF8Encoding(false /* encoderShouldEmitUTF8Identifier */); this.reader = new StreamReader(stream, this.encoding, false /* detectEncodingFromByteOrderMarks */, bufferSize); this.position = 0; this.isFirstFieldInRecord = true; } /// <summary> /// Indicates whether this is the end of the file. /// </summary> public bool IsEndOfFile { get { return this.reader.EndOfStream; } } /// <summary> /// Checks the position of the stream. /// </summary> /// <value>A long containing the current position of the stream.</value> public long Position { get { return this.position; } } /// <summary> /// Checks whether another field exists in the record. /// </summary> /// <returns>A boolean value indicating whether another field exists.</returns> public bool HasMoreFieldsInRecord() { return this.TryPeekDelimiter(LogRecordStreamReader.FieldDelimiter); } /// <summary> /// Reads a string from the stream. /// </summary> /// <returns>The string value read from the stream.</returns> public string ReadString() { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return temp; } } /// <summary> /// Reads a quoted string from the stream. /// </summary> /// <returns>The quote string value read from the stream.</returns> public string ReadQuotedString() { string temp = this.ReadField(true /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return temp; } } /// <summary> /// Ends the current record by reading the record delimiter and adjusting internal state. /// </summary> /// <remarks>The caller is expected to know when the record ends. </remarks> public void EndCurrentRecord() { this.ReadDelimiter(LogRecordStreamReader.RecordDelimiter); this.isFirstFieldInRecord = true; } /// <summary> /// Reads a bool from the stream. /// </summary> /// <returns>The boolean value read from the stream.</returns> public bool? ReadBool() { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return bool.Parse(temp); } } /// <summary> /// Reads a <see cref="System.DateTimeOffset"/> value in a specific format from the stream. /// </summary> /// <param name="format">A string representing the DateTime format to use when parsing.</param> /// <returns>The <see cref="System.DateTimeOffset"/> value read.</returns> public DateTimeOffset? ReadDateTimeOffset(string format) { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { DateTimeOffset tempDateTime; bool parsed = DateTimeOffset.TryParseExact( temp, format, null /* provider */, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out tempDateTime); if (parsed) { return tempDateTime; } else { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.LogStreamParseError, temp, format)); } } } /// <summary> /// Reads a <see cref="System.TimeSpan"/> value, represented as a number of milliseconds, from the stream. /// </summary> /// <returns>The <see cref="System.TimeSpan"/> value read from the stream.</returns> public TimeSpan? ReadTimeSpanInMS() { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return new TimeSpan(0, 0, 0, 0, int.Parse(temp, NumberStyles.None, CultureInfo.InvariantCulture)); } } /// <summary> /// Reads a double from the stream. /// </summary> /// <returns>The double value read from the stream.</returns> public double? ReadDouble() { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return double.Parse(temp, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); } } /// <summary>Reads a GUID value from the stream. </summary> /// <returns>The <see cref="System.Guid"/> value read from the stream.</returns> public Guid? ReadGuid() { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return Guid.ParseExact(temp, "D"); } } /// <summary>Reads an integer value from the stream. </summary> /// <returns>The integer value read from the stream.</returns> public int? ReadInt() { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return int.Parse(temp, NumberStyles.None, CultureInfo.InvariantCulture); } } /// <summary> Reads a long value from the stream. </summary> /// <returns>The long value read from the stream.</returns> public long? ReadLong() { string temp = this.ReadField(false /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return long.Parse(temp, NumberStyles.None, CultureInfo.InvariantCulture); } } /// <summary> /// Read a Uri from the stream. /// </summary> /// <returns>The <see cref="System.Uri"/> object read from the stream.</returns> public Uri ReadUri() { string temp = this.ReadField(true /* isQuotedString */); if (string.IsNullOrEmpty(temp)) { return null; } else { return new Uri(WebUtility.HtmlDecode(temp)); } } private void ReadDelimiter(char delimiterToRead) { this.EnsureNotEndOfFile(); long current = this.position; int temp = this.reader.Read(); if (temp == -1 || (char)temp != delimiterToRead) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.LogStreamDelimiterError, delimiterToRead, (char)temp, current)); } // Expected delimiter read this.position++; } private bool TryPeekDelimiter(char delimiterToRead) { this.EnsureNotEndOfFile(); int temp = this.reader.Peek(); if (temp == -1 || (char)temp != delimiterToRead) { return false; } return true; } private void EnsureNotEndOfFile() { if (this.IsEndOfFile) { throw new EndOfStreamException(string.Format(CultureInfo.InvariantCulture, SR.LogStreamEndError, this.Position)); } } private string ReadField(bool isQuotedString) { if (!this.isFirstFieldInRecord) { this.ReadDelimiter(LogRecordStreamReader.FieldDelimiter); } else { this.isFirstFieldInRecord = false; } // Read a field, handling field/record delimiters in quotes and not counting them, // and also check that there are no record delimiters since they are only expected // outside of a field. // Note: We only need to handle strings that are quoted once from the beginning, // (e.g. "mystring"). We do not need to handle nested quotes or anything because // we control the string format. StringBuilder fieldBuilder = new StringBuilder(); bool hasSeenQuoteForQuotedString = false; bool isExpectingDelimiterForNextCharacterForQuotedString = false; while (true) { // If EOF when we have not read any delimiter char, this is unexpected. this.EnsureNotEndOfFile(); char c = (char)this.reader.Peek(); // If we hit a delimiter that is not quoted or we hit the delimiter for // a quoted string or we hit the empty value string and hit a delimiter, // then we have finished reading the field. // Note: The empty value string is the only string that we don't require // quotes for for a quoted string. if ((!isQuotedString || isExpectingDelimiterForNextCharacterForQuotedString || fieldBuilder.Length == 0) && (c == LogRecordStreamReader.FieldDelimiter || c == LogRecordStreamReader.RecordDelimiter)) { // Note: We only peeked this character, so it has not yet // been consumed. Field delimiters will be consumed on the // next ReadField call; record delimiters will be consumed // on a call to EndCurrentRecord. break; } if (isExpectingDelimiterForNextCharacterForQuotedString) { // We finished reading a quoted string, but the next character after // the closing quote was not a delimiter, which is not expected. throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.LogStreamQuoteError, fieldBuilder.ToString(), c)); } // The character was not a delimiter, so consume it and // add it to our field string this.reader.Read(); fieldBuilder.Append(c); this.position++; // We need to handle quotes specially since quoted delimiters // do not count since they are considered to be part of the // quoted string and not actually a delimiter. // Note: We use a specific quote character since we control the format // and we only allow non-encoded quote characters at the beginning/end // of the string. if (c == LogRecordStreamReader.QuoteChar) { if (!isQuotedString) { // The quote character non-encoded is only allowed for quoted strings throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.LogStreamQuoteError, fieldBuilder.ToString(), LogRecordStreamReader.QuoteChar)); } else if (fieldBuilder.Length == 1) { // This is the opening quote for a quoted string hasSeenQuoteForQuotedString = true; } else if (hasSeenQuoteForQuotedString) { // This is the closing quote for a quoted string isExpectingDelimiterForNextCharacterForQuotedString = true; } else { // We encountered an unexpected non-encoded quote character throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.LogStreamQuoteError, fieldBuilder.ToString(), LogRecordStreamReader.QuoteChar)); } } } string field; // Note: For quoted strings we remove the quotes. // We do not do this for the empty value string since it represents empty // and we don't write that out in quotes even for quoted strings. if (isQuotedString && fieldBuilder.Length != 0) { field = fieldBuilder.ToString(1, fieldBuilder.Length - 2); } else { field = fieldBuilder.ToString(); } return field; } #region IDisposable Members /// <summary> /// Dispose this LogRecordStreamReader. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose this LogRecordStreamReader /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing) { this.reader.Close(); } } ~LogRecordStreamReader() { this.Dispose(false); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities; using Microsoft.MixedReality.Toolkit.Core.Utilities; using System.Collections.Generic; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.SDK.Utilities.Solvers { /// <summary> /// This class handles the solver components that are attached to this <see cref="GameObject"/> /// </summary> public class SolverHandler : ControllerFinder { [SerializeField] [Tooltip("Tracked object to calculate position and orientation from. If you want to manually override and use a scene object, use the TransformTarget field.")] private TrackedObjectType trackedObjectToReference = TrackedObjectType.Head; /// <summary> /// Tracked object to calculate position and orientation from. If you want to manually override and use a scene object, use the TransformTarget field. /// </summary> public TrackedObjectType TrackedObjectToReference { get { return trackedObjectToReference; } set { if (trackedObjectToReference != value) { trackedObjectToReference = value; RefreshTrackedObject(); } } } [SerializeField] [Tooltip("Add an additional offset of the tracked object to base the solver on. Useful for tracking something like a halo position above your head or off the side of a controller.")] private Vector3 additionalOffset; /// <summary> /// Add an additional offset of the tracked object to base the solver on. Useful for tracking something like a halo position above your head or off the side of a controller. /// </summary> public Vector3 AdditionalOffset { get { return additionalOffset; } set { additionalOffset = value; transformTarget = MakeOffsetTransform(transformTarget); } } [SerializeField] [Tooltip("Add an additional rotation on top of the tracked object. Useful for tracking what is essentially the up or right/left vectors.")] private Vector3 additionalRotation; /// <summary> /// Add an additional rotation on top of the tracked object. Useful for tracking what is essentially the up or right/left vectors. /// </summary> public Vector3 AdditionalRotation { get { return additionalRotation; } set { additionalRotation = value; transformTarget = MakeOffsetTransform(transformTarget); } } [SerializeField] [Tooltip("Manual override for TrackedObjectToReference if you want to use a scene object. Leave empty if you want to use head or motion-tracked controllers.")] private Transform transformTarget; /// <summary> /// The target transform that the solvers will act upon. /// </summary> public Transform TransformTarget { get { return transformTarget; } set { transformTarget = value; } } [SerializeField] [Tooltip("Whether or not this SolverHandler calls SolverUpdate() every frame. Only one SolverHandler should manage SolverUpdate(). This setting does not affect whether the Target Transform of this SolverHandler gets updated or not.")] private bool updateSolvers = true; /// <summary> /// Whether or not this SolverHandler calls SolverUpdate() every frame. Only one SolverHandler should manage SolverUpdate(). This setting does not affect whether the Target Transform of this SolverHandler gets updated or not. /// </summary> public bool UpdateSolvers { get { return updateSolvers; } set { updateSolvers = value; } } /// <summary> /// The position the solver is trying to move to. /// </summary> public Vector3 GoalPosition { get; set; } /// <summary> /// The rotation the solver is trying to rotate to. /// </summary> public Quaternion GoalRotation { get; set; } /// <summary> /// The scale the solver is trying to scale to. /// </summary> public Vector3 GoalScale { get; set; } /// <summary> /// Alternate scale. /// </summary> public Vector3Smoothed AltScale { get; set; } /// <summary> /// The timestamp the solvers will use to calculate with. /// </summary> public float DeltaTime { get; set; } private bool RequiresOffset => AdditionalOffset.sqrMagnitude != 0 || AdditionalRotation.sqrMagnitude != 0; protected readonly List<Solver> solvers = new List<Solver>(); private float lastUpdateTime; private GameObject transformWithOffset; #region MonoBehaviour Implementation private void Awake() { GoalScale = Vector3.one; AltScale = new Vector3Smoothed(Vector3.one, 0.1f); DeltaTime = 0.0f; solvers.AddRange(GetComponents<Solver>()); } private void Start() { // TransformTarget overrides TrackedObjectToReference if (!transformTarget) { AttachToNewTrackedObject(); } } private void Update() { DeltaTime = Time.realtimeSinceStartup - lastUpdateTime; lastUpdateTime = Time.realtimeSinceStartup; } private void LateUpdate() { if (UpdateSolvers) { for (int i = 0; i < solvers.Count; ++i) { Solver solver = solvers[i]; if (solver.enabled) { solver.SolverUpdate(); } } } } protected void OnDestroy() { DetachFromCurrentTrackedObject(); } #endregion MonoBehaviour Implementation protected override void OnControllerFound() { if (!transformTarget) { TrackTransform(ControllerTransform); } } protected override void OnControllerLost() { DetachFromCurrentTrackedObject(); } /// <summary> /// Clears the transform target and attaches to the current <see cref="TrackedObjectToReference"/>. /// </summary> public void RefreshTrackedObject() { DetachFromCurrentTrackedObject(); AttachToNewTrackedObject(); } protected virtual void DetachFromCurrentTrackedObject() { transformTarget = null; if (transformWithOffset != null) { Destroy(transformWithOffset); transformWithOffset = null; } } protected virtual void AttachToNewTrackedObject() { switch (TrackedObjectToReference) { case TrackedObjectType.Head: // No need to search for a controller if we've already attached to the head. Handedness = Handedness.None; TrackTransform(CameraCache.Main.transform); break; case TrackedObjectType.MotionControllerLeft: Handedness = Handedness.Left; break; case TrackedObjectType.MotionControllerRight: Handedness = Handedness.Right; break; } } private void TrackTransform(Transform newTrackedTransform) { transformTarget = RequiresOffset ? MakeOffsetTransform(newTrackedTransform) : newTrackedTransform; } private Transform MakeOffsetTransform(Transform parentTransform) { if (transformWithOffset == null) { transformWithOffset = new GameObject(); transformWithOffset.transform.parent = parentTransform; } transformWithOffset.transform.localPosition = Vector3.Scale(AdditionalOffset, transformWithOffset.transform.localScale); transformWithOffset.transform.localRotation = Quaternion.Euler(AdditionalRotation); transformWithOffset.name = string.Format("{0} on {1} with offset {2}, {3}", gameObject.name, TrackedObjectToReference.ToString(), AdditionalOffset, AdditionalRotation); return transformWithOffset.transform; } } }