context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using MasterExtensionKit.Core.Exceptions; using MasterExtensionKit.Core.Numbers.Validations; using MasterExtensionKit.Core.UnitTests._Shared; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MasterExtensionKit.Core.UnitTests.Numbers.Validations { public class IsGreaterThanExtensionTests { #region General String Tests [TestMethod] [ExpectedException(typeof(SourceNullException), "")] public void Number_Validation_IsGreaterThan_Null_Exception() { Assert.Fail(); } [TestMethod] [ExpectedException(typeof(SourceNullException), "")] public void Number_Validation_IsGreaterThan_Empty_Invalid() { Assert.Fail(); } #endregion [TestMethod] public void Number_Validation_Integer_NegativeTwo_IsGreaterThan_NegativeTwo_False() { Assert.IsFalse(TestNumberData.INTEGER_NEGATIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Integer_NegativeTwo_IsGreaterThan_NegativeOne_False() { Assert.IsFalse(TestNumberData.INTEGER_NEGATIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_NEGATIVE_ONE)); } [TestMethod] public void Number_Validation_Integer_NegativeTwo_IsGreaterThan_Zero_False() { Assert.IsFalse(TestNumberData.INTEGER_NEGATIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_ZERO)); } [TestMethod] public void Number_Validation_Integer_NegativeTwo_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.INTEGER_NEGATIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Integer_Zero_IsGreaterThan_NegativeTwo_True() { Assert.IsTrue(TestNumberData.INTEGER_ZERO.IsGreaterThan(TestNumberData.INTEGER_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Integer_Zero_IsGreaterThan_Zero_False() { Assert.IsFalse(TestNumberData.INTEGER_ZERO.IsGreaterThan(TestNumberData.INTEGER_ZERO)); } [TestMethod] public void Number_Validation_Integer_Zero_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.INTEGER_ZERO.IsGreaterThan(TestNumberData.INTEGER_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Integer_PositiveTwo_IsGreaterThan_NegativeTwo_True() { Assert.IsTrue(TestNumberData.INTEGER_POSITIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_NEGATIVE_TWO)); } [TestMethod] public void Integer_PositiveTwo_IsGreaterThan_Zero_True() { Assert.IsTrue(TestNumberData.INTEGER_POSITIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_ZERO)); } [TestMethod] public void Number_Validation_Integer_PositiveTwo_IsGreaterThan_PositiveOne_True() { Assert.IsTrue(TestNumberData.INTEGER_POSITIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_NEGATIVE_ONE)); } [TestMethod] public void Number_Validation_Integer_PositiveTwo_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.INTEGER_POSITIVE_TWO.IsGreaterThan(TestNumberData.INTEGER_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Decimal_NegativeTwo_IsGreaterThan_NegativeTwo_False() { Assert.IsFalse(TestNumberData.DECIMAL_NEGATIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Decimal_NegativeTwo_IsGreaterThan_NegativeOne_False() { Assert.IsFalse(TestNumberData.DECIMAL_NEGATIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_NEGATIVE_ONE)); } [TestMethod] public void Number_Validation_Decimal_NegativeTwo_IsGreaterThan_Zero_False() { Assert.IsFalse(TestNumberData.DECIMAL_NEGATIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_ZERO)); } [TestMethod] public void Number_Validation_Decimal_NegativeTwo_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.DECIMAL_NEGATIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Decimal_Zero_IsGreaterThan_NegativeTwo_True() { Assert.IsTrue(TestNumberData.DECIMAL_ZERO.IsGreaterThan(TestNumberData.DECIMAL_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Decimal_Zero_IsGreaterThan_Zero_False() { Assert.IsFalse(TestNumberData.DECIMAL_ZERO.IsGreaterThan(TestNumberData.DECIMAL_ZERO)); } [TestMethod] public void Number_Validation_Decimal_Zero_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.DECIMAL_ZERO.IsGreaterThan(TestNumberData.DECIMAL_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Decimal_PositiveTwo_IsGreaterThan_NegativeTwo_True() { Assert.IsTrue(TestNumberData.DECIMAL_POSITIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Decimal_PositiveTwo_IsGreaterThan_Zero_True() { Assert.IsTrue(TestNumberData.DECIMAL_POSITIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_ZERO)); } [TestMethod] public void Number_Validation_Decimal_PositiveTwo_IsGreaterThan_PositiveOne_True() { Assert.IsTrue(TestNumberData.DECIMAL_POSITIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_NEGATIVE_ONE)); } [TestMethod] public void Number_Validation_Decimal_PositiveTwo_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.DECIMAL_POSITIVE_TWO.IsGreaterThan(TestNumberData.DECIMAL_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Float_NegativeTwo_IsGreaterThan_NegativeTwo_False() { Assert.IsFalse(TestNumberData.FLOAT_NEGATIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Float_NegativeTwo_IsGreaterThan_NegativeOne_False() { Assert.IsFalse(TestNumberData.FLOAT_NEGATIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_NEGATIVE_ONE)); } [TestMethod] public void Number_Validation_Float_NegativeTwo_IsGreaterThan_Zero_False() { Assert.IsFalse(TestNumberData.FLOAT_NEGATIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_ZERO)); } [TestMethod] public void Number_Validation_Float_NegativeTwo_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.FLOAT_NEGATIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Float_Zero_IsGreaterThan_NegativeTwo_True() { Assert.IsTrue(TestNumberData.FLOAT_ZERO.IsGreaterThan(TestNumberData.FLOAT_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Float_Zero_IsGreaterThan_Zero_False() { Assert.IsFalse(TestNumberData.FLOAT_ZERO.IsGreaterThan(TestNumberData.FLOAT_ZERO)); } [TestMethod] public void Number_Validation_Float_Zero_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.FLOAT_ZERO.IsGreaterThan(TestNumberData.FLOAT_POSITIVE_TWO)); } [TestMethod] public void Number_Validation_Float_PositiveTwo_IsGreaterThan_NegativeTwo_True() { Assert.IsTrue(TestNumberData.FLOAT_POSITIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_NEGATIVE_TWO)); } [TestMethod] public void Number_Validation_Float_PositiveTwo_IsGreaterThan_Zero_True() { Assert.IsTrue(TestNumberData.FLOAT_POSITIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_ZERO)); } [TestMethod] public void Number_Validation_Float_PositiveTwo_IsGreaterThan_PositiveOne_True() { Assert.IsTrue(TestNumberData.FLOAT_POSITIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_NEGATIVE_ONE)); } [TestMethod] public void Number_Validation_Float_PositiveTwo_IsGreaterThan_PositiveTwo_False() { Assert.IsFalse(TestNumberData.FLOAT_POSITIVE_TWO.IsGreaterThan(TestNumberData.FLOAT_POSITIVE_TWO)); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI.Windows; using UnityEngine.UI; using UnityEngine.UI.Windows.Extensions; using UnityEngine.UI.Windows.Components.Modules; namespace UnityEngine.UI.Windows.Components { public class ImageComponent : WindowComponent, IImageComponent { public override void Setup(IComponentParameters parameters) { base.Setup(parameters); var inputParameters = parameters as ImageComponentParameters; #region source macros UI.Windows.Initialization.ImageComponent { if (inputParameters != null) inputParameters.Setup(this as IImageComponent); } #endregion } public override void OnLocalizationChanged() { base.OnLocalizationChanged(); #region source macros UI.Windows.OnLocalizationChanged.ImageComponent { if (this.lastImageLocalization == true) { this.SetImage(this.lastImageLocalizationKey, this.lastImageLocalizationParameters); } else { if (this.image is UnityEngine.UI.Windows.Plugins.Localization.UI.LocalizationImage) { (this.image as UnityEngine.UI.Windows.Plugins.Localization.UI.LocalizationImage).OnLocalizationChanged(); } } } #endregion } public override void OnWindowInactive() { base.OnWindowInactive(); #region source macros UI.Windows.OnWindowInactive.ImageComponent { if (this.IsVisible() == true) { this.tempMovieIsPlaying = (this.IsMovie() == true && this.IsPlaying() == true); this.Pause(); } } #endregion } public override void OnWindowActive() { base.OnWindowActive(); #region source macros UI.Windows.OnWindowActive.ImageComponent { if (this.IsVisible() == true && this.tempMovieIsPlaying == true) { this.Play(); this.tempMovieIsPlaying = false; } } #endregion } public override void OnInit() { base.OnInit(); #region source macros UI.Windows.OnInit.ImageComponent { this.tempImagePlayOnShow = false; if (this.imageLocalizationKey.IsNone() == false) { if ((this.imageResource.controlType & ResourceAuto.ControlType.Init) != 0) { this.SetImage(this.imageLocalizationKey); } } else { WindowSystemResources.LoadAuto(this, onDataLoaded: () => { this.tempImagePlayOnShow = true; if (this.IsVisible() == true) { if (this.playOnShow == true) { this.Play(); } } }, onComplete: null, onShowHide: false); } this.imageCrossFadeModule.Init(this); } #endregion } public override void OnDeinit(System.Action callback) { base.OnDeinit(callback); #region source macros UI.Windows.OnDeinit.ImageComponent { this.Stop(); WindowSystemResources.UnloadAuto(this, onShowHide: false); } #endregion } public override void DoShowBegin(AppearanceParameters parameters) { #region source macros UI.Windows.DoShowBegin.ImageComponent { if (this.imageResourceWait == true && this.imageResource.IsValid() == true) { WindowSystemResources.LoadAuto(this, onDataLoaded: () => { this.tempImagePlayOnShow = true; if (this.playOnShow == true) { this.Play(); } }, onComplete: () => { base.DoShowBegin(parameters); }, onShowHide: true, onFailed: () => { base.DoShowBegin(parameters); }); } else { base.DoShowBegin(parameters); } } #endregion } public override void OnShowBegin(AppearanceParameters parameters) { #region source macros UI.Windows.OnShowBegin.ImageComponent { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } if (this.imageLocalizationKey.IsNone() == false) { if ((this.imageResource.controlType & ResourceAuto.ControlType.Show) != 0) { this.SetImage(this.imageLocalizationKey); } } else { WindowSystemResources.LoadAuto(this, onDataLoaded: () => { if (this.playOnShow == true) { this.Play(); } }, onComplete: null, onShowHide: true); } if (this.tempImagePlayOnShow == true) { if (this.playOnShow == true) { this.Play(); } } } #endregion base.OnShowBegin(parameters); } public override void OnHideBegin() { base.OnHideBegin(); #region source macros UI.Windows.OnHideBegin.ImageComponent { this.tempImagePlayOnShow = (this.IsMovie() == true && this.IsPlaying() == true); this.Pause(); } #endregion } public override void OnHideEnd() { base.OnHideEnd(); #region source macros UI.Windows.OnHideEnd.ImageComponent { //this.Stop(); WindowSystemResources.UnloadAuto(this, onShowHide: true); } #endregion } #region source macros UI.Windows.ImageComponent [Header("Image Component")] [SerializeField] private Image image; [BeginGroup("image")][SerializeField] private RawImage rawImage; [SerializeField] private bool flipHorizontal; [SerializeField] private bool flipVertical; private bool flipHorizontalInternal; private bool flipVerticalInternal; [SerializeField] private bool preserveAspect; [HideInInspector][SerializeField] private UIFlippable flippableEffect; [HideInInspector][SerializeField] private UIPreserveAspect preserveAspectEffect; public UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey imageLocalizationKey; [ReadOnly("rawImage", null)] [SerializeField][UnityEngine.Serialization.FormerlySerializedAs("playOnStart")] private bool playOnShow; [ReadOnly("rawImage", null)] [SerializeField] private bool loop; [SerializeField] private bool imageResourceWait = false; [SerializeField] private ResourceAuto imageResource = new ResourceAuto(); [EndGroup][SerializeField] private ImageCrossFadeModule imageCrossFadeModule = new ImageCrossFadeModule(); private bool tempImagePlayOnShow = false; private bool tempMovieIsPlaying = false; public ImageCrossFadeModule GetImageCrossFadeModule() { return this.imageCrossFadeModule; } public ResourceBase GetResource() { return this.imageResource; } public IImageComponent SetPreserveAspectState(bool state) { this.preserveAspect = state; return this; } public IImageComponent SetLoop(bool state) { this.loop = state; return this; } public bool IsLoop() { return this.loop; } public bool IsMovie() { var image = this.GetRawImageSource(); if (image == null) return false; return this.imageResource.IsMovie() == true && MovieSystem.IsMovie(image.mainTexture) == true; } public IImageComponent Unload(ResourceBase resource) { WindowSystemResources.Unload(this, resource); return this; } public void SetVerticesDirty() { if (this.image != null) this.image.SetVerticesDirty(); if (this.rawImage != null) this.rawImage.SetVerticesDirty(); } public IImageComponent SetImageLocalizationKey(UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey key) { this.imageLocalizationKey = key; return this; } public IImageComponent SetMovieTexture(ResourceAuto resource, System.Action onDataLoaded, System.Action onComplete = null, System.Action onFailed = null) { this.flipVerticalInternal = MovieSystem.IsVerticalFlipped(); this.SetVerticesDirty(); this.Stop(); this.SetImage(resource, onDataLoaded: () => { if (onDataLoaded != null) onDataLoaded.Invoke(); }, onComplete: () => { //Debug.Log("SetMovieTexture: " + this.name); MovieSystem.UnregisterOnUpdateTexture(this.ValidateTexture); MovieSystem.RegisterOnUpdateTexture(this.ValidateTexture); if (onComplete != null) onComplete.Invoke(); }, onFailed: onFailed); return this; } private void ValidateTexture(IImageComponent component, Texture texture) { //Debug.Log("ValidateTexture: " + (component as MonoBehaviour) + ", tex: " + texture, component as MonoBehaviour); if (this as IImageComponent == component) { if (this.rawImage != null) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.ValidateTexture(texture); } else { this.rawImage.texture = texture; } } } } public bool GetPlayOnShow() { return this.playOnShow; } public IImageComponent SetPlayOnShow(bool state) { this.playOnShow = state; return this; } public virtual bool IsPlaying() { return MovieSystem.IsPlaying(this); } public virtual IImageComponent PlayAndPause() { MovieSystem.PlayAndPause(this, this.loop); return this; } public virtual IImageComponent Rewind(bool pause = true) { MovieSystem.Rewind(this, pause); return this; } public virtual IImageComponent Play() { return this.Play(this.loop); } public virtual IImageComponent Play(bool loop) { if (this.GetWindow() != null && this.GetWindow().GetActiveState() == ActiveState.Active) { MovieSystem.Play(this, loop); } else { this.tempMovieIsPlaying = true; } return this; } public virtual IImageComponent Play(bool loop, System.Action onComplete) { MovieSystem.Play(this, loop, onComplete); return this; } public virtual IImageComponent Stop() { MovieSystem.UnregisterOnUpdateMaterial(this.ValidateMaterial); MovieSystem.UnregisterOnUpdateTexture(this.ValidateTexture); MovieSystem.Stop(this); return this; } public virtual IImageComponent Pause() { MovieSystem.Pause(this); return this; } public Texture GetTexture() { if (this.image != null) { return (this.image.sprite != null ? this.image.sprite.texture : null); } if (this.rawImage != null) { return this.rawImage.texture; } return null; } public IImageComponent ResetImage() { if (this.image != null) { this.image.sprite = null; } if (this.rawImage != null) { this.Stop(); this.rawImage.texture = null; } this.flipHorizontalInternal = false; this.flipVerticalInternal = false; return this; } Graphic IImageComponent.GetGraphicSource() { if (this.image != null) return this.image; return this.rawImage; } public Image GetImageSource() { return this.image; } public RawImage GetRawImageSource() { return this.rawImage; } public bool IsHorizontalFlip() { return this.flipHorizontal == true || this.flipHorizontalInternal == true; } public bool IsVerticalFlip() { return this.flipVertical == true || this.flipVerticalInternal == true; } public bool IsPreserveAspect() { return this.preserveAspect; } public IImageComponent SetImage(ImageComponent source) { if (source.GetImageSource() != null) this.SetImage(source.GetImageSource().sprite); if (source.GetRawImageSource() != null) this.SetImage(source.GetRawImageSource().texture); return this; } public IImageComponent SetImage(ResourceAuto resource, System.Action onDataLoaded = null, System.Action onComplete = null, System.Action onFailed = null) { ME.Coroutines.Run(this.SetImage_INTERNAL(resource, onDataLoaded, onComplete, onFailed)); return this; } private System.Collections.Generic.IEnumerator<byte> SetImage_INTERNAL(ResourceAuto resource, System.Action onDataLoaded = null, System.Action onComplete = null, System.Action onFailed = null) { yield return 0; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } var oldResource = this.imageResource; var newResource = resource; this.imageResource = resource; // Debug.Log("Loading resource: " + this.imageResource.GetId()); WindowSystemResources.Load(this, onDataLoaded: onDataLoaded, onComplete: () => { //Debug.Log("Resource loaded: " + newResource.GetId() + " :: " + this.name, this); if (newResource.GetId() != oldResource.GetId()) { // Debug.Log("Unloading: " + newResource.GetId() + " != " + oldResource.GetId() + " :: " + this.name, this); WindowSystemResources.Unload(this, oldResource, resetController: false); } if (onComplete != null) onComplete.Invoke(); }, onFailed: () => { //Debug.Log("Resource loading failed: " + newResource.GetId() + " :: " + this.name, this); if (newResource.GetId() != oldResource.GetId()) { //Debug.Log("Failed, Unloading: " + this.imageResource.GetId() + " != " + oldResource.GetId() + " :: " + this.name, this); WindowSystemResources.Unload(this, oldResource, resetController: false); } if (onFailed != null) onFailed.Invoke(); } ); } private bool lastImageLocalization = false; private Plugins.Localization.LocalizationKey lastImageLocalizationKey; private object[] lastImageLocalizationParameters; public IImageComponent SetImage(UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey key, params object[] parameters) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } this.lastImageLocalization = true; this.lastImageLocalizationKey = key; this.lastImageLocalizationParameters = parameters; this.SetImage(ResourceAuto.CreateResourceRequest(UnityEngine.UI.Windows.Plugins.Localization.LocalizationSystem.GetSpritePath(key, parameters))); //this.SetImage(UnityEngine.UI.Windows.Plugins.Localization.LocalizationSystem.GetSprite(key, parameters)); //WindowSystemResources.Unload(this, this.GetResource()); //WindowSystemResources.Load(this, onDataLoaded: null, onComplete: null, customResourcePath: UnityEngine.UI.Windows.Plugins.Localization.LocalizationSystem.GetSpritePath(key, parameters)); return this; } public IImageComponent SetImage(Sprite sprite) { return this.SetImage(sprite, this.preserveAspect, false, null, false); } public IImageComponent SetImage(Sprite sprite, bool immediately) { return this.SetImage(sprite, this.preserveAspect, false, null, immediately); } public IImageComponent SetImage(Sprite sprite, System.Action onComplete) { return this.SetImage(sprite, this.preserveAspect, false, onComplete, false); } public IImageComponent SetImage(Sprite sprite, System.Action onComplete, bool immediately) { return this.SetImage(sprite, this.preserveAspect, false, onComplete, immediately); } public IImageComponent SetImage(Sprite sprite, bool preserveAspect, bool withPivotsAndSize, System.Action onComplete) { return this.SetImage(sprite, preserveAspect, withPivotsAndSize, onComplete, false); } public IImageComponent SetImage(Sprite sprite, bool preserveAspect, bool withPivotsAndSize, System.Action onComplete = null, bool immediately = false) { if (this.image != null) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } this.image.preserveAspect = preserveAspect; if (withPivotsAndSize == true && sprite != null) { var rect = (this.transform as RectTransform); rect.sizeDelta = sprite.rect.size; rect.pivot = sprite.GetPivot(); rect.anchoredPosition = Vector2.zero; } if (immediately == false && this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo(this, sprite, onComplete); } else { this.image.sprite = sprite; if (onComplete != null) onComplete.Invoke(); } } else { if (onComplete != null) onComplete.Invoke(); } return this; } public IImageComponent SetImage(Texture texture) { return this.SetImage(texture, this.preserveAspect, null, false); } public IImageComponent SetImage(Texture texture, bool immediately) { return this.SetImage(texture, this.preserveAspect, null, immediately); } public IImageComponent SetImage(Texture texture, System.Action onComplete) { return this.SetImage(texture, this.preserveAspect, onComplete, false); } public IImageComponent SetImage(Texture texture, System.Action onComplete, bool immediately) { return this.SetImage(texture, this.preserveAspect, onComplete, immediately); } public IImageComponent SetImage(Texture texture, bool preserveAspect, System.Action onComplete) { return this.SetImage(texture, preserveAspect, onComplete, false); } public IImageComponent SetImage(Texture texture, bool preserveAspect, System.Action onComplete, bool immediately) { //MovieSystem.UnregisterOnUpdateTexture(this.ValidateTexture); //MovieSystem.Stop(this, this.rawImage.texture.GetInstanceID()); if (this.rawImage != null) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } if (immediately == false && this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo(this, texture, onComplete); } else { this.rawImage.texture = texture; if (onComplete != null) onComplete.Invoke(); } } else { if (onComplete != null) onComplete.Invoke(); } return this; } public /*{overrideColor}*/ Color GetColor() { Color color = Color.white; if (this.image != null) { color = this.image.color; } else if (this.rawImage != null) { color = this.rawImage.color; } return color; } public /*{overrideColor}*/ void SetColor(Color color) { if (this.image != null) { this.image.color = color; } if (this.rawImage != null) { this.rawImage.color = color; } } public IAlphaComponent SetAlpha(float value) { var color = this.GetColor(); color.a = value; this.SetColor(color); return this; } public IImageComponent SetMaterial(Material material, bool setMainTexture = false, System.Action onComplete = null) { MovieSystem.UnregisterOnUpdateMaterial(this.ValidateMaterial); if (material == null) { if (this.image != null) { this.image.material = null; this.image.SetMaterialDirty(); } else if (this.rawImage != null) { this.rawImage.material = null; this.rawImage.SetMaterialDirty(); } if (onComplete != null) onComplete.Invoke(); return this; } MovieSystem.RegisterOnUpdateMaterial(this.ValidateMaterial); if (this.image != null) { if (this.image.enabled == false) this.image.enabled = true; var tex = material.mainTexture; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo<Image>(this, material, () => { if (setMainTexture == true) { var sprite = Sprite.Create(tex as Texture2D, new Rect(0f, 0f, tex.width, tex.height), Vector2.one * 0.5f); this.image.sprite = sprite; } this.image.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); }, ImageCrossFadeModule.DataType.Material); } else { if (setMainTexture == true) { var sprite = Sprite.Create(tex as Texture2D, new Rect(0f, 0f, tex.width, tex.height), Vector2.one * 0.5f); this.image.sprite = sprite; } this.image.material = material; this.image.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); } } else if (this.rawImage != null) { if (this.rawImage.enabled == false) this.rawImage.enabled = true; var tex = material.mainTexture; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo<RawImage>(this, material, () => { if (setMainTexture == true) { this.rawImage.texture = tex; } this.rawImage.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); }, ImageCrossFadeModule.DataType.Material); } else { if (setMainTexture == true) { this.rawImage.texture = tex; } this.rawImage.material = material; this.rawImage.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); } } return this; } public void ValidateMaterial(Material material) { if (this.rawImage != null) { this.rawImage.texture = this.rawImage.material.mainTexture; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.ValidateMaterial(material); } //Debug.Log("MATERIAL DIRTY: " + this.rawImage.texture, this); } } /* public void ModifyMesh(Mesh mesh) {} private System.Collections.Generic.List<UIVertex> modifyVertsTemp = new System.Collections.Generic.List<UIVertex>(); public void ModifyMesh(VertexHelper helper) { if (this.rawImage != null && this.preserveAspect == true) { var vh = helper; var drawingDimensions = ME.Utilities.GetDrawingDimensions(this.rawImage, this.preserveAspect, this.rawImage.texture == null ? Vector2.zero : new Vector2(this.rawImage.texture.width, this.rawImage.texture.height), Vector4.zero); var vector = new Vector4(this.rawImage.uvRect.x, this.rawImage.uvRect.y, this.rawImage.uvRect.width, this.rawImage.uvRect.height); var color = this.GetColor(); vh.Clear(); vh.AddVert(new Vector3(drawingDimensions.x, drawingDimensions.y), color, new Vector2(vector.x, vector.y)); vh.AddVert(new Vector3(drawingDimensions.x, drawingDimensions.w), color, new Vector2(vector.x, vector.w)); vh.AddVert(new Vector3(drawingDimensions.z, drawingDimensions.w), color, new Vector2(vector.z, vector.w)); vh.AddVert(new Vector3(drawingDimensions.z, drawingDimensions.y), color, new Vector2(vector.z, vector.y)); vh.AddTriangle(0, 1, 2); vh.AddTriangle(2, 3, 0); } if (this.flipHorizontal == true || this.flipVertical == true || this.flipHorizontalInternal == true || this.flipVerticalInternal == true) { this.modifyVertsTemp.Clear(); helper.GetUIVertexStream(this.modifyVertsTemp); this.ModifyVertices(this.modifyVertsTemp); helper.AddUIVertexTriangleStream(this.modifyVertsTemp); } } public void ModifyVertices(System.Collections.Generic.List<UIVertex> verts) { var rt = this.GetRectTransform(); var rectCenter = rt.rect.center; for (var i = 0; i < verts.Count; ++i) { var v = verts[i]; v.position = new Vector3( ((this.flipHorizontal == true || this.flipHorizontalInternal == true) ? (v.position.x + (rectCenter.x - v.position.x) * 2f) : v.position.x), ((this.flipVertical == true || this.flipVerticalInternal == true) ? (v.position.y + (rectCenter.y - v.position.y) * 2f) : v.position.y), v.position.z ); verts[i] = v; } }*/ #endregion #if UNITY_EDITOR [ContextMenu("Setup UI.Image")] public void SetupImage() { this.image = ME.Utilities.FindReferenceChildren<Image>(this); } [ContextMenu("Setup UI.RawImage")] public void SetupRawImage() { this.rawImage = ME.Utilities.FindReferenceChildren<RawImage>(this); } public override void OnValidateEditor() { base.OnValidateEditor(); //if (this.gameObject.activeSelf == false) return; #region source macros UI.Windows.Editor.ImageComponent { //if (this.image == null) this.image = this.GetComponent<Image>(); //if (this.rawImage == null) this.rawImage = this.GetComponent<RawImage>(); WindowSystemResources.Validate(this); this.imageCrossFadeModule.Init(this); this.imageCrossFadeModule.OnValidateEditor(); /*if (this.image == null || this.image.GetComponent<UIFlippable>() == null || this.rawImage == null || this.rawImage.GetComponent<UIFlippable>() == null) { if (this.flippableEffect != null) ME.EditorUtilities.Destroy(this.flippableEffect, () => { this.flippableEffect = null; }); } if (this.rawImage == null || this.rawImage.GetComponent<UIPreserveAspect>() == null) { if (this.preserveAspectEffect != null) ME.EditorUtilities.Destroy(this.preserveAspectEffect, () => { this.preserveAspectEffect = null; }); }*/ var gr = (this.rawImage as Graphic ?? this.image as Graphic); if (gr != null) { this.flippableEffect = gr.GetComponent<UIFlippable>(); if (this.flippableEffect == null) this.flippableEffect = gr.gameObject.AddComponent<UIFlippable>(); if (this.flippableEffect != null) { this.flippableEffect.horizontal = this.flipHorizontal; this.flippableEffect.vertical = this.flipVertical; } } if (this.rawImage != null) { this.preserveAspectEffect = this.rawImage.GetComponent<UIPreserveAspect>(); if (this.preserveAspectEffect == null) this.preserveAspectEffect = this.rawImage.gameObject.AddComponent<UIPreserveAspect>(); if (this.preserveAspectEffect != null) { this.preserveAspectEffect.preserveAspect = this.preserveAspect; this.preserveAspectEffect.rawImage = this.rawImage; } } } #endregion } #endif } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; public class tk2dTileMapSceneGUI { ITileMapEditorHost host; tk2dTileMap tileMap; tk2dTileMapData tileMapData; tk2dTileMapEditorData editorData; tk2dScratchpadGUI scratchpadGUI; int cursorX0 = 0, cursorY0 = 0; int cursorX = 0, cursorY = 0; int vertexCursorX = 0, vertexCursorY = 0; Color tileSelectionFillColor = new Color32(0, 128, 255, 32); Color tileSelectionOutlineColor = new Color32(0,200,255,255); int currentModeForBrushColor = -1; tk2dTileMapEditorBrush workingBrush = null; tk2dTileMapEditorBrush WorkingBrush { get { if (workingBrush == null) workingBrush = new tk2dTileMapEditorBrush(); return workingBrush; } } tk2dEditor.BrushRenderer brushRenderer = null; tk2dEditor.BrushRenderer BrushRenderer { get { if (brushRenderer == null) brushRenderer = new tk2dEditor.BrushRenderer(tileMap); return brushRenderer; } } // Data from one sprite in the collection Vector2 curSpriteDefTexelSize = Vector2.one; public tk2dTileMapSceneGUI(ITileMapEditorHost host, tk2dTileMap tileMap, tk2dTileMapEditorData editorData) { this.host = host; this.tileMap = tileMap; this.editorData = editorData; this.tileMapData = tileMap.data; // create default brush if (tileMap.SpriteCollectionInst && this.editorData) { this.editorData.InitBrushes(tileMap.SpriteCollectionInst); tk2dUtil.SetDirty(this.editorData); } scratchpadGUI = new tk2dScratchpadGUI(this, BrushRenderer, WorkingBrush); if (editorData != null) { scratchpadGUI.SetActiveScratchpads(editorData.scratchpads); } } public void Destroy() { if (brushRenderer != null) { brushRenderer.Destroy(); brushRenderer = null; } } void DrawCursorAt(int x, int y) { switch (tileMap.data.tileType) { case tk2dTileMapData.TileType.Rectangular: { float xOffsetMult, yOffsetMult; tileMap.data.GetTileOffset(out xOffsetMult, out yOffsetMult); float xOffset = (y & 1) * xOffsetMult; Vector3 p0 = new Vector3(tileMapData.tileOrigin.x + (x + xOffset) * tileMapData.tileSize.x, tileMapData.tileOrigin.y + y * tileMapData.tileSize.y, 0); Vector3 p1 = new Vector3(p0.x + tileMapData.tileSize.x, p0.y + tileMapData.tileSize.y, 0); Vector3[] v = new Vector3[4]; v[0] = new Vector3(p0.x, p0.y, 0); v[1] = new Vector3(p1.x, p0.y, 0); v[2] = new Vector3(p1.x, p1.y, 0); v[3] = new Vector3(p0.x, p1.y, 0); for (int i = 0; i < v.Length; ++i) v[i] = tileMap.transform.TransformPoint(v[i]); Handles.DrawSolidRectangleWithOutline(v, tileSelectionFillColor, tileSelectionOutlineColor); } break; case tk2dTileMapData.TileType.Isometric: { float xOffsetMult, yOffsetMult; tileMap.data.GetTileOffset(out xOffsetMult, out yOffsetMult); float xOffset = (y & 1) * xOffsetMult; Vector3 p0 = new Vector3(tileMapData.tileOrigin.x + (x + xOffset) * tileMapData.tileSize.x, tileMapData.tileOrigin.y + y * tileMapData.tileSize.y, 0); Vector3 p1 = new Vector3(p0.x + tileMapData.tileSize.x, p0.y + tileMapData.tileSize.y * 2, 0); Vector3[] v = new Vector3[4]; v[0] = new Vector3(p0.x + (p1.x-p0.x)*0.5f, p0.y, 0); v[1] = new Vector3(p1.x, p0.y + (p1.y-p0.y)*0.5f, 0); v[2] = new Vector3(p1.x - (p1.x-p0.x)*0.5f, p1.y, 0); v[3] = new Vector3(p0.x, p1.y - (p1.y-p0.y)*0.5f, 0); for (int i = 0; i < v.Length; ++i) v[i] = tileMap.transform.TransformPoint(v[i]); Handles.DrawSolidRectangleWithOutline(v, tileSelectionFillColor, tileSelectionOutlineColor); } break; } } void DrawTileMapRectCursor(int x0, int y0, int x1, int y1) { Vector3 p0 = new Vector3(tileMapData.tileOrigin.x + x0 * tileMapData.tileSize.x, tileMapData.tileOrigin.y + y0 * tileMapData.tileSize.y, 0); Vector3 p1 = new Vector3(tileMapData.tileOrigin.x + (x1 + 1) * tileMapData.tileSize.x, tileMapData.tileOrigin.y + (y1 + 1) * tileMapData.tileSize.y, 0); float layerDepth = GetLayerDepth(editorData.layer); Vector3[] v = new Vector3[4]; v[0] = new Vector3(p0.x, p0.y, layerDepth); v[1] = new Vector3(p1.x, p0.y, layerDepth); v[2] = new Vector3(p1.x, p1.y, layerDepth); v[3] = new Vector3(p0.x, p1.y, layerDepth); for (int i = 0; i < v.Length; ++i) v[i] = tileMap.transform.TransformPoint(v[i]); Handles.DrawSolidRectangleWithOutline(v, tileSelectionFillColor, tileSelectionOutlineColor); } void DrawScratchpadRectCursor(int x1, int y1, int x2, int y2) { if (scratchpadGUI.padAreaRect.width < 1.0f || scratchpadGUI.padAreaRect.height < 1.0f) return; float scale = scratchpadGUI.scratchZoom; Vector3 p0 = new Vector3(x1 * scale * (tileMapData.tileSize.x / curSpriteDefTexelSize.x), y1 * scale * (tileMapData.tileSize.y / curSpriteDefTexelSize.y), 0); Vector3 p1 = new Vector3((x2 + 1) * scale * (tileMapData.tileSize.x / curSpriteDefTexelSize.x), (y2 + 1) * scale * (tileMapData.tileSize.y / curSpriteDefTexelSize.y), 0); float temp = p0.y; p0.y = scratchpadGUI.padAreaRect.height - p1.y; p1.y = scratchpadGUI.padAreaRect.height - temp; Rect viewRect = tk2dSpriteThumbnailCache.VisibleRect; p0.x = Mathf.Max(p0.x, viewRect.xMin); p0.y = Mathf.Max(p0.y, viewRect.yMin); p1.x = Mathf.Min(p1.x, viewRect.xMax); p1.y = Mathf.Min(p1.y, viewRect.yMax); if (p0.x > p1.x || p0.y > p1.y) return; Vector3[] v = new Vector3[4]; v[0] = new Vector3(p0.x, p0.y, 0); v[1] = new Vector3(p1.x, p0.y, 0); v[2] = new Vector3(p1.x, p1.y, 0); v[3] = new Vector3(p0.x, p1.y, 0); for (int i = 0; i < v.Length; ++i) v[i] = new Vector3(v[i].x, v[i].y, 0.0f); Handles.DrawSolidRectangleWithOutline(v, tileSelectionFillColor, tileSelectionOutlineColor); } public void DrawTileCursor() { // Where to draw the cursor bool workTiles = false; bool mouseRect = false; if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Brush || tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.BrushRandom) { workTiles = true; } else { // Erase, Eyedropper or Cut mouseRect = true; } if (!workTiles && !mouseRect) return; int x1 = cursorX; int y1 = cursorY; int x2 = cursorX; int y2 = cursorY; if (workTiles) { foreach (var tile in WorkingBrush.tiles) { x1 = Mathf.Min (x1, tile.x); y1 = Mathf.Min (y1, tile.y); x2 = Mathf.Max (x2, tile.x); y2 = Mathf.Max (y2, tile.y); } } else if (mouseRect) { x1 = Mathf.Min(cursorX, cursorX0); y1 = Mathf.Min(cursorY, cursorY0); x2 = Mathf.Max(cursorX, cursorX0); y2 = Mathf.Max(cursorY, cursorY0); } // Clip rect appropriately int clipW, clipH; if (scratchpadGUI.workingHere) { scratchpadGUI.GetScratchpadSize(out clipW, out clipH); } else { clipW = tileMap.width; clipH = tileMap.height; } x1 = Mathf.Max(0, x1); y1 = Mathf.Max(0, y1); x2 = Mathf.Min(clipW - 1, x2); y2 = Mathf.Min(clipH - 1, y2); if (x2 < x1 || y2 < y1) return; // Draw cursor if (tileMap.data.tileType == tk2dTileMapData.TileType.Rectangular) { if (scratchpadGUI.workingHere) { DrawScratchpadRectCursor(x1, y1, x2, y2); } else { DrawTileMapRectCursor(x1, y1, x2, y2); } } else { // would be nice to have an isometric outlined poly... if (scratchpadGUI.workingHere) { ; } else { for (int y = y1; y <= y2; ++y) { for (int x = x1; x <= x2; ++x) { DrawCursorAt(x, y); } } } } } void DrawPaintCursor() { float layerZ = 0.0f; Vector3 p0 = new Vector3(tileMapData.tileOrigin.x + vertexCursorX * tileMapData.tileSize.x, tileMapData.tileOrigin.y + vertexCursorY * tileMapData.tileSize.y, layerZ); float radius = Mathf.Max(tileMapData.tileSize.x, tileMapData.tileSize.y) * tk2dTileMapToolbar.colorBrushRadius; // We get intensity, and tint the handle color by this. float t = tk2dTileMapToolbar.colorBrushIntensity; Color c = editorData.brushColor; Color oldColor = Handles.color; Handles.color = new Color( c.r, c.g, c.b, t * 0.7f + 0.3f ); Handles.DrawWireDisc(tileMap.transform.TransformPoint(p0), tileMap.transform.TransformDirection(Vector3.forward), radius); Handles.color = oldColor; } void DrawOutline() { Vector3 p0 = tileMapData.tileOrigin; Vector3 p1 = new Vector3(p0.x + tileMapData.tileSize.x * tileMap.width, p0.y + tileMapData.tileSize.y * tileMap.height, 0); Vector3[] v = new Vector3[5]; v[0] = new Vector3(p0.x, p0.y, 0); v[1] = new Vector3(p1.x, p0.y, 0); v[2] = new Vector3(p1.x, p1.y, 0); v[3] = new Vector3(p0.x, p1.y, 0); v[4] = new Vector3(p0.x, p0.y, 0); for (int i = 0; i < 5; ++i) { v[i] = tileMap.transform.TransformPoint(v[i]); } Handles.DrawPolyLine(v); } public static int tileMapHashCode = "TileMap".GetHashCode(); bool UpdateCursorPosition() { if (scratchpadGUI.workingHere) { cursorX = (int)((scratchpadGUI.paintMousePosition.x / scratchpadGUI.scratchZoom) / (tileMapData.tileSize.x / curSpriteDefTexelSize.x)); cursorY = (int)((scratchpadGUI.paintMousePosition.y / scratchpadGUI.scratchZoom) / (tileMapData.tileSize.y / curSpriteDefTexelSize.y)); return true; } bool isInside = false; Vector3 layerDepthOffset = new Vector3(0, 0, GetLayerDepth(editorData.layer)); layerDepthOffset = tileMap.transform.TransformDirection(layerDepthOffset); Plane p = new Plane(tileMap.transform.forward, tileMap.transform.position + layerDepthOffset); Ray r = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); float hitD = 0.0f; if (p.Raycast(r, out hitD)) { float fx, fy; if (tileMap.GetTileFracAtPosition(r.GetPoint(hitD), out fx, out fy)) { isInside = true; } int x = (int)(fx); int y = (int)(fy); cursorX = x; cursorY = y; vertexCursorX = (int)Mathf.Round(fx); vertexCursorY = (int)Mathf.Round(fy); HandleUtility.Repaint(); } return isInside; } bool IsCursorInside() { return UpdateCursorPosition(); } void SplatWorkingBrush() { foreach (var tile in WorkingBrush.tiles) { if (tile.spriteId != -1) { SplatTile(tile.x, tile.y, tile.layer, tile.spriteId); } } } tk2dTileMapToolbar.MainMode pushedToolbarMainMode = tk2dTileMapToolbar.MainMode.Brush; bool pencilDragActive = false; tk2dTileMapToolbar.ColorBlendMode pushedToolbarColorBlendMode = tk2dTileMapToolbar.ColorBlendMode.Replace; bool hotkeyModeSwitchActive = false; void PencilDrag() { pencilDragActive = true; if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Cut || tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Eyedropper) { // fake hotkey so it will pop back to brush mode hotkeyModeSwitchActive = true; pushedToolbarMainMode = tk2dTileMapToolbar.MainMode.Brush; } host.BuildIncremental(); } void RectangleDragBegin() { } int RectangleDragSize() { if (!pencilDragActive) return 0; if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Brush || tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.BrushRandom) { return WorkingBrush.tiles.Length; } if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Erase || tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Cut) { int x0 = Mathf.Min(cursorX, cursorX0); int x1 = Mathf.Max(cursorX, cursorX0); int y0 = Mathf.Min(cursorY, cursorY0); int y1 = Mathf.Max(cursorY, cursorY0); return (x1 - x0) * (y1 - y0); } return 0; } void RectangleDragEnd() { if (!pencilDragActive) return; if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Brush || tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.BrushRandom) { SplatWorkingBrush(); } if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Eyedropper || tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Cut) { PickUpBrush(editorData.activeBrush, false); tk2dTileMapToolbar.workBrushFlipX = false; tk2dTileMapToolbar.workBrushFlipY = false; tk2dTileMapToolbar.workBrushRot90 = false; } if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Erase || tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Cut) { int x0 = Mathf.Min(cursorX, cursorX0); int x1 = Mathf.Max(cursorX, cursorX0); int y0 = Mathf.Min(cursorY, cursorY0); int y1 = Mathf.Max(cursorY, cursorY0); if (scratchpadGUI.workingHere) { scratchpadGUI.EraseTiles(x0, y0, x1, y1); } else { tileMap.DeleteSprites(editorData.layer, x0, y0, x1, y1); } } host.BuildIncremental(); pencilDragActive = false; } void CheckVisible(int layer) { if (tileMap != null && tileMap.Layers != null && layer < tileMap.Layers.Length && tileMap.Layers[layer].gameObject != null && tk2dEditorUtility.IsGameObjectActive(tileMap.Layers[layer].gameObject) == false) { tk2dEditorUtility.SetGameObjectActive(tileMap.Layers[layer].gameObject, true); } } Vector2 tooltipPos = Vector2.zero; bool lastScratchpadOpen = false; bool openedScratchpadWithTab = false; float GetLayerDepth(int idx) { var layers = tileMapData.Layers; if (idx < 0 || idx >= layers.Length) return 0.0f; if (tileMapData.layersFixedZ) { return -(layers[idx].z); } else { float result = 0.0f; for (int i = 1; i <= idx; ++i) { result -= layers[idx].z; } return result; } } void UpdateScratchpadTileSizes() { if (scratchpadGUI != null && tileMap != null && tileMapData != null) { var spriteDef = tileMap.SpriteCollectionInst.FirstValidDefinition; if (spriteDef != null) scratchpadGUI.SetTileSizes(new Vector3(tileMapData.tileSize.x / spriteDef.texelSize.x, tileMapData.tileSize.y / spriteDef.texelSize.y, 0), spriteDef.texelSize); } } public void OnSceneGUI() { // Always draw the outline DrawOutline(); if (Application.isPlaying || !tileMap.AllowEdit) return; if (editorData.editMode == tk2dTileMapEditorData.EditMode.Settings) { return; } if (editorData.editMode != tk2dTileMapEditorData.EditMode.Paint && editorData.editMode != tk2dTileMapEditorData.EditMode.Color) return; if (editorData.editMode == tk2dTileMapEditorData.EditMode.Color && !tileMap.HasColorChannel()) return; if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.MouseDrag) tooltipPos = Event.current.mousePosition; UpdateScratchpadTileSizes(); // Scratchpad tilesort scratchpadGUI.SetTileSort(tileMapData.sortMethod == tk2dTileMapData.SortMethod.BottomLeft || tileMapData.sortMethod == tk2dTileMapData.SortMethod.TopLeft, tileMapData.sortMethod == tk2dTileMapData.SortMethod.BottomLeft || tileMapData.sortMethod == tk2dTileMapData.SortMethod.BottomRight); // Spritedef vars if (tileMap != null) { var spriteDef = tileMap.SpriteCollectionInst.FirstValidDefinition; if (spriteDef != null) { curSpriteDefTexelSize = spriteDef.texelSize; } } // Working brush / tile or paint cursor (behind scratchpad) switch (editorData.editMode) { case tk2dTileMapEditorData.EditMode.Paint: if (!scratchpadGUI.workingHere) { if (Event.current.type == EventType.Repaint) { Matrix4x4 matrix = tileMap.transform.localToWorldMatrix; // Brush mesh is offset so origin is at bottom left. Do the reverse here... // Also add layer depth float layerDepth = GetLayerDepth(editorData.layer); matrix *= Matrix4x4.TRS (tileMapData.tileOrigin + new Vector3(0, 0, layerDepth), Quaternion.identity, Vector3.one); BrushRenderer.DrawBrushInScene(matrix, WorkingBrush, 1000000); } DrawTileCursor(); } break; case tk2dTileMapEditorData.EditMode.Color: DrawPaintCursor(); break; } // Toolbar and scratchpad if (editorData.editMode == tk2dTileMapEditorData.EditMode.Paint) { Handles.BeginGUI(); GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height)); Event ev = Event.current; bool mouseOverToolbar = false; bool mouseOverScratchpad = false; GUILayout.BeginVertical(tk2dEditorSkin.GetStyle("TilemapToolbarBG"), GUILayout.Width(20), GUILayout.Height(34)); tk2dTileMapToolbar.ToolbarWindow(); GUILayout.EndVertical(); mouseOverToolbar = GUILayoutUtility.GetLastRect().Contains(ev.mousePosition); if (tk2dTileMapToolbar.scratchpadOpen) { GUILayout.BeginVertical(tk2dEditorSkin.GetStyle("TilemapToolbarBG"), GUILayout.Width(20), GUILayout.Height(Screen.height - 74)); scratchpadGUI.DrawGUI(); GUILayout.EndVertical(); mouseOverScratchpad = GUILayoutUtility.GetLastRect().Contains(ev.mousePosition); } if (ev.type == EventType.MouseMove) { scratchpadGUI.workingHere = mouseOverToolbar || mouseOverScratchpad; if (scratchpadGUI.workingHere) ev.Use(); } GUILayout.EndArea(); Handles.EndGUI(); } else { scratchpadGUI.workingHere = false; } // Draw Tooltip string curTooltip = ""; if (tk2dTileMapToolbar.tooltip.Length > 0) curTooltip = tk2dTileMapToolbar.tooltip; if (scratchpadGUI.tooltip.Length > 0) curTooltip = scratchpadGUI.tooltip; if (curTooltip.Length > 0 && scratchpadGUI.workingHere) { Handles.BeginGUI(); GUI.contentColor = Color.white; GUIContent tooltipContent = new GUIContent(curTooltip); Vector2 size = GUI.skin.GetStyle("label").CalcSize(tooltipContent); GUI.Label(new Rect(tooltipPos.x, tooltipPos.y + 20, size.x + 10, size.y + 5), curTooltip, "textarea"); Handles.EndGUI(); } if (tk2dTileMapToolbar.scratchpadOpen && !lastScratchpadOpen) { scratchpadGUI.FocusOnSearchFilter(openedScratchpadWithTab); } if (!tk2dTileMapToolbar.scratchpadOpen && lastScratchpadOpen) { openedScratchpadWithTab = false; } lastScratchpadOpen = tk2dTileMapToolbar.scratchpadOpen; int controlID = tileMapHashCode; if (tk2dTileMapToolbar.scratchpadOpen && scratchpadGUI.workingHere) { if (scratchpadGUI.doMouseDown) { GUIUtility.hotControl = controlID; randomSeed = Random.Range(0, int.MaxValue); cursorX0 = cursorX; cursorY0 = cursorY; PencilDrag(); RectangleDragBegin(); } if (scratchpadGUI.doMouseDrag) { UpdateCursorPosition(); UpdateWorkingBrush(); PencilDrag(); } if (scratchpadGUI.doMouseUp) { tk2dUndo.RecordObject(editorData, "Edit scratchpad"); RectangleDragEnd(); cursorX0 = cursorX; cursorY0 = cursorY; UpdateWorkingBrush(); GUIUtility.hotControl = 0; } if (scratchpadGUI.doMouseMove) { UpdateCursorPosition(); cursorX0 = cursorX; cursorY0 = cursorY; UpdateWorkingBrush(); } } else { EventType controlEventType = Event.current.GetTypeForControl(controlID); switch (controlEventType) { case EventType.MouseDown: case EventType.MouseDrag: if ((controlEventType == EventType.MouseDrag && GUIUtility.hotControl != controlID) || (Event.current.button != 0 && Event.current.button != 1)) { return; } // make sure we don't use up reserved combinations bool inhibitMouseDown = false; if (Application.platform == RuntimePlatform.OSXEditor) { if (Event.current.command && Event.current.alt) { // pan combination on mac inhibitMouseDown = true; } } if (Event.current.type == EventType.MouseDown && !inhibitMouseDown) { CheckVisible(editorData.layer); if (IsCursorInside() && !Event.current.shift) { if (editorData.editMode == tk2dTileMapEditorData.EditMode.Paint) { GUIUtility.hotControl = controlID; randomSeed = Random.Range(0, int.MaxValue); PencilDrag(); RectangleDragBegin(); } if (editorData.editMode == tk2dTileMapEditorData.EditMode.Color) { GUIUtility.hotControl = controlID; if (tk2dTileMapToolbar.colorBlendMode != tk2dTileMapToolbar.ColorBlendMode.Eyedropper) { tk2dUndo.RecordObject(tileMap, "Paint tile map"); PaintColorBrush((float)vertexCursorX, (float)vertexCursorY); host.BuildIncremental(); } } } } if (Event.current.type == EventType.MouseDrag && GUIUtility.hotControl == controlID) { UpdateCursorPosition(); UpdateWorkingBrush(); if (editorData.editMode == tk2dTileMapEditorData.EditMode.Paint) { PencilDrag(); } if (editorData.editMode == tk2dTileMapEditorData.EditMode.Color) { if (tk2dTileMapToolbar.colorBlendMode != tk2dTileMapToolbar.ColorBlendMode.Eyedropper) { tk2dUndo.RecordObject(tileMap, "Paint tile map"); PaintColorBrush((float)vertexCursorX, (float)vertexCursorY); host.BuildIncremental(); } } } break; case EventType.MouseUp: if ((Event.current.button == 0 || Event.current.button == 1) && GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; if (editorData.editMode == tk2dTileMapEditorData.EditMode.Paint) { if (RectangleDragSize() > 50) { tk2dUndo.RegisterCompleteObjectUndo(tileMap, "Edit tile map"); } else { tk2dUndo.RecordObject(tileMap, "Edit tile map"); } RectangleDragEnd(); } if (editorData.editMode == tk2dTileMapEditorData.EditMode.Color) { if (tk2dTileMapToolbar.colorBlendMode == tk2dTileMapToolbar.ColorBlendMode.Eyedropper) { PickUpColor(); } } cursorX0 = cursorX; cursorY0 = cursorY; UpdateWorkingBrush(); HandleUtility.Repaint(); } break; case EventType.Layout: //HandleUtility.AddDefaultControl(controlID); break; case EventType.MouseMove: UpdateCursorPosition(); cursorX0 = cursorX; cursorY0 = cursorY; UpdateWorkingBrush(); break; } } // Set cursor color based on toolbar main mode bool updateCursorColor = false; if (currentModeForBrushColor != (int)tk2dTileMapToolbar.mainMode) { currentModeForBrushColor = (int)tk2dTileMapToolbar.mainMode; updateCursorColor = true; } if (tk2dPreferencesEditor.CheckTilemapCursorColorUpdate()) { updateCursorColor = true; } if (updateCursorColor) { switch (tk2dTileMapToolbar.mainMode) { case tk2dTileMapToolbar.MainMode.Brush: tileSelectionFillColor = tk2dPreferences.inst.tileMapToolColor_brush; break; case tk2dTileMapToolbar.MainMode.BrushRandom: tileSelectionFillColor = tk2dPreferences.inst.tileMapToolColor_brushRandom; break; case tk2dTileMapToolbar.MainMode.Erase: tileSelectionFillColor = tk2dPreferences.inst.tileMapToolColor_erase; break; case tk2dTileMapToolbar.MainMode.Eyedropper: tileSelectionFillColor = tk2dPreferences.inst.tileMapToolColor_eyedropper; break; case tk2dTileMapToolbar.MainMode.Cut: tileSelectionFillColor = tk2dPreferences.inst.tileMapToolColor_cut; break; } tileSelectionOutlineColor = (tileSelectionFillColor + Color.white) * new Color(0.5f, 0.5f, 0.5f, 1.0f); } // Hotkeys switch the static toolbar mode { bool pickupKeyDown = (Application.platform == RuntimePlatform.OSXEditor)?Event.current.control:Event.current.alt; if (Event.current.button == 1) pickupKeyDown = true; bool eraseKeyDown = false; if (Application.platform == RuntimePlatform.OSXEditor) { if (Event.current.command && !Event.current.alt) eraseKeyDown = true; } else eraseKeyDown = Event.current.control; bool hotkeysPressed = pickupKeyDown || eraseKeyDown; if (editorData.editMode == tk2dTileMapEditorData.EditMode.Paint) { if (!pencilDragActive) { if (hotkeysPressed) { if (!hotkeyModeSwitchActive) { // Push mode pushedToolbarMainMode = tk2dTileMapToolbar.mainMode; } if (pickupKeyDown) { if (eraseKeyDown) { pendingModeChange = delegate(int i) { tk2dTileMapToolbar.mainMode = tk2dTileMapToolbar.MainMode.Cut; hotkeyModeSwitchActive = true; }; } else { pendingModeChange = delegate(int i) { tk2dTileMapToolbar.mainMode = tk2dTileMapToolbar.MainMode.Eyedropper; hotkeyModeSwitchActive = true; }; } } else if (eraseKeyDown) { pendingModeChange = delegate(int i) { tk2dTileMapToolbar.mainMode = tk2dTileMapToolbar.MainMode.Erase; hotkeyModeSwitchActive = true; }; } } else { if (hotkeyModeSwitchActive) { // Pop mode pendingModeChange = delegate(int i) { tk2dTileMapToolbar.mainMode = pushedToolbarMainMode; hotkeyModeSwitchActive = false; }; } } } } if (editorData.editMode == tk2dTileMapEditorData.EditMode.Color) { if (hotkeysPressed) { if (!hotkeyModeSwitchActive) { // Push mode pushedToolbarColorBlendMode = tk2dTileMapToolbar.colorBlendMode; if (pickupKeyDown) { tk2dTileMapToolbar.colorBlendMode = tk2dTileMapToolbar.ColorBlendMode.Eyedropper; hotkeyModeSwitchActive = true; } else if (eraseKeyDown) { switch (tk2dTileMapToolbar.colorBlendMode) { case tk2dTileMapToolbar.ColorBlendMode.Addition: tk2dTileMapToolbar.colorBlendMode = tk2dTileMapToolbar.ColorBlendMode.Subtraction; break; case tk2dTileMapToolbar.ColorBlendMode.Subtraction: tk2dTileMapToolbar.colorBlendMode = tk2dTileMapToolbar.ColorBlendMode.Addition; break; } hotkeyModeSwitchActive = true; } } } else { if (hotkeyModeSwitchActive) { tk2dTileMapToolbar.colorBlendMode = pushedToolbarColorBlendMode; hotkeyModeSwitchActive = false; } } } } // Hotkeys toggle flipping, scratchpad, paint { Event ev = Event.current; if (ev.type == EventType.KeyDown) { if (ev.keyCode == KeyCode.Tab) { if (!tk2dTileMapToolbar.scratchpadOpen) { pendingModeChange = delegate(int i) { tk2dTileMapToolbar.scratchpadOpen = !tk2dTileMapToolbar.scratchpadOpen; if (tk2dTileMapToolbar.scratchpadOpen) openedScratchpadWithTab = true; }; } } switch (ev.character) { case 'h': ev.Use(); tk2dTileMapToolbar.workBrushFlipX = !tk2dTileMapToolbar.workBrushFlipX; UpdateWorkingBrush(); break; case 'j': ev.Use(); tk2dTileMapToolbar.workBrushFlipY = !tk2dTileMapToolbar.workBrushFlipY; UpdateWorkingBrush(); break; case '[': ev.Use(); tk2dTileMapToolbar.colorBrushRadius -= 0.5f; if (tk2dTileMapToolbar.colorBrushRadius < 1.0f) tk2dTileMapToolbar.colorBrushRadius = 1.0f; break; case ']': ev.Use(); tk2dTileMapToolbar.colorBrushRadius += 0.5f; break; case '-': case '_': ev.Use(); tk2dTileMapToolbar.colorBrushIntensity -= 0.01f; break; case '=': case '+': ev.Use(); tk2dTileMapToolbar.colorBrushIntensity += 0.01f; break; } } if (scratchpadGUI.requestClose) { scratchpadGUI.requestClose = false; pendingModeChange = delegate(int i) { tk2dTileMapToolbar.scratchpadOpen = false; }; } } // Hotkey (enter) selects scratchpad tiles if (scratchpadGUI.requestSelectAllTiles) { // fake mouse coords scratchpadGUI.GetTilesCropRect(out cursorX, out cursorY, out cursorX0, out cursorY0); PickUpBrush(editorData.activeBrush, false); tk2dTileMapToolbar.workBrushFlipX = false; tk2dTileMapToolbar.workBrushFlipY = false; tk2dTileMapToolbar.workBrushRot90 = false; scratchpadGUI.requestSelectAllTiles = false; } if (pendingModeChange != null && Event.current.type == EventType.Repaint) { pendingModeChange(0); pendingModeChange = null; UpdateWorkingBrush(); HandleUtility.Repaint(); } } System.Action<int> pendingModeChange = null; void SplatTile(int x, int y, int layerId, int spriteId) { if (scratchpadGUI.workingHere) { scratchpadGUI.SplatTile(x, y, spriteId); } else { if (x >= 0 && x < tileMap.width && y >= 0 && y < tileMap.height && layerId >= 0 && layerId < tileMap.data.NumLayers) { var layer = tileMap.Layers[layerId]; layer.SetRawTile(x, y, spriteId); } } } int randomSeed = 0; public void UpdateWorkingBrush() { tk2dTileMapEditorBrush workBrush = WorkingBrush; tk2dTileMapEditorBrush activeBrush = editorData.activeBrush; int rectX1 = Mathf.Min(cursorX, cursorX0); int rectX2 = Mathf.Max(cursorX, cursorX0); int rectY1 = Mathf.Min(cursorY, cursorY0); int rectY2 = Mathf.Max(cursorY, cursorY0); int xoffset = 0; if (tileMap.data.tileType == tk2dTileMapData.TileType.Isometric && (cursorY & 1) == 1) xoffset = 1; workBrush.tiles = new tk2dSparseTile[0]; tk2dSparseTile[] srcTiles; if (activeBrush.type != tk2dTileMapEditorBrush.Type.MultiSelect) { srcTiles = activeBrush.tiles; } else { int n = activeBrush.multiSelectTiles.Length; srcTiles = new tk2dSparseTile[n]; for (int i = 0; i < n; ++i) { srcTiles[i] = new tk2dSparseTile(i, 0, editorData.layer, activeBrush.multiSelectTiles[i]); } } if (srcTiles.Length == 0) { workBrush.UpdateBrushHash(); return; } bool flipH = tk2dTileMapToolbar.workBrushFlipX; bool flipV = tk2dTileMapToolbar.workBrushFlipY; bool rot90 = tk2dTileMapToolbar.workBrushRot90; if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.Brush) { if (rectX1 == rectX2 && rectY1 == rectY2) { int nTiles = srcTiles.Length; workBrush.tiles = new tk2dSparseTile[nTiles]; for (int i = 0; i < nTiles; ++i) { int spriteId = srcTiles[i].spriteId; int tx = srcTiles[i].x; int ty = srcTiles[i].y; if (rot90) { int tmp = tx; tx = ty; ty = -tmp; tk2dRuntime.TileMap.BuilderUtil.SetRawTileFlag(ref spriteId, tk2dTileFlags.Rot90, true); } if (flipH) { tx = -tx; tk2dRuntime.TileMap.BuilderUtil.InvertRawTileFlag(ref spriteId, tk2dTileFlags.FlipX); } if (flipV) { ty = -ty; tk2dRuntime.TileMap.BuilderUtil.InvertRawTileFlag(ref spriteId, tk2dTileFlags.FlipY); } int thisRowXOffset = ((ty & 1) == 1) ? xoffset : 0; workBrush.tiles[i] = new tk2dSparseTile( cursorX + tx + thisRowXOffset, cursorY + ty, editorData.layer, spriteId ); } } else { int gridWidth = 1 + rectX2 - rectX1; int gridHeight = 1 + rectY2 - rectY1; workBrush.tiles = new tk2dSparseTile[gridWidth * gridHeight]; // fill with tiles repeated pattern... int patternX1 = 0; int patternY1 = 0; int patternX2 = 0; int patternY2 = 0; foreach (var tile in srcTiles) { patternX1 = Mathf.Min (patternX1, tile.x); patternY1 = Mathf.Min (patternY1, tile.y); patternX2 = Mathf.Max (patternX2, tile.x); patternY2 = Mathf.Max (patternY2, tile.y); } int patternW = 1 + patternX2 - patternX1; int patternH = 1 + patternY2 - patternY1; int idx = 0; for (int y = 0; y < gridHeight; ++y) { int thisRowXOffset = ((y & 1) == 1) ? xoffset : 0; for (int x = 0; x < gridWidth; ++x) { int spriteId = srcTiles[0].spriteId; foreach (var tile in srcTiles) { if ((x % patternW) == (tile.x - patternX1) && (y % patternH) == (tile.y - patternY1)) { spriteId = tile.spriteId; break; } } if (rot90) tk2dRuntime.TileMap.BuilderUtil.SetRawTileFlag(ref spriteId, tk2dTileFlags.Rot90, true); if (flipH) tk2dRuntime.TileMap.BuilderUtil.InvertRawTileFlag(ref spriteId, tk2dTileFlags.FlipX); if (flipV) tk2dRuntime.TileMap.BuilderUtil.InvertRawTileFlag(ref spriteId, tk2dTileFlags.FlipY); workBrush.tiles[idx++] = new tk2dSparseTile( rectX1 + x + thisRowXOffset, rectY1 + y, editorData.layer, spriteId); } } } } if (tk2dTileMapToolbar.mainMode == tk2dTileMapToolbar.MainMode.BrushRandom) { int gridWidth = 1 + rectX2 - rectX1; int gridHeight = 1 + rectY2 - rectY1; workBrush.tiles = new tk2dSparseTile[gridWidth * gridHeight]; var rng = new System.Random(randomSeed + cursorY * tileMap.width + cursorX); int idx = 0; for (int y = 0; y < gridHeight; ++y) { int thisRowXOffset = ((y & 1) == 1) ? xoffset : 0; for (int x = 0; x < gridWidth; ++x) { int spriteId = srcTiles[rng.Next(srcTiles.Length)].spriteId; if (rot90) tk2dRuntime.TileMap.BuilderUtil.SetRawTileFlag(ref spriteId, tk2dTileFlags.Rot90, true); if (flipH) tk2dRuntime.TileMap.BuilderUtil.InvertRawTileFlag(ref spriteId, tk2dTileFlags.FlipX); if (flipV) tk2dRuntime.TileMap.BuilderUtil.InvertRawTileFlag(ref spriteId, tk2dTileFlags.FlipY); workBrush.tiles[idx++] = new tk2dSparseTile( rectX1 + x + thisRowXOffset, rectY1 + y, editorData.layer, spriteId); } } } if (scratchpadGUI.workingHere) { int scratchW, scratchH; scratchpadGUI.GetScratchpadSize(out scratchW, out scratchH); workBrush.ClipTiles(0, 0, scratchW - 1, scratchH - 1); } else { workBrush.ClipTiles(0, 0, tileMap.width - 1, tileMap.height - 1); } workBrush.SortTiles(tileMapData.sortMethod == tk2dTileMapData.SortMethod.BottomLeft || tileMapData.sortMethod == tk2dTileMapData.SortMethod.TopLeft, tileMapData.sortMethod == tk2dTileMapData.SortMethod.BottomLeft || tileMapData.sortMethod == tk2dTileMapData.SortMethod.BottomRight); workBrush.UpdateBrushHash(); } void PickUpBrush(tk2dTileMapEditorBrush brush, bool allLayers) { bool pickFromScratchpad = (scratchpadGUI.workingHere || scratchpadGUI.requestSelectAllTiles); int x0 = Mathf.Min(cursorX, cursorX0); int x1 = Mathf.Max(cursorX, cursorX0); int y0 = Mathf.Min(cursorY, cursorY0); int y1 = Mathf.Max(cursorY, cursorY0); if (pickFromScratchpad) { // Clamp to scratchpad int scratchW, scratchH; scratchpadGUI.GetScratchpadSize(out scratchW, out scratchH); x0 = Mathf.Clamp(x0, 0, scratchW - 1); y0 = Mathf.Clamp(y0, 0, scratchH - 1); x1 = Mathf.Clamp(x1, 0, scratchW - 1); y1 = Mathf.Clamp(y1, 0, scratchH - 1); } else { // Clamp to tilemap x0 = Mathf.Clamp(x0, 0, tileMap.width - 1); y0 = Mathf.Clamp(y0, 0, tileMap.height - 1); x1 = Mathf.Clamp(x1, 0, tileMap.width - 1); y1 = Mathf.Clamp(y1, 0, tileMap.height - 1); } int numTilesX = x1 - x0 + 1; int numTilesY = y1 - y0 + 1; List<tk2dSparseTile> sparseTile = new List<tk2dSparseTile>(); List<int> tiles = new List<int>(); int numLayers = tileMap.data.NumLayers; int startLayer = 0; int endLayer = numLayers; if (allLayers) { brush.multiLayer = true; } else { brush.multiLayer = false; startLayer = editorData.layer; endLayer = startLayer + 1; } // Scratchpad only allows one layer for now if (pickFromScratchpad) { startLayer = 0; endLayer = 1; } if (tileMap.data.tileType == tk2dTileMapData.TileType.Rectangular) { for (int layer = startLayer; layer < endLayer; ++layer) { for (int y = numTilesY - 1; y >= 0; --y) { for (int x = 0; x < numTilesX; ++x) { int tile; if (pickFromScratchpad) { tile = scratchpadGUI.GetTile(x0 + x, y0 + y, layer); } else { tile = tileMap.Layers[layer].GetRawTile(x0 + x, y0 + y); } tiles.Add(tile); sparseTile.Add(new tk2dSparseTile(x, y, allLayers?layer:0, tile)); } } } } else if (tileMap.data.tileType == tk2dTileMapData.TileType.Isometric) { int xOffset = 0; int yOffset = 0; if ((y0 & 1) != 0) yOffset -= 1; for (int layer = startLayer; layer < endLayer; ++layer) { for (int y = numTilesY - 1; y >= 0; --y) { for (int x = 0; x < numTilesX; ++x) { int tile; if (pickFromScratchpad) { tile = scratchpadGUI.GetTile(x0 + x, y0 + y, layer); } else { tile = tileMap.Layers[layer].GetRawTile(x0 + x, y0 + y); } tiles.Add(tile); sparseTile.Add(new tk2dSparseTile(x + xOffset, y + yOffset, allLayers?layer:0, tile)); } } } } brush.type = tk2dTileMapEditorBrush.Type.Custom; if (numTilesX == 1 && numTilesY == 3) brush.edgeMode = tk2dTileMapEditorBrush.EdgeMode.Vertical; else if (numTilesX == 3 && numTilesY == 1) brush.edgeMode = tk2dTileMapEditorBrush.EdgeMode.Horizontal; else if (numTilesX == 3 && numTilesY == 3) brush.edgeMode = tk2dTileMapEditorBrush.EdgeMode.Square; else brush.edgeMode = tk2dTileMapEditorBrush.EdgeMode.None; brush.tiles = sparseTile.ToArray(); brush.multiSelectTiles = tiles.ToArray(); brush.UpdateBrushHash(); // Make the inspector update tk2dUtil.SetDirty(tileMap); } void PaintColorBrush(float x, float y) { float maskR = 1.0f; float maskG = 1.0f; float maskB = 1.0f; Color src = tk2dTileMapToolbar.colorBrushColor; switch (tk2dTileMapToolbar.colorChannelsMode) { case tk2dTileMapToolbar.ColorChannelsMode.Red: maskG = maskB = 0.0f; src.r = 1.0f; break; case tk2dTileMapToolbar.ColorChannelsMode.Green: maskR = maskB = 0.0f; src.g = 1.0f; break; case tk2dTileMapToolbar.ColorChannelsMode.Blue: maskR = maskG = 0.0f; src.b = 1.0f; break; } var colorGrid = tileMap.ColorChannel; float r = tk2dTileMapToolbar.colorBrushRadius; int x1 = Mathf.Max((int)Mathf.Floor(x - r), 0); int y1 = Mathf.Max((int)Mathf.Floor(y - r), 0); int x2 = Mathf.Min((int)Mathf.Ceil(x + r), tileMap.width); int y2 = Mathf.Min((int)Mathf.Ceil(y + r), tileMap.height); for (int py = y1; py <= y2; ++py) { for (int px = x1; px <= x2; ++px) { float dx = x - (float)px; float dy = y - (float)py; float a = 1.0f - Mathf.Sqrt(dx * dx + dy * dy) / r; if (a > 0.0f) { float alpha = tk2dTileMapToolbar.colorBrushCurve.Evaluate(a); alpha *= tk2dTileMapToolbar.colorBrushIntensity; float srcFactor = 0.0f; float dstFactor = 0.0f; switch (tk2dTileMapToolbar.colorBlendMode) { case tk2dTileMapToolbar.ColorBlendMode.Replace: srcFactor = alpha; dstFactor = 1.0f - alpha; break; case tk2dTileMapToolbar.ColorBlendMode.Addition: srcFactor = alpha; dstFactor = 1.0f; break; case tk2dTileMapToolbar.ColorBlendMode.Subtraction: srcFactor = -alpha; dstFactor = 1.0f; break; } Color dst = colorGrid.GetColor(px, py); float resultR = maskR * (src.r * srcFactor + dst.r * dstFactor) + (1.0f - maskR) * dst.r; float resultG = maskG * (src.g * srcFactor + dst.g * dstFactor) + (1.0f - maskG) * dst.g; float resultB = maskB * (src.b * srcFactor + dst.b * dstFactor) + (1.0f - maskB) * dst.b; colorGrid.SetColor(px, py, new Color(resultR, resultG, resultB)); } } } } void PickUpColor() { vertexCursorX = Mathf.Clamp(vertexCursorX, 0, tileMap.width - 1); vertexCursorY = Mathf.Clamp(vertexCursorY, 0, tileMap.height - 1); tk2dTileMapToolbar.colorBrushColor = tileMap.ColorChannel.GetColor(vertexCursorX, vertexCursorY); } }
using System.Threading; using Lucene.Net.Support; using System; using System.Diagnostics; using System.IO; namespace Lucene.Net.Store { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /// <summary> /// An <seealso cref="FSDirectory"/> implementation that uses java.nio's FileChannel's /// positional read, which allows multiple threads to read from the same file /// without synchronizing. /// <p> /// this class only uses FileChannel when reading; writing is achieved with /// <seealso cref="FSDirectory.FSIndexOutput"/>. /// <p> /// <b>NOTE</b>: NIOFSDirectory is not recommended on Windows because of a bug in /// how FileChannel.read is implemented in Sun's JRE. Inside of the /// implementation the position is apparently synchronized. See <a /// href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6265734">here</a> /// for details. /// </p> /// <p> /// <font color="red"><b>NOTE:</b> Accessing this class either directly or /// indirectly from a thread while it's interrupted can close the /// underlying file descriptor immediately if at the same time the thread is /// blocked on IO. The file descriptor will remain closed and subsequent access /// to <seealso cref="NIOFSDirectory"/> will throw a <seealso cref="ClosedChannelException"/>. If /// your application uses either <seealso cref="Thread#interrupt()"/> or /// <seealso cref="Future#cancel(boolean)"/> you should use <seealso cref="SimpleFSDirectory"/> in /// favor of <seealso cref="NIOFSDirectory"/>.</font> /// </p> /// </summary> public class NIOFSDirectory : FSDirectory { /// <summary> /// Create a new NIOFSDirectory for the named location. /// </summary> /// <param name="path"> the path of the directory </param> /// <param name="lockFactory"> the lock factory to use, or null for the default /// (<seealso cref="NativeFSLockFactory"/>); </param> /// <exception cref="System.IO.IOException"> if there is a low-level I/O error </exception> public NIOFSDirectory(DirectoryInfo path, LockFactory lockFactory) : base(path, lockFactory) { } /// <summary> /// Create a new NIOFSDirectory for the named location and <seealso cref="NativeFSLockFactory"/>. /// </summary> /// <param name="path"> the path of the directory </param> /// <exception cref="System.IO.IOException"> if there is a low-level I/O error </exception> public NIOFSDirectory(DirectoryInfo path) : base(path, null) { } /// <summary> /// Creates an IndexInput for the file with the given name. </summary> public override IndexInput OpenInput(string name, IOContext context) { EnsureOpen(); var path = new FileInfo(Path.Combine(Directory.FullName, name)); var fc = new FileStream(path.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return new NIOFSIndexInput("NIOFSIndexInput(path=\"" + path + "\")", fc, context); } public override IndexInputSlicer CreateSlicer(string name, IOContext context) { EnsureOpen(); var path = new FileInfo(Path.Combine(Directory.FullName, name)); var fc = new FileStream(path.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return new IndexInputSlicerAnonymousInnerClassHelper(this, context, path, fc); } private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer { private readonly IOContext Context; private readonly FileInfo Path; private readonly FileStream Descriptor; public IndexInputSlicerAnonymousInnerClassHelper(NIOFSDirectory outerInstance, IOContext context, FileInfo path, FileStream descriptor) : base(outerInstance) { this.Context = context; this.Path = path; this.Descriptor = descriptor; } public override void Dispose(bool disposing) { if (disposing) { Descriptor.Close(); } } public override IndexInput OpenSlice(string sliceDescription, long offset, long length) { return new NIOFSIndexInput("NIOFSIndexInput(" + sliceDescription + " in path=\"" + Path + "\" slice=" + offset + ":" + (offset + length) + ")", Descriptor, offset, length, BufferedIndexInput.BufferSize(Context)); } public override IndexInput OpenFullSlice() { try { return OpenSlice("full-slice", 0, Descriptor.Length); } catch (IOException ex) { throw new Exception(ex.Message, ex); } } } /// <summary> /// Reads bytes with <seealso cref="FileChannel#read(ByteBuffer, long)"/> /// </summary> protected internal class NIOFSIndexInput : BufferedIndexInput { /// <summary> /// The maximum chunk size for reads of 16384 bytes. /// </summary> internal const int CHUNK_SIZE = 16384; /// <summary> /// the file channel we will read from </summary> protected internal readonly FileStream Channel; /// <summary> /// is this instance a clone and hence does not own the file to close it </summary> internal bool IsClone = false; /// <summary> /// start offset: non-zero in the slice case </summary> protected internal readonly long Off; /// <summary> /// end offset (start+length) </summary> protected internal readonly long End; internal ByteBuffer ByteBuf; // wraps the buffer for NIO public NIOFSIndexInput(string resourceDesc, FileStream fc, IOContext context) : base(resourceDesc, context) { this.Channel = fc; this.Off = 0L; this.End = fc.Length; } public NIOFSIndexInput(string resourceDesc, FileStream fc, long off, long length, int bufferSize) : base(resourceDesc, bufferSize) { this.Channel = fc; this.Off = off; this.End = off + length; this.IsClone = true; } public override void Dispose() { if (!IsClone) { Channel.Close(); } } public override object Clone() { NIOFSIndexInput clone = (NIOFSIndexInput)base.Clone(); clone.IsClone = true; return clone; } public override sealed long Length() { return End - Off; } protected internal override void NewBuffer(byte[] newBuffer) { base.NewBuffer(newBuffer); ByteBuf = ByteBuffer.Wrap((byte[])(Array)newBuffer); } protected internal override void ReadInternal(byte[] b, int offset, int len) { ByteBuffer bb; // Determine the ByteBuffer we should use if (b == Buffer && 0 == offset) { // Use our own pre-wrapped byteBuf: Debug.Assert(ByteBuf != null); ByteBuf.Clear(); ByteBuf.Limit = len; bb = ByteBuf; } else { bb = ByteBuffer.Wrap((byte[])(Array)b, offset, len); } int readOffset = bb.Position; int readLength = bb.Limit - readOffset; long pos = FilePointer + Off; if (pos + len > End) { throw new EndOfStreamException("read past EOF: " + this); } try { while (readLength > 0) { int limit; if (readLength > CHUNK_SIZE) { limit = readOffset + CHUNK_SIZE; } else { limit = readOffset + readLength; } bb.Limit = limit; int i = Channel.Read(bb, pos); if (i <= 0) // be defensive here, even though we checked before hand, something could have changed { throw new Exception("read past EOF: " + this + " off: " + offset + " len: " + len + " pos: " + pos + " chunkLen: " + readLength + " end: " + End); } pos += i; readOffset += i; readLength -= i; } Debug.Assert(readLength == 0); } catch (System.IO.IOException ioe) { throw new System.IO.IOException(ioe.Message + ": " + this, ioe); } } protected override void SeekInternal(long pos) { } } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Mono.Debugger.Soft { public class InvokeResult { public Value Result { get; set; } // // The value of the receiver after the call for calls to valuetype methods or null. // Only set when using the InvokeOptions.ReturnOutThis flag. // Since protocol version 2.35 // public Value OutThis { get; set; } // // The value of the arguments after the call // Only set when using the InvokeOptions.ReturnOutArgs flag. // Since protocol version 2.35 // public Value[] OutArgs { get; set; } } public interface IInvokable { Value InvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments); Value InvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options); IAsyncResult BeginInvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options, AsyncCallback callback, object state); Value EndInvokeMethod (IAsyncResult asyncResult); InvokeResult EndInvokeMethodWithResult (IAsyncResult asyncResult); Task<Value> InvokeMethodAsync (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options = InvokeOptions.None); Task<InvokeResult> InvokeMethodAsyncWithResult (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options = InvokeOptions.None); } public class ObjectMirror : Value, IInvokable { TypeMirror type; AppDomainMirror domain; internal ObjectMirror (VirtualMachine vm, long id) : base (vm, id) { } internal ObjectMirror (VirtualMachine vm, long id, TypeMirror type, AppDomainMirror domain) : base (vm, id) { this.type = type; this.domain = domain; } void GetInfo () { var info = vm.conn.Object_GetInfo (id); type = vm.GetType (info.type_id); domain = vm.GetDomain (info.domain_id); } public TypeMirror Type { get { if (type == null) { if (vm.conn.Version.AtLeast (2, 5)) GetInfo (); else type = vm.GetType (vm.conn.Object_GetType (id)); } return type; } } public AppDomainMirror Domain { get { if (domain == null) { if (vm.conn.Version.AtLeast (2, 5)) GetInfo (); else domain = vm.GetDomain (vm.conn.Object_GetDomain (id)); } return domain; } } public bool IsCollected { get { return vm.conn.Object_IsCollected (id); } } public Value GetValue (FieldInfoMirror field) { return GetValues (new FieldInfoMirror [] { field }) [0]; } public Value[] GetValues (IList<FieldInfoMirror> fields) { if (fields == null) throw new ArgumentNullException ("fields"); foreach (FieldInfoMirror f in fields) { if (f == null) throw new ArgumentNullException ("field"); CheckMirror (f); } long[] ids = new long [fields.Count]; for (int i = 0; i < fields.Count; ++i) ids [i] = fields [i].Id; try { return vm.DecodeValues (vm.conn.Object_GetValues (id, ids)); } catch (CommandException ex) { if (ex.ErrorCode == ErrorCode.INVALID_FIELDID) { if (fields.Count == 1) throw new ArgumentException (string.Format ("The field '{0}' is not valid for this type.", fields[0].Name)); throw new ArgumentException ("One of the fields is not valid for this type.", "fields"); } else throw; } } public void SetValues (IList<FieldInfoMirror> fields, Value[] values) { if (fields == null) throw new ArgumentNullException ("fields"); if (values == null) throw new ArgumentNullException ("values"); foreach (FieldInfoMirror f in fields) { if (f == null) throw new ArgumentNullException ("field"); CheckMirror (f); } foreach (Value v in values) { if (v == null) throw new ArgumentNullException ("values"); CheckMirror (v); } long[] ids = new long [fields.Count]; for (int i = 0; i < fields.Count; ++i) ids [i] = fields [i].Id; try { vm.conn.Object_SetValues (id, ids, vm.EncodeValues (values)); } catch (CommandException ex) { if (ex.ErrorCode == ErrorCode.INVALID_FIELDID) throw new ArgumentException ("One of the fields is not valid for this type.", "fields"); else if (ex.ErrorCode == ErrorCode.INVALID_ARGUMENT) throw new ArgumentException ("One of the values is not valid for its field.", "values"); else throw; } } public void SetValue (FieldInfoMirror field, Value value) { SetValues (new FieldInfoMirror [] { field }, new Value [] { value }); } /* * The current address of the object. It can change during garbage * collections. Use a long since the debuggee might have a different * pointer size. */ public long Address { get { return vm.conn.Object_GetAddress (id); } } public Value InvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments) { return InvokeMethod (vm, thread, method, this, arguments, InvokeOptions.None); } public Value InvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options) { return InvokeMethod (vm, thread, method, this, arguments, options); } [Obsolete ("Use the overload without the 'vm' argument")] public IAsyncResult BeginInvokeMethod (VirtualMachine vm, ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options, AsyncCallback callback, object state) { return BeginInvokeMethod (vm, thread, method, this, arguments, options, callback, state); } public IAsyncResult BeginInvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options, AsyncCallback callback, object state) { return BeginInvokeMethod (vm, thread, method, this, arguments, options, callback, state); } public Value EndInvokeMethod (IAsyncResult asyncResult) { return EndInvokeMethodInternal (asyncResult); } public InvokeResult EndInvokeMethodWithResult (IAsyncResult asyncResult) { return ObjectMirror.EndInvokeMethodInternalWithResult (asyncResult); } public Task<Value> InvokeMethodAsync (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options = InvokeOptions.None) { return InvokeMethodAsync (vm, thread, method, this, arguments, options); } internal static Task<Value> InvokeMethodAsync (VirtualMachine vm, ThreadMirror thread, MethodMirror method, Value this_obj, IList<Value> arguments, InvokeOptions options) { return InvokeMethodAsync (vm, thread, method, this_obj, arguments, options, EndInvokeMethodInternal); } public Task<InvokeResult> InvokeMethodAsyncWithResult (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options = InvokeOptions.None) { return InvokeMethodAsyncWithResult (vm, thread, method, this, arguments, options); } internal static Task<InvokeResult> InvokeMethodAsyncWithResult (VirtualMachine vm, ThreadMirror thread, MethodMirror method, Value this_obj, IList<Value> arguments, InvokeOptions options) { return InvokeMethodAsync (vm, thread, method, this_obj, arguments, options, EndInvokeMethodInternalWithResult); } internal static Task<TResult> InvokeMethodAsync<TResult> (VirtualMachine vm, ThreadMirror thread, MethodMirror method, Value this_obj, IList<Value> arguments, InvokeOptions options, Func<IAsyncResult, TResult> callback) { var tcs = new TaskCompletionSource<TResult> (); BeginInvokeMethod (vm, thread, method, this_obj, arguments, options, iar => { try { tcs.SetResult (callback (iar)); } catch (OperationCanceledException) { tcs.TrySetCanceled (); } catch (Exception ex) { tcs.TrySetException (ex); } }, null); return tcs.Task; } // // Invoke the members of METHODS one-by-one, calling CALLBACK after each invoke was finished. The IAsyncResult will be marked as completed after all invokes have // finished. The callback will be called with a different IAsyncResult that represents one method invocation. // From protocol version 2.22. // public IAsyncResult BeginInvokeMultiple (ThreadMirror thread, MethodMirror[] methods, IList<IList<Value>> arguments, InvokeOptions options, AsyncCallback callback, object state) { return BeginInvokeMultiple (vm, thread, methods, this, arguments, options, callback, state); } public void EndInvokeMultiple (IAsyncResult asyncResult) { EndInvokeMultipleInternal (asyncResult); } /* * Common implementation for invokes */ class InvokeAsyncResult : IInvokeAsyncResult { public object AsyncState { get; set; } public WaitHandle AsyncWaitHandle { get; set; } public bool CompletedSynchronously { get { return false; } } public bool IsCompleted { get; set; } public AsyncCallback Callback { get; set; } public ErrorCode ErrorCode { get; set; } public VirtualMachine VM { get; set; } public ThreadMirror Thread { get; set; } public ValueImpl Value { get; set; } public ValueImpl OutThis { get; set; } public ValueImpl[] OutArgs { get; set; } public ValueImpl Exception { get; set; } public int ID { get; set; } public bool IsMultiple { get; set; } public int NumPending; public void Abort () { if (ID == 0) // Ooops return; ObjectMirror.AbortInvoke (VM, Thread, ID); } } internal static IInvokeAsyncResult BeginInvokeMethod (VirtualMachine vm, ThreadMirror thread, MethodMirror method, Value this_obj, IList<Value> arguments, InvokeOptions options, AsyncCallback callback, object state) { if (thread == null) throw new ArgumentNullException ("thread"); if (method == null) throw new ArgumentNullException ("method"); if (arguments == null) arguments = new Value [0]; InvokeFlags f = InvokeFlags.NONE; if ((options & InvokeOptions.DisableBreakpoints) != 0) f |= InvokeFlags.DISABLE_BREAKPOINTS; if ((options & InvokeOptions.SingleThreaded) != 0) f |= InvokeFlags.SINGLE_THREADED; if ((options & InvokeOptions.ReturnOutThis) != 0) f |= InvokeFlags.OUT_THIS; if ((options & InvokeOptions.ReturnOutArgs) != 0) f |= InvokeFlags.OUT_ARGS; if ((options & InvokeOptions.Virtual) != 0) f |= InvokeFlags.VIRTUAL; InvokeAsyncResult r = new InvokeAsyncResult { AsyncState = state, AsyncWaitHandle = new ManualResetEvent (false), VM = vm, Thread = thread, Callback = callback }; thread.InvalidateFrames (); r.ID = vm.conn.VM_BeginInvokeMethod (thread.Id, method.Id, this_obj != null ? vm.EncodeValue (this_obj) : vm.EncodeValue (vm.CreateValue (null)), vm.EncodeValues (arguments), f, InvokeCB, r); return r; } // This is called when the result of an invoke is received static void InvokeCB (ValueImpl v, ValueImpl exc, ValueImpl out_this, ValueImpl[] out_args, ErrorCode error, object state) { InvokeAsyncResult r = (InvokeAsyncResult)state; if (error != 0) { r.ErrorCode = error; } else { r.Value = v; r.Exception = exc; } r.OutThis = out_this; r.OutArgs = out_args; r.IsCompleted = true; ((ManualResetEvent)r.AsyncWaitHandle).Set (); if (r.Callback != null) Task.Run (() => r.Callback.Invoke (r)); } internal static InvokeResult EndInvokeMethodInternalWithResult (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); InvokeAsyncResult r = (InvokeAsyncResult)asyncResult; if (!r.IsCompleted) r.AsyncWaitHandle.WaitOne (); if (r.ErrorCode != 0) { try { r.VM.ErrorHandler (null, new ErrorHandlerEventArgs () { ErrorCode = r.ErrorCode }); } catch (CommandException ex) { if (ex.ErrorCode == ErrorCode.INVALID_ARGUMENT) throw new ArgumentException ("Incorrect number or types of arguments", "arguments"); throw; } throw new NotImplementedException (); } else { if (r.Exception != null) throw new InvocationException ((ObjectMirror)r.VM.DecodeValue (r.Exception)); //refresh frames from thread after running an invoke r.Thread.GetFrames(); Value out_this = null; if (r.OutThis != null) out_this = r.VM.DecodeValue (r.OutThis); Value[] out_args = null; if (r.OutArgs != null) out_args = r.VM.DecodeValues (r.OutArgs); return new InvokeResult () { Result = r.VM.DecodeValue (r.Value), OutThis = out_this, OutArgs = out_args }; } } internal static Value EndInvokeMethodInternal (IAsyncResult asyncResult) { InvokeResult res = EndInvokeMethodInternalWithResult (asyncResult); return res.Result; } internal static void EndInvokeMultipleInternal (IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); InvokeAsyncResult r = (InvokeAsyncResult)asyncResult; if (!r.IsCompleted) r.AsyncWaitHandle.WaitOne (); } internal static Value InvokeMethod (VirtualMachine vm, ThreadMirror thread, MethodMirror method, Value this_obj, IList<Value> arguments, InvokeOptions options) { return EndInvokeMethodInternal (BeginInvokeMethod (vm, thread, method, this_obj, arguments, options, null, null)); } internal static void AbortInvoke (VirtualMachine vm, ThreadMirror thread, int id) { vm.conn.VM_AbortInvoke (thread.Id, id); } // // Implementation of InvokeMultiple // internal static IInvokeAsyncResult BeginInvokeMultiple (VirtualMachine vm, ThreadMirror thread, MethodMirror[] methods, Value this_obj, IList<IList<Value>> arguments, InvokeOptions options, AsyncCallback callback, object state) { if (thread == null) throw new ArgumentNullException ("thread"); if (methods == null) throw new ArgumentNullException ("methods"); foreach (var m in methods) if (m == null) throw new ArgumentNullException ("method"); if (arguments == null) { arguments = new List<IList<Value>> (); for (int i = 0; i < methods.Length; ++i) arguments.Add (new Value [0]); } else { // FIXME: Not needed for property evaluation throw new NotImplementedException (); } if (callback == null) throw new ArgumentException ("A callback argument is required for this method.", "callback"); InvokeFlags f = InvokeFlags.NONE; if ((options & InvokeOptions.DisableBreakpoints) != 0) f |= InvokeFlags.DISABLE_BREAKPOINTS; if ((options & InvokeOptions.SingleThreaded) != 0) f |= InvokeFlags.SINGLE_THREADED; InvokeAsyncResult r = new InvokeAsyncResult { AsyncState = state, AsyncWaitHandle = new ManualResetEvent (false), VM = vm, Thread = thread, Callback = callback, NumPending = methods.Length, IsMultiple = true }; var mids = new long [methods.Length]; for (int i = 0; i < methods.Length; ++i) mids [i] = methods [i].Id; var args = new List<ValueImpl[]> (); for (int i = 0; i < methods.Length; ++i) args.Add (vm.EncodeValues (arguments [i])); thread.InvalidateFrames (); r.ID = vm.conn.VM_BeginInvokeMethods (thread.Id, mids, this_obj != null ? vm.EncodeValue (this_obj) : vm.EncodeValue (vm.CreateValue (null)), args, f, InvokeMultipleCB, r); return r; } // This is called when the result of an invoke is received static void InvokeMultipleCB (ValueImpl v, ValueImpl exc, ValueImpl out_this, ValueImpl[] out_args, ErrorCode error, object state) { var r = (InvokeAsyncResult)state; Interlocked.Decrement (ref r.NumPending); if (error != 0) r.ErrorCode = error; if (r.NumPending == 0) { r.IsCompleted = true; ((ManualResetEvent)r.AsyncWaitHandle).Set (); } // Have to pass another asyncresult to the callback since multiple threads can execute it concurrently with results of multiple invocations var r2 = new InvokeAsyncResult { AsyncState = r.AsyncState, AsyncWaitHandle = null, VM = r.VM, Thread = r.Thread, Callback = r.Callback, IsCompleted = true }; if (error != 0) { r2.ErrorCode = error; } else { r2.Value = v; r2.Exception = exc; } Task.Run (() => r.Callback.Invoke (r2)); } } }
/* ======================================================================= * vCard Library for .NET * Copyright (c) 2007-2009 David Pinch; http://wwww.thoughtproject.com * See LICENSE.TXT for licensing information. * ======================================================================= */ using System; using System.Collections.Generic; using System.IO; using Thought.vCards; namespace VcardLibrary { /// <summary> /// A vCard object for exchanging personal contact information. /// </summary> /// <remarks> /// <para> /// A vCard contains personal information, such as postal /// addresses, public security certificates, email addresses, and /// web sites. The vCard specification makes it possible for /// different computer programs to exchange personal contact /// information; for example, a vCard can be attached to an email or /// sent over a wireless connection. /// </para> /// <para> /// The standard vCard format is a text file with properties in /// name:value format. However, there are multiple versions of /// this format as well as compatible alternatives in XML and /// HTML formats. This class library aims to accomodate these /// variations but be aware some some formats do not support /// all possible properties. /// </para> /// </remarks> public class vCard { private vCardAccessClassification accessClassification; private string additionalNames; private DateTime? birthDate; private ICollection<string> categories; private string department; private string displayName; private string familyName; private string formattedName; private vCardGender gender; private string givenName; private float? latitude; private float? longitude; private string mailer; private string namePrefix; private string nameSuffix; private ICollection<string> nicknames; private string office; private string organization; private string productId; private DateTime? revisionDate; private string role; private string timeZone; private string title; private string uniqueId; private vCardCertificateCollection certificates; private vCardDeliveryAddressCollection deliveryAddresses; private vCardDeliveryLabelCollection deliveryLabels; private vCardEmailAddressCollection emailAddresses; private vCardNoteCollection notes; private vCardPhoneCollection phones; private vCardPhotoCollection photos; private vCardSourceCollection sources; private vCardWebsiteCollection websites; /// <summary> /// Initializes a new instance of the <see cref="vCard"/> class. /// </summary> public vCard() { // Per Microsoft best practices, string properties should // never return null. String properties should always // return String.Empty. this.additionalNames = string.Empty; this.department = string.Empty; this.displayName = string.Empty; this.familyName = string.Empty; this.formattedName = string.Empty; this.givenName = string.Empty; this.mailer = string.Empty; this.namePrefix = string.Empty; this.nameSuffix = string.Empty; this.office = string.Empty; this.organization = string.Empty; this.productId = string.Empty; this.role = string.Empty; this.timeZone = string.Empty; this.title = string.Empty; this.uniqueId = string.Empty; this.categories = new List<string>(); this.certificates = new vCardCertificateCollection(); this.deliveryAddresses = new vCardDeliveryAddressCollection(); this.deliveryLabels = new vCardDeliveryLabelCollection(); this.emailAddresses = new vCardEmailAddressCollection(); this.nicknames = new List<string>(); this.notes = new vCardNoteCollection(); this.phones = new vCardPhoneCollection(); this.photos = new vCardPhotoCollection(); this.sources = new vCardSourceCollection(); this.websites = new vCardWebsiteCollection(); } /// <summary> /// Loads a new instance of the <see cref="vCard"/> class /// from a text reader. /// </summary> /// <param name="input"> /// An initialized text reader. /// </param> public vCard(TextReader input) : this() { vCardReader reader = new vCardStandardReader(); reader.ReadInto(this, input); } ///// <summary> ///// Loads a new instance of the <see cref="vCard"/> class ///// from a text file. ///// </summary> ///// <param name="path"> ///// The path to a text file containing vCard data in ///// any recognized vCard format. ///// </param> //public vCard(string path) // : this() //{ // using (StreamReader streamReader = new StreamReader(path)) // { // vCardReader reader = new vCardStandardReader(); // reader.ReadInto(this, streamReader); // } //} /// <summary> /// The security access classification of the vCard owner (e.g. private). /// </summary> public vCardAccessClassification AccessClassification { get { return this.accessClassification; } set { this.accessClassification = value; } } /// <summary> /// Any additional (e.g. middle) names of the person. /// </summary> /// <seealso cref="FamilyName"/> /// <seealso cref="FormattedName"/> /// <seealso cref="GivenName"/> /// <seealso cref="Nicknames"/> public string AdditionalNames { get { return this.additionalNames ?? string.Empty; } set { this.additionalNames = value; } } /// <summary> /// The birthdate of the person. /// </summary> public DateTime? BirthDate { get { return this.birthDate; } set { this.birthDate = value; } } /// <summary> /// Categories of the vCard. /// </summary> /// <remarks> /// This property is a collection of strings containing /// keywords or category names. /// </remarks> public ICollection<string> Categories { get { return this.categories; } } /// <summary> /// Public key certificates attached to the vCard. /// </summary> /// <seealso cref="vCardCertificate"/> public vCardCertificateCollection Certificates { get { return this.certificates; } } /// <summary> /// Delivery addresses associated with the person. /// </summary> public vCardDeliveryAddressCollection DeliveryAddresses { get { return this.deliveryAddresses; } } /// <summary> /// Formatted delivery labels. /// </summary> public vCardDeliveryLabelCollection DeliveryLabels { get { return this.deliveryLabels; } } /// <summary> /// The department of the person in the organization. /// </summary> /// <seealso cref="Office"/> /// <seealso cref="Organization"/> public string Department { get { return this.department ?? string.Empty; } set { this.department = value; } } /// <summary> /// The display name of the vCard. /// </summary> /// <remarks> /// This property is used by vCard applications for titles, /// headers, and other visual elements. /// </remarks> public string DisplayName { get { return this.displayName ?? string.Empty; } set { this.displayName = value; } } /// <summary> /// A collection of <see cref="vCardEmailAddress"/> objects for the person. /// </summary> /// <seealso cref="vCardEmailAddress"/> public vCardEmailAddressCollection EmailAddresses { get { return this.emailAddresses; } } /// <summary> /// The family (last) name of the person. /// </summary> /// <seealso cref="AdditionalNames"/> /// <seealso cref="FormattedName"/> /// <seealso cref="GivenName"/> /// <seealso cref="Nicknames"/> public string FamilyName { get { return this.familyName ?? string.Empty; } set { this.familyName = value; } } /// <summary> /// The formatted name of the person. /// </summary> /// <remarks> /// This property allows the name of the person to be /// written in a manner specific to his or her culture. /// The formatted name is not required to strictly /// correspond with the family name, given name, etc. /// </remarks> /// <seealso cref="AdditionalNames"/> /// <seealso cref="FamilyName"/> /// <seealso cref="GivenName"/> /// <seealso cref="Nicknames"/> public string FormattedName { get { return this.formattedName ?? string.Empty; } set { this.formattedName = value; } } /// <summary> /// The gender of the person. /// </summary> /// <remarks> /// The vCard specification does not define a property /// to indicate the gender of the contact. Microsoft /// Outlook implements it as a custom property named /// X-WAB-GENDER. /// </remarks> /// <seealso cref="vCardGender"/> public vCardGender Gender { get { return this.gender; } set { this.gender = value; } } /// <summary> /// The given (first) name of the person. /// </summary> /// <seealso cref="AdditionalNames"/> /// <seealso cref="FamilyName"/> /// <seealso cref="FormattedName"/> /// <seealso cref="Nicknames"/> public string GivenName { get { return this.givenName ?? string.Empty; } set { this.givenName = value; } } /// <summary> /// The latitude of the person in decimal degrees. /// </summary> /// <seealso cref="Longitude"/> public float? Latitude { get { return this.latitude; } set { this.latitude = value; } } /// <summary> /// The longitude of the person in decimal degrees. /// </summary> /// <seealso cref="Latitude"/> public float? Longitude { get { return this.longitude; } set { this.longitude = value; } } /// <summary> /// The mail software used by the person. /// </summary> public string Mailer { get { return this.mailer ?? string.Empty; } set { this.mailer = value; } } /// <summary> /// The prefix (e.g. "Mr.") of the person. /// </summary> /// <seealso cref="NameSuffix"/> public string NamePrefix { get { return this.namePrefix ?? string.Empty; } set { this.namePrefix = value; } } /// <summary> /// The suffix (e.g. "Jr.") of the person. /// </summary> /// <seealso cref="NamePrefix"/> public string NameSuffix { get { return this.nameSuffix ?? string.Empty; } set { this.nameSuffix = value; } } /// <summary> /// A collection of nicknames for the person. /// </summary> /// <seealso cref="AdditionalNames"/> /// <seealso cref="FamilyName"/> /// <seealso cref="FormattedName"/> /// <seealso cref="GivenName"/> public ICollection<string> Nicknames { get { return this.nicknames; } } /// <summary> /// A collection of notes or comments. /// </summary> public vCardNoteCollection Notes { get { return this.notes; } } /// <summary> /// The office of the person at the organization. /// </summary> /// <seealso cref="Department"/> /// <seealso cref="Organization"/> public string Office { get { return this.office ?? string.Empty; } set { this.office = value; } } /// <summary> /// The organization or company of the person. /// </summary> /// <seealso cref="Office"/> /// <seealso cref="Role"/> /// <seealso cref="Title"/> public string Organization { get { return this.organization ?? string.Empty; } set { this.organization = value; } } /// <summary> /// A collection of telephone numbers. /// </summary> public vCardPhoneCollection Phones { get { return this.phones; } } /// <summary> /// A collection of photographic images embedded or /// referenced by the vCard. /// </summary> public vCardPhotoCollection Photos { get { return this.photos; } } /// <summary> /// The name of the product that generated the vCard. /// </summary> public string ProductId { get { return this.productId ?? string.Empty; } set { this.productId = value; } } /// <summary> /// The revision date of the vCard. /// </summary> /// <remarks> /// The revision date is not automatically updated by the /// vCard when modifying properties. It is up to the /// developer to change the revision date as needed. /// </remarks> public DateTime? RevisionDate { get { return this.revisionDate; } set { this.revisionDate = value; } } /// <summary> /// The role of the person (e.g. Executive). /// </summary> /// <remarks> /// The role is shown as "Profession" in Microsoft Outlook. /// </remarks> /// <seealso cref="Department"/> /// <seealso cref="Office"/> /// <seealso cref="Organization"/> /// <seealso cref="Title"/> public string Role { get { return this.role ?? string.Empty; } set { this.role = value; } } /// <summary> /// Directory sources for the vCard information. /// </summary> /// <remarks> /// A vCard may contain zero or more sources. A source /// identifies a directory that contains (or provided) /// information found in the vCard. A program can /// hypothetically connect to the source in order to /// obtain updated information. /// </remarks> public vCardSourceCollection Sources { get { return this.sources; } } /// <summary> /// A string identifying the time zone of the entity /// represented by the vCard. /// </summary> public string TimeZone { get { return this.timeZone ?? string.Empty; } set { this.timeZone = value; } } /// <summary> /// The job title of the person. /// </summary> /// <seealso cref="Organization"/> /// <seealso cref="Role"/> public string Title { get { return this.title ?? string.Empty; } set { this.title = value; } } /// <summary> /// Builds a string that represents the vCard. /// </summary> /// <returns> /// The formatted name of the contact person, if defined, /// or the default object.ToString(). /// </returns> public override string ToString() { if (string.IsNullOrEmpty(this.formattedName)) { return base.ToString(); } else { return this.formattedName; } } /// <summary> /// A value that uniquely identifies the vCard. /// </summary> /// <remarks> /// This value is optional. The string must be any string /// that can be used to uniquely identify the vCard. The /// usage of the field is determined by the software. Typical /// possibilities for a unique string include a URL, a GUID, /// or an LDAP directory path. However, there is no particular /// standard dictated by the vCard specification. /// </remarks> public string UniqueId { get { return this.uniqueId ?? string.Empty; } set { this.uniqueId = value; } } /// <summary> /// Web sites associated with the person. /// </summary> /// <seealso cref="vCardWebsite"/> /// <seealso cref="vCardWebsiteCollection"/> public vCardWebsiteCollection Websites { get { return this.websites; } } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Globalization; #if NET_1_1 using FluorineFx.Util.Nullables; #else using NullableDateTime = System.Nullable<System.DateTime>; #endif namespace FluorineFx.Util { /// <summary> /// DateTime related utility methods. /// </summary> public abstract class DateTimeUtils { private static readonly string[] _internetDateFormats = { "dd MMM yyyy HH':'mm", "dd MMM yyyy HH':'mm':'ss", "ddd, dd MMM yyyy HH':'mm", "ddd, dd MMM yyyy HH':'mm':'ss", }; /// <summary> /// Assumes that given input is in UTC and sets the kind to be UTC. /// Just a precaution if somebody does not set it explicitly. /// <strong>This only works in .NET Framework 2.0 onwards.</strong> /// </summary> /// <param name="dt">The datetime to check.</param> /// <returns>DateTime with kind set to UTC.</returns> public static DateTime AssumeUniversalTime(DateTime dt) { #if NET_1_1 // can't really do anything in 1.x return dt; #else return new DateTime(dt.Ticks, DateTimeKind.Utc); #endif } /// <summary> /// Assumes that given input is in UTC and sets the kind to be UTC. /// Just a precaution if somebody does not set it explicitly. /// </summary> /// <param name="dt">The datetime to check.</param> /// <returns>DateTime with kind set to UTC.</returns> public static NullableDateTime AssumeUniversalTime(NullableDateTime dt) { if (dt.HasValue) { return AssumeUniversalTime(dt.Value); } else { return null; } } /// <summary> /// Returns a date from a string using the internet format. /// </summary> /// <param name="input">Date string using the internet format.</param> /// <returns>DateTime parsed from string.</returns> public static DateTime ParseInternetDate(string input) { ValidationUtils.ArgumentNotNull(input, "input"); if (input.Length < _internetDateFormats[0].Length) throw new ArgumentException("input"); // // Parse according to the following syntax: // // date-time = [ day "," ] date time ; dd mm yy // ; hh:mm:ss zzz // // day = "Mon" / "Tue" / "Wed" / "Thu" // / "Fri" / "Sat" / "Sun" // // date = 1*2DIGIT month 2DIGIT ; day month year // ; e.g. 20 Jun 82 // // month = "Jan" / "Feb" / "Mar" / "Apr" // / "May" / "Jun" / "Jul" / "Aug" // / "Sep" / "Oct" / "Nov" / "Dec" // // time = hour zone ; ANSI and Military // // hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] // ; 00:00:00 - 23:59:59 // // zone = "UT" / "GMT" ; Universal Time // ; North American : UT // / "EST" / "EDT" ; Eastern: - 5/ - 4 // / "CST" / "CDT" ; Central: - 6/ - 5 // / "MST" / "MDT" ; Mountain: - 7/ - 6 // / "PST" / "PDT" ; Pacific: - 8/ - 7 // / 1ALPHA ; Military: Z = UT; // ; A:-1; (J not used) // ; M:-12; N:+1; Y:+12 // / ( ("+" / "-") 4DIGIT ) ; Local differential // ; hours+min. (HHMM) // // For more information, see: // http://www.w3.org/Protocols/rfc822/#z28 // // // Start by processing the time zone component, which is the // part that cannot be delegated to DateTime.ParseExact. // int zzz; // time zone offset stored as HH * 100 + MM int zoneSpaceIndex = input.LastIndexOf(' '); if (zoneSpaceIndex <= 0) throw new FormatException(); string zone = input.Substring(zoneSpaceIndex + 1); if (zone.Length == 0) throw new FormatException("Missing time zone."); switch (zone) { // // Greenwich Mean Time (GMT) or Universal Time (UT) // case "UT": case "GMT": zzz = +0000; break; // // Common North American time zones // case "EDT": zzz = -0400; break; case "EST": case "CDT": zzz = -0500; break; case "CST": case "MDT": zzz = -0600; break; case "MST": case "PDT": zzz = -0700; break; case "PST": zzz = -0800; break; // // Local differential = ( "+" / "-" ) HHMM // default: { if (zone.Length < 4) throw new FormatException("Length of local differential component must be at least 4 characters (HHMM)."); try { zzz = int.Parse(zone, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture); } catch (FormatException e) { throw new FormatException("Invalid local differential.", e); } break; } } // // Strip the time zone component along with any trailing space // and parse out just the time piece by simply delegating to // DateTime.ParseExact. // input = input.Substring(0, zoneSpaceIndex).TrimEnd(); DateTime time = DateTime.ParseExact(input, _internetDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.AllowInnerWhite); // // Subtract the offset to produce zulu time and then return the // result as local time. // TimeSpan offset = new TimeSpan(zzz / 100, zzz % 100, 0); return time.Subtract(offset).ToLocalTime(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace CliParse { /// <summary> /// Information content builder for help screens. /// </summary> public static class InfoBuilder { /// <summary> /// Returns help content derived from the provided assembly and parsable object. /// </summary> /// <param name="parsable"></param> /// <param name="asm"></param> /// <param name="template"></param> /// <param name="argumentTemplate"></param> /// <param name="maxLineLength">The maximum number of characters in a line before it is wrapped</param> /// <returns></returns> public static string GetHelpInfoFromAssembly(Parsable parsable, Assembly asm, string template, string argumentTemplate, int maxLineLength = 80) { if (parsable == null) throw new ArgumentNullException("parsable"); if(asm == null) throw new ArgumentNullException("asm"); if (string.IsNullOrEmpty(template)) return ""; var parsableClass = Helper.GetObjectAttribute(parsable, typeof(ParsableClassAttribute)) as ParsableClassAttribute; if (parsableClass == null) throw new CliParseException("Unable to find 'ParsableClass' attribute on provided object."); var title = GetAssemblyAttribute(asm, typeof (AssemblyTitleAttribute)); template = template.Replace("{title}", title); var version = asm.GetName().Version.ToString(); template = template.Replace("{version}", version); var company = GetAssemblyAttribute(asm, typeof(AssemblyCompanyAttribute)); template = template.Replace("{company}", company); var description = GetAssemblyAttribute(asm, typeof (AssemblyDescriptionAttribute)); template = template.Replace("{description}", description); var syntax = GetSyntaxInfo(parsable, argumentTemplate, parsableClass.AllowedPrefixes); template = template.Replace("{syntax}", syntax); var copyright = GetAssemblyAttribute(asm, typeof (AssemblyCopyrightAttribute)); template = template.Replace("{copyright}", copyright); var footer = GetAssemblyMetadataAttribute(asm, "footer"); template = template.Replace("{footer}", footer); return FormatTextForScreen(template.Trim(), maxLineLength); } /// <summary> /// Returns help content derived from the provided parsable object. /// </summary> /// <param name="parsable"></param> /// <param name="template"></param> /// <param name="argumentTemplate"></param> /// <param name="maxLineLength">The maximum number of characters in a line before it is wrapped</param> /// <returns></returns> public static string GetHelpInfo(Parsable parsable, string template, string argumentTemplate, int maxLineLength = 80) { if (parsable == null) throw new ArgumentNullException("parsable"); if (string.IsNullOrEmpty(template)) return ""; var parsableClass = Helper.GetObjectAttribute(parsable, typeof(ParsableClassAttribute)) as ParsableClassAttribute; if(parsableClass == null) throw new CliParseException("Unable to find 'ParsableClass' attribute on provided object."); template = template.Replace("{title}", parsableClass.Title); template = template.Replace("{description}", parsableClass.Description); template = template.Replace("{copyright}", string.IsNullOrEmpty(parsableClass.Copyright) ? "" : parsableClass.Copyright); template = template.Replace("{version}", parsableClass.Version); var syntax = GetSyntaxInfo(parsable, argumentTemplate, parsableClass.AllowedPrefixes); template = template.Replace("{syntax}", syntax); template = template.Replace("{example}", parsableClass.ExampleText); template = template.Replace("{footer}", parsableClass.FooterText); return FormatTextForScreen(template.Trim(), maxLineLength); } private static string GetSyntaxInfo(Parsable parsable, string argumentTemplate, ICollection<char> prefixes) { var arguments = GetListArgumentAttributes(parsable); var sb = new StringBuilder(); var prefix = "-"; // default if (prefixes.Count > 1) { prefix = prefixes.FirstOrDefault().ToString(); var allowedPrefixes = ""; prefixes.ToList().ForEach(x => allowedPrefixes += "'" + x + "',"); allowedPrefixes = allowedPrefixes.Substring(0, allowedPrefixes.Length - 1); sb.AppendLine("The following argument prefix characters can be used: "+allowedPrefixes); } foreach (var argument in arguments) { sb.AppendLine(argument.GetSyntax(argumentTemplate, prefix)); } return sb.ToString(); } private static IEnumerable<ParsableArgumentAttribute> GetListArgumentAttributes(Parsable parsable) { var parsableType = parsable.GetType(); var properties = parsableType.GetProperties(); var arguments = new List<ParsableArgumentAttribute>(); foreach (var prop in properties) { arguments.AddRange(prop.GetCustomAttributes(true).OfType<ParsableArgumentAttribute>()); } return arguments; } private static string GetAssemblyMetadataAttribute(Assembly asm, string key) { var customAttributes = asm.GetCustomAttributes(typeof (AssemblyMetadataAttribute)); var t = (from AssemblyMetadataAttribute attribute in customAttributes select attribute).FirstOrDefault(x => x.Key.Equals(key)); return t == null ? "" : t.Value; } private static string GetAssemblyAttribute(Assembly asm, Type type) { var customAttribute = asm.GetCustomAttributes(type).FirstOrDefault(x => x.GetType() == type); if (customAttribute == null) return ""; return GetAssemblyAttributeValue(type, customAttribute); } private static string GetAssemblyAttributeValue(Type type, Attribute customAttribute) { if (type == typeof (AssemblyTitleAttribute)) { var t = customAttribute as AssemblyTitleAttribute; return t == null ? "" : t.Title; } if (type == typeof (AssemblyDescriptionAttribute)) { var t = customAttribute as AssemblyDescriptionAttribute; return t == null ? "" : t.Description; } if (type == typeof (AssemblyCompanyAttribute)) { var t = customAttribute as AssemblyCompanyAttribute; return t == null ? "" : t.Company; } if (type == typeof (AssemblyCopyrightAttribute)) { var t = customAttribute as AssemblyCopyrightAttribute; return t == null ? "" : t.Copyright; } return ""; } private static string FormatTextForScreen(string text, int maxLineLength) { var sb = new StringBuilder(); var lines = text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); foreach (string line in lines) { sb.AppendLine(BreakStringToLength(line, maxLineLength)); } return sb.ToString(); } internal static string BreakStringToLength(string line, int maximumLineLength) { if (string.IsNullOrEmpty(line)) return ""; if (maximumLineLength <= 1) throw new ArgumentOutOfRangeException("maximumLineLength"); if (line.Length <= maximumLineLength - 1) return line; var maxLineLength = maximumLineLength; var sb = new StringBuilder(); var startingWhiteSpace = GetLeadingWhitespaceAsSpaces(line); var startingWhiteSpaceLength = startingWhiteSpace.Length; var currentIndex = 0; var possibleIndex = 0; var keepGoing = true; while (keepGoing) { var scanIndex = line.IndexOf(' ', possibleIndex); if (scanIndex != -1) scanIndex += 1; // move to location after the space so we wrap at start of word. if (scanIndex - currentIndex + startingWhiteSpaceLength > maxLineLength) { sb.Append(line.Substring(currentIndex, possibleIndex - currentIndex)); sb.AppendLine(); sb.Append(startingWhiteSpace); currentIndex = possibleIndex; } // no more spaces if (scanIndex == -1) { var lengthRemaining = line.Length - currentIndex; if (currentIndex == 0) { if (lengthRemaining > maxLineLength) { sb.AppendLine(line.Substring(currentIndex, maxLineLength)); sb.Append(startingWhiteSpace); currentIndex += maxLineLength; } else { sb.Append(line.Substring(currentIndex, lengthRemaining)); keepGoing = false; } } else { if (lengthRemaining + startingWhiteSpaceLength > maxLineLength) { sb.AppendLine(line.Substring(currentIndex, maxLineLength - startingWhiteSpaceLength)); sb.Append(startingWhiteSpace); currentIndex += maxLineLength - startingWhiteSpaceLength; } else { sb.Append(line.Substring(currentIndex, lengthRemaining)); keepGoing = false; } } } else { possibleIndex = scanIndex; } } return sb.ToString(); } private static string GetLeadingWhitespaceAsSpaces(string line) { int count = 0; foreach (var c in line) { if (!Char.IsWhiteSpace(c)) break; if (c == ' ') count++; if (c.Equals('\t')) count += 4; } return new string(' ', count); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI.Windows.Components; using UnityEngine.UI.Windows.Types; using UnityEngine.UI.Extensions; namespace UnityEngine.UI.Windows.Animations { [TransitionCamera] public class WindowAnimationTransitionScreenTransform : TransitionBase { [System.Serializable] public class Parameters : TransitionBase.ParametersVideoBase { public Parameters() : base() {} public Parameters(TransitionBase.ParametersBase baseDefaults) : base(baseDefaults) {} [System.Serializable] public class State { [Header("Canvas Group")] public float alpha = 1f; [Header("Rect Transform")] public Vector2 anchorMin; public Vector2 anchorMax; public Vector2 anchoredPosition; public Vector2 sizeDelta; public Vector2 pivot; [Header("Transform")] public Quaternion localRotation = Quaternion.identity; public Vector3 localScale = Vector3.one; [Header("Material")] public float materialStrength = 0f; public State() { } public State(WindowLayoutRoot root) { this.alpha = root.alpha; this.anchorMin = root.rectTransform.anchorMin; this.anchorMax = root.rectTransform.anchorMax; this.anchoredPosition = root.rectTransform.anchoredPosition; this.sizeDelta = root.rectTransform.sizeDelta; this.pivot = root.rectTransform.pivot; this.localRotation = root.rectTransform.localRotation; this.localScale = root.rectTransform.localScale; this.materialStrength = 0f; } public State(State source) { this.alpha = source.alpha; this.anchorMin = source.anchorMin; this.anchorMax = source.anchorMax; this.anchoredPosition = source.anchoredPosition; this.sizeDelta = source.sizeDelta; this.pivot = source.pivot; this.localRotation = source.localRotation; this.localScale = source.localScale; this.materialStrength = source.materialStrength; } } public State resetState = new State(); public State inState = new State(); public State outState = new State(); public override void Setup(TransitionBase.ParametersBase defaults) { var param = defaults as Parameters; if (param == null) return; // Place params installation here this.inState = new State(param.inState); this.outState = new State(param.outState); this.resetState = new State(param.resetState); } public void Apply(Material material, WindowLayoutRoot root, State startState, State resultState, float value) { root.alpha = Mathf.Lerp(startState.alpha, resultState.alpha, value); root.rectTransform.anchorMin = Vector2.Lerp(startState.anchorMin, resultState.anchorMin, value); root.rectTransform.anchorMax = Vector2.Lerp(startState.anchorMax, resultState.anchorMax, value); root.rectTransform.anchoredPosition = Vector2.Lerp(startState.anchoredPosition, resultState.anchoredPosition, value); root.rectTransform.sizeDelta = Vector2.Lerp(startState.sizeDelta, resultState.sizeDelta, value); root.rectTransform.pivot = Vector2.Lerp(startState.pivot, resultState.pivot, value); root.rectTransform.localRotation = Quaternion.Slerp(startState.localRotation, resultState.localRotation, value); root.rectTransform.localScale = Vector3.Lerp(startState.localScale, resultState.localScale, value); if (material != null) { material.SetFloat(this.GetMaterialStrengthName(), Mathf.Lerp(startState.materialStrength, resultState.materialStrength, value)); } } public void Apply(Material material, WindowLayoutRoot root, State state) { root.alpha = state.alpha; root.rectTransform.anchorMin = state.anchorMin; root.rectTransform.anchorMax = state.anchorMax; root.rectTransform.anchoredPosition = state.anchoredPosition; root.rectTransform.sizeDelta = state.sizeDelta; root.rectTransform.pivot = state.pivot; root.rectTransform.localRotation = state.localRotation; root.rectTransform.localScale = state.localScale; if (material != null) { material.SetFloat(this.GetMaterialStrengthName(), state.materialStrength); } } public State GetIn() { return this.inState; } public State GetOut() { return this.outState; } public State GetReset() { return this.resetState; } public State GetResult(bool forward) { if (forward == true) { return this.GetIn(); } return this.GetOut(); } } public Parameters defaultInputParams; private WindowLayoutRoot GetRoot(Parameters parameters, WindowBase window) { return (window as LayoutWindowType).GetCurrentLayout().GetLayoutInstance().root; } public override TransitionBase.ParametersBase GetDefaultInputParameters() { return this.defaultInputParams; } public override void Set(WindowBase window, TransitionInputParameters parameters, WindowComponentBase root, bool forward, float value) { var param = this.GetParams<Parameters>(parameters); if (param == null) { return; } //var duration = this.GetDuration(parameters, forward); var rect = this.GetRoot(param, window); var state = new Parameters.State(rect); var resultState = param.GetResult(forward); var material = param.GetMaterialInstance(); param.Apply(material, rect, state, resultState, ME.Ease.GetByType(forward == true ? param.inEase : param.outEase).interpolate(0f, 1f, value, 1f)); } public override void OnPlay(WindowBase window, ME.Tweener.MultiTag tag, TransitionInputParameters parameters, WindowComponentBase root, bool forward, System.Action callback) { var param = this.GetParams<Parameters>(parameters); if (param == null) { if (callback != null) callback(); return; } var duration = this.GetDuration(parameters, forward); var resultState = param.GetResult(forward); var rect = this.GetRoot(param, window); var state = new Parameters.State(rect); var material = param.GetMaterialInstance(); if (TweenerGlobal.instance != null) { //TweenerGlobal.instance.removeTweens(tag); TweenerGlobal.instance.addTween(rect, duration, 0f, 1f).onUpdate((obj, value) => { if (obj != null) { param.Apply(material, obj, state, resultState, value); } }).onComplete((obj) => { if (callback != null) callback(); }).onCancel((obj) => { if (callback != null) callback(); }).tag(tag).ease(ME.Ease.GetByType(forward == true ? param.inEase : param.outEase)); } else { param.Apply(material, rect, resultState); if (callback != null) callback(); } } public override void SetInState(TransitionInputParameters parameters, WindowBase window, WindowComponentBase root) { var param = this.GetParams<Parameters>(parameters); if (param == null) return; param.Apply(param.GetMaterialInstance(), this.GetRoot(param, window), param.GetIn()); } public override void SetOutState(TransitionInputParameters parameters, WindowBase window, WindowComponentBase root) { var param = this.GetParams<Parameters>(parameters); if (param == null) return; param.Apply(param.GetMaterialInstance(), this.GetRoot(param, window), param.GetOut()); } public override void SetResetState(TransitionInputParameters parameters, WindowBase window, WindowComponentBase root) { var param = this.GetParams<Parameters>(parameters); if (param == null) return; param.Apply(param.GetMaterialInstance(), this.GetRoot(param, window), param.GetReset()); } #if UNITY_EDITOR [UnityEditor.MenuItem("Assets/Create/UI Windows/Transitions/Screen/Transform")] public static void CreateInstance() { ME.EditorUtilities.CreateAsset<WindowAnimationTransitionScreenTransform>(); } #endif } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.DataGridComboBoxColumn.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class DataGridComboBoxColumn : DataGridColumn { #region Methods and constructors public DataGridComboBoxColumn() { } protected override System.Windows.FrameworkElement GenerateEditingElement(DataGridCell cell, Object dataItem) { return default(System.Windows.FrameworkElement); } protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, Object dataItem) { return default(System.Windows.FrameworkElement); } protected override bool OnCoerceIsReadOnly(bool baseValue) { return default(bool); } protected virtual new void OnSelectedItemBindingChanged(System.Windows.Data.BindingBase oldBinding, System.Windows.Data.BindingBase newBinding) { } protected virtual new void OnSelectedValueBindingChanged(System.Windows.Data.BindingBase oldBinding, System.Windows.Data.BindingBase newBinding) { } protected virtual new void OnTextBindingChanged(System.Windows.Data.BindingBase oldBinding, System.Windows.Data.BindingBase newBinding) { } protected override Object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs) { return default(Object); } protected internal override void RefreshCellContent(System.Windows.FrameworkElement element, string propertyName) { } #endregion #region Properties and indexers public override System.Windows.Data.BindingBase ClipboardContentBinding { get { return default(System.Windows.Data.BindingBase); } set { } } public static System.Windows.Style DefaultEditingElementStyle { get { Contract.Ensures(Contract.Result<System.Windows.Style>() != null); Contract.Ensures(Contract.Result<System.Windows.Style>() == System.Windows.Controls.DataGridComboBoxColumn.DefaultElementStyle); return default(System.Windows.Style); } } public static System.Windows.Style DefaultElementStyle { get { Contract.Ensures(Contract.Result<System.Windows.Style>() != null); return default(System.Windows.Style); } } public string DisplayMemberPath { get { return default(string); } set { } } public System.Windows.Style EditingElementStyle { get { return default(System.Windows.Style); } set { } } public System.Windows.Style ElementStyle { get { return default(System.Windows.Style); } set { } } public System.Collections.IEnumerable ItemsSource { get { return default(System.Collections.IEnumerable); } set { } } public virtual new System.Windows.Data.BindingBase SelectedItemBinding { get { return default(System.Windows.Data.BindingBase); } set { } } public virtual new System.Windows.Data.BindingBase SelectedValueBinding { get { return default(System.Windows.Data.BindingBase); } set { } } public string SelectedValuePath { get { return default(string); } set { } } public virtual new System.Windows.Data.BindingBase TextBinding { get { return default(System.Windows.Data.BindingBase); } set { } } public static System.Windows.ComponentResourceKey TextBlockComboBoxStyleKey { get { Contract.Ensures(Contract.Result<System.Windows.ComponentResourceKey>() != null); return default(System.Windows.ComponentResourceKey); } } #endregion #region Fields public readonly static System.Windows.DependencyProperty DisplayMemberPathProperty; public readonly static System.Windows.DependencyProperty EditingElementStyleProperty; public readonly static System.Windows.DependencyProperty ElementStyleProperty; public readonly static System.Windows.DependencyProperty ItemsSourceProperty; public readonly static System.Windows.DependencyProperty SelectedValuePathProperty; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.ServiceModel { public partial class BasicHttpBinding : System.ServiceModel.HttpBindingBase { public BasicHttpBinding() { } public BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode securityMode) { } public System.ServiceModel.WSMessageEncoding MessageEncoding { get { return default; } set { } } public System.ServiceModel.BasicHttpSecurity Security { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public enum BasicHttpMessageCredentialType { Certificate = 1, UserName = 0, } public sealed partial class BasicHttpMessageSecurity { public BasicHttpMessageSecurity() { } public System.ServiceModel.BasicHttpMessageCredentialType ClientCredentialType { get { return default; } set { } } public System.ServiceModel.Security.SecurityAlgorithmSuite AlgorithmSuite { get { return default; } set { } } } public sealed partial class BasicHttpSecurity { public BasicHttpSecurity() { } public System.ServiceModel.BasicHttpSecurityMode Mode { get { return default; } set { } } public System.ServiceModel.HttpTransportSecurity Transport { get { return default; } set { } } public System.ServiceModel.BasicHttpMessageSecurity Message { get { return default; } set { } } } public enum BasicHttpSecurityMode { None = 0, Transport = 1, Message = 2, TransportWithMessageCredential = 3, TransportCredentialOnly = 4, } public partial class BasicHttpsBinding : System.ServiceModel.HttpBindingBase { public BasicHttpsBinding() { } public BasicHttpsBinding(System.ServiceModel.BasicHttpsSecurityMode securityMode) { } public System.ServiceModel.BasicHttpsSecurity Security { get { return default; } set { } } public System.ServiceModel.WSMessageEncoding MessageEncoding { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public sealed partial class BasicHttpsSecurity { internal BasicHttpsSecurity() { } public System.ServiceModel.BasicHttpsSecurityMode Mode { get { return default; } set { } } public System.ServiceModel.HttpTransportSecurity Transport { get { return default; } set { } } public System.ServiceModel.BasicHttpMessageSecurity Message { get { return default; } set { } } } public enum BasicHttpsSecurityMode { Transport = 0, TransportWithMessageCredential = 1, } public abstract partial class HttpBindingBase : System.ServiceModel.Channels.Binding { internal HttpBindingBase() { } [System.ComponentModel.DefaultValueAttribute(false)] public bool AllowCookies { get { return default; } set { } } [System.ComponentModel.DefaultValue(false)] public bool BypassProxyOnLocal { get { return default; } set { } } public System.ServiceModel.EnvelopeVersion EnvelopeVersion { get { return default; } } [System.ComponentModel.DefaultValueAttribute((long)524288)] public long MaxBufferPoolSize { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(65536)] public int MaxBufferSize { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((long)65536)] public long MaxReceivedMessageSize { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] [System.ComponentModel.TypeConverter(typeof(System.UriTypeConverter))] public System.Uri ProxyAddress { get { return default; } set { } } public System.Xml.XmlDictionaryReaderQuotas ReaderQuotas { get { return default; } set { } } public override string Scheme { get { return default; } } public System.Text.Encoding TextEncoding { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.TransferMode)(0))] public System.ServiceModel.TransferMode TransferMode { get { return default; } set { } } [System.ComponentModel.DefaultValue(true)] public bool UseDefaultWebProxy { get { return default; } set { } } } public enum HttpClientCredentialType { Basic = 1, Certificate = 5, Digest = 2, InheritedFromHost = 6, None = 0, Ntlm = 3, Windows = 4, } public enum HttpProxyCredentialType { None, Basic, Digest, Ntlm, Windows, } public sealed partial class HttpTransportSecurity { public HttpTransportSecurity() { } public System.ServiceModel.HttpClientCredentialType ClientCredentialType { get { return default; } set { } } public System.ServiceModel.HttpProxyCredentialType ProxyCredentialType { get { return default; } set { } } public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionPolicy { get { return default; } set { } } } public partial class NetHttpBinding : System.ServiceModel.HttpBindingBase { public NetHttpBinding() { } public NetHttpBinding(System.ServiceModel.BasicHttpSecurityMode securityMode) { } public NetHttpBinding(System.ServiceModel.BasicHttpSecurityMode securityMode, bool reliableSessionEnabled) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public NetHttpBinding(string configurationName) { } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.NetHttpMessageEncoding)(0))] public System.ServiceModel.NetHttpMessageEncoding MessageEncoding { get { return default; } set { } } public System.ServiceModel.BasicHttpSecurity Security { get { return default; } set { } } public System.ServiceModel.OptionalReliableSession ReliableSession { get { return default; } set { } } public System.ServiceModel.Channels.WebSocketTransportSettings WebSocketSettings { get { return default; } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public partial class NetHttpsBinding : System.ServiceModel.HttpBindingBase { public NetHttpsBinding() { } public NetHttpsBinding(System.ServiceModel.BasicHttpsSecurityMode securityMode) { } public NetHttpsBinding(System.ServiceModel.BasicHttpsSecurityMode securityMode, bool reliableSessionEnabled) { } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.NetHttpMessageEncoding)(0))] public System.ServiceModel.NetHttpMessageEncoding MessageEncoding { get { return default; } set { } } public System.ServiceModel.BasicHttpsSecurity Security { get { return default; } set { } } public System.ServiceModel.OptionalReliableSession ReliableSession { get { return default; } set { } } public System.ServiceModel.Channels.WebSocketTransportSettings WebSocketSettings { get { return default; } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public enum NetHttpMessageEncoding { Binary = 0, Text = 1, Mtom = 2, } public abstract partial class WSHttpBindingBase : System.ServiceModel.Channels.Binding { protected WSHttpBindingBase() { } protected WSHttpBindingBase(bool reliableSessionEnabled) { } public bool BypassProxyOnLocal { get { return default; } set { } } public bool TransactionFlow { get { return default; } set { } } //public System.ServiceModel.HostNameComparisonMode HostNameComparisonMode { get { return default; } set { } } public long MaxBufferPoolSize { get { return default; } set { } } public long MaxReceivedMessageSize { get { return default; } set { } } public System.ServiceModel.WSMessageEncoding MessageEncoding { get { return default; } set { } } public Uri ProxyAddress { get { return default; } set { } } public System.Xml.XmlDictionaryReaderQuotas ReaderQuotas { get { return default; } set { } } public System.ServiceModel.OptionalReliableSession ReliableSession { get { return default; } set { } } public override string Scheme { get { return default; } } public System.ServiceModel.EnvelopeVersion EnvelopeVersion { get { return default; } set { } } public System.Text.Encoding TextEncoding { get { return default; } set { } } public bool UseDefaultWebProxy { get { return default; } set { } } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } protected abstract System.ServiceModel.Channels.TransportBindingElement GetTransport(); protected abstract System.ServiceModel.Channels.SecurityBindingElement CreateMessageSecurity(); } public partial class WSHttpBinding : System.ServiceModel.WSHttpBindingBase { public WSHttpBinding() { } public WSHttpBinding(System.ServiceModel.SecurityMode securityMode) { } public WSHttpBinding(System.ServiceModel.SecurityMode securityMode, bool reliableSessionEnabled) { } public bool AllowCookies { get { return default; } set { } } public System.ServiceModel.WSHttpSecurity Security { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } protected override System.ServiceModel.Channels.TransportBindingElement GetTransport() { return default; } protected override System.ServiceModel.Channels.SecurityBindingElement CreateMessageSecurity() { return default; } } public class WS2007HttpBinding : WSHttpBinding { public WS2007HttpBinding() { } public WS2007HttpBinding(System.ServiceModel.SecurityMode securityMode) { } public WS2007HttpBinding(System.ServiceModel.SecurityMode securityMode, bool reliableSessionEnabled) { } protected override System.ServiceModel.Channels.SecurityBindingElement CreateMessageSecurity() { return default; } } public sealed partial class WSHttpSecurity { public WSHttpSecurity() { } public System.ServiceModel.SecurityMode Mode { get { return default; } set { } } public System.ServiceModel.HttpTransportSecurity Transport { get { return default; } set { } } public System.ServiceModel.NonDualMessageSecurityOverHttp Message { get { return default; } set { } } } public sealed class NonDualMessageSecurityOverHttp : System.ServiceModel.MessageSecurityOverHttp { public NonDualMessageSecurityOverHttp() { } public bool EstablishSecurityContext { get { return default; } set { } } protected override bool IsSecureConversationEnabled() { return default; } } public class MessageSecurityOverHttp { public MessageSecurityOverHttp() { } public System.ServiceModel.MessageCredentialType ClientCredentialType { get { return default; } set { } } public bool NegotiateServiceCredential { get { return default; } set { } } public System.ServiceModel.Security.SecurityAlgorithmSuite AlgorithmSuite { get { return default; } set { } } protected virtual bool IsSecureConversationEnabled() { return default; } } public enum WSMessageEncoding { Text = 0, Mtom, } } namespace System.ServiceModel.Channels { public sealed partial class HttpRequestMessageProperty : System.ServiceModel.Channels.IMessageProperty { public HttpRequestMessageProperty() { } public System.Net.WebHeaderCollection Headers { get { return default; } } public string Method { get { return default; } set { } } public static string Name { get { return default; } } public string QueryString { get { return default; } set { } } public bool SuppressEntityBody { get { return default; } set { } } System.ServiceModel.Channels.IMessageProperty System.ServiceModel.Channels.IMessageProperty.CreateCopy() { return default; } } public sealed partial class HttpResponseMessageProperty : System.ServiceModel.Channels.IMessageProperty { public HttpResponseMessageProperty() { } public System.Net.WebHeaderCollection Headers { get { return default; } } public static string Name { get { return default; } } public System.Net.HttpStatusCode StatusCode { get { return default; } set { } } public string StatusDescription { get { return default; } set { } } System.ServiceModel.Channels.IMessageProperty System.ServiceModel.Channels.IMessageProperty.CreateCopy() { return default; } } public partial class HttpsTransportBindingElement : System.ServiceModel.Channels.HttpTransportBindingElement { public HttpsTransportBindingElement() { } protected HttpsTransportBindingElement(System.ServiceModel.Channels.HttpsTransportBindingElement elementToBeCloned) { } public bool RequireClientCertificate { get { return default; } set { } } public override string Scheme { get { return default; } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public override System.ServiceModel.Channels.BindingElement Clone() { return default; } public override T GetProperty<T>(System.ServiceModel.Channels.BindingContext context) { return default; } } public partial class HttpTransportBindingElement : System.ServiceModel.Channels.TransportBindingElement { public HttpTransportBindingElement() { } protected HttpTransportBindingElement(System.ServiceModel.Channels.HttpTransportBindingElement elementToBeCloned) { } [System.ComponentModel.DefaultValueAttribute(false)] public bool AllowCookies { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.Net.AuthenticationSchemes)(32768))] public System.Net.AuthenticationSchemes AuthenticationScheme { get { return default; } set { } } [System.ComponentModel.DefaultValue(false)] public bool BypassProxyOnLocal { get { return default; } set { } } [System.ComponentModel.DefaultValue(true)] public bool DecompressionEnabled { get { return default; } set { } } public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionPolicy { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(65536)] public int MaxBufferSize { get { return default; } set { } } [System.ComponentModel.DefaultValue(null)] [System.ComponentModel.TypeConverter(typeof(System.UriTypeConverter))] public System.Uri ProxyAddress { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.Net.AuthenticationSchemes)(32768))] public System.Net.AuthenticationSchemes ProxyAuthenticationScheme { get { return default; } set { } } public System.Net.IWebProxy Proxy { get { return default; } set { } } public override string Scheme { get { return default; } } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.TransferMode)(0))] public System.ServiceModel.TransferMode TransferMode { get { return default; } set { } } public System.ServiceModel.Channels.WebSocketTransportSettings WebSocketSettings { get { return default; } set { } } [System.ComponentModel.DefaultValue(true)] public bool UseDefaultWebProxy { get { return default; } set { } } [System.ComponentModel.DefaultValue(true)] public bool KeepAliveEnabled { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public override bool CanBuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public override System.ServiceModel.Channels.BindingElement Clone() { return default; } public override T GetProperty<T>(System.ServiceModel.Channels.BindingContext context) { return default; } } public partial interface IHttpCookieContainerManager { System.Net.CookieContainer CookieContainer { get; set; } } public sealed partial class WebSocketTransportSettings : System.IEquatable<System.ServiceModel.Channels.WebSocketTransportSettings> { public const string BinaryMessageReceivedAction = "http://schemas.microsoft.com/2011/02/websockets/onbinarymessage"; public const string TextMessageReceivedAction = "http://schemas.microsoft.com/2011/02/websockets/ontextmessage"; public WebSocketTransportSettings() { } [System.ComponentModel.DefaultValueAttribute(false)] public bool DisablePayloadMasking { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(typeof(System.TimeSpan), "00:00:00")] public System.TimeSpan KeepAliveInterval { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] public string SubProtocol { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.Channels.WebSocketTransportUsage)(2))] public System.ServiceModel.Channels.WebSocketTransportUsage TransportUsage { get { return default; } set { } } public override bool Equals(object obj) { return default; } public bool Equals(System.ServiceModel.Channels.WebSocketTransportSettings other) { return default; } public override int GetHashCode() { return default; } } public enum WebSocketTransportUsage { Always = 1, Never = 2, WhenDuplex = 0, } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // 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. // using NLog.Config; namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using Xunit; public class TargetTests : NLogTestBase { [Fact] public void InitializeTest() { var target = new MyTarget(); target.Initialize(null); // initialize was called once Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void InitializeFailedTest() { var target = new MyTarget(); target.ThrowOnInitialize = true; LogManager.ThrowExceptions = true; Assert.Throws<InvalidOperationException>(() => target.Initialize(null)); // after exception in Initialize(), the target becomes non-functional and all Write() operations var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(0, target.WriteCount); Assert.Equal(1, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message); Assert.Equal("Init error.", exceptions[0].InnerException.Message); } [Fact] public void DoubleInitializeTest() { var target = new MyTarget(); target.Initialize(null); target.Initialize(null); // initialize was called once Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void DoubleCloseTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); target.Close(); // initialize and close were called once each Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void CloseWithoutInitializeTest() { var target = new MyTarget(); target.Close(); // nothing was called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void WriteWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); // write was not called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.Equal(4, exceptions.Count); exceptions.ForEach(Assert.Null); } [Fact] public void WriteOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); var exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); // write was not called Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); // but all callbacks were invoked with null values Assert.Equal(4, exceptions.Count); exceptions.ForEach(Assert.Null); } [Fact] public void FlushTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Initialize(null); target.Flush(exceptions.Add); // flush was called Assert.Equal(1, target.FlushCount); Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); Assert.Equal(1, exceptions.Count); exceptions.ForEach(Assert.Null); } [Fact] public void FlushWithoutInitializeTest() { var target = new MyTarget(); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.Equal(1, exceptions.Count); exceptions.ForEach(Assert.Null); // flush was not called Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void FlushOnClosedTargetTest() { var target = new MyTarget(); target.Initialize(null); target.Close(); Assert.Equal(1, target.InitializeCount); Assert.Equal(1, target.CloseCount); List<Exception> exceptions = new List<Exception>(); target.Flush(exceptions.Add); Assert.Equal(1, exceptions.Count); exceptions.ForEach(Assert.Null); // flush was not called Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3); } [Fact] public void LockingTest() { var target = new MyTarget(); target.Initialize(null); var mre = new ManualResetEvent(false); Exception backgroundThreadException = null; Thread t = new Thread(() => { try { target.BlockingOperation(1000); } catch (Exception ex) { backgroundThreadException = ex; } finally { mre.Set(); } }); target.Initialize(null); t.Start(); Thread.Sleep(50); List<Exception> exceptions = new List<Exception>(); target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents(new[] { LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), }); target.Flush(exceptions.Add); target.Close(); exceptions.ForEach(Assert.Null); mre.WaitOne(); if (backgroundThreadException != null) { Assert.True(false, backgroundThreadException.ToString()); } } [Fact] public void GivenNullEvents_WhenWriteAsyncLogEvents_ThenNoExceptionAreThrown() { var target = new MyTarget(); try { target.WriteAsyncLogEvents(null); } catch (Exception e) { Assert.True(false, "Exception thrown: " + e); } } [Fact] public void WriteFormattedStringEvent_WithNullArgument() { var target = new MyTarget(); SimpleConfigurator.ConfigureForTargetLogging(target); var logger = LogManager.GetLogger("WriteFormattedStringEvent_EventWithNullArguments"); string t = null; logger.Info("Testing null:{0}",t); Assert.Equal(1, target.WriteCount); } public class MyTarget : Target { private int inBlockingOperation; public int InitializeCount { get; set; } public int CloseCount { get; set; } public int FlushCount { get; set; } public int WriteCount { get; set; } public int WriteCount2 { get; set; } public bool ThrowOnInitialize { get; set; } public int WriteCount3 { get; set; } protected override void InitializeTarget() { if (this.ThrowOnInitialize) { throw new InvalidOperationException("Init error."); } Assert.Equal(0, this.inBlockingOperation); this.InitializeCount++; base.InitializeTarget(); } protected override void CloseTarget() { Assert.Equal(0, this.inBlockingOperation); this.CloseCount++; base.CloseTarget(); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Assert.Equal(0, this.inBlockingOperation); this.FlushCount++; base.FlushAsync(asyncContinuation); } protected override void Write(LogEventInfo logEvent) { Assert.Equal(0, this.inBlockingOperation); this.WriteCount++; } protected override void Write(AsyncLogEventInfo logEvent) { Assert.Equal(0, this.inBlockingOperation); this.WriteCount2++; base.Write(logEvent); } protected override void Write(AsyncLogEventInfo[] logEvents) { Assert.Equal(0, this.inBlockingOperation); this.WriteCount3++; base.Write(logEvents); } public void BlockingOperation(int millisecondsTimeout) { lock (this.SyncRoot) { this.inBlockingOperation++; Thread.Sleep(millisecondsTimeout); this.inBlockingOperation--; } } } } }
// // ImageReader.cs // // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using RVA = System.UInt32; namespace Imazen.NativeDependencyManager.BinaryParsers.PE { internal sealed class ImageReader : BinaryReader { internal ImageReader(Stream stream) : base (stream) { image = new Image(); image.FileName = FileStreamName; } /// <summary> /// If true, will read the CLR version and assembly characteristics - this can require 2 additional seeks over dozens of kb /// </summary> internal bool ReadClrInfo { get; set; } protected void Advance(int bytes) { BaseStream.Seek(bytes, SeekOrigin.Current); } protected DataDirectory ReadDataDirectory() { return new DataDirectory(ReadUInt32(), ReadUInt32()); } readonly Image image; DataDirectory cli; DataDirectory metadata; /// <summary> /// Returns the full path of the underlying FileStream - if it's actually a file stream. /// </summary> internal string FileStreamName { get { var fs = this.BaseStream as FileStream; return fs == null ? "" : Path.GetFullPath(fs.Name); } } internal void MoveTo(DataDirectory directory) { BaseStream.Position = image.ResolveVirtualAddress (directory.VirtualAddress); } internal void MoveTo(uint position) { BaseStream.Position = position; } void ReadImage () { if (BaseStream.Length < 128) throw new BadImageFormatException (); // - DOSHeader // PE 2 // Start 58 // Lfanew 4 // End 64 if (ReadUInt16 () != 0x5a4d) throw new BadImageFormatException (); Advance (58); MoveTo (ReadUInt32 ()); if (ReadUInt32 () != 0x00004550) throw new BadImageFormatException (); // - PEFileHeader // Machine 2 image.Architecture = ReadArchitecture (); // NumberOfSections 2 ushort sections = ReadUInt16 (); // TimeDateStamp 4 // PointerToSymbolTable 4 // NumberOfSymbols 4 // OptionalHeaderSize 2 Advance (14); // Characteristics 2 ushort characteristics = ReadUInt16 (); ushort subsystem, dll_characteristics; ReadOptionalHeaders (out subsystem, out dll_characteristics); image.Kind = GetModuleKind (characteristics, subsystem); image.Characteristics = (ModuleCharacteristics) dll_characteristics; if (!cli.IsZero) image.DotNetRuntime = TargetRuntime.DotNet; if (ReadClrInfo && !cli.IsZero) { ReadSections(sections); ReadCLIInfo(); } } InstructionSets ReadArchitecture () { var machine = ReadUInt16 (); switch (machine) { case 0x014c: return InstructionSets.x86; case 0x8664: return InstructionSets.x86_64; case 0x0200: return InstructionSets.IA64; case 0x01c4: return InstructionSets.ARM; } throw new NotSupportedException (); } static ModuleKind GetModuleKind (ushort characteristics, ushort subsystem) { if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll return ModuleKind.Dll; if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui return ModuleKind.Windows; return ModuleKind.Console; } void ReadOptionalHeaders (out ushort subsystem, out ushort dll_characteristics) { // - PEOptionalHeader // - StandardFieldsHeader // Magic 2 bool pe64 = ReadUInt16 () == 0x20b; // pe32 || pe64 // LMajor 1 // LMinor 1 // CodeSize 4 // InitializedDataSize 4 // UninitializedDataSize4 // EntryPointRVA 4 // BaseOfCode 4 // BaseOfData 4 || 0 // - NTSpecificFieldsHeader // ImageBase 4 || 8 // SectionAlignment 4 // FileAlignement 4 // OSMajor 2 // OSMinor 2 // UserMajor 2 // UserMinor 2 // SubSysMajor 2 // SubSysMinor 2 // Reserved 4 // ImageSize 4 // HeaderSize 4 // FileChecksum 4 Advance (66); // SubSystem 2 subsystem = ReadUInt16 (); // DLLFlags 2 dll_characteristics = ReadUInt16 (); // StackReserveSize 4 || 8 // StackCommitSize 4 || 8 // HeapReserveSize 4 || 8 // HeapCommitSize 4 || 8 // LoaderFlags 4 // NumberOfDataDir 4 // - DataDirectoriesHeader // ExportTable 8 // ImportTable 8 // ResourceTable 8 // ExceptionTable 8 // CertificateTable 8 // BaseRelocationTable 8 Advance (pe64 ? 88 : 72); // Debug 8 image.Debug = ReadDataDirectory (); // Copyright 8 // GlobalPtr 8 // TLSTable 8 // LoadConfigTable 8 // BoundImport 8 // IAT 8 // DelayImportDescriptor8 Advance (56); // CLIHeader 8 cli = ReadDataDirectory (); // Reserved 8 Advance (8); } string ReadZeroTerminatedString (int length) { int read = 0; var buffer = new char [length]; var bytes = ReadBytes (length); while (read < length) { var current = bytes [read]; if (current == 0) break; buffer [read++] = (char) current; } return new string (buffer, 0, read); } void ReadSections (ushort count) { var sections = new Section [count]; for (int i = 0; i < count; i++) { var section = new Section (); // Name section.Name = ReadZeroTerminatedString (8); // VirtualSize 4 Advance (4); // VirtualAddress 4 section.VirtualAddress = ReadUInt32 (); // SizeOfRawData 4 section.SizeOfRawData = ReadUInt32 (); // PointerToRawData 4 section.PointerToRawData = ReadUInt32 (); // PointerToRelocations 4 // PointerToLineNumbers 4 // NumberOfRelocations 2 // NumberOfLineNumbers 2 // Characteristics 4 Advance (16); sections [i] = section; } image.Sections = sections; } void ReadCLIInfo () { MoveTo (cli); // - CLIHeader // Cb 4 (0x48 00 00 00) // MajorRuntimeVersion 2 (0x02 0x00) // MinorRuntimeVersion 2 (0x05 0x00) Advance (8); // Metadata 8 metadata = ReadDataDirectory (); // Flags 4 image.Attributes = (BinaryClrFlags) ReadUInt32 (); // EntryPointToken 4 image.EntryPointToken = ReadUInt32 (); // Resources 8 image.Resources = ReadDataDirectory (); // StrongNameSignature 8 image.StrongName = ReadDataDirectory (); // CodeManagerTable 8 // VTableFixups 8 // ExportAddressTableJumps 8 // ManagedNativeHeader 8 MoveTo (metadata); if (ReadUInt32 () != 0x424a5342) throw new BadImageFormatException (); // MajorVersion 2 // MinorVersion 2 // Reserved 4 Advance (8); var s = ReadZeroTerminatedString (ReadInt32 ()); image.DotNetRuntimeVersionString = s; image.DotNetRuntime = ParseDotNetRuntimeVersion(s); } private TargetRuntime ParseDotNetRuntimeVersion(string s) { if (string.IsNullOrEmpty(s)) return TargetRuntime.NotDotNet; switch (s[1]) { case '1': return s[3] == '0' ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case '2': return TargetRuntime.Net_2_0; case '4': default: return TargetRuntime.Net_4_0; } } internal static Image ReadImageFrom(Stream stream, bool minimal) { var reader = new ImageReader(stream) { ReadClrInfo =true }; try { reader.ReadImage (); return reader.image; } catch (EndOfStreamException e) { throw new BadImageFormatException (reader.FileStreamName, e); } } } }
using System.Runtime.Remoting; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Core.Exceptions; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Services; using Umbraco.Tests.CodeFirst.TestModels.Composition; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class ContentTypeServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Content() { IContentType contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); IContent contentItem = MockedContent.CreateTextpageContent(contentType1, "Testing", -1); ServiceContext.ContentService.SaveAndPublishWithStatus(contentItem); var initProps = contentItem.Properties.Count; var initPropTypes = contentItem.PropertyTypes.Count(); //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); //re-load it from the db contentItem = ServiceContext.ContentService.GetById(contentItem.Id); Assert.AreEqual(initPropTypes - 1, contentItem.PropertyTypes.Count()); Assert.AreEqual(initProps - 1, contentItem.Properties.Count); } [Test] public void Rebuild_Content_Xml_On_Alias_Change() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); var contentType2 = MockedContentTypes.CreateTextpageContentType("test2", "Test2"); ServiceContext.ContentTypeService.Save(contentType1); ServiceContext.ContentTypeService.Save(contentType2); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); var contentItems2 = MockedContent.CreateTextpageContent(contentType2, -1, 5).ToArray(); contentItems2.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); //only update the contentType1 alias which will force an xml rebuild for all content of that type contentType1.Alias = "newAlias"; ServiceContext.ContentTypeService.Save(contentType1); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<newAlias")); } foreach (var c in contentItems2) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<test2")); //should remain the same } } [Test] public void Rebuild_Content_Xml_On_Property_Removal() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); var alias = contentType1.PropertyTypes.First().Alias; var elementToMatch = "<" + alias + ">"; foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.Contains(elementToMatch)); //verify that it is there before we remove the property } //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); var reQueried = ServiceContext.ContentTypeService.GetContentType(contentType1.Id); var reContent = ServiceContext.ContentService.GetById(contentItems1.First().Id); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsFalse(xml.Xml.Contains(elementToMatch)); //verify that it is no longer there } } [Test] public void Get_Descendants() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.Descendants(); //Assert Assert.AreEqual(10, descendants.Count()); } [Test] public void Get_Descendants_And_Self() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.DescendantsAndSelf(); //Assert Assert.AreEqual(11, descendants.Count()); } [Test] public void Get_With_Missing_Guid() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; //Act var result = contentTypeService.GetMediaType(Guid.NewGuid()); //Assert Assert.IsNull(result); } [Test] public void Can_Bulk_Save_New_Hierarchy_Content_Types() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); // Act contentTypeService.Save(hierarchy, 0); Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); for (var i = 0; i < hierarchy.Count(); i++) { if (i == 0) continue; Assert.AreEqual(hierarchy.ElementAt(i).ParentId, hierarchy.ElementAt(i - 1).Id); } } [Test] public void Can_Save_ContentType_Structure_And_Create_Content_Based_On_It() { // Arrange var cs = ServiceContext.ContentService; var cts = ServiceContext.ContentTypeService; var dtdYesNo = ServiceContext.DataTypeService.GetDataTypeDefinitionById(-49); var ctBase = new ContentType(-1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" }; ctBase.AddPropertyType(new PropertyType(dtdYesNo, Constants.Conventions.Content.NaviHide) { Name = "Hide From Navigation", } /*,"Navigation"*/); cts.Save(ctBase); const string contentTypeAlias = "HomePage"; var ctHomePage = new ContentType(ctBase, contentTypeAlias) { Name = "Home Page", Alias = contentTypeAlias, Icon = "settingDomain.gif", Thumbnail = "folder.png", AllowedAsRoot = true }; ctHomePage.AddPropertyType(new PropertyType(dtdYesNo, "someProperty") { Name = "Some property" } /*,"Navigation"*/); cts.Save(ctHomePage); // Act var homeDoc = cs.CreateContent("Home Page", -1, contentTypeAlias); cs.SaveAndPublishWithStatus(homeDoc); // Assert Assert.That(ctBase.HasIdentity, Is.True); Assert.That(ctHomePage.HasIdentity, Is.True); Assert.That(homeDoc.HasIdentity, Is.True); Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); } [Test] public void Create_Content_Type_Ensures_Sort_Orders() { var service = ServiceContext.ContentTypeService; var contentType = new ContentType(-1) { Alias = "test", Name = "Test", Description = "ContentType used for simple text pages", Icon = ".sprTreeDoc3", Thumbnail = "doc2.png", SortOrder = 1, CreatorId = 0, Trashed = false }; contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, DataTypeDefinitionId = -88 }); contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TinyMCEAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, DataTypeDefinitionId = -87 }); contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "Name of the author", Mandatory = false, DataTypeDefinitionId = -88 }); service.Save(contentType); var sortOrders = contentType.PropertyTypes.Select(x => x.SortOrder).ToArray(); Assert.AreEqual(1, sortOrders.Count(x => x == 0)); Assert.AreEqual(1, sortOrders.Count(x => x == 1)); Assert.AreEqual(1, sortOrders.Count(x => x == 2)); } [Test] public void Can_Create_And_Save_ContentType_Composition() { /* * Global * - Components * - Category */ var service = ServiceContext.ContentTypeService; var global = MockedContentTypes.CreateSimpleContentType("global", "Global"); service.Save(global); var components = MockedContentTypes.CreateSimpleContentType("components", "Components", global, true); service.Save(components); var component = MockedContentTypes.CreateSimpleContentType("component", "Component", components, true); service.Save(component); var category = MockedContentTypes.CreateSimpleContentType("category", "Category", global, true); service.Save(category); var success = category.AddContentType(component); Assert.That(success, Is.False); } [Test] public void Can_Delete_Parent_ContentType_When_Child_Has_Content() { var cts = ServiceContext.ContentTypeService; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true); cts.Save(contentType); var childContentType = MockedContentTypes.CreateSimpleContentType("childPage", "Child Page", contentType, true, "Child Content"); cts.Save(childContentType); var cs = ServiceContext.ContentService; var content = cs.CreateContent("Page 1", -1, childContentType.Alias); cs.Save(content); cts.Delete(contentType); Assert.IsNotNull(content.Id); Assert.AreNotEqual(0, content.Id); Assert.IsNotNull(childContentType.Id); Assert.AreNotEqual(0, childContentType.Id); Assert.IsNotNull(contentType.Id); Assert.AreNotEqual(0, contentType.Id); var deletedContent = cs.GetById(content.Id); var deletedChildContentType = cts.GetContentType(childContentType.Id); var deletedContentType = cts.GetContentType(contentType.Id); Assert.IsNull(deletedChildContentType); Assert.IsNull(deletedContent); Assert.IsNull(deletedContentType); } [Test] public void Deleting_ContentType_Sends_Correct_Number_Of_DeletedEntities_In_Events() { var cts = ServiceContext.ContentTypeService; var deletedEntities = 0; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page"); cts.Save(contentType); ContentTypeService.DeletedContentType += (sender, args) => { deletedEntities += args.DeletedEntities.Count(); }; cts.Delete(contentType); Assert.AreEqual(deletedEntities, 1); } [Test] public void Deleting_Multiple_ContentTypes_Sends_Correct_Number_Of_DeletedEntities_In_Events() { var cts = ServiceContext.ContentTypeService; var deletedEntities = 0; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page"); cts.Save(contentType); var contentType2 = MockedContentTypes.CreateSimpleContentType("otherPage", "Other page"); cts.Save(contentType2); ContentTypeService.DeletedContentType += (sender, args) => { deletedEntities += args.DeletedEntities.Count(); }; cts.Delete(contentType); cts.Delete(contentType2); Assert.AreEqual(2, deletedEntities); } [Test] public void Deleting_ContentType_With_Child_Sends_Correct_Number_Of_DeletedEntities_In_Events() { var cts = ServiceContext.ContentTypeService; var deletedEntities = 0; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page"); cts.Save(contentType); var contentType2 = MockedContentTypes.CreateSimpleContentType("subPage", "Sub page"); contentType2.ParentId = contentType.Id; cts.Save(contentType2); ContentTypeService.DeletedContentType += (sender, args) => { deletedEntities += args.DeletedEntities.Count(); }; cts.Delete(contentType); Assert.AreEqual(2, deletedEntities); } [Test] public void Can_Remove_ContentType_Composition_From_ContentType() { //Test for U4-2234 var cts = ServiceContext.ContentTypeService; //Arrange var component = CreateComponent(); cts.Save(component); var banner = CreateBannerComponent(component); cts.Save(banner); var site = CreateSite(); cts.Save(site); var homepage = CreateHomepage(site); cts.Save(homepage); //Add banner to homepage var added = homepage.AddContentType(banner); cts.Save(homepage); //Assert composition var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(added, Is.True); Assert.That(bannerExists, Is.True); Assert.That(bannerPropertyExists, Is.True); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); //Remove banner from homepage var removed = homepage.RemoveContentType(banner.Alias); cts.Save(homepage); //Assert composition var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(removed, Is.True); Assert.That(bannerStillExists, Is.False); Assert.That(bannerPropertyStillExists, Is.False); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); } [Test] public void Can_Copy_ContentType_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var sut = simpleContentType.DeepCloneWithResetIdentities("newcategory"); service.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); var contentType = service.GetContentType(sut.Id); var category = service.GetContentType(categoryId); Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); Assert.AreEqual(contentType.ParentId, category.ParentId); Assert.AreEqual(contentType.Level, category.Level); Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); Assert.AreNotEqual(contentType.Id, category.Id); Assert.AreNotEqual(contentType.Key, category.Key); Assert.AreNotEqual(contentType.Path, category.Path); Assert.AreNotEqual(contentType.SortOrder, category.SortOrder); Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2", null, true); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1, true); service.Save(simpleContentType); // Act var clone = simpleContentType.DeepCloneWithResetIdentities("newcategory"); clone.RemoveContentType("parent1"); clone.AddContentType(parentContentType2); clone.ParentId = parentContentType2.Id; service.Save(clone); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id); } [Test] public void Can_Copy_ContentType_With_Service_To_Root() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var clone = service.Copy(simpleContentType, "newcategory", "new category"); // Assert Assert.That(clone.HasIdentity, Is.True); var cloned = service.GetContentType(clone.Id); var original = service.GetContentType(categoryId); Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); //it's been copied to root Assert.AreEqual(cloned.ParentId, -1); Assert.AreEqual(cloned.Level, 1); Assert.AreEqual(cloned.PropertyTypes.Count(), original.PropertyTypes.Count()); Assert.AreEqual(cloned.PropertyGroups.Count(), original.PropertyGroups.Count()); for (int i = 0; i < cloned.PropertyGroups.Count; i++) { Assert.AreEqual(cloned.PropertyGroups[i].PropertyTypes.Count, original.PropertyGroups[i].PropertyTypes.Count); foreach (var propertyType in cloned.PropertyGroups[i].PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } } foreach (var propertyType in cloned.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } Assert.AreNotEqual(cloned.Id, original.Id); Assert.AreNotEqual(cloned.Key, original.Key); Assert.AreNotEqual(cloned.Path, original.Path); Assert.AreNotEqual(cloned.SortOrder, original.SortOrder); Assert.AreNotEqual(cloned.PropertyTypes.First(x => x.Alias.Equals("title")).Id, original.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(cloned.PropertyGroups.First(x => x.Name.Equals("Content")).Id, original.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_With_Service() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2", null, true); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1, true); service.Save(simpleContentType); // Act var clone = service.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id); } [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_To_Referenced_Composition() { //Related the second issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange var service = ServiceContext.ContentTypeService; var parent = MockedContentTypes.CreateSimpleContentType(); service.Save(parent); var child = MockedContentTypes.CreateSimpleContentType("simpleChildPage", "Simple Child Page", parent, true); service.Save(child); var composition = MockedContentTypes.CreateMetaContentType(); service.Save(composition); //Adding Meta-composition to child doc type child.AddContentType(composition); service.Save(child); // Act var duplicatePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var added = composition.AddPropertyType(duplicatePropertyType, "Meta"); // Assert Assert.That(added, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(composition)); Assert.DoesNotThrow(() => service.GetContentType("simpleChildPage")); } [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_In_Composition_Graph() { // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateSimpleContentType("basePage", "Base Page", null, true); service.Save(basePage); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true); service.Save(advancedPage); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); var seoComposition = MockedContentTypes.CreateSeoContentType(); service.Save(seoComposition); var metaAdded = contentPage.AddContentType(metaComposition); service.Save(contentPage); var seoAdded = advancedPage.AddContentType(seoComposition); service.Save(advancedPage); // Act var duplicatePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var addedToBasePage = basePage.AddPropertyType(duplicatePropertyType, "Content"); var addedToAdvancedPage = advancedPage.AddPropertyType(duplicatePropertyType, "Content"); var addedToMeta = metaComposition.AddPropertyType(duplicatePropertyType, "Meta"); var addedToSeo = seoComposition.AddPropertyType(duplicatePropertyType, "Seo"); // Assert Assert.That(metaAdded, Is.True); Assert.That(seoAdded, Is.True); Assert.That(addedToBasePage, Is.True); Assert.That(addedToAdvancedPage, Is.False); Assert.That(addedToMeta, Is.True); Assert.That(addedToSeo, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(basePage)); Assert.Throws<InvalidCompositionException>(() => service.Save(metaComposition)); Assert.Throws<InvalidCompositionException>(() => service.Save(seoComposition)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); Assert.DoesNotThrow(() => service.GetContentType("meta")); Assert.DoesNotThrow(() => service.GetContentType("seo")); } [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_At_Root_Which_Conflicts_With_Third_Levels_Composition() { /* * BasePage, gets 'Title' added but should not be allowed * -- Content Page * ---- Advanced Page -> Content Meta * Content Meta :: Composition, has 'Title' * * Content Meta has 'Title' PropertyType * Adding 'Title' to BasePage should fail */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var compositionAdded = advancedPage.AddContentType(contentMetaComposition); service.Save(advancedPage); //NOTE: It should not be possible to Save 'BasePage' with the Title PropertyType added var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(compositionAdded, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(basePage)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); } [Test] public void Cannot_Rename_PropertyType_Alias_On_Composition_Which_Would_Cause_Conflict_In_Other_Composition() { /* * Meta renames alias to 'title' * Seo has 'Title' * BasePage * -- ContentPage * ---- AdvancedPage -> Seo * ------ MoreAdvanedPage -> Meta */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var moreAdvancedPage = MockedContentTypes.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); service.Save(moreAdvancedPage); var seoComposition = MockedContentTypes.CreateSeoContentType(); service.Save(seoComposition); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); service.Save(advancedPage); var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); service.Save(seoComposition); var seoCompositionAdded = advancedPage.AddContentType(seoComposition); var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); service.Save(advancedPage); service.Save(moreAdvancedPage); var keywordsPropertyType = metaComposition.PropertyTypes.First(x => x.Alias.Equals("metakeywords")); keywordsPropertyType.Alias = "title"; // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(seoCompositionAdded, Is.True); Assert.That(metaCompositionAdded, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(metaComposition)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); Assert.DoesNotThrow(() => service.GetContentType("moreAdvancedPage")); } [Test] public void Can_Add_Additional_Properties_On_Composition_Once_Composition_Has_Been_Saved() { /* * Meta renames alias to 'title' * Seo has 'Title' * BasePage * -- ContentPage * ---- AdvancedPage -> Seo * ------ MoreAdvancedPage -> Meta */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var moreAdvancedPage = MockedContentTypes.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); service.Save(moreAdvancedPage); var seoComposition = MockedContentTypes.CreateSeoContentType(); service.Save(seoComposition); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); service.Save(advancedPage); var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); service.Save(seoComposition); var seoCompositionAdded = advancedPage.AddContentType(seoComposition); var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); service.Save(advancedPage); service.Save(moreAdvancedPage); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(seoCompositionAdded, Is.True); Assert.That(metaCompositionAdded, Is.True); var testPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "test") { Name = "Test", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var testAdded = seoComposition.AddPropertyType(testPropertyType, "Content"); service.Save(seoComposition); Assert.That(testAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); Assert.DoesNotThrow(() => service.GetContentType("moreAdvancedPage")); } [Test] public void Cannot_Rename_PropertyGroup_On_Child_Avoiding_Conflict_With_Parent_PropertyGroup() { // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true, "Content"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true, "Content_"); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true, "Details"); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); //Change the name of the tab on the "root" content type 'page'. var propertyGroup = contentPage.PropertyGroups["Content_"]; Assert.Throws<Exception>(() => contentPage.PropertyGroups.Add(new PropertyGroup { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 })); // Assert Assert.That(compositionAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); } [Test] public void Cannot_Rename_PropertyType_Alias_Causing_Conflicts_With_Parents() { // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); // Act var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content"); var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content"); service.Save(basePage); service.Save(contentPage); service.Save(advancedPage); //Rename the PropertyType to something that already exists in the Composition - NOTE this should not be allowed and Saving should throw an exception var authorPropertyTypeToRename = advancedPage.PropertyTypes.First(x => x.Alias.Equals("author")); authorPropertyTypeToRename.Alias = "title"; // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(advancedPage)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); } [Test] public void Can_Add_PropertyType_Alias_Which_Exists_In_Composition_Outside_Graph() { /* * Meta (Composition) * Content Meta (Composition) has 'Title' -> Meta * BasePage * -- ContentPage gets 'Title' added -> Meta * ---- Advanced Page */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateSimpleContentType("basePage", "Base Page", null, true); service.Save(basePage); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", basePage, true); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true); service.Save(advancedPage); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); var metaAdded = contentPage.AddContentType(metaComposition); service.Save(contentPage); var metaAddedToComposition = contentMetaComposition.AddContentType(metaComposition); service.Save(contentMetaComposition); // Act var propertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var addedToContentPage = contentPage.AddPropertyType(propertyType, "Content"); // Assert Assert.That(metaAdded, Is.True); Assert.That(metaAddedToComposition, Is.True); Assert.That(addedToContentPage, Is.True); Assert.DoesNotThrow(() => service.Save(contentPage)); } [Test] public void Can_Rename_PropertyGroup_With_Inherited_PropertyGroups() { //Related the first issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, false, "Content_"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true); service.Save(contentPage); var composition = MockedContentTypes.CreateMetaContentType(); composition.AddPropertyGroup("Content"); service.Save(composition); //Adding Meta-composition to child doc type contentPage.AddContentType(composition); service.Save(contentPage); // Act var propertyTypeOne = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "testTextbox") { Name = "Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var firstOneAdded = contentPage.AddPropertyType(propertyTypeOne, "Content_"); var propertyTypeTwo = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "anotherTextbox") { Name = "Another Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var secondOneAdded = contentPage.AddPropertyType(propertyTypeTwo, "Content"); service.Save(contentPage); Assert.That(page.PropertyGroups.Contains("Content_"), Is.True); var propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup{ Id = propertyGroup.Id, Name = "ContentTab", SortOrder = 0}); service.Save(page); // Assert Assert.That(firstOneAdded, Is.True); Assert.That(secondOneAdded, Is.True); var contentType = service.GetContentType("contentPage"); Assert.That(contentType, Is.Not.Null); var compositionPropertyGroups = contentType.CompositionPropertyGroups; // now it is still 1, because we don't propagate renames anymore Assert.That(compositionPropertyGroups.Count(x => x.Name.Equals("Content_")), Is.EqualTo(1)); var propertyTypeCount = contentType.PropertyTypes.Count(); var compPropertyTypeCount = contentType.CompositionPropertyTypes.Count(); Assert.That(propertyTypeCount, Is.EqualTo(5)); Assert.That(compPropertyTypeCount, Is.EqualTo(10)); } [Test] public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true, "Content_"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true, "Contentx"); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true, "Contenty"); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content_");//Will be added to the parent tab var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content");//Will be added to the "Content Meta" composition service.Save(contentPage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var descriptionPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "description") { Name = "Description", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var keywordsPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "keywords") { Name = "Keywords", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content_");//Will be added to an ancestor tab var descriptionAdded = advancedPage.AddPropertyType(descriptionPropertyType, "Contentx");//Will be added to a parent tab var keywordsAdded = advancedPage.AddPropertyType(keywordsPropertyType, "Content");//Will be added to the "Content Meta" composition service.Save(advancedPage); //Change the name of the tab on the "root" content type 'page'. var propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); service.Save(page); // Assert Assert.That(compositionAdded, Is.True); Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(descriptionAdded, Is.True); Assert.That(keywordsAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); var advancedPageReloaded = service.GetContentType("advancedPage"); var contentUnderscoreTabExists = advancedPageReloaded.CompositionPropertyGroups.Any(x => x.Name.Equals("Content_")); // now is true, because we don't propagate renames anymore Assert.That(contentUnderscoreTabExists, Is.True); var numberOfContentTabs = advancedPageReloaded.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(4)); } [Test] public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups_v2() { // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true, "Content_"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true, "Content"); service.Save(contentPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = page.AddPropertyType(bodyTextPropertyType, "Content_"); var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content_"); service.Save(page); service.Save(contentPage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); //Change the name of the tab on the "root" content type 'page'. var propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); service.Save(page); // Assert Assert.That(compositionAdded, Is.True); Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); } [Test] public void Can_Remove_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); basePage.RemovePropertyGroup("Content"); service.Save(basePage); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(compositionAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); var contentType = service.GetContentType("contentPage"); var propertyGroup = contentType.PropertyGroups["Content"]; } [Test] public void Can_Remove_PropertyGroup_Without_Removing_Property_Types() { var service = ServiceContext.ContentTypeService; var basePage = (IContentType)MockedContentTypes.CreateBasicContentType(); basePage.AddPropertyGroup("Content"); basePage.AddPropertyGroup("Meta"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = basePage.AddPropertyType(authorPropertyType, "Content"); var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = basePage.AddPropertyType(authorPropertyType, "Meta"); service.Save(basePage); basePage = service.GetContentType(basePage.Id); var totalPt = basePage.PropertyTypes.Count(); basePage.RemovePropertyGroup("Content"); service.Save(basePage); basePage = service.GetContentType(basePage.Id); Assert.AreEqual(totalPt, basePage.PropertyTypes.Count()); } [Test] public void Can_Add_PropertyGroup_With_Same_Name_On_Parent_and_Child() { /* * BasePage * - Content Page * -- Advanced Page * Content Meta :: Composition */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(compositionAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); var contentType = service.GetContentType("contentPage"); var propertyGroup = contentType.PropertyGroups["Content"]; var numberOfContentTabs = contentType.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(3)); //Ensure that adding a new PropertyType to the "Content"-tab also adds it to the right group var descriptionPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "description", Name = "Description", Description = "", Mandatory = false, SortOrder = 1,DataTypeDefinitionId = -88 }; var descriptionAdded = contentType.AddPropertyType(descriptionPropertyType, "Content"); service.Save(contentType); Assert.That(descriptionAdded, Is.True); var contentPageReloaded = service.GetContentType("contentPage"); var propertyGroupReloaded = contentPageReloaded.PropertyGroups["Content"]; var hasDescriptionPropertyType = propertyGroupReloaded.PropertyTypes.Contains("description"); Assert.That(hasDescriptionPropertyType, Is.True); var descriptionPropertyTypeReloaded = propertyGroupReloaded.PropertyTypes["description"]; Assert.That(descriptionPropertyTypeReloaded.PropertyGroupId.IsValueCreated, Is.False); } private ContentType CreateComponent() { var component = new ContentType(-1) { Alias = "component", Name = "Component", Description = "ContentType used for Component grouping", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "componentGroup") { Name = "Component Group", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); return component; } private ContentType CreateBannerComponent(ContentType parent) { const string contentTypeAlias = "banner"; var banner = new ContentType(parent, contentTypeAlias) { Alias = contentTypeAlias, Name = "Banner Component", Description = "ContentType used for Banner Component", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var propertyType = new PropertyType("test", DataTypeDatabaseType.Ntext, "bannerName") { Name = "Banner Name", Description = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -88 }; banner.AddPropertyType(propertyType, "Component"); return banner; } private ContentType CreateSite() { var site = new ContentType(-1) { Alias = "site", Name = "Site", Description = "ContentType used for Site inheritence", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 2, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "hostname") { Name = "Hostname", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); return site; } private ContentType CreateHomepage(ContentType parent) { const string contentTypeAlias = "homepage"; var contentType = new ContentType(parent, contentTypeAlias) { Alias = contentTypeAlias, Name = "Homepage", Description = "ContentType used for the Homepage", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "Name of the author", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); return contentType; } private IContentType[] CreateContentTypeHierarchy() { //create the master type var masterContentType = MockedContentTypes.CreateSimpleContentType("masterContentType", "MasterContentType"); masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); ServiceContext.ContentTypeService.Save(masterContentType); //add the one we just created var list = new List<IContentType> { masterContentType }; for (var i = 0; i < 10; i++) { var contentType = MockedContentTypes.CreateSimpleContentType("childType" + i, "ChildType" + i, //make the last entry in the list, this one's parent list.Last(), true); list.Add(contentType); } return list.ToArray(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Validation; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableSortedSet{T}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableSortedSet<T> { /// <summary> /// A sorted set that mutates with little or no memory allocations, /// can produce and/or build on immutable sorted set instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableSortedSet{T}.Union"/> and other bulk change methods /// already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableSortedSetBuilderDebuggerProxy<>))] public sealed class Builder : ISortKeyCollection<T>, IReadOnlyCollection<T>, ISet<T>, ICollection { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private ImmutableSortedSet<T>.Node _root = ImmutableSortedSet<T>.Node.EmptyNode; /// <summary> /// The comparer to use for sorting the set. /// </summary> private IComparer<T> _comparer = Comparer<T>.Default; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableSortedSet<T> _immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int _version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object _syncRoot; /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> /// <param name="set">A set to act as the basis for a new set.</param> internal Builder(ImmutableSortedSet<T> set) { Requires.NotNull(set, "set"); _root = set._root; _comparer = set.KeyComparer; _immutable = set; } #region ISet<T> Properties /// <summary> /// Gets the number of elements in this set. /// </summary> public int Count { get { return this.Root.Count; } } /// <summary> /// Gets a value indicating whether this instance is read-only. /// </summary> /// <value>Always <c>false</c>.</value> bool ICollection<T>.IsReadOnly { get { return false; } } #endregion /// <summary> /// Gets the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>The element at the given position.</returns> /// <remarks> /// No index setter is offered because the element being replaced may not sort /// to the same position in the sorted collection as the replacing element. /// </remarks> public T this[int index] { get { return _root[index]; } } /// <summary> /// Gets the maximum value in the collection, as defined by the comparer. /// </summary> /// <value>The maximum value in the set.</value> public T Max { get { return _root.Max; } } /// <summary> /// Gets the minimum value in the collection, as defined by the comparer. /// </summary> /// <value>The minimum value in the set.</value> public T Min { get { return _root.Min; } } /// <summary> /// Gets or sets the <see cref="IComparer{T}"/> object that is used to determine equality for the values in the <see cref="ImmutableSortedSet{T}"/>. /// </summary> /// <value>The comparer that is used to determine equality for the values in the set.</value> /// <remarks> /// When changing the comparer in such a way as would introduce collisions, the conflicting elements are dropped, /// leaving only one of each matching pair in the collection. /// </remarks> public IComparer<T> KeyComparer { get { return _comparer; } set { Requires.NotNull(value, "value"); if (value != _comparer) { var newRoot = Node.EmptyNode; foreach (T item in this) { bool mutated; newRoot = newRoot.Add(item, value, out mutated); } _immutable = null; _comparer = value; this.Root = newRoot; } } } /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets or sets the root node that represents the data in this collection. /// </summary> private Node Root { get { return _root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. _version++; if (_root != value) { _root = value; // Clear any cached value for the immutable view since it is now invalidated. _immutable = null; } } } #region ISet<T> Methods /// <summary> /// Adds an element to the current set and returns a value to indicate if the /// element was successfully added. /// </summary> /// <param name="item">The element to add to the set.</param> /// <returns>true if the element is added to the set; false if the element is already in the set.</returns> public bool Add(T item) { bool mutated; this.Root = this.Root.Add(item, _comparer, out mutated); return mutated; } /// <summary> /// Removes all elements in the specified collection from the current set. /// </summary> /// <param name="other">The collection of items to remove from the set.</param> public void ExceptWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); foreach (T item in other) { bool mutated; this.Root = this.Root.Remove(item, _comparer, out mutated); } } /// <summary> /// Modifies the current set so that it contains only elements that are also in a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void IntersectWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); var result = ImmutableSortedSet<T>.Node.EmptyNode; foreach (T item in other) { if (this.Contains(item)) { bool mutated; result = result.Add(item, _comparer, out mutated); } } this.Root = result; } /// <summary> /// Determines whether the current set is a proper (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> public bool IsProperSubsetOf(IEnumerable<T> other) { return this.ToImmutable().IsProperSubsetOf(other); } /// <summary> /// Determines whether the current set is a proper (strict) superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsProperSupersetOf(IEnumerable<T> other) { return this.ToImmutable().IsProperSupersetOf(other); } /// <summary> /// Determines whether the current set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> public bool IsSubsetOf(IEnumerable<T> other) { return this.ToImmutable().IsSubsetOf(other); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsSupersetOf(IEnumerable<T> other) { return this.ToImmutable().IsSupersetOf(other); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> public bool Overlaps(IEnumerable<T> other) { return this.ToImmutable().Overlaps(other); } /// <summary> /// Determines whether the current set and the specified collection contain the same elements. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is equal to other; otherwise, false.</returns> public bool SetEquals(IEnumerable<T> other) { return this.ToImmutable().SetEquals(other); } /// <summary> /// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void SymmetricExceptWith(IEnumerable<T> other) { this.Root = this.ToImmutable().SymmetricExcept(other)._root; } /// <summary> /// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void UnionWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); foreach (T item in other) { bool mutated; this.Root = this.Root.Add(item, _comparer, out mutated); } } /// <summary> /// Adds an element to the current set and returns a value to indicate if the /// element was successfully added. /// </summary> /// <param name="item">The element to add to the set.</param> void ICollection<T>.Add(T item) { this.Add(item); } /// <summary> /// Removes all elements from this set. /// </summary> public void Clear() { this.Root = ImmutableSortedSet<T>.Node.EmptyNode; } /// <summary> /// Determines whether the set contains a specific value. /// </summary> /// <param name="item">The object to locate in the set.</param> /// <returns>true if item is found in the set; false otherwise.</returns> public bool Contains(T item) { return this.Root.Contains(item, _comparer); } /// <summary> /// See <see cref="ICollection{T}"/> /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { _root.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the set. /// </summary> /// <param name="item">The object to remove from the set.</param> /// <returns><c>true</c> if the item was removed from the set; <c>false</c> if the item was not found in the set.</returns> public bool Remove(T item) { bool mutated; this.Root = this.Root.Remove(item, _comparer, out mutated); return mutated; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> public ImmutableSortedSet<T>.Enumerator GetEnumerator() { return this.Root.GetEnumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.Root.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an <see cref="IEnumerable{T}"/> that iterates over this /// collection in reverse order. /// </summary> /// <returns> /// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}.Builder"/> /// in reverse order. /// </returns> [Pure] public IEnumerable<T> Reverse() { return new ReverseEnumerable(_root); } /// <summary> /// Creates an immutable sorted set based on the contents of this instance. /// </summary> /// <returns>An immutable set.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableSortedSet<T> ToImmutable() { // Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (_immutable == null) { _immutable = ImmutableSortedSet<T>.Wrap(this.Root, _comparer); } return _immutable; } #region ICollection members /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="System.NotImplementedException"></exception> void ICollection.CopyTo(Array array, int arrayIndex) { this.Root.CopyTo(array, arrayIndex); } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> /// <exception cref="System.NotImplementedException"></exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> /// <exception cref="System.NotImplementedException"></exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } #endregion } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableSortedSetBuilderDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableSortedSet<T>.Builder _set; /// <summary> /// The simple view of the collection. /// </summary> private T[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSetBuilderDebuggerProxy{T}"/> class. /// </summary> /// <param name="builder">The collection to display in the debugger</param> public ImmutableSortedSetBuilderDebuggerProxy(ImmutableSortedSet<T>.Builder builder) { Requires.NotNull(builder, "builder"); _set = builder; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Contents { get { if (_contents == null) { _contents = _set.ToArray(_set.Count); } return _contents; } } } }
#region Licence /**************************************************************************** Copyright 1999-2015 Vincent J. Jacquet. All rights reserved. Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it, subject to the following restrictions: 1. The author is not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. 4. This notice may not be removed or altered. ****************************************************************************/ #endregion using System; using System.Diagnostics; namespace WmcSoft.Units { /// <summary> /// Represents an amount measured in some <see cref="Metric"/>. /// </summary> [DebuggerDisplay("{_amount,nq} {_metric.Symbol,nq}")] public struct Quantity : IComparable<Quantity>, IComparable, IEquatable<Quantity> { #region Fields readonly decimal _amount; readonly Metric _metric; #endregion #region Lifecycle public Quantity(Metric metric) : this(decimal.Zero, metric) { } public Quantity(decimal amount, Metric metric) { if (metric == null) throw new ArgumentNullException(nameof(metric)); _amount = amount; _metric = metric; } public void Deconstruct(out decimal amount, out Metric metric) { amount = _amount; metric = _metric; } #endregion #region Properties public decimal Amount => _amount; public Metric Metric => _metric; #endregion #region Methods public Quantity Round(RoundingPolicy policy) { if (policy == null) throw new ArgumentNullException("policy"); return new Quantity(policy.Round(_amount), _metric); } #endregion #region Operators public static implicit operator decimal(Quantity that) { return that._amount; } public static Quantity operator +(Quantity x, Quantity y) { if (x.Metric != y.Metric) throw new IncompatibleMetricException(); return new Quantity(x._amount + y._amount, x.Metric); } public static Quantity Add(Quantity x, Quantity y) { return x + y; } public static Quantity operator -(Quantity x, Quantity y) { if (x.Metric != y.Metric) throw new IncompatibleMetricException(); return new Quantity(x._amount - y._amount, x.Metric); } public static Quantity Subtract(Quantity x, Quantity y) { return x - y; } public static Quantity operator *(Quantity x, Quantity y) { int count = 0; int index = 0; if (x.Metric is DerivedUnit) { count += ((DerivedUnit)x.Metric).Terms.Length; } else { count += 1; } if (y.Metric is DerivedUnit) { count += ((DerivedUnit)y.Metric).Terms.Length; } else { count += 1; } DerivedUnitTerm[] terms = new DerivedUnitTerm[count]; if (x.Metric is DerivedUnit) { ((DerivedUnit)x.Metric).Terms.CopyTo(terms, index); index += ((DerivedUnit)x.Metric).Terms.Length; } else { terms[index++] = new DerivedUnitTerm((Unit)x.Metric, 1); } if (y.Metric is DerivedUnit) { ((DerivedUnit)x.Metric).Terms.CopyTo(terms, index); } else { terms[index++] = new DerivedUnitTerm((Unit)y.Metric, 1); } return new Quantity(x._amount * y._amount, new DerivedUnit(terms)); } public static Quantity Multiply(Quantity x, Quantity y) { return x * y; } public static Quantity operator *(Quantity value, decimal multiplier) { return new Quantity(multiplier * value._amount, value.Metric); } public static Quantity Multiply(Quantity value, decimal multiplier) { return value * multiplier; } public static Quantity operator /(Quantity x, Quantity y) { int count = 0; int index = 0; if (x.Metric is DerivedUnit) { count += ((DerivedUnit)x.Metric).Terms.Length; } else { count += 1; } if (y.Metric is DerivedUnit) { count += ((DerivedUnit)y.Metric).Terms.Length; } else { count += 1; } DerivedUnitTerm[] terms = new DerivedUnitTerm[count]; if (x.Metric is DerivedUnit) { ((DerivedUnit)x.Metric).Terms.CopyTo(terms, index); index += ((DerivedUnit)x.Metric).Terms.Length; } else { terms[index++] = new DerivedUnitTerm((Unit)x.Metric, 1); } if (y.Metric is DerivedUnit) { DerivedUnitTerm term; for (int i = 0; i < ((DerivedUnit)x.Metric).Terms.Length; i++) { term = ((DerivedUnit)x.Metric).Terms[i]; terms[index++] = new DerivedUnitTerm(term.Unit, -term.Power); } ((DerivedUnit)x.Metric).Terms.CopyTo(terms, index); } else { terms[index++] = new DerivedUnitTerm((Unit)y.Metric, -1); } return new Quantity(x._amount / y._amount, new DerivedUnit(terms)); } public static Quantity Divide(Quantity x, Quantity y) { return x / y; } public static Quantity operator /(Quantity value, decimal divider) { return new Quantity(value._amount / divider, value.Metric); } public static Quantity Divide(Quantity value, decimal divider) { return value / divider; } public static bool operator ==(Quantity x, Quantity y) { return ((IComparable)x).CompareTo(y) == 0; } public static bool operator !=(Quantity x, Quantity y) { return x.CompareTo(y) != 0; } public static bool operator <(Quantity x, Quantity y) { return x.CompareTo(y) < 0; } public static bool operator <=(Quantity x, Quantity y) { return x.CompareTo(y) <= 0; } public static bool operator >(Quantity x, Quantity y) { return x.CompareTo(y) > 0; } public static bool operator >=(Quantity x, Quantity y) { return x.CompareTo(y) >= 0; } public override bool Equals(object obj) { if (obj == null) return false; return CompareTo((Quantity)obj) == 0; } public override int GetHashCode() { if (_metric == null) return 0; return _amount.GetHashCode() ^ _metric.GetHashCode(); } #endregion #region Membres de IComparable int IComparable.CompareTo(object obj) { if (obj == null) return 1; return CompareTo((Quantity)obj); } #endregion #region IEquatable<Quantity> Membres public bool Equals(Quantity other) { return CompareTo(other) == 0; } #endregion #region IComparable<Quantity> Membres public int CompareTo(Quantity other) { // TODO: attempt to convert before deciding... if (_metric != other._metric) throw new IncompatibleMetricException(); return _amount.CompareTo(other._amount); } #endregion } /// <summary> /// Represents an amount measured in some <see cref="Metric"/>. Strongly typed version. /// </summary> /// <typeparam name="M">The metric</typeparam> public struct Quantity<M> : IComparable<Quantity<M>>, IComparable, IEquatable<Quantity<M>> where M : Metric, new() { #region Fields private static readonly M _metric = new M(); readonly decimal _amount; #endregion #region Lifecycle public Quantity(decimal amount) { _amount = amount; } public void Deconstruct(out decimal amount, out Metric metric) { amount = _amount; metric = _metric; } #endregion #region Properties public decimal Amount => _amount; public Metric Metric => _metric; #endregion #region Operators public static implicit operator Quantity<M>(int value) { return new Quantity<M>(value); } public static implicit operator Quantity<M>(double value) { return new Quantity<M>((decimal)value); } public static implicit operator Quantity<M>(decimal value) { return new Quantity<M>(value); } public static explicit operator decimal(Quantity<M> that) { return that._amount; } public static implicit operator Quantity(Quantity<M> that) { return new Quantity(that._amount, new M()); } public static Quantity<M> operator +(Quantity<M> x, Quantity<M> y) { return new Quantity<M>(x._amount + y._amount); } public static Quantity<M> Add(Quantity<M> x, Quantity<M> y) { return x + y; } public static Quantity<M> operator -(Quantity<M> x, Quantity<M> y) { return new Quantity<M>(x._amount - y._amount); } public static Quantity<M> Subtract(Quantity<M> x, Quantity<M> y) { return x - y; } public static Quantity<M> operator *(decimal multiplier, Quantity<M> value) { return new Quantity<M>(multiplier * value._amount); } public static Quantity<M> Multiply(decimal multiplier, Quantity<M> value) { return value * multiplier; } public static Quantity<M> operator *(Quantity<M> value, decimal multiplier) { return new Quantity<M>(multiplier * value._amount); } public static Quantity<M> Multiply(Quantity<M> value, decimal multiplier) { return value * multiplier; } public static Quantity operator *(Quantity<M> x, Quantity y) { return ((Quantity)x) * y; } public static Quantity Multiply(Quantity<M> x, Quantity y) { return x * y; } public static Quantity<M> operator /(Quantity<M> value, decimal divider) { return new Quantity<M>(value._amount / divider); } public static Quantity<M> Divide(Quantity<M> value, decimal divider) { return value / divider; } public static Quantity operator /(decimal divider, Quantity<M> value) { return new Quantity(divider / value._amount, new DerivedUnit(new DerivedUnitTerm((Unit)Activator.CreateInstance(typeof(M)), -1))); } public static Quantity Divide(decimal divider, Quantity<M> value) { return divider / value; } public static Quantity operator /(Quantity<M> x, Quantity y) { return ((Quantity)x) / y; } public static Quantity Divide(Quantity<M> x, Quantity y) { return x / y; } public static bool operator >=(Quantity<M> x, Quantity<M> y) { return x.CompareTo(y) >= 0; } public static bool operator >(Quantity<M> x, Quantity<M> y) { return x.CompareTo(y) > 0; } public static bool operator <=(Quantity<M> x, Quantity<M> y) { return x.CompareTo(y) <= 0; } public static bool operator <(Quantity<M> x, Quantity<M> y) { return x.CompareTo(y) < 0; } public static bool operator ==(Quantity<M> x, Quantity<M> y) { return x.CompareTo(y) == 0; } public static bool operator !=(Quantity<M> x, Quantity<M> y) { return x.CompareTo(y) != 0; } #endregion #region IComparable<Quantity<M>> Members public int CompareTo(Quantity<M> other) { return _amount.CompareTo(other._amount); } #endregion #region IEquatable<Quantity<M>> Members public bool Equals(Quantity<M> other) { return CompareTo(other) == 0; } #endregion #region IComparable Members public int CompareTo(object obj) { if (obj == null || GetType() != obj.GetType()) return 1; var other = (Quantity<M>)obj; return _amount.CompareTo(other._amount); } #endregion public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var that = (Quantity<M>)obj; return (that == this); } public override int GetHashCode() { return _amount.GetHashCode(); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TakeOrSkipWhileQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// Take- and SkipWhile work similarly. Execution is broken into two phases: Search /// and Yield. /// /// During the Search phase, many partitions at once search for the first occurrence /// of a false element. As they search, any time a partition finds a false element /// whose index is lesser than the current lowest-known false element, the new index /// will be published, so other partitions can stop the search. The search stops /// as soon as (1) a partition exhausts its input, (2) the predicate yields false for /// one of the partition's elements, or (3) its input index passes the current lowest- /// known index (sufficient since a given partition's indices are always strictly /// incrementing -- asserted below). Elements are buffered during this process. /// /// Partitions use a barrier after Search and before moving on to Yield. Once all /// have passed the barrier, Yielding begins. At this point, the lowest-known false /// index will be accurate for the entire set, since all partitions have finished /// scanning. This is where TakeWhile and SkipWhile differ. TakeWhile will start at /// the beginning of its buffer and yield all elements whose indices are less than /// the lowest-known false index. SkipWhile, on the other hand, will skipp any such /// elements in the buffer, yielding those whose index is greater than or equal to /// the lowest-known false index, and then finish yielding any remaining elements in /// its data source (since it may have stopped prematurely due to (3) above). /// </summary> /// <typeparam name="TResult"></typeparam> internal sealed class TakeOrSkipWhileQueryOperator<TResult> : UnaryQueryOperator<TResult, TResult> { // Predicate function used to decide when to stop yielding elements. One pair is used for // index-based evaluation (i.e. it is passed the index as well as the element's value). private Func<TResult, bool> _predicate; private Func<TResult, int, bool> _indexedPredicate; private readonly bool _take; // Whether to take (true) or skip (false). private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. private bool _limitsParallelism = false; // The precomputed value of LimitsParallelism //--------------------------------------------------------------------------------------- // Initializes a new take-while operator. // // Arguments: // child - the child data source to enumerate // predicate - the predicate function (if expression tree isn't provided) // indexedPredicate - the index-based predicate function (if expression tree isn't provided) // take - whether this is a TakeWhile (true) or SkipWhile (false) // // Notes: // Only one kind of predicate can be specified, an index-based one or not. If an // expression tree is provided, the delegate cannot also be provided. // internal TakeOrSkipWhileQueryOperator(IEnumerable<TResult> child, Func<TResult, bool> predicate, Func<TResult, int, bool> indexedPredicate, bool take) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); Debug.Assert(predicate != null || indexedPredicate != null, "need a predicate function"); _predicate = predicate; _indexedPredicate = indexedPredicate; _take = take; InitOrderIndexState(); } /// <summary> /// Determines the order index state for the output operator /// </summary> private void InitOrderIndexState() { // SkipWhile/TakeWhile needs an increasing index. However, if the predicate expression depends on the index, // the index needs to be correct, not just increasing. OrdinalIndexState requiredIndexState = OrdinalIndexState.Increasing; OrdinalIndexState childIndexState = Child.OrdinalIndexState; if (_indexedPredicate != null) { requiredIndexState = OrdinalIndexState.Correct; _limitsParallelism = childIndexState == OrdinalIndexState.Increasing; } OrdinalIndexState indexState = ExchangeUtilities.Worse(childIndexState, OrdinalIndexState.Correct); if (indexState.IsWorseThan(requiredIndexState)) { _prematureMerge = true; } if (!_take) { // If the index was correct, now it is only increasing. indexState = indexState.Worse(OrdinalIndexState.Increasing); } SetOrdinalIndexState(indexState); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, bool preferStriping, QuerySettings settings) { if (_prematureMerge) { ListQueryResults<TResult> results = ExecuteAndCollectResults(inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings); PartitionedStream<TResult, int> listInputStream = results.GetPartitionedStream(); WrapHelper<int>(listInputStream, recipient, settings); } else { WrapHelper<TKey>(inputStream, recipient, settings); } } private void WrapHelper<TKey>(PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // Create shared data. OperatorState<TKey> operatorState = new OperatorState<TKey>(); CountdownEvent sharedBarrier = new CountdownEvent(partitionCount); Debug.Assert(_indexedPredicate == null || typeof(TKey) == typeof(int)); Func<TResult, TKey, bool> convertedIndexedPredicate = (Func<TResult, TKey, bool>)(object)_indexedPredicate; PartitionedStream<TResult, TKey> partitionedStream = new PartitionedStream<TResult, TKey>(partitionCount, inputStream.KeyComparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { partitionedStream[i] = new TakeOrSkipWhileQueryOperatorEnumerator<TKey>( inputStream[i], _predicate, convertedIndexedPredicate, _take, operatorState, sharedBarrier, settings.CancellationState.MergedCancellationToken, inputStream.KeyComparer); } recipient.Receive(partitionedStream); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TResult> Open(QuerySettings settings, bool preferStriping) { QueryResults<TResult> childQueryResults = Child.Open(settings, true); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TResult> AsSequentialQuery(CancellationToken token) { if (_take) { if (_indexedPredicate != null) { return Child.AsSequentialQuery(token).TakeWhile(_indexedPredicate); } return Child.AsSequentialQuery(token).TakeWhile(_predicate); } if (_indexedPredicate != null) { IEnumerable<TResult> wrappedIndexedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedIndexedChild.SkipWhile(_indexedPredicate); } IEnumerable<TResult> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.SkipWhile(_predicate); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the take- or skip-while. // class TakeOrSkipWhileQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TResult, TKey> { private readonly QueryOperatorEnumerator<TResult, TKey> _source; // The data source to enumerate. private readonly Func<TResult, bool> _predicate; // The actual predicate function. private readonly Func<TResult, TKey, bool> _indexedPredicate; // The actual index-based predicate function. private readonly bool _take; // Whether to execute a take- (true) or skip-while (false). private readonly IComparer<TKey> _keyComparer; // Comparer for the order keys. // These fields are all shared among partitions. private readonly OperatorState<TKey> _operatorState; // The lowest false found by any partition. private readonly CountdownEvent _sharedBarrier; // To separate the search/yield phases. private readonly CancellationToken _cancellationToken; // Token used to cancel this operator. private List<Pair> _buffer; // Our buffer. private Shared<int> _bufferIndex; // Our current index within the buffer. [allocate in moveNext to avoid false-sharing] private int _updatesSeen; // How many updates has this enumerator observed? (Each other enumerator will contribute one update.) private TKey _currentLowKey; // The lowest key rejected by one of the other enumerators. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal TakeOrSkipWhileQueryOperatorEnumerator( QueryOperatorEnumerator<TResult, TKey> source, Func<TResult, bool> predicate, Func<TResult, TKey, bool> indexedPredicate, bool take, OperatorState<TKey> operatorState, CountdownEvent sharedBarrier, CancellationToken cancelToken, IComparer<TKey> keyComparer) { Debug.Assert(source != null); Debug.Assert(predicate != null || indexedPredicate != null); Debug.Assert(operatorState != null); Debug.Assert(sharedBarrier != null); Debug.Assert(keyComparer != null); _source = source; _predicate = predicate; _indexedPredicate = indexedPredicate; _take = take; _operatorState = operatorState; _sharedBarrier = sharedBarrier; _cancellationToken = cancelToken; _keyComparer = keyComparer; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TResult currentElement, ref TKey currentKey) { // If the buffer has not been created, we will generate it lazily on demand. if (_buffer == null) { // Create a buffer, but don't publish it yet (in case of exception). List<Pair> buffer = new List<Pair>(); // Enter the search phase. In this phase, we scan the input until one of three // things happens: (1) all input has been exhausted, (2) the predicate yields // false for one of our elements, or (3) we move past the current lowest index // found by other partitions for a false element. As we go, we have to remember // the elements by placing them into the buffer. try { TResult current = default(TResult); TKey key = default(TKey); int i = 0; //counter to help with cancellation while (_source.MoveNext(ref current, ref key)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Add the current element to our buffer. buffer.Add(new Pair(current, key)); // See if another partition has found a false value before this element. If so, // we should stop scanning the input now and reach the barrier ASAP. if (_updatesSeen != _operatorState._updatesDone) { lock (_operatorState) { _currentLowKey = _operatorState._currentLowKey; _updatesSeen = _operatorState._updatesDone; } } if (_updatesSeen > 0 && _keyComparer.Compare(key, _currentLowKey) > 0) { break; } // Evaluate the predicate, either indexed or not based on info passed to the ctor. bool predicateResult; if (_predicate != null) { predicateResult = _predicate(current); } else { Debug.Assert(_indexedPredicate != null); predicateResult = _indexedPredicate(current, key); } if (!predicateResult) { // Signal that we've found a false element, racing with other partitions to // set the shared index value. lock (_operatorState) { if (_operatorState._updatesDone == 0 || _keyComparer.Compare(_operatorState._currentLowKey, key) > 0) { _currentLowKey = _operatorState._currentLowKey = key; _updatesSeen = ++_operatorState._updatesDone; } } break; } } } finally { // No matter whether we exit due to an exception or normal completion, we must ensure // that we signal other partitions that we have completed. Otherwise, we can cause deadlocks. _sharedBarrier.Signal(); } // Before exiting the search phase, we will synchronize with others. This is a barrier. _sharedBarrier.Wait(_cancellationToken); // Publish the buffer and set the index to just before the 1st element. _buffer = buffer; _bufferIndex = new Shared<int>(-1); } // Now either enter (or continue) the yielding phase. As soon as we reach this, we know the // current shared "low false" value is the absolute lowest with a false. if (_take) { // In the case of a take-while, we will yield each element from our buffer for which // the element is lesser than the lowest false index found. if (_bufferIndex.Value >= _buffer.Count - 1) { return false; } // Increment the index, and remember the values. ++_bufferIndex.Value; currentElement = (TResult)_buffer[_bufferIndex.Value].First; currentKey = (TKey)_buffer[_bufferIndex.Value].Second; return _operatorState._updatesDone == 0 || _keyComparer.Compare(_operatorState._currentLowKey, currentKey) > 0; } else { // If no false was found, the output is empty. if (_operatorState._updatesDone == 0) { return false; } // In the case of a skip-while, we must skip over elements whose index is lesser than the // lowest index found. Once we've exhausted the buffer, we must go back and continue // enumerating the data source until it is empty. if (_bufferIndex.Value < _buffer.Count - 1) { for (_bufferIndex.Value++; _bufferIndex.Value < _buffer.Count; _bufferIndex.Value++) { // If the current buffered element's index is greater than or equal to the smallest // false index found, we will yield it as a result. if (_keyComparer.Compare((TKey)_buffer[_bufferIndex.Value].Second, _operatorState._currentLowKey) >= 0) { currentElement = (TResult)_buffer[_bufferIndex.Value].First; currentKey = (TKey)_buffer[_bufferIndex.Value].Second; return true; } } } // Lastly, so long as our input still has elements, they will be yieldable. if (_source.MoveNext(ref currentElement, ref currentKey)) { Debug.Assert(_keyComparer.Compare(currentKey, _operatorState._currentLowKey) > 0, "expected remaining element indices to be greater than smallest"); return true; } } return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } class OperatorState<TKey> { volatile internal int _updatesDone = 0; internal TKey _currentLowKey; } } }
// 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. // //permutations for (((class_s.a+class_s.b)+class_s.c)+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+(class_s.b+class_s.c)) //(class_s.b+(class_s.a+class_s.c)) //(class_s.b+class_s.c) //(class_s.a+class_s.c) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //((class_s.a+class_s.b)+(class_s.c+class_s.d)) //(class_s.c+((class_s.a+class_s.b)+class_s.d)) //(class_s.c+class_s.d) //((class_s.a+class_s.b)+class_s.d) //(class_s.a+(class_s.b+class_s.d)) //(class_s.b+(class_s.a+class_s.d)) //(class_s.b+class_s.d) //(class_s.a+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) namespace CseTest { using System; public class Test_Main { static int Main() { int ret = 100; class_s s = new class_s(); class_s.a = return_int(false, -51); class_s.b = return_int(false, 86); class_s.c = return_int(false, 89); class_s.d = return_int(false, 56); int v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24; v1 = v2 = v3 = v4 = v5 = v6 = v7 = v8 = v9 = v10 = v11 = v12 = v13 = v14 = v15 = v16 = v17 = v18 = v19 = v20 = v21 = v22 = v23 = v24 = 0; #if LOOP do { #endif #if TRY try { #endif #if LOOP do { for (int i = 0; i < 10; i++) { #endif int stage = 0; start_try: try { checked { stage++; switch (stage) { case 1: v1 = (((class_s.a + class_s.b) + class_s.c) + class_s.d) + System.Int32.MaxValue; break; case 2: v2 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)) + System.Int32.MaxValue; ; break; case 3: v3 = ((class_s.a + class_s.b) + class_s.c) + System.Int32.MaxValue; ; break; case 4: v4 = (class_s.c + (class_s.a + class_s.b)) + System.Int32.MaxValue; ; break; case 5: v5 = (class_s.a + class_s.b) + System.Int32.MaxValue; break; case 6: v6 = (class_s.b + class_s.a) + System.Int32.MaxValue; ; break; case 7: v7 = (class_s.a + class_s.b) + System.Int32.MaxValue; ; break; case 8: v8 = (class_s.b + class_s.a) + System.Int32.MaxValue; ; break; case 9: v9 = (class_s.a + (class_s.b + class_s.c)) + System.Int32.MaxValue; break; case 10: v10 = (class_s.b + (class_s.a + class_s.c)) + System.Int32.MaxValue; break; case 11: v11 = (class_s.b + class_s.c) + System.Int32.MaxValue; break; case 12: v12 = (class_s.a + class_s.c) + System.Int32.MaxValue; break; case 13: v13 = ((class_s.a + class_s.b) + class_s.c) + System.Int32.MaxValue; break; case 14: v14 = (class_s.c + (class_s.a + class_s.b)) + System.Int32.MaxValue; break; case 15: v15 = ((class_s.a + class_s.b) + (class_s.c + class_s.d)) + System.Int32.MaxValue; break; case 16: v16 = (class_s.c + ((class_s.a + class_s.b) + class_s.d)) + System.Int32.MaxValue; break; case 17: v17 = (class_s.c + class_s.d) + System.Int32.MaxValue; break; case 18: v18 = ((class_s.a + class_s.b) + class_s.d) + System.Int32.MaxValue; break; case 19: v19 = (class_s.a + (class_s.b + class_s.d)) + System.Int32.MaxValue; break; case 20: v20 = (class_s.b + (class_s.a + class_s.d)) + System.Int32.MaxValue; break; case 21: v21 = (class_s.b + class_s.d) + System.Int32.MaxValue; break; case 22: v22 = (class_s.a + class_s.d) + System.Int32.MaxValue; break; case 23: v23 = (((class_s.a + class_s.b) + class_s.c) + class_s.d) + System.Int32.MaxValue; break; case 24: v24 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)) + System.Int32.MaxValue; break; } } } catch (System.OverflowException) { switch (stage) { case 1: v1 = (((class_s.a + class_s.b) + class_s.c) + class_s.d); break; case 2: v2 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); break; case 3: v3 = ((class_s.a + class_s.b) + class_s.c); break; case 4: v4 = (class_s.c + (class_s.a + class_s.b)); break; case 5: v5 = (class_s.a + class_s.b); break; case 6: v6 = (class_s.b + class_s.a); break; case 7: v7 = (class_s.a + class_s.b); break; case 8: v8 = (class_s.b + class_s.a); break; case 9: v9 = (class_s.a + (class_s.b + class_s.c)); break; case 10: v10 = (class_s.b + (class_s.a + class_s.c)); break; case 11: v11 = (class_s.b + class_s.c); break; case 12: v12 = (class_s.a + class_s.c); break; case 13: v13 = ((class_s.a + class_s.b) + class_s.c); break; case 14: v14 = (class_s.c + (class_s.a + class_s.b)); break; case 15: v15 = ((class_s.a + class_s.b) + (class_s.c + class_s.d)); break; case 16: v16 = (class_s.c + ((class_s.a + class_s.b) + class_s.d)); break; case 17: v17 = (class_s.c + class_s.d); break; case 18: v18 = ((class_s.a + class_s.b) + class_s.d); break; case 19: v19 = (class_s.a + (class_s.b + class_s.d)); break; case 20: v20 = (class_s.b + (class_s.a + class_s.d)); break; case 21: v21 = (class_s.b + class_s.d); break; case 22: v22 = (class_s.a + class_s.d); break; case 23: v23 = (((class_s.a + class_s.b) + class_s.c) + class_s.d); break; case 24: v24 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); break; } goto start_try; } if (stage != 25) { Console.WriteLine("test for stage failed actual value {0} ", stage); ret = ret + 1; } if (v1 != 180) { Console.WriteLine("test0: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v1); ret = ret + 1; } if (v2 != 180) { Console.WriteLine("test1: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v2); ret = ret + 1; } if (v3 != 124) { Console.WriteLine("test2: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v3); ret = ret + 1; } if (v4 != 124) { Console.WriteLine("test3: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v4); ret = ret + 1; } if (v5 != 35) { Console.WriteLine("test4: for (class_s.a+class_s.b) failed actual value {0} ", v5); ret = ret + 1; } if (v6 != 35) { Console.WriteLine("test5: for (class_s.b+class_s.a) failed actual value {0} ", v6); ret = ret + 1; } if (v7 != 35) { Console.WriteLine("test6: for (class_s.a+class_s.b) failed actual value {0} ", v7); ret = ret + 1; } if (v8 != 35) { Console.WriteLine("test7: for (class_s.b+class_s.a) failed actual value {0} ", v8); ret = ret + 1; } if (v9 != 124) { Console.WriteLine("test8: for (class_s.a+(class_s.b+class_s.c)) failed actual value {0} ", v9); ret = ret + 1; } if (v10 != 124) { Console.WriteLine("test9: for (class_s.b+(class_s.a+class_s.c)) failed actual value {0} ", v10); ret = ret + 1; } if (v11 != 175) { Console.WriteLine("test10: for (class_s.b+class_s.c) failed actual value {0} ", v11); ret = ret + 1; } if (v12 != 38) { Console.WriteLine("test11: for (class_s.a+class_s.c) failed actual value {0} ", v12); ret = ret + 1; } if (v13 != 124) { Console.WriteLine("test12: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v13); ret = ret + 1; } if (v14 != 124) { Console.WriteLine("test13: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v14); ret = ret + 1; } if (v15 != 180) { Console.WriteLine("test14: for ((class_s.a+class_s.b)+(class_s.c+class_s.d)) failed actual value {0} ", v15); ret = ret + 1; } if (v16 != 180) { Console.WriteLine("test15: for (class_s.c+((class_s.a+class_s.b)+class_s.d)) failed actual value {0} ", v16); ret = ret + 1; } if (v17 != 145) { Console.WriteLine("test16: for (class_s.c+class_s.d) failed actual value {0} ", v17); ret = ret + 1; } if (v18 != 91) { Console.WriteLine("test17: for ((class_s.a+class_s.b)+class_s.d) failed actual value {0} ", v18); ret = ret + 1; } if (v19 != 91) { Console.WriteLine("test18: for (class_s.a+(class_s.b+class_s.d)) failed actual value {0} ", v19); ret = ret + 1; } if (v20 != 91) { Console.WriteLine("test19: for (class_s.b+(class_s.a+class_s.d)) failed actual value {0} ", v20); ret = ret + 1; } if (v21 != 142) { Console.WriteLine("test20: for (class_s.b+class_s.d) failed actual value {0} ", v21); ret = ret + 1; } if (v22 != 5) { Console.WriteLine("test21: for (class_s.a+class_s.d) failed actual value {0} ", v22); ret = ret + 1; } if (v23 != 180) { Console.WriteLine("test22: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v23); ret = ret + 1; } if (v24 != 180) { Console.WriteLine("test23: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v24); ret = ret + 1; } #if LOOP class_s.d = return_int(false, 56); } } while (v24 == 0); #endif #if TRY } finally { } #endif #if LOOP } while (ret== 1000); #endif Console.WriteLine(ret); return ret; } private static int return_int(bool verbose, int input) { int ans; try { ans = input; } finally { if (verbose) { Console.WriteLine("returning : ans"); } } return ans; } } public class class_s { public static int a; public static int b; public static int c; public static int d; } }
// 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.AcceptanceTestsAzureCompositeModelClient { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for PolymorphismOperations. /// </summary> public static partial class PolymorphismOperationsExtensions { /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Fish GetValid(this IPolymorphismOperations operations) { return Task.Factory.StartNew(s => ((IPolymorphismOperations)s).GetValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Fish> GetValidAsync(this IPolymorphismOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, /// 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> public static void PutValid(this IPolymorphismOperations operations, Fish complexBody) { Task.Factory.StartNew(s => ((IPolymorphismOperations)s).PutValidAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, /// 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutValidAsync(this IPolymorphismOperations operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutValidWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> public static void PutValidMissingRequired(this IPolymorphismOperations operations, Fish complexBody) { Task.Factory.StartNew(s => ((IPolymorphismOperations)s).PutValidMissingRequiredAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutValidMissingRequiredAsync(this IPolymorphismOperations operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutValidMissingRequiredWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace System.Reflection.Context.Delegation { internal abstract class DelegatingType : TypeInfo { private readonly TypeInfo _typeInfo; public DelegatingType(Type type) { Debug.Assert(null != type); _typeInfo = type.GetTypeInfo(); if (_typeInfo == null) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_NoTypeInfoForThisType, type.FullName)); } } public override Assembly Assembly { get { return _typeInfo.Assembly; } } public override string AssemblyQualifiedName { get { return _typeInfo.AssemblyQualifiedName; } } public override Type BaseType { get { return _typeInfo.BaseType; } } public override bool ContainsGenericParameters { get { return _typeInfo.ContainsGenericParameters; } } public override int GenericParameterPosition { get { return _typeInfo.GenericParameterPosition; } } public override MethodBase DeclaringMethod { get { return _typeInfo.DeclaringMethod; } } public override Type DeclaringType { get { return _typeInfo.DeclaringType; } } public override string FullName { get { return _typeInfo.FullName; } } public override GenericParameterAttributes GenericParameterAttributes { get { return _typeInfo.GenericParameterAttributes; } } public override Guid GUID { get { return _typeInfo.GUID; } } public override bool IsEnum { get { return _typeInfo.IsEnum; } } public override bool IsGenericParameter { get { return _typeInfo.IsGenericParameter; } } public override bool IsGenericType { get { return _typeInfo.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return _typeInfo.IsGenericTypeDefinition; } } public override bool IsSecurityCritical { get { return _typeInfo.IsSecurityCritical; } } public override bool IsSecuritySafeCritical { get { return _typeInfo.IsSecuritySafeCritical; } } public override bool IsSecurityTransparent { get { return _typeInfo.IsSecurityTransparent; } } public override bool IsSerializable { get { return _typeInfo.IsSerializable; } } public override int MetadataToken { get { return _typeInfo.MetadataToken; } } public override Module Module { get { return _typeInfo.Module; } } public override string Name { get { return _typeInfo.Name; } } public override string Namespace { get { return _typeInfo.Namespace; } } public override Type ReflectedType { get { return _typeInfo.ReflectedType; } } public override StructLayoutAttribute StructLayoutAttribute { get { return _typeInfo.StructLayoutAttribute; } } public override RuntimeTypeHandle TypeHandle { get { return _typeInfo.TypeHandle; } } public override Type UnderlyingSystemType { get { return _typeInfo.UnderlyingSystemType; } } public Type UnderlyingType { get { return _typeInfo; } } internal object Delegate { get { return UnderlyingType; } } public override int GetArrayRank() { return _typeInfo.GetArrayRank(); } public override MemberInfo[] GetDefaultMembers() { return _typeInfo.GetDefaultMembers(); } public override string GetEnumName(object value) { return _typeInfo.GetEnumName(value); } public override string[] GetEnumNames() { return _typeInfo.GetEnumNames(); } public override Array GetEnumValues() { return _typeInfo.GetEnumValues(); } public override Type GetEnumUnderlyingType() { return _typeInfo.GetEnumUnderlyingType(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return _typeInfo.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return _typeInfo.GetCustomAttributes(inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return _typeInfo.GetCustomAttributesData(); } public override EventInfo[] GetEvents() { return _typeInfo.GetEvents(); } public override Type[] GetGenericArguments() { return _typeInfo.GetGenericArguments(); } public override Type[] GetGenericParameterConstraints() { return _typeInfo.GetGenericParameterConstraints(); } public override Type GetGenericTypeDefinition() { return _typeInfo.GetGenericTypeDefinition(); } public override InterfaceMapping GetInterfaceMap(Type interfaceType) { return _typeInfo.GetInterfaceMap(interfaceType); } public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { return _typeInfo.GetMember(name, type, bindingAttr); } protected override TypeCode GetTypeCodeImpl() { return Type.GetTypeCode(_typeInfo); } public override bool IsAssignableFrom(Type c) { return _typeInfo.IsAssignableFrom(c); } protected override bool IsContextfulImpl() { return _typeInfo.IsContextful; } public override bool IsDefined(Type attributeType, bool inherit) { return _typeInfo.IsDefined(attributeType, inherit); } public override bool IsEnumDefined(object value) { return _typeInfo.IsEnumDefined(value); } public override bool IsEquivalentTo(Type other) { return _typeInfo.IsEquivalentTo(other); } public override bool IsInstanceOfType(object o) { return _typeInfo.IsInstanceOfType(o); } protected override bool IsMarshalByRefImpl() { return _typeInfo.IsMarshalByRef; } // We could have used the default implementation of this on Type // if it handled special cases like generic type constraints // and interfaces->objec. public override bool IsSubclassOf(Type c) { return _typeInfo.IsSubclassOf(c); } protected override bool IsValueTypeImpl() { return _typeInfo.IsValueType; } protected override TypeAttributes GetAttributeFlagsImpl() { return _typeInfo.Attributes; } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return _typeInfo.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return _typeInfo.GetConstructors(bindingAttr); } public override Type GetElementType() { return _typeInfo.GetElementType(); } public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { return _typeInfo.GetEvent(name, bindingAttr); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return _typeInfo.GetEvents(bindingAttr); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { return _typeInfo.GetField(name, bindingAttr); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return _typeInfo.GetFields(bindingAttr); } public override Type GetInterface(string name, bool ignoreCase) { return _typeInfo.GetInterface(name, ignoreCase); } public override Type[] GetInterfaces() { return _typeInfo.GetInterfaces(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return _typeInfo.GetMembers(bindingAttr); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { // Unfortunately we cannot directly call the protected GetMethodImpl on _typeInfo. return (types == null) ? _typeInfo.GetMethod(name, bindingAttr) : _typeInfo.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return _typeInfo.GetMethods(bindingAttr); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { return _typeInfo.GetNestedType(name, bindingAttr); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return _typeInfo.GetNestedTypes(bindingAttr); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return _typeInfo.GetProperties(bindingAttr); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { // Unfortunately we cannot directly call the protected GetPropertyImpl on _typeInfo. PropertyInfo property; if (types == null) { // if types is null, we can ignore binder and modifiers if (returnType == null) { property = _typeInfo.GetProperty(name, bindingAttr); } else { // Ideally we should call a GetProperty overload that takes name, returnType, and bindingAttr, but not types. // But such an overload doesn't exist. On the other hand, this also guarantees that bindingAttr will be // the default lookup flags if types is null but returnType is not. Debug.Assert(bindingAttr == (BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)); property = _typeInfo.GetProperty(name, returnType); } } else { property = _typeInfo.GetProperty(name, bindingAttr, binder, returnType, types, modifiers); } return property; } protected override bool HasElementTypeImpl() { return _typeInfo.HasElementType; } public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { return _typeInfo.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } protected override bool IsArrayImpl() { return _typeInfo.IsArray; } protected override bool IsByRefImpl() { return _typeInfo.IsByRef; } protected override bool IsCOMObjectImpl() { return _typeInfo.IsCOMObject; } protected override bool IsPointerImpl() { return _typeInfo.IsPointer; } protected override bool IsPrimitiveImpl() { return _typeInfo.IsPrimitive; } public override Type MakeArrayType() { return _typeInfo.MakeArrayType(); } public override Type MakeArrayType(int rank) { return _typeInfo.MakeArrayType(rank); } public override Type MakePointerType() { return _typeInfo.MakePointerType(); } public override Type MakeGenericType(params Type[] typeArguments) { return _typeInfo.MakeGenericType(typeArguments); } public override Type MakeByRefType() { return _typeInfo.MakeByRefType(); } public override string ToString() { return _typeInfo.ToString(); } } }
using System; using System.Runtime.InteropServices; using System.Security.Permissions; using Microsoft.SharePoint; namespace Awesome.VersioningSiteColumns.Features.VersioningSiteColumns { /// <summary> /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. /// </summary> /// <remarks> /// The GUID attached to this class may be used during packaging and should not be modified. /// </remarks> [Guid("a052ad5e-f2e1-40e7-970a-9313f7b44b7a")] public class VersioningSiteColumnsEventReceiver : SPFeatureReceiver { public override void FeatureActivated(SPFeatureReceiverProperties properties) { using (SPSite site = properties.Feature.Parent as SPSite) { using (SPWeb rootWeb = site.RootWeb) { try { string columnCurrentVersion = "<Field Type=\"Text\" " + "Name=\"Current_Version\" " + "Description=\"The current version number of the file in SharePoint.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnCurrentVersionDisplay\" " + "StaticName=\"Current_Version\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnCurrentVersion); } catch { } try { string columnCurrentVersionDate = "<Field Type=\"DateTime\" " + "Name=\"Current_Date\" " + "Description=\"The current version number creation date.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnCurrentDisplay\" " + "StaticName=\"Current_Date\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnCurrentVersionDate); } catch { } try { string columnCurrentVersionBy = "<Field Type=\"User\" " + "Name=\"Current_By\" " + "Description=\"The current version number creator.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnCurrentByDisplay\" " + "StaticName=\"Current_By\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnCurrentVersionBy); } catch { } try { string columnApprovedVersion = "<Field Type=\"Text\" " + "Name=\"Approved_Version\" " + "Description=\"The latest approved version number of the file in SharePoint.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnApprovedVersionDisplay\" " + "StaticName=\"Approved_Version\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnApprovedVersion); } catch { } try { string columnApprovalDate = "<Field Type=\"DateTime\" " + "Name=\"Approval_Date\" " + "Description=\"Date and time the file was last approved in SharePoint.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnApprovedDisplay\" " + "StaticName=\"Approval_Date\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnApprovalDate); } catch { } try { string columnApprovedBy = "<Field Type=\"User\" " + "Name=\"Approved_By\" " + "Description=\"The person who last approved the file in SharePoint.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnApprovedByDisplay\" " + "StaticName=\"Approved_By\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnApprovedBy); } catch { } try { string columnPublishedVersion = "<Field Type=\"Text\" " + "Name=\"Published_Version\" " + "Description=\"The latest published version number of the file in SharePoint.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnPublishedVersionDisplay\" " + "StaticName=\"Published_Version\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnPublishedVersion); } catch { } try { string columnPublishDate = "<Field Type=\"DateTime\" " + "Name=\"Publish_Date\" " + "Description=\"Date and time the file was last published in SharePoint.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnPublishDisplay\" " + "StaticName=\"Publish_Date\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnPublishDate); } catch { } try { string columnPublishedBy = "<Field Type=\"User\" " + "Name=\"Published_By\" " + "Description=\"The person who last published the file in SharePoint.\" " + "DisplayName=\"$Resources:AwesomeVersioning,ColumnPublishedByDisplay\" " + "StaticName=\"Published_By\" " + "Group=\"$Resources:AwesomeVersioning,ColumnGroup\" " + "Hidden=\"TRUE\" " + "Required=\"FALSE\" " + "Sealed=\"FALSE\" " + "ShowInDisplayForm=\"FALSE\" " + "ShowInEditForm=\"FALSE\" " + "ShowInFileDlg=\"FALSE\" " + "ShowInListSettings=\"TRUE\" " + "ShowInNewForm=\"FALSE\"></Field>"; rootWeb.Fields.AddFieldAsXml(columnPublishedBy); } catch { } rootWeb.Update(); } } } } }
#region Namespaces using System; using System.Data; using System.Xml; using System.Collections.Generic; #endregion //Namespaces namespace Epi.Fields { /// <summary> /// Grid field /// </summary> public class GridField : FieldWithSeparatePrompt { #region Private Members private XmlElement viewElement; private XmlNode fieldNode; private List<GridColumnBase> columns; private DataTable dataSource; #endregion Private Members #region Public Events #endregion #region Constructors /// <summary> /// Constructor for the class. Receives Page object. /// </summary> /// <param name="page">The page this field belongs to.</param> public GridField(Page page) : base(page) { } /// <summary> /// Constructor for the class. Receives View object. /// </summary> /// <param name="view">The view this field belongs to.</param> public GridField(View view) : base(view) { } /// <summary> /// Constructor /// </summary> /// <param name="page">The page this field belongs to.</param> /// <param name="viewElement">The Xml view element of the GridField.</param> public GridField(Page page, XmlElement viewElement) : base(page) { this.viewElement = viewElement; this.Page = page; } /// <summary> /// /// </summary> /// <param name="view"></param> /// <param name="fieldNode"></param> public GridField(View view, XmlNode fieldNode) : base(view) { this.fieldNode = fieldNode; this.view.Project.Metadata.GetFieldData(this, this.fieldNode); } public GridField Clone() { GridField clone = (GridField)this.MemberwiseClone(); base.AssignMembers(clone); return clone; } #endregion Constructors #region Protected Properties #endregion Protected Properties #region Public Methods /// <summary> /// Deletes the field /// </summary> public override void Delete() { GetMetadata().DeleteField(this); view.MustRefreshFieldCollection = true; } /// <summary> /// Constructs a GridColumnBase object from a MetaFieldType enum /// </summary> /// <param name="columnType">A MetaFieldType enum</param> /// <returns>A GridColumnBase object</returns> public GridColumnBase CreateGridColumn(MetaFieldType columnType) { switch (columnType) { case MetaFieldType.UniqueKey: return new UniqueKeyColumn(this); case MetaFieldType.RecStatus: return new RecStatusColumn(this); case MetaFieldType.ForeignKey: return new ForeignKeyColumn(this); case MetaFieldType.Text: return new TextColumn(this); case MetaFieldType.PhoneNumber: return new PhoneNumberColumn(this); case MetaFieldType.Date: return new DateColumn(this); case MetaFieldType.Number: return new NumberColumn(this); default: return new TextColumn(this); } } public void SetNewRecordValue() { if (DataSource is DataTable) { foreach (DataRow row in ((DataTable)DataSource).Rows) { if (row.RowState != DataRowState.Deleted) { foreach (GridColumnBase column in Columns) { if (column is GridColumnBase && ((GridColumnBase)column).ShouldRepeatLast == false) { row[column.Name] = DBNull.Value; } } } } DataSource.AcceptChanges(); } } #endregion #region Public Properties /// <summary> /// Database Table Name of the page /// </summary> public string TableName { get { if (this.Page == null) { return null; } else { return this.Page.TableName + this.Name; } } } /// <summary> /// Returns field type /// </summary> public override MetaFieldType FieldType { get { return MetaFieldType.Grid; } } /// <summary> /// Gets the column collection /// </summary> public List<GridColumnBase> Columns { get { if (this.columns == null && !this.Id.Equals(0)) { this.columns = GetMetadata().GetGridColumnCollection(this); if (this.columns.Count.Equals(0)) { UniqueRowIdColumn uniqueRowIdColumn = new UniqueRowIdColumn(this); RecStatusColumn recStatusColumn = new RecStatusColumn(this); ForeignKeyColumn foreignKeyColumn = new ForeignKeyColumn(this); GlobalRecordIdColumn globalRecordIdColumn = new GlobalRecordIdColumn(this); uniqueRowIdColumn.SaveToDb(); recStatusColumn.SaveToDb(); foreignKeyColumn.SaveToDb(); globalRecordIdColumn.SaveToDb(); columns = GetMetadata().GetGridColumnCollection(this); } } return this.columns; } set { this.columns = value; } } /// <summary> /// In-memory storage of rows editing in Epi.Enter. /// This allows the datagrid control's contents to be persisted to the database. /// </summary> public DataTable DataSource { get { return dataSource; } set { dataSource = value; } } /// <summary> /// The view element of the field /// </summary> public XmlElement ViewElement { get { return viewElement; } set { viewElement = value; } } #endregion #region Protected Methods /// <summary> /// Inserts the field to the database /// </summary> protected override void InsertField() { this.Id = GetMetadata().CreateField(this); if (columns != null) { foreach (GridColumnBase column in columns) { column.Id = 0; ((Epi.Fields.Field)(column.Grid)).Id = this.Id; } } SaveColumnsToDb(); base.OnFieldAdded(); } /// <summary> /// Update the field to the database /// </summary> protected override void UpdateField() { GetMetadata().UpdateField(this); SaveColumnsToDb(); } #endregion Protected Methods #region Private Methods private void SaveColumnsToDb() { foreach (GridColumnBase gridColumn in Columns) { gridColumn.SaveToDb(); } } #endregion Private Methods #region Event Handlers #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedGlobalOrganizationOperationsClientTest { [xunit::FactAttribute] public void DeleteRequestObject() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); DeleteGlobalOrganizationOperationRequest request = new DeleteGlobalOrganizationOperationRequest { Operation = "operation615a23f7", ParentId = "parent_id8279e36b", }; DeleteGlobalOrganizationOperationResponse expectedResponse = new DeleteGlobalOrganizationOperationResponse { }; mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); DeleteGlobalOrganizationOperationResponse response = client.Delete(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteRequestObjectAsync() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); DeleteGlobalOrganizationOperationRequest request = new DeleteGlobalOrganizationOperationRequest { Operation = "operation615a23f7", ParentId = "parent_id8279e36b", }; DeleteGlobalOrganizationOperationResponse expectedResponse = new DeleteGlobalOrganizationOperationResponse { }; mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteGlobalOrganizationOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); DeleteGlobalOrganizationOperationResponse responseCallSettings = await client.DeleteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DeleteGlobalOrganizationOperationResponse responseCancellationToken = await client.DeleteAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Delete() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); DeleteGlobalOrganizationOperationRequest request = new DeleteGlobalOrganizationOperationRequest { Operation = "operation615a23f7", }; DeleteGlobalOrganizationOperationResponse expectedResponse = new DeleteGlobalOrganizationOperationResponse { }; mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); DeleteGlobalOrganizationOperationResponse response = client.Delete(request.Operation); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAsync() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); DeleteGlobalOrganizationOperationRequest request = new DeleteGlobalOrganizationOperationRequest { Operation = "operation615a23f7", }; DeleteGlobalOrganizationOperationResponse expectedResponse = new DeleteGlobalOrganizationOperationResponse { }; mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteGlobalOrganizationOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); DeleteGlobalOrganizationOperationResponse responseCallSettings = await client.DeleteAsync(request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DeleteGlobalOrganizationOperationResponse responseCancellationToken = await client.DeleteAsync(request.Operation, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); GetGlobalOrganizationOperationRequest request = new GetGlobalOrganizationOperationRequest { Operation = "operation615a23f7", ParentId = "parent_id8279e36b", }; Operation expectedResponse = new Operation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", User = "userb1cb11ee", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StartTime = "start_timebd8dd9c4", OperationGroupId = "operation_group_idd2040cf0", TargetLink = "target_link9b435dc0", Progress = 278622268, Error = new Error(), EndTime = "end_time89285d30", Region = "regionedb20d96", OperationType = "operation_typeece9e153", Status = Operation.Types.Status.Pending, HttpErrorMessage = "http_error_messageb5ef3c7f", TargetId = 6263187990225347157UL, ClientOperationId = "client_operation_id4e51b631", StatusMessage = "status_message2c618f86", HttpErrorStatusCode = 1766362655, Description = "description2cf9da67", InsertTime = "insert_time7467185a", SelfLink = "self_link7e87f12d", Warnings = { new Warnings(), }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); Operation response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); GetGlobalOrganizationOperationRequest request = new GetGlobalOrganizationOperationRequest { Operation = "operation615a23f7", ParentId = "parent_id8279e36b", }; Operation expectedResponse = new Operation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", User = "userb1cb11ee", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StartTime = "start_timebd8dd9c4", OperationGroupId = "operation_group_idd2040cf0", TargetLink = "target_link9b435dc0", Progress = 278622268, Error = new Error(), EndTime = "end_time89285d30", Region = "regionedb20d96", OperationType = "operation_typeece9e153", Status = Operation.Types.Status.Pending, HttpErrorMessage = "http_error_messageb5ef3c7f", TargetId = 6263187990225347157UL, ClientOperationId = "client_operation_id4e51b631", StatusMessage = "status_message2c618f86", HttpErrorStatusCode = 1766362655, Description = "description2cf9da67", InsertTime = "insert_time7467185a", SelfLink = "self_link7e87f12d", Warnings = { new Warnings(), }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); Operation responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Operation responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); GetGlobalOrganizationOperationRequest request = new GetGlobalOrganizationOperationRequest { Operation = "operation615a23f7", }; Operation expectedResponse = new Operation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", User = "userb1cb11ee", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StartTime = "start_timebd8dd9c4", OperationGroupId = "operation_group_idd2040cf0", TargetLink = "target_link9b435dc0", Progress = 278622268, Error = new Error(), EndTime = "end_time89285d30", Region = "regionedb20d96", OperationType = "operation_typeece9e153", Status = Operation.Types.Status.Pending, HttpErrorMessage = "http_error_messageb5ef3c7f", TargetId = 6263187990225347157UL, ClientOperationId = "client_operation_id4e51b631", StatusMessage = "status_message2c618f86", HttpErrorStatusCode = 1766362655, Description = "description2cf9da67", InsertTime = "insert_time7467185a", SelfLink = "self_link7e87f12d", Warnings = { new Warnings(), }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); Operation response = client.Get(request.Operation); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient> mockGrpcClient = new moq::Mock<GlobalOrganizationOperations.GlobalOrganizationOperationsClient>(moq::MockBehavior.Strict); GetGlobalOrganizationOperationRequest request = new GetGlobalOrganizationOperationRequest { Operation = "operation615a23f7", }; Operation expectedResponse = new Operation { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", User = "userb1cb11ee", Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", StartTime = "start_timebd8dd9c4", OperationGroupId = "operation_group_idd2040cf0", TargetLink = "target_link9b435dc0", Progress = 278622268, Error = new Error(), EndTime = "end_time89285d30", Region = "regionedb20d96", OperationType = "operation_typeece9e153", Status = Operation.Types.Status.Pending, HttpErrorMessage = "http_error_messageb5ef3c7f", TargetId = 6263187990225347157UL, ClientOperationId = "client_operation_id4e51b631", StatusMessage = "status_message2c618f86", HttpErrorStatusCode = 1766362655, Description = "description2cf9da67", InsertTime = "insert_time7467185a", SelfLink = "self_link7e87f12d", Warnings = { new Warnings(), }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GlobalOrganizationOperationsClient client = new GlobalOrganizationOperationsClientImpl(mockGrpcClient.Object, null); Operation responseCallSettings = await client.GetAsync(request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Operation responseCancellationToken = await client.GetAsync(request.Operation, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.ComponentModel; using System.Drawing; using System.ServiceProcess; using System.Windows.Forms; namespace ServiceManager { public partial class frmServiceSettings : Form { private IContainer components = (IContainer)null; private ServiceController currentControl; private GroupBox groupBox1; private TextBox txtDes; private TextBox txtDN; private TextBox txtSN; private Label label3; private Label label2; private Label label1; private GroupBox groupBox2; private GroupBox groupBox3; private Label label4; private ComboBox cmbStatus; private Label label5; private ComboBox cmbStartMode; private Button btnCancel; private Button btnAPPLY; private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(frmServiceSettings)); this.groupBox1 = new GroupBox(); this.txtDes = new TextBox(); this.txtDN = new TextBox(); this.txtSN = new TextBox(); this.label3 = new Label(); this.label2 = new Label(); this.label1 = new Label(); this.groupBox2 = new GroupBox(); this.cmbStatus = new ComboBox(); this.label5 = new Label(); this.cmbStartMode = new ComboBox(); this.label4 = new Label(); this.groupBox3 = new GroupBox(); this.btnCancel = new Button(); this.btnAPPLY = new Button(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); this.groupBox1.Controls.Add((Control)this.txtDes); this.groupBox1.Controls.Add((Control)this.txtDN); this.groupBox1.Controls.Add((Control)this.txtSN); this.groupBox1.Controls.Add((Control)this.label3); this.groupBox1.Controls.Add((Control)this.label2); this.groupBox1.Controls.Add((Control)this.label1); this.groupBox1.Location = new Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new Size(328, 133); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.txtDes.Font = new Font("Calibri", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtDes.Location = new Point(91, 73); this.txtDes.Multiline = true; this.txtDes.Name = "txtDes"; this.txtDes.ReadOnly = true; this.txtDes.ScrollBars = ScrollBars.Vertical; this.txtDes.Size = new Size(221, 48); this.txtDes.TabIndex = 5; this.txtDN.Font = new Font("Calibri", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtDN.Location = new Point(91, 46); this.txtDN.Name = "txtDN"; this.txtDN.ReadOnly = true; this.txtDN.Size = new Size(221, 23); this.txtDN.TabIndex = 4; this.txtSN.Font = new Font("Calibri", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtSN.Location = new Point(92, 19); this.txtSN.Name = "txtSN"; this.txtSN.ReadOnly = true; this.txtSN.Size = new Size(221, 23); this.txtSN.TabIndex = 3; this.label3.AutoSize = true; this.label3.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label3.Location = new Point(18, 75); this.label3.Name = "label3"; this.label3.Size = new Size(66, 13); this.label3.TabIndex = 2; this.label3.Text = "Description"; this.label2.AutoSize = true; this.label2.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label2.Location = new Point(6, 48); this.label2.Name = "label2"; this.label2.Size = new Size(79, 13); this.label2.TabIndex = 1; this.label2.Text = "Display Name"; this.label1.AutoSize = true; this.label1.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label1.Location = new Point(9, 21); this.label1.Name = "label1"; this.label1.Size = new Size(77, 13); this.label1.TabIndex = 0; this.label1.Text = "Service Name"; this.groupBox2.Controls.Add((Control)this.cmbStatus); this.groupBox2.Controls.Add((Control)this.label5); this.groupBox2.Controls.Add((Control)this.cmbStartMode); this.groupBox2.Controls.Add((Control)this.label4); this.groupBox2.Location = new Point(12, 151); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new Size(328, 83); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.cmbStatus.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbStatus.Font = new Font("Calibri", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.cmbStatus.FormattingEnabled = true; this.cmbStatus.Items.AddRange(new object[2] { (object) "Running", (object) "Stopped" }); this.cmbStatus.Location = new Point(91, 47); this.cmbStatus.Name = "cmbStatus"; this.cmbStatus.Size = new Size(154, 23); this.cmbStatus.TabIndex = 3; this.cmbStatus.SelectedIndexChanged += new EventHandler(this.cmbStatus_SelectedIndexChanged); this.label5.AutoSize = true; this.label5.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label5.Location = new Point(45, 49); this.label5.Name = "label5"; this.label5.Size = new Size(39, 13); this.label5.TabIndex = 2; this.label5.Text = "Status"; this.cmbStartMode.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbStartMode.Font = new Font("Calibri", 9.75f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.cmbStartMode.FormattingEnabled = true; this.cmbStartMode.Items.AddRange(new object[3] { (object) "Automatic", (object) "Manual", (object) "Disabled" }); this.cmbStartMode.Location = new Point(91, 19); this.cmbStartMode.Name = "cmbStartMode"; this.cmbStartMode.Size = new Size(154, 23); this.cmbStartMode.TabIndex = 1; this.cmbStartMode.SelectedIndexChanged += new EventHandler(this.cmbStartMode_SelectedIndexChanged); this.label4.AutoSize = true; this.label4.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.label4.Location = new Point(21, 21); this.label4.Name = "label4"; this.label4.Size = new Size(65, 13); this.label4.TabIndex = 0; this.label4.Text = "Start Mode"; this.groupBox3.Controls.Add((Control)this.btnCancel); this.groupBox3.Controls.Add((Control)this.btnAPPLY); this.groupBox3.Location = new Point(12, 240); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new Size(328, 50); this.groupBox3.TabIndex = 2; this.groupBox3.TabStop = false; this.btnCancel.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnCancel.Location = new Point(237, 17); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new Size(75, 23); this.btnCancel.TabIndex = 1; this.btnCancel.Text = "Close"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new EventHandler(this.btnCancel_Click); this.btnAPPLY.Enabled = false; this.btnAPPLY.Font = new Font("Segoe UI", 8.25f, FontStyle.Bold, GraphicsUnit.Point, (byte)0); this.btnAPPLY.Location = new Point(156, 17); this.btnAPPLY.Name = "btnAPPLY"; this.btnAPPLY.Size = new Size(75, 23); this.btnAPPLY.TabIndex = 0; this.btnAPPLY.Text = "Apply"; this.btnAPPLY.UseVisualStyleBackColor = true; this.btnAPPLY.Click += new EventHandler(this.btnAPPLY_Click); this.AutoScaleDimensions = new SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new Size(352, 304); this.Controls.Add((Control)this.groupBox3); this.Controls.Add((Control)this.groupBox2); this.Controls.Add((Control)this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = (Icon)resources.GetObject("$this.Icon"); this.MaximizeBox = false; this.Name = "frmServiceSettings"; this.ShowInTaskbar = false; this.StartPosition = FormStartPosition.CenterParent; this.Text = "Service Settings"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.ResumeLayout(false); } protected override void Dispose(bool disposing) { if (disposing && this.components != null) this.components.Dispose(); base.Dispose(disposing); } } }
using System; using System.Reflection; namespace Core { // Null Class // Class for dealing with the translation of database null values. public class Null { public static string NullString { get { return ""; } } public static bool NullBoolean { get { return false; } } public static DateTime NullDate { get { return DateTime.MinValue; } } public static decimal NullDecimal { get { return decimal.MinValue; } } public static double NullDouble { get { return double.MinValue; } } public static Guid NullGuid { get { return Guid.Empty; } } public static int NullInteger { get { return -1; } } public static short NullShort { get { return -1; } } public static float NullSingle { get { return float.MinValue; } } // convert an application encoded null value to a database null value ( used in DAL ) public static object GetNull(object objField, object objDBNull) { if (objField == null) return objDBNull; if (objField is short && Convert.ToInt16(objField) == NullShort) return objDBNull; if (objField is int && Convert.ToInt32(objField) == NullInteger) return objDBNull; if (objField is float && Convert.ToSingle(objField) == NullSingle) return objDBNull; if (objField is double && Convert.ToDouble(objField) == NullDouble) return objDBNull; if (objField is decimal && Convert.ToDecimal(objField) == NullDecimal) return objDBNull; if (objField is DateTime && Convert.ToDateTime(objField).Date == NullDate) return objDBNull; if (objField is bool && Convert.ToBoolean(objField) == NullBoolean) return objDBNull; if (objField is string) { if (objField == null) return objDBNull; if (objField.ToString() == NullString) return objDBNull; } if (objField is Guid) { var guild = (Guid) objField; if (guild.Equals(NullGuid)) return objDBNull; } return objField; } // checks if a field contains an application encoded null value public static bool IsNull(object objField) { if (objField != null) { if (objField is int) { return objField.Equals(NullInteger); } if (objField is float) { return objField.Equals(NullSingle); } if (objField is double) { return objField.Equals(NullDouble); } if (objField is decimal) { return objField.Equals(NullDecimal); } if (objField is DateTime) { DateTime objDateTime = Convert.ToDateTime(objField); return objDateTime.Date.Equals(NullDate); } if (objField is string) { return objField.Equals(NullString); } if (objField is bool) { return objField.Equals(NullBoolean); } if (objField is Guid) { return objField.Equals(NullGuid); } return false; } return true; } // sets a field to an application encoded null value ( used in BLL layer ) public static object SetNull(object objValue, object objField) { if (Convert.IsDBNull(objValue)) { if (objField is short) { return NullShort; } if (objField is int) { return NullInteger; } if (objField is float) { return NullSingle; } if (objField is double) { return NullDouble; } if (objField is decimal) { return NullDecimal; } if (objField is DateTime) { return NullDate; } if (objField is string) { return NullString; } if (objField is bool) { return NullBoolean; } if (objField is Guid) { return NullGuid; } return null; } return objValue; } public static object SetNull(PropertyInfo objPropertyInfo) { switch (objPropertyInfo.PropertyType.ToString()) { case "System.Int16": return NullShort; case "System.Int32": return NullInteger; case "System.Single": return NullSingle; case "System.Double": return NullDouble; case "System.Decimal": return NullDecimal; case "System.DateTime": return NullDate; case "System.String": return NullString; case "System.Boolean": return NullBoolean; case "System.Guid": return NullGuid; default: Type pType = objPropertyInfo.PropertyType; if (pType.BaseType.Equals(typeof (Enum))) { Array objEnumValues = Enum.GetValues(pType); Array.Sort(objEnumValues); return Enum.ToObject(pType, objEnumValues.GetValue(0)); } return null; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedPacketMirroringsClientSnippets { /// <summary>Snippet for AggregatedList</summary> public void AggregatedListRequestObject() { // Snippet: AggregatedList(AggregatedListPacketMirroringsRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) AggregatedListPacketMirroringsRequest request = new AggregatedListPacketMirroringsRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<PacketMirroringAggregatedList, KeyValuePair<string, PacketMirroringsScopedList>> response = packetMirroringsClient.AggregatedList(request); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, PacketMirroringsScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (PacketMirroringAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, PacketMirroringsScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListRequestObjectAsync() { // Snippet: AggregatedListAsync(AggregatedListPacketMirroringsRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) AggregatedListPacketMirroringsRequest request = new AggregatedListPacketMirroringsRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<PacketMirroringAggregatedList, KeyValuePair<string, PacketMirroringsScopedList>> response = packetMirroringsClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, PacketMirroringsScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((PacketMirroringAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, PacketMirroringsScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedList</summary> public void AggregatedList() { // Snippet: AggregatedList(string, string, int?, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<PacketMirroringAggregatedList, KeyValuePair<string, PacketMirroringsScopedList>> response = packetMirroringsClient.AggregatedList(project); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, PacketMirroringsScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (PacketMirroringAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, PacketMirroringsScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListAsync() { // Snippet: AggregatedListAsync(string, string, int?, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<PacketMirroringAggregatedList, KeyValuePair<string, PacketMirroringsScopedList>> response = packetMirroringsClient.AggregatedListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, PacketMirroringsScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((PacketMirroringAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, PacketMirroringsScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, PacketMirroringsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeletePacketMirroringRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) DeletePacketMirroringRequest request = new DeletePacketMirroringRequest { PacketMirroring = "", RequestId = "", Region = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = packetMirroringsClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = packetMirroringsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeletePacketMirroringRequest, CallSettings) // Additional: DeleteAsync(DeletePacketMirroringRequest, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) DeletePacketMirroringRequest request = new DeletePacketMirroringRequest { PacketMirroring = "", RequestId = "", Region = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await packetMirroringsClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await packetMirroringsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string packetMirroring = ""; // Make the request lro::Operation<Operation, Operation> response = packetMirroringsClient.Delete(project, region, packetMirroring); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = packetMirroringsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string packetMirroring = ""; // Make the request lro::Operation<Operation, Operation> response = await packetMirroringsClient.DeleteAsync(project, region, packetMirroring); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await packetMirroringsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetPacketMirroringRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) GetPacketMirroringRequest request = new GetPacketMirroringRequest { PacketMirroring = "", Region = "", Project = "", }; // Make the request PacketMirroring response = packetMirroringsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetPacketMirroringRequest, CallSettings) // Additional: GetAsync(GetPacketMirroringRequest, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) GetPacketMirroringRequest request = new GetPacketMirroringRequest { PacketMirroring = "", Region = "", Project = "", }; // Make the request PacketMirroring response = await packetMirroringsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string packetMirroring = ""; // Make the request PacketMirroring response = packetMirroringsClient.Get(project, region, packetMirroring); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string packetMirroring = ""; // Make the request PacketMirroring response = await packetMirroringsClient.GetAsync(project, region, packetMirroring); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertPacketMirroringRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) InsertPacketMirroringRequest request = new InsertPacketMirroringRequest { RequestId = "", Region = "", Project = "", PacketMirroringResource = new PacketMirroring(), }; // Make the request lro::Operation<Operation, Operation> response = packetMirroringsClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = packetMirroringsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertPacketMirroringRequest, CallSettings) // Additional: InsertAsync(InsertPacketMirroringRequest, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) InsertPacketMirroringRequest request = new InsertPacketMirroringRequest { RequestId = "", Region = "", Project = "", PacketMirroringResource = new PacketMirroring(), }; // Make the request lro::Operation<Operation, Operation> response = await packetMirroringsClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await packetMirroringsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, string, PacketMirroring, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; PacketMirroring packetMirroringResource = new PacketMirroring(); // Make the request lro::Operation<Operation, Operation> response = packetMirroringsClient.Insert(project, region, packetMirroringResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = packetMirroringsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, string, PacketMirroring, CallSettings) // Additional: InsertAsync(string, string, PacketMirroring, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; PacketMirroring packetMirroringResource = new PacketMirroring(); // Make the request lro::Operation<Operation, Operation> response = await packetMirroringsClient.InsertAsync(project, region, packetMirroringResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await packetMirroringsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListPacketMirroringsRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) ListPacketMirroringsRequest request = new ListPacketMirroringsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<PacketMirroringList, PacketMirroring> response = packetMirroringsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (PacketMirroring item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (PacketMirroringList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PacketMirroring item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PacketMirroring> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PacketMirroring item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListPacketMirroringsRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) ListPacketMirroringsRequest request = new ListPacketMirroringsRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<PacketMirroringList, PacketMirroring> response = packetMirroringsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PacketMirroring item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((PacketMirroringList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PacketMirroring item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PacketMirroring> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PacketMirroring item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, string, int?, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<PacketMirroringList, PacketMirroring> response = packetMirroringsClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (PacketMirroring item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (PacketMirroringList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PacketMirroring item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PacketMirroring> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PacketMirroring item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, string, int?, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<PacketMirroringList, PacketMirroring> response = packetMirroringsClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PacketMirroring item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((PacketMirroringList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PacketMirroring item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PacketMirroring> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PacketMirroring item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Patch</summary> public void PatchRequestObject() { // Snippet: Patch(PatchPacketMirroringRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) PatchPacketMirroringRequest request = new PatchPacketMirroringRequest { PacketMirroring = "", RequestId = "", Region = "", Project = "", PacketMirroringResource = new PacketMirroring(), }; // Make the request lro::Operation<Operation, Operation> response = packetMirroringsClient.Patch(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = packetMirroringsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchRequestObjectAsync() { // Snippet: PatchAsync(PatchPacketMirroringRequest, CallSettings) // Additional: PatchAsync(PatchPacketMirroringRequest, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) PatchPacketMirroringRequest request = new PatchPacketMirroringRequest { PacketMirroring = "", RequestId = "", Region = "", Project = "", PacketMirroringResource = new PacketMirroring(), }; // Make the request lro::Operation<Operation, Operation> response = await packetMirroringsClient.PatchAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await packetMirroringsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Patch</summary> public void Patch() { // Snippet: Patch(string, string, string, PacketMirroring, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string packetMirroring = ""; PacketMirroring packetMirroringResource = new PacketMirroring(); // Make the request lro::Operation<Operation, Operation> response = packetMirroringsClient.Patch(project, region, packetMirroring, packetMirroringResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = packetMirroringsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, string, PacketMirroring, CallSettings) // Additional: PatchAsync(string, string, string, PacketMirroring, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string packetMirroring = ""; PacketMirroring packetMirroringResource = new PacketMirroring(); // Make the request lro::Operation<Operation, Operation> response = await packetMirroringsClient.PatchAsync(project, region, packetMirroring, packetMirroringResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await packetMirroringsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissionsRequestObject() { // Snippet: TestIamPermissions(TestIamPermissionsPacketMirroringRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) TestIamPermissionsPacketMirroringRequest request = new TestIamPermissionsPacketMirroringRequest { Region = "", Resource = "", Project = "", TestPermissionsRequestResource = new TestPermissionsRequest(), }; // Make the request TestPermissionsResponse response = packetMirroringsClient.TestIamPermissions(request); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsRequestObjectAsync() { // Snippet: TestIamPermissionsAsync(TestIamPermissionsPacketMirroringRequest, CallSettings) // Additional: TestIamPermissionsAsync(TestIamPermissionsPacketMirroringRequest, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsPacketMirroringRequest request = new TestIamPermissionsPacketMirroringRequest { Region = "", Resource = "", Project = "", TestPermissionsRequestResource = new TestPermissionsRequest(), }; // Make the request TestPermissionsResponse response = await packetMirroringsClient.TestIamPermissionsAsync(request); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions() { // Snippet: TestIamPermissions(string, string, string, TestPermissionsRequest, CallSettings) // Create client PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string resource = ""; TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest(); // Make the request TestPermissionsResponse response = packetMirroringsClient.TestIamPermissions(project, region, resource, testPermissionsRequestResource); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync() { // Snippet: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CallSettings) // Additional: TestIamPermissionsAsync(string, string, string, TestPermissionsRequest, CancellationToken) // Create client PacketMirroringsClient packetMirroringsClient = await PacketMirroringsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string resource = ""; TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest(); // Make the request TestPermissionsResponse response = await packetMirroringsClient.TestIamPermissionsAsync(project, region, resource, testPermissionsRequestResource); // End snippet } } }
using System; using System.Collections.Generic; using System.Xml.Serialization; using Palaso.Annotations; using Palaso.Code; namespace Palaso.Text { /// <summary> /// A LanguageForm is a unicode string plus the id of its writing system /// </summary> public class LanguageForm : Annotatable, IComparable<LanguageForm> { private string _writingSystemId; private string _form; private readonly List<FormatSpan> _spans = new List<FormatSpan>(); /// <summary> /// See the comment on MultiText._parent for information on /// this field. /// </summary> private MultiTextBase _parent; /// <summary> /// for netreflector /// </summary> public LanguageForm() { } public LanguageForm(string writingSystemId, string form, MultiTextBase parent) { _parent = parent; _writingSystemId = writingSystemId; _form = form; } public LanguageForm(LanguageForm form, MultiTextBase parent) : this(form.WritingSystemId, form.Form, parent) { foreach (var span in form.Spans) AddSpan(span.Index, span.Length, span.Lang, span.Class, span.LinkURL); } [XmlAttribute("ws")] public string WritingSystemId { get { return _writingSystemId; } // needed for depersisting with netreflector set { _writingSystemId = value; } } [XmlText] public string Form { get { return _form; } set { _form = value; } } [XmlIgnore] public List<FormatSpan> Spans { get { return _spans; } } /// <summary> /// See the comment on MultiText._parent for information on /// this field. /// </summary> [XmlIgnore] public MultiTextBase Parent { get { return _parent; } } public override bool Equals(object other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (other.GetType() != typeof(LanguageForm)) return false; return Equals((LanguageForm)other); } public bool Equals(LanguageForm other) { if(other == null) return false; if (!IsStarred.Equals(other.IsStarred)) return false; if ((WritingSystemId != null && !WritingSystemId.Equals(other.WritingSystemId)) || (other.WritingSystemId != null && !other.WritingSystemId.Equals(WritingSystemId))) return false; if ((Form != null && !Form.Equals(other.Form)) || (other.Form != null && !other.Form.Equals(Form))) return false; if ((_annotation != null && !_annotation.Equals(other._annotation)) || (other._annotation != null && !other._annotation.Equals(_annotation))) return false; if (_spans != other.Spans) { if (_spans == null || other.Spans == null || _spans.Count != other.Spans.Count) return false; for (int i = 0; i < _spans.Count; ++i) { if (!_spans[i].Equals(other.Spans[i])) return false; } } return true; } public int CompareTo(LanguageForm other) { if(other == null) { return 1; } int writingSystemOrder = this.WritingSystemId.CompareTo(other.WritingSystemId); if (writingSystemOrder != 0) { return writingSystemOrder; } int formOrder = this.Form.CompareTo(other.Form); return formOrder; } public override Annotatable Clone() { var clone = new LanguageForm(); clone._writingSystemId = _writingSystemId; clone._form = _form; clone._annotation = _annotation == null ? null : _annotation.Clone(); foreach (var span in _spans) clone._spans.Add(new FormatSpan{Index=span.Index, Length=span.Length, Class=span.Class, Lang=span.Lang, LinkURL=span.LinkURL}); return clone; } /// <summary> /// Store formatting information for one span of characters in the form. /// (This information is not used, but needs to be maintained for output.) /// </summary> /// <remarks> /// Although the LIFT standard officially allows nested spans, we don't /// bother because FieldWorks doesn't support them. /// </remarks> public class FormatSpan { /// <summary>Store the starting index of the span</summary> public int Index { get; set; } /// <summary>Store the length of the span</summary> public int Length { get; set; } /// <summary>Store the language of the data in the span</summary> public string Lang { get; set; } /// <summary>Store the class (style) applied to the data in the span</summary> public string Class { get; set; } /// <summary>Store the underlying URL link of the span</summary> public string LinkURL { get; set; } public override bool Equals(object other) { var that = other as FormatSpan; if (that == null) return false; if (this.Index != that.Index || this.Length!= that.Length) return false; return (this.Class == that.Class && this.Lang == that.Lang && this.LinkURL == that.LinkURL); } } public void AddSpan(int index, int length, string lang, string style, string url) { var span = new FormatSpan {Index=index, Length=length, Lang=lang, Class=style, LinkURL=url}; _spans.Add(span); } /// <summary> /// Adjusts the spans for the changes from oldText to newText. Assume that only one chunk of /// text has changed between the two strings. /// </summary> public static void AdjustSpansForTextChange(string oldText, string newText, List<FormatSpan> spans) { // Be paranoid and check for null strings... Just convert them to empty strings for our purposes. // (I don't think they'll ever be null, but that fits the category of famous last words...) if (oldText == null) oldText = String.Empty; if (newText == null) newText = String.Empty; // If there are no spans, the text hasn't actually changed, or the text length hasn't changed, // then we'll assume we don't need to do anything. if (spans == null || spans.Count == 0 || newText == oldText || newText.Length == oldText.Length) return; // Get the locations of the first changing character in the old string. // We assume that OnTextChanged gets called for every single change, so that // pinpoints the location, and the change in string length tells us the length // of the change itself. (>0 = insertion, <0 = deletion) int minLength = Math.Min(newText.Length, oldText.Length); int diffLocation = minLength; for (int i = 0; i < minLength; ++i) { if (newText[i] != oldText[i]) { diffLocation = i; break; } } int diffLength = newText.Length - oldText.Length; foreach (var span in spans) AdjustSpan(span, diffLocation, diffLength); } private static void AdjustSpan(FormatSpan span, int location, int length) { if (span.Length <= 0) return; // we've already deleted all the characters in the span. if (location > span.Index + span.Length || length == 0) return; // the change doesn't affect the span. // Adding characters to the end of the span is probably desireable if they differ. if (length > 0) { // Inserting characters is fairly easy to deal with. if (location <= span.Index) span.Index += length; else span.Length += length; } // The span changes only if the deletion starts before the end of the span. else if (location < span.Index + span.Length) { // Deleting characters has a number of cases to deal with. // Remember, length is a negative number here! if (location < span.Index) { if (span.Index + length >= location) { span.Index += length; } else { int before = span.Index - location; span.Index = location; span.Length += (before + length); } } else { span.Length += length; if (span.Length < location - span.Index) span.Length = location - span.Index; } } } } }
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Represents an Azure Batch JobManager task. /// </summary> public partial class JobManagerTask : ITransportObjectProvider<Models.JobManagerTask>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty; public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty; public readonly PropertyAccessor<string> CommandLineProperty; public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<bool?> KillJobOnCompletionProperty; public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty; public readonly PropertyAccessor<bool?> RunExclusiveProperty; public readonly PropertyAccessor<UserIdentity> UserIdentityProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>("ApplicationPackageReferences", BindingAccess.Read | BindingAccess.Write); this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>("AuthenticationTokenSettings", BindingAccess.Read | BindingAccess.Write); this.CommandLineProperty = this.CreatePropertyAccessor<string>("CommandLine", BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write); this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write); this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("EnvironmentSettings", BindingAccess.Read | BindingAccess.Write); this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write); this.KillJobOnCompletionProperty = this.CreatePropertyAccessor<bool?>("KillJobOnCompletion", BindingAccess.Read | BindingAccess.Write); this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>("ResourceFiles", BindingAccess.Read | BindingAccess.Write); this.RunExclusiveProperty = this.CreatePropertyAccessor<bool?>("RunExclusive", BindingAccess.Read | BindingAccess.Write); this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>("UserIdentity", BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.JobManagerTask protocolObject) : base(BindingState.Bound) { this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor( ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences), "ApplicationPackageReferences", BindingAccess.Read | BindingAccess.Write); this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o)), "AuthenticationTokenSettings", BindingAccess.Read | BindingAccess.Write); this.CommandLineProperty = this.CreatePropertyAccessor( protocolObject.CommandLine, "CommandLine", BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)), "Constraints", BindingAccess.Read | BindingAccess.Write); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, "DisplayName", BindingAccess.Read | BindingAccess.Write); this.EnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings), "EnvironmentSettings", BindingAccess.Read | BindingAccess.Write); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, "Id", BindingAccess.Read | BindingAccess.Write); this.KillJobOnCompletionProperty = this.CreatePropertyAccessor( protocolObject.KillJobOnCompletion, "KillJobOnCompletion", BindingAccess.Read | BindingAccess.Write); this.ResourceFilesProperty = this.CreatePropertyAccessor( ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles), "ResourceFiles", BindingAccess.Read | BindingAccess.Write); this.RunExclusiveProperty = this.CreatePropertyAccessor( protocolObject.RunExclusive, "RunExclusive", BindingAccess.Read | BindingAccess.Write); this.UserIdentityProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o)), "UserIdentity", BindingAccess.Read | BindingAccess.Write); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="JobManagerTask"/> class. /// </summary> /// <param name='id'>The id of the task.</param> /// <param name='commandLine'>The command line of the task.</param> public JobManagerTask( string id, string commandLine) { this.propertyContainer = new PropertyContainer(); this.Id = id; this.CommandLine = commandLine; } internal JobManagerTask(Models.JobManagerTask protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region JobManagerTask /// <summary> /// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running /// the command line. /// </summary> public IList<ApplicationPackageReference> ApplicationPackageReferences { get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; } set { this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the settings for an authentication token that the task can use to perform Batch service operations. /// </summary> /// <remarks> /// If this property is set, the Batch service provides the task with an authentication token which can be used to /// authenticate Batch service operations without requiring an account access key. The token is provided via the /// AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token /// depend on the settings. For example, a task can request job permissions in order to add other tasks to the job, /// or check the status of the job or of other tasks. /// </remarks> public AuthenticationTokenSettings AuthenticationTokenSettings { get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; } set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; } } /// <summary> /// Gets or sets the command line of the task. /// </summary> /// <remarks> /// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment /// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command /// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. /// </remarks> public string CommandLine { get { return this.propertyContainer.CommandLineProperty.Value; } set { this.propertyContainer.CommandLineProperty.Value = value; } } /// <summary> /// Gets or sets the execution constraints for this JobManager task. /// </summary> public TaskConstraints Constraints { get { return this.propertyContainer.ConstraintsProperty.Value; } set { this.propertyContainer.ConstraintsProperty.Value = value; } } /// <summary> /// Gets or sets the display name of the JobManager task. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets or sets a set of environment settings for the JobManager task. /// </summary> public IList<EnvironmentSetting> EnvironmentSettings { get { return this.propertyContainer.EnvironmentSettingsProperty.Value; } set { this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the id of the task. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets a value that indicates whether to terminate all tasks in the job and complete the job when the job /// manager task completes. /// </summary> public bool? KillJobOnCompletion { get { return this.propertyContainer.KillJobOnCompletionProperty.Value; } set { this.propertyContainer.KillJobOnCompletionProperty.Value = value; } } /// <summary> /// Gets or sets a list of files that the Batch service will download to the compute node before running the command /// line. /// </summary> public IList<ResourceFile> ResourceFiles { get { return this.propertyContainer.ResourceFilesProperty.Value; } set { this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets whether the Job Manager task requires exclusive use of the compute node where it runs. /// </summary> public bool? RunExclusive { get { return this.propertyContainer.RunExclusiveProperty.Value; } set { this.propertyContainer.RunExclusiveProperty.Value = value; } } /// <summary> /// Gets or sets the user identity under which the task runs. /// </summary> /// <remarks> /// If omitted, the task runs as a non-administrative user unique to the task. /// </remarks> public UserIdentity UserIdentity { get { return this.propertyContainer.UserIdentityProperty.Value; } set { this.propertyContainer.UserIdentityProperty.Value = value; } } #endregion // JobManagerTask #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.JobManagerTask ITransportObjectProvider<Models.JobManagerTask>.GetTransportObject() { Models.JobManagerTask result = new Models.JobManagerTask() { ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences), AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()), CommandLine = this.CommandLine, Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings), Id = this.Id, KillJobOnCompletion = this.KillJobOnCompletion, ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles), RunExclusive = this.RunExclusive, UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()), }; return result; } #endregion // Internal/private methods } }
// // StringBody.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2013, 2014 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. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.IO; using System.Text; using Org.Apache.Http.Entity.Mime; using Org.Apache.Http.Entity.Mime.Content; using Sharpen; namespace Org.Apache.Http.Entity.Mime.Content { /// <since>4.0</since> public class StringBody : AbstractContentBody { private readonly byte[] content; private readonly Encoding charset; /// <since>4.1</since> /// <exception cref="System.ArgumentException"></exception> public static Org.Apache.Http.Entity.Mime.Content.StringBody Create(string text, string mimeType, Encoding charset) { try { return new Org.Apache.Http.Entity.Mime.Content.StringBody(text, mimeType, charset ); } catch (UnsupportedEncodingException ex) { throw new ArgumentException("Charset " + charset + " is not supported", ex); } } /// <since>4.1</since> /// <exception cref="System.ArgumentException"></exception> public static Org.Apache.Http.Entity.Mime.Content.StringBody Create(string text, Encoding charset) { return Create(text, null, charset); } /// <since>4.1</since> /// <exception cref="System.ArgumentException"></exception> public static Org.Apache.Http.Entity.Mime.Content.StringBody Create(string text) { return Create(text, null, null); } /// <summary>Create a StringBody from the specified text, mime type and character set. /// </summary> /// <remarks>Create a StringBody from the specified text, mime type and character set. /// </remarks> /// <param name="text"> /// to be used for the body, not /// <code>null</code> /// </param> /// <param name="mimeType"> /// the mime type, not /// <code>null</code> /// </param> /// <param name="charset"> /// the character set, may be /// <code>null</code> /// , in which case the US-ASCII charset is used /// </param> /// <exception cref="System.IO.UnsupportedEncodingException">System.IO.UnsupportedEncodingException /// </exception> /// <exception cref="System.ArgumentException"> /// if the /// <code>text</code> /// parameter is null /// </exception> public StringBody(string text, string mimeType, Encoding charset) : base(mimeType ) { if (text == null) { throw new ArgumentException("Text may not be null"); } if (charset == null) { charset = Sharpen.Extensions.GetEncoding("US-ASCII"); } this.content = Sharpen.Runtime.GetBytesForString(text, charset.Name()); this.charset = charset; } /// <summary>Create a StringBody from the specified text and character set.</summary> /// <remarks> /// Create a StringBody from the specified text and character set. /// The mime type is set to "text/plain". /// </remarks> /// <param name="text"> /// to be used for the body, not /// <code>null</code> /// </param> /// <param name="charset"> /// the character set, may be /// <code>null</code> /// , in which case the US-ASCII charset is used /// </param> /// <exception cref="System.IO.UnsupportedEncodingException">System.IO.UnsupportedEncodingException /// </exception> /// <exception cref="System.ArgumentException"> /// if the /// <code>text</code> /// parameter is null /// </exception> public StringBody(string text, Encoding charset) : this(text, "text/plain", charset ) { } /// <summary>Create a StringBody from the specified text.</summary> /// <remarks> /// Create a StringBody from the specified text. /// The mime type is set to "text/plain". /// The hosts default charset is used. /// </remarks> /// <param name="text"> /// to be used for the body, not /// <code>null</code> /// </param> /// <exception cref="System.IO.UnsupportedEncodingException">System.IO.UnsupportedEncodingException /// </exception> /// <exception cref="System.ArgumentException"> /// if the /// <code>text</code> /// parameter is null /// </exception> public StringBody(string text) : this(text, "text/plain", null) { } public virtual StreamReader GetReader() { return new InputStreamReader(new ByteArrayInputStream(this.content), this.charset ); } /// <exception cref="System.IO.IOException"></exception> [Obsolete] [System.ObsoleteAttribute(@"use WriteTo(System.IO.OutputStream)")] public virtual void WriteTo(OutputStream @out, int mode) { WriteTo(@out); } /// <exception cref="System.IO.IOException"></exception> public override void WriteTo(OutputStream @out) { if (@out == null) { throw new ArgumentException("Output stream may not be null"); } InputStream @in = new ByteArrayInputStream(this.content); byte[] tmp = new byte[4096]; int l; while ((l = @in.Read(tmp)) != -1) { @out.Write(tmp, 0, l); } @out.Flush(); } public override string GetTransferEncoding() { return MIME.Enc8bit; } public override string GetCharset() { return this.charset.Name(); } public override long GetContentLength() { return this.content.Length; } public override string GetFilename() { return null; } } }
/* * 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.IO; using System.Net; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Serialization; using log4net; namespace OpenSim.Framework.Servers.HttpServer { public class RestSessionObject<TRequest> { private string sid; private string aid; private TRequest request_body; public string SessionID { get { return sid; } set { sid = value; } } public string AvatarID { get { return aid; } set { aid = value; } } public TRequest Body { get { return request_body; } set { request_body = value; } } } public class SynchronousRestSessionObjectPoster<TRequest, TResponse> { public static TResponse BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid) { RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>(); sobj.SessionID = sid; sobj.AvatarID = aid; sobj.Body = obj; Type type = typeof(RestSessionObject<TRequest>); WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; request.ContentType = "text/xml"; request.Timeout = 20000; using (MemoryStream buffer = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, sobj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer.ToArray(), 0, length); } TResponse deserial = default(TResponse); using (WebResponse resp = request.GetResponse()) { XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); using (Stream respStream = resp.GetResponseStream()) deserial = (TResponse)deserializer.Deserialize(respStream); } return deserial; } } public class RestSessionObjectPosterResponse<TRequest, TResponse> { public ReturnResponse<TResponse> ResponseCallback; public void BeginPostObject(string requestUrl, TRequest obj, string sid, string aid) { BeginPostObject("POST", requestUrl, obj, sid, aid); } public void BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid) { RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>(); sobj.SessionID = sid; sobj.AvatarID = aid; sobj.Body = obj; Type type = typeof(RestSessionObject<TRequest>); WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; request.ContentType = "text/xml"; request.Timeout = 10000; using (MemoryStream buffer = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, sobj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer.ToArray(), 0, length); } // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request); request.BeginGetResponse(AsyncCallback, request); } private void AsyncCallback(IAsyncResult result) { WebRequest request = (WebRequest)result.AsyncState; using (WebResponse resp = request.EndGetResponse(result)) { TResponse deserial; XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); Stream stream = resp.GetResponseStream(); // This is currently a bad debug stanza since it gobbles us the response... // StreamReader reader = new StreamReader(stream); // m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd()); deserial = (TResponse)deserializer.Deserialize(stream); if (stream != null) stream.Close(); if (deserial != null && ResponseCallback != null) { ResponseCallback(deserial); } } } } public delegate bool CheckIdentityMethod(string sid, string aid); public class RestDeserialiseSecureHandler<TRequest, TResponse> : BaseOutputStreamHandler, IStreamHandler where TRequest : new() { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private RestDeserialiseMethod<TRequest, TResponse> m_method; private CheckIdentityMethod m_smethod; public RestDeserialiseSecureHandler( string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckIdentityMethod smethod) : base(httpMethod, path) { m_smethod = smethod; m_method = method; } protected override void ProcessRequest(string path, Stream request, Stream responseStream, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { RestSessionObject<TRequest> deserial = default(RestSessionObject<TRequest>); bool fail = false; using (XmlTextReader xmlReader = new XmlTextReader(request)) { try { XmlSerializer deserializer = new XmlSerializer(typeof(RestSessionObject<TRequest>)); deserial = (RestSessionObject<TRequest>)deserializer.Deserialize(xmlReader); } catch (Exception e) { m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e); fail = true; } } TResponse response = default(TResponse); if (!fail && m_smethod(deserial.SessionID, deserial.AvatarID)) { response = m_method(deserial.Body); } using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream)) { XmlSerializer serializer = new XmlSerializer(typeof(TResponse)); serializer.Serialize(xmlWriter, response); } } } public delegate bool CheckTrustedSourceMethod(IPEndPoint peer); public class RestDeserialiseTrustedHandler<TRequest, TResponse> : BaseOutputStreamHandler, IStreamHandler where TRequest : new() { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The operation to perform once trust has been established. /// </summary> private RestDeserialiseMethod<TRequest, TResponse> m_method; /// <summary> /// The method used to check whether a request is trusted. /// </summary> private CheckTrustedSourceMethod m_tmethod; public RestDeserialiseTrustedHandler(string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckTrustedSourceMethod tmethod) : base(httpMethod, path) { m_tmethod = tmethod; m_method = method; } protected override void ProcessRequest(string path, Stream request, Stream responseStream, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { TRequest deserial = default(TRequest); bool fail = false; using (XmlTextReader xmlReader = new XmlTextReader(request)) { try { XmlSerializer deserializer = new XmlSerializer(typeof(TRequest)); deserial = (TRequest)deserializer.Deserialize(xmlReader); } catch (Exception e) { m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e); fail = true; } } TResponse response = default(TResponse); if (!fail && m_tmethod(httpRequest.RemoteIPEndPoint)) { response = m_method(deserial); } using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream)) { XmlSerializer serializer = new XmlSerializer(typeof(TResponse)); serializer.Serialize(xmlWriter, response); } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Linq; using System.Abstract; using System.Collections.ObjectModel; using System.Collections.Generic; namespace Contoso.Abstract { /// <remark> /// An application service bus specific service bus interface /// </remark> public interface IAppServiceBus : IServiceBus { /// <summary> /// Adds this instance. /// </summary> /// <typeparam name="TMessageHandler">The type of the message handler.</typeparam> /// <returns></returns> IAppServiceBus Add<TMessageHandler>() where TMessageHandler : class; /// <summary> /// Adds the specified message handler type. /// </summary> /// <param name="messageHandlerType">Type of the message handler.</param> /// <returns></returns> IAppServiceBus Add(Type messageHandlerType); } /// <remark> /// An application service bus implementation /// </remark> /// <example> /// <code> /// ServiceBusManager.SetProvider(() => new AppServiceBus() /// .Add(Handler1) /// .Add(Handler2)) /// .RegisterWithServiceLocator(); /// ServiceBusManager.Send&lt;Message1&gt;(x => x.Body = "Message"); /// </code> /// </example> public class AppServiceBus : Collection<AppServiceBusRegistration>, IAppServiceBus, ServiceBusManager.ISetupRegistration { private readonly IAppServiceMessageHandlerFactory _messageHandlerFactory; private readonly Func<IServiceLocator> _locator; static AppServiceBus() { ServiceBusManager.EnsureRegistration(); } /// <summary> /// Initializes a new instance of the <see cref="AppServiceBus"/> class. /// </summary> public AppServiceBus() : this(null, () => ServiceLocatorManager.Current) { } /// <summary> /// Initializes a new instance of the <see cref="AppServiceBus"/> class. /// </summary> /// <param name="messageHandlerFactory">The message handler factory.</param> public AppServiceBus(IAppServiceMessageHandlerFactory messageHandlerFactory) : this(messageHandlerFactory, () => ServiceLocatorManager.Current) { } /// <summary> /// Initializes a new instance of the <see cref="AppServiceBus"/> class. /// </summary> /// <param name="messageHandlerFactory">The message handler factory.</param> /// <param name="locator">The locator.</param> public AppServiceBus(IAppServiceMessageHandlerFactory messageHandlerFactory, Func<IServiceLocator> locator) { if (messageHandlerFactory == null) throw new ArgumentNullException("messageHandlerFactory"); if (locator == null) throw new ArgumentNullException("locator"); _messageHandlerFactory = messageHandlerFactory; _locator = locator; } Action<IServiceLocator, string> ServiceBusManager.ISetupRegistration.DefaultServiceRegistrar { get { return (locator, name) => ServiceBusManager.RegisterInstance<IAppServiceBus>(this, locator, name); } } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType">An object that specifies the type of service object to get.</param> /// <returns> /// Throws NotImplementedException. /// </returns> public object GetService(Type serviceType) { throw new NotImplementedException(); } /// <summary> /// Creates a new message. /// </summary> /// <typeparam name="TMessage">The type of the message.</typeparam> /// <param name="messageBuilder">The message builder.</param> /// <returns>The newly created message.</returns> public TMessage CreateMessage<TMessage>(Action<TMessage> messageBuilder) where TMessage : class { var message = _locator().Resolve<TMessage>(); if (messageBuilder == null) messageBuilder(message); return message; } /// <summary> /// Adds a message handler. /// </summary> /// <typeparam name="TMessageHandler">The type of the message handler.</typeparam> /// <returns>Fluent</returns> public IAppServiceBus Add<TMessageHandler>() where TMessageHandler : class { return Add(typeof(TMessageHandler)); } /// <summary> /// Adds a message handler /// </summary> /// <param name="messageHandlerType"></param> /// <returns>Fluent</returns> public IAppServiceBus Add(Type messageHandlerType) { var messageType = GetMessageTypeFromHandler(messageHandlerType); if (messageType == null) throw new InvalidOperationException("Unable find a message handler"); base.Add(new AppServiceBusRegistration { MessageHandlerType = messageHandlerType, MessageType = messageType, }); return this; } /// <summary> /// Sends a message on the bus /// </summary> /// <param name="destination"></param> /// <param name="messages"></param> /// <returns>Null</returns> public IServiceBusCallback Send(IServiceBusEndpoint destination, params object[] messages) { if (messages == null) throw new ArgumentNullException("messages"); foreach (var message in messages) foreach (var type in GetTypesOfMessageHandlers(message.GetType())) HandleTheMessage(type, message); return null; } private void HandleTheMessage(Type type, object message) { _messageHandlerFactory.Create<object>(type) .Handle(message); } private IEnumerable<Type> GetTypesOfMessageHandlers(Type messageType) { return Items.Where(x => x.MessageType == messageType) .Select(x => x.MessageHandlerType); } private static Type GetMessageTypeFromHandler(Type messageHandlerType) { return null; //var serviceMessageType = typeof(IServiceMessage); //var applicationServiceMessageType = typeof(IApplicationServiceMessage); //return messageHandlerType.GetInterfaces() // .Where(h => h.IsGenericType && (h.FullName.StartsWith("System.Abstract.IServiceMessageHandler`1") || h.FullName.StartsWith("Contoso.Abstract.IApplicationServiceMessageHandler`1"))) // .Select(h => h.GetGenericArguments()[0]) // .Where(m => m.GetInterfaces().Any(x => x == serviceMessageType || x == applicationServiceMessageType)) // .SingleOrDefault(); } /// <summary> /// Replies messages back up the bus. /// </summary> /// <param name="messages">The messages.</param> public void Reply(params object[] messages) { throw new NotImplementedException(); } /// <summary> /// Returns a value back up the bus. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> public void Return<T>(T value) { throw new NotImplementedException(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace TekConf.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
namespace Nancy.Tests.Unit { using System; using Xunit; public class HttpLinkFixture { [Fact] public void Add_duplicate_parameter_in_different_casing_throws_argument_exception() { // Given var link = new HttpLink("http://nancyfx.org/", "home"); link.Parameters.Add("up", "up"); // When, Then Assert.Throws<ArgumentException>(() => link.Parameters.Add("UP", "UP")); } [Fact] public void Links_in_different_casing_should_be_considered_equal() { // Given var first = new HttpLink("http://NANCYFX.ORG/", "home"); var second = new HttpLink("http://nancyfx.org/", "home"); // When var equal = first.Equals(second); // Then equal.ShouldBeTrue(); } [Fact] public void Links_in_different_casing_should_have_same_hash_code() { // Given var first = new HttpLink("http://NANCYFX.ORG/", "home"); var second = new HttpLink("http://nancyfx.org/", "home"); // When var firstHashCode = first.GetHashCode(); var secondHashCode = second.GetHashCode(); // Then firstHashCode.ShouldEqual(secondHashCode); } [Fact] public void Links_with_different_parameters_should_not_be_considered_equal() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); first.Parameters.Add("a", "b"); var second = new HttpLink("http://nancyfx.org/", "home"); second.Parameters.Add("x", "y"); // When var equal = first.Equals(second); // Then equal.ShouldBeFalse(); } [Fact] public void Links_with_different_parameters_should_not_have_same_hash_code() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); first.Parameters.Add("a", "b"); var second = new HttpLink("http://nancyfx.org/", "home"); second.Parameters.Add("x", "y"); // When var firstHashCode = first.GetHashCode(); var secondHashCode = second.GetHashCode(); // Then firstHashCode.ShouldNotEqual(secondHashCode); } [Fact] public void Links_with_equal_parameters_in_different_casing_should_be_considered_equal() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); first.Parameters.Add("param", "value"); var second = new HttpLink("http://nancyfx.org/", "home"); second.Parameters.Add("PARAM", "value"); // When var equal = first.Equals(second); // Then equal.ShouldBeTrue(); } [Fact] public void Links_with_equal_parameters_in_different_casing_should_have_same_hash_code() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); first.Parameters.Add("param", "value"); var second = new HttpLink("http://nancyfx.org/", "home"); second.Parameters.Add("PARAM", "value"); // When var firstHashCode = first.GetHashCode(); var secondHashCode = second.GetHashCode(); // Then firstHashCode.ShouldEqual(secondHashCode); } [Fact] public void Links_with_equal_parameters_should_be_considered_equal() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); first.Parameters.Add("param", "value"); var second = new HttpLink("http://nancyfx.org/", "home"); second.Parameters.Add("param", "value"); // When var equal = first.Equals(second); // Then equal.ShouldBeTrue(); } [Fact] public void Links_with_equal_parameters_should_have_same_hash_code() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); first.Parameters.Add("param", "value"); var second = new HttpLink("http://nancyfx.org/", "home"); second.Parameters.Add("param", "value"); // When var firstHashCode = first.GetHashCode(); var secondHashCode = second.GetHashCode(); // Then firstHashCode.ShouldEqual(secondHashCode); } [Fact] public void Links_with_relations_in_different_casing_should_be_considered_equal() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); var second = new HttpLink("http://nancyfx.org/", "HOME"); // When var equal = first.Equals(second); // Then equal.ShouldBeTrue(); } [Fact] public void Links_with_relations_in_different_casing_should_have_same_hash_code() { // Given var first = new HttpLink("http://nancyfx.org/", "home"); var second = new HttpLink("http://nancyfx.org/", "HOME"); // When var firstHashCode = first.GetHashCode(); var secondHashCode = second.GetHashCode(); // Then firstHashCode.ShouldEqual(secondHashCode); } [Fact] public void ToString_link_with_boolean_parameter_should_exist_without_value_in_string() { // Given var link = new HttpLink("http://nancyfx.org/", "up"); link.Parameters.Add("parameter", null); // When var stringValue = link.ToString(); // Then stringValue.ShouldEqual("<http://nancyfx.org/>; rel=\"up\"; parameter"); } [Fact] public void ToString_link_with_empty_parameter_should_not_exist_in_string() { // Given var link = new HttpLink("http://nancyfx.org/", "up"); link.Parameters.Add(string.Empty, null); // When var stringValue = link.ToString(); // Then stringValue.ShouldEqual("<http://nancyfx.org/>; rel=\"up\""); } [Fact] public void ToString_link_with_extension_parameter_should_exist_in_string() { // Given var link = new HttpLink("http://nancyfx.org/", "up"); link.Parameters.Add("ext", "extension-param"); // When var stringValue = link.ToString(); // Then stringValue.ShouldEqual("<http://nancyfx.org/>; rel=\"up\"; ext=\"extension-param\""); } [Fact] public void ToString_link_with_relation_should_exist_in_string() { // Given var link = new HttpLink("http://nancyfx.org/", "up"); // When var stringValue = link.ToString(); // Then stringValue.ShouldEqual("<http://nancyfx.org/>; rel=\"up\""); } [Fact] public void ToString_link_with_type_should_exist_in_string() { // Given var link = new HttpLink("http://nancyfx.org/", "up", "application/json"); // When var stringValue = link.ToString(); // Then stringValue.ShouldEqual("<http://nancyfx.org/>; rel=\"up\"; type=\"application/json\""); } [Fact] public void ToString_link_with_whitespace_parameter_should_not_exist_in_string() { // Given var link = new HttpLink("http://nancyfx.org/", "up"); link.Parameters.Add(" ", null); // When var stringValue = link.ToString(); // Then stringValue.ShouldEqual("<http://nancyfx.org/>; rel=\"up\""); } } }
/* * Copyright 2013 ThirdMotion, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @class strange.framework.impl.Binder * * Collection class for bindings. * * Binders are a collection class (akin to ArrayList and Dictionary) * with the specific purpose of connecting lists of things that are * not necessarily related, but need some type of runtime association. * Binders are the core concept of the StrangeIoC framework, allowing * all the other functionality to exist and further functionality to * easily be created. * * Think of each Binder as a collection of causes and effects, or actions * and reactions. If the Key action happens, it triggers the Value * action. So, for example, an Event may be the Key that triggers * instantiation of a particular class. * * <h2>Runtime Bindings</h2> * As of V1.0, Strange supports runtime bindings via JSON. This allows you to * instruct Strange to create its bindings by using loaded data, for example via * a downloaded .json file, or a server response. * * binder.ConsumeBindings(stringOfLoadedJson); * * Below are examples for basic runtime * binding options for Binder. The complete set of JSON runtime bindings for all * officially supported binders can be found in The Big, Strange How-To: * (http://strangeioc.github.io/strangeioc/TheBigStrangeHowTo.html) * * <h3>Example: basic binding via JSON</h3> * The simplest possible binding is an array of objects. We bind "This" to "That" * * [ * { * "Bind":"This", * "To":"That" * } * ] * * You can of course load as many bindings as you like in your array: * * [ * { * "Bind":"This", * "To":"That" * }, * { * "Bind":"Han", * "To":"Leia" * }, * { * "Bind":"Greedo", * "To":"Table" * } *] * * You can name bindings as you would expect: * * [ * { * "Bind":"Battle", * "To":"Planet", * "ToName":"Endor" * } * ] * * If you need more than a single item in a "Bind" or "To" statement, use an array. * * [ * { * "Bind":["Luke", "Han", "Wedge", "Biggs"], * "To":"Pilot" * } * ] * * There is also an "Options" array for special behaviors required by * individual Binders. The core Binder supports "Weak". * * [ * { * "Bind":"X-Wing", * "To":"Ship", * "Options":["Weak"] * } * ] * * Other Binders support other Options. Here's a case from the InjectionBinder. Note * how Options can be either a string or an array. * * [ * { * "Bind":"strange.unittests.ISimpleInterface", * "To":"strange.unittests.SimpleInterfaceImplementer", * "Options":"ToSingleton" * } * ] */ using System.Collections.Generic; using strange.framework.api; using MiniJSON; namespace strange.framework.impl { public class Binder : IBinder { /// Dictionary of all bindings /// Two-layer keys. First key to individual Binding keys, /// then to Binding names. (This wouldn't be required if /// Unity supported Tuple or HashSet.) protected Dictionary <object, Dictionary<object, IBinding>> bindings; protected Dictionary <object, Dictionary<IBinding, object>> conflicts; protected List<object> bindingWhitelist; /// A handler for resolving the nature of a binding during chained commands public delegate void BindingResolver(IBinding binding); public Binder () { bindings = new Dictionary <object, Dictionary<object, IBinding>> (); conflicts = new Dictionary <object, Dictionary<IBinding, object>> (); } virtual public IBinding Bind<T>() { return Bind (typeof(T)); } virtual public IBinding Bind(object key) { IBinding binding; binding = GetRawBinding (); binding.Bind(key); return binding; } virtual public IBinding GetBinding<T>() { return GetBinding (typeof(T), null); } virtual public IBinding GetBinding(object key) { return GetBinding (key, null); } virtual public IBinding GetBinding<T>(object name) { return GetBinding (typeof(T), name); } virtual public IBinding GetBinding(object key, object name) { if (conflicts.Count > 0) { string conflictSummary = ""; Dictionary<object, Dictionary<IBinding, object>>.KeyCollection keys = conflicts.Keys; foreach (object k in keys) { if (conflictSummary.Length > 0) { conflictSummary+= ", "; } conflictSummary += k.ToString (); } throw new BinderException ("Binder cannot fetch Bindings when the binder is in a conflicted state.\nConflicts: " + conflictSummary, BinderExceptionType.CONFLICT_IN_BINDER); } if(bindings.ContainsKey (key)) { Dictionary<object, IBinding> dict = bindings [key]; name = (name == null) ? BindingConst.NULLOID : name; if (dict.ContainsKey(name)) { return dict [name]; } } return null; } virtual public void Unbind<T>() { Unbind (typeof(T), null); } virtual public void Unbind(object key) { Unbind (key, null); } virtual public void Unbind<T>(object name) { Unbind (typeof(T), name); } virtual public void Unbind(object key, object name) { if (bindings.ContainsKey(key)) { Dictionary<object, IBinding> dict = bindings[key]; object bindingName = (name == null) ? BindingConst.NULLOID : name; if (dict.ContainsKey(bindingName)) { dict.Remove(bindingName); } } } virtual public void Unbind(IBinding binding) { if (binding == null) { return; } Unbind (binding.key, binding.name); } virtual public void RemoveValue (IBinding binding, object value) { if (binding == null || value == null) { return; } object key = binding.key; Dictionary<object, IBinding> dict; if ((bindings.ContainsKey(key))) { dict = bindings [key]; if (dict.ContainsKey(binding.name)) { IBinding useBinding = dict [binding.name]; useBinding.RemoveValue (value); //If result is empty, clean it out object[] values = useBinding.value as object[]; if (values == null || values.Length == 0) { dict.Remove(useBinding.name); } } } } virtual public void RemoveKey (IBinding binding, object key) { if (binding == null || key == null || bindings.ContainsKey(key) == false) { return; } Dictionary<object, IBinding> dict = bindings[key]; if (dict.ContainsKey (binding.name)) { IBinding useBinding = dict [binding.name]; useBinding.RemoveKey (key); object[] keys = useBinding.key as object[]; if (keys != null && keys.Length == 0) { dict.Remove(binding.name); } } } virtual public void RemoveName (IBinding binding, object name) { if (binding == null || name == null) { return; } object key; if (binding.keyConstraint.Equals(BindingConstraintType.ONE)) { key = binding.key; } else { object[] keys = binding.key as object[]; key = keys [0]; } Dictionary<object, IBinding> dict = bindings[key]; if (dict.ContainsKey (name)) { IBinding useBinding = dict [name]; useBinding.RemoveName (name); } } virtual public IBinding GetRawBinding() { return new Binding (resolver); } /// The default handler for resolving bindings during chained commands virtual protected void resolver(IBinding binding) { object key = binding.key; if (binding.keyConstraint.Equals(BindingConstraintType.ONE)) { ResolveBinding (binding, key); } else { object[] keys = key as object[]; int aa = keys.Length; for(int a = 0; a < aa; a++) { ResolveBinding (binding, keys[a]); } } } /** * This method places individual Bindings into the bindings Dictionary * as part of the resolving process. Note that while some Bindings * may store multiple keys, each key takes a unique position in the * bindings Dictionary. * * Conflicts in the course of fluent binding are expected, but GetBinding * will throw an error if there are any unresolved conflicts. */ virtual public void ResolveBinding(IBinding binding, object key) { //Check for existing conflicts if (conflicts.ContainsKey(key)) //does the current key have any conflicts? { Dictionary<IBinding, object> inConflict = conflicts [key]; if (inConflict.ContainsKey(binding)) //Am I on the conflict list? { object conflictName = inConflict[binding]; if (isConflictCleared(inConflict, binding)) //Am I now out of conflict? { clearConflict (key, conflictName, inConflict); //remove all from conflict list. } else { return; //still in conflict } } } //Check for and assign new conflicts object bindingName = (binding.name == null) ? BindingConst.NULLOID : binding.name; Dictionary<object, IBinding> dict; if ((bindings.ContainsKey(key))) { dict = bindings [key]; //Will my registration create a new conflict? if (dict.ContainsKey(bindingName)) { //If the existing binding is not this binding, and the existing binding is not weak //If it IS weak, we will proceed normally and overwrite the binding in the dictionary IBinding existingBinding = dict[bindingName]; //if (existingBinding != binding && !existingBinding.isWeak) //SDM2014-01-20: as part of cross-context implicit bindings fix, attempts by a weak binding to replace a non-weak binding are ignored instead of being if (existingBinding != binding) { if (!existingBinding.isWeak && !binding.isWeak) { //register both conflictees registerNameConflict(key, binding, dict[bindingName]); return; } if (existingBinding.isWeak && (!binding.isWeak || existingBinding.value == null || existingBinding.value is System.Type)) { //SDM2014-01-20: (in relation to the cross-context implicit bindings fix) // 1) if the previous binding is weak and the new binding is not weak, then the new binding replaces the previous; // 2) but if the new binding is also weak, then it only replaces the previous weak binding if the previous binding // has not already been instantiated: //Remove the previous binding. dict.Remove(bindingName); } } } } else { dict = new Dictionary<object, IBinding>(); bindings [key] = dict; } //Remove nulloid bindings if (dict.ContainsKey(BindingConst.NULLOID) && dict[BindingConst.NULLOID].Equals(binding) ) { dict.Remove (BindingConst.NULLOID); } //Add (or override) our new binding! if (!dict.ContainsKey(bindingName)) { dict.Add (bindingName, binding); } } /// <summary> /// For consumed bindings, provide a secure whitelist of legal bindings. /// </summary> /// <param name="list"> A List of fully-qualified classnames eligible to be consumed during dynamic runtime binding.</param> virtual public void WhitelistBindings(List<object> list) { bindingWhitelist = list; } /// <summary> /// Provide the Binder with JSON data to perform runtime binding /// </summary> /// <param name="jsonString">A json-parsable string containing the bindings.</param> virtual public void ConsumeBindings(string jsonString) { List<object> list = Json.Deserialize(jsonString) as List<object>; IBinding testBinding = GetRawBinding (); for (int a=0, aa=list.Count; a < aa; a++) { ConsumeItem(list[a] as Dictionary<string, object>, testBinding); } } /// <summary> /// Consumes an individual JSON element and returns the Binding that element represents /// </summary> /// <returns>The Binding represented the provided JSON</returns> /// <param name="item">A Dictionary of definitions for the individual binding parameters</param> /// <param name="testBinding">An example binding for the current Binder. This method uses the /// binding constraints of the example to raise errors if asked to parse illegally</param> virtual protected IBinding ConsumeItem(Dictionary<string, object> item, IBinding testBinding) { int bindConstraints = (testBinding.keyConstraint == BindingConstraintType.ONE) ? 0 : 1; bindConstraints |= (testBinding.valueConstraint == BindingConstraintType.ONE) ? 0 : 2; IBinding binding = null; List<object> keyList; List<object> valueList; if (item != null) { item = ConformRuntimeItem (item); // Check that Bind exists if (!item.ContainsKey ("Bind")) { throw new BinderException ("Attempted to consume a binding without a bind key.", BinderExceptionType.RUNTIME_NO_BIND); } else { keyList = conformRuntimeToList (item ["Bind"]); } // Check that key counts match the binding constraint if (keyList.Count > 1 && (bindConstraints & 1) == 0) { throw new BinderException ("Binder " + this.ToString () + " supports only a single binding key. A runtime binding key including " + keyList [0].ToString () + " is trying to add more.", BinderExceptionType.RUNTIME_TOO_MANY_KEYS); } if (!item.ContainsKey ("To")) { valueList = keyList; } else { valueList = conformRuntimeToList (item ["To"]); } // Check that value counts match the binding constraint if (valueList.Count > 1 && (bindConstraints & 2) == 0) { throw new BinderException ("Binder " + this.ToString () + " supports only a single binding value. A runtime binding value including " + valueList [0].ToString () + " is trying to add more.", BinderExceptionType.RUNTIME_TOO_MANY_VALUES); } // Check Whitelist if it exists if (bindingWhitelist != null) { foreach (object value in valueList) { if (bindingWhitelist.IndexOf (value) == -1) { throw new BinderException ("Value " + value.ToString () + " not found on whitelist for " + this.ToString () + ".", BinderExceptionType.RUNTIME_FAILED_WHITELIST_CHECK); } } } binding = performKeyValueBindings (keyList, valueList); // Optionally look for ToName if (item.ContainsKey ("ToName")) { binding = binding.ToName (item ["ToName"]); } // Add runtime options if (item.ContainsKey ("Options")) { List<object> optionsList = conformRuntimeToList (item ["Options"]); addRuntimeOptions (binding, optionsList); } } return binding; } /// <summary> /// Override this method in subclasses to add special-case SYNTACTICAL SUGAR for Runtime JSON bindings. /// For example, if your Binder needs a special JSON tag BindView, such that BindView is simply /// another way of expressing 'Bind', override this method conform the sugar to /// match the base definition (BindView becomes Bind). /// </summary> /// <returns>The conformed Dictionary.</returns> /// <param name="dictionary">A Dictionary representing the options for a Binding.</param> virtual protected Dictionary<string, object> ConformRuntimeItem(Dictionary<string, object> dictionary) { return dictionary; } /// <summary> /// Performs the key value bindings for a JSON runtime binding. /// </summary> /// <returns>A Binding.</returns> /// <param name="keyList">A list of things to Bind.</param> /// <param name="valueList">A list of the things to which we're binding.</param> virtual protected IBinding performKeyValueBindings(List<object> keyList, List<object> valueList) { IBinding binding = null; // Bind in order foreach (object key in keyList) { binding = Bind (key); } foreach (object value in valueList) { binding = binding.To (value); } return binding; } /// <summary> /// Override this method to decorate subclasses with further runtime capabilities. /// For example, InjectionBinder adds ToSingleton and CrossContext capabilities so that /// these can be specified in JSON. /// /// By default, the Binder supports 'Weak' as a runtime option. /// </summary> /// <returns>The provided Binding.</returns> /// <param name="binding">A Binding to have capabilities added.</param> /// <param name="options">The list of runtime options for this Binding.</param> virtual protected IBinding addRuntimeOptions(IBinding binding, List<object> options) { if (options.IndexOf ("Weak") > -1) { binding.Weak(); } return binding; } /// <summary> /// Convert the object to List<object> /// </summary> /// <returns>If a List, returns the original object, typed to List<object>. If a value, creates a List and adds the value to it.</returns> /// <param name="bindObject">The object on which we're operating.</param> protected List<object> conformRuntimeToList(object bindObject) { List<object> conformed = new List<object> (); string t = bindObject.GetType().ToString (); if (t.IndexOf ("System.Collections.Generic.List") > -1) { return bindObject as List<object>; } // Conform strings to Lists switch (t) { case "System.String": string stringValue = bindObject as string; conformed.Add(stringValue); break; case "System.Int64": int intValue = (int)bindObject; conformed.Add(intValue); break; case "System.Double": float floatValue = (float)bindObject; conformed.Add(floatValue); break; default: throw new BinderException ("Runtime binding keys (Bind) must be strings or numbers.\nBinding detected of type " + t, BinderExceptionType.RUNTIME_TYPE_UNKNOWN); } return conformed; } /// Take note of bindings that are in conflict. /// This occurs routinely during fluent binding, but will spark an error if /// GetBinding is called while this Binder still has conflicts. protected void registerNameConflict(object key, IBinding newBinding, IBinding existingBinding) { Dictionary<IBinding, object> dict; if (conflicts.ContainsKey(key) == false) { dict = new Dictionary<IBinding, object> (); conflicts [key] = dict; } else { dict = conflicts [key]; } dict [newBinding] = newBinding.name; dict [existingBinding] = newBinding.name; } /// Returns true if the provided binding and the binding in the dict are no longer conflicting protected bool isConflictCleared(Dictionary<IBinding, object> dict, IBinding binding) { foreach (KeyValuePair<IBinding, object> kv in dict) { if (kv.Key != binding && kv.Key.name == binding.name) { return false; } } return true; } protected void clearConflict(object key, object name, Dictionary<IBinding, object> dict) { List<IBinding> removalList = new List<IBinding>(); foreach(KeyValuePair<IBinding, object> kv in dict) { object v = kv.Value; if (v.Equals(name)) { removalList.Add (kv.Key); } } int aa = removalList.Count; for (int a = 0; a < aa; a++) { dict.Remove(removalList[a]); } if (dict.Count == 0) { conflicts.Remove (key); } } protected T[] spliceValueAt<T>(int splicePos, object[] objectValue) { T[] newList = new T[objectValue.Length - 1]; int mod = 0; int aa = objectValue.Length; for(int a = 0; a < aa; a++) { if (a == splicePos) { mod = -1; continue; } newList [a + mod] = (T)objectValue [a]; } return newList; } /// Remove the item at splicePos from the list objectValue protected object[] spliceValueAt(int splicePos, object[] objectValue) { return spliceValueAt<object>(splicePos, objectValue); } virtual public void OnRemove() { } } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using System; using System.Reflection; using System.Reflection.Emit; using System.Globalization; using System.Diagnostics; internal class JSProperty : PropertyInfo{ private String name; private ParameterInfo[] formal_parameters; internal PropertyBuilder metaData; internal JSMethod getter; internal JSMethod setter; internal JSProperty(String name){ this.name = name; this.formal_parameters = null; this.getter = null; this.setter = null; } public override PropertyAttributes Attributes{ get{ return PropertyAttributes.None; } } public override bool CanRead{ get{ return JSProperty.GetGetMethod(this, true) != null; } } public override bool CanWrite{ get{ return JSProperty.GetSetMethod(this, true) != null; } } internal virtual String GetClassFullName(){ if (this.getter != null) return this.getter.GetClassFullName(); else return this.setter.GetClassFullName(); } internal bool GetterAndSetterAreConsistent(){ if (this.getter == null || this.setter == null) return true; ((JSFieldMethod)this.getter).func.PartiallyEvaluate(); ((JSFieldMethod)this.setter).func.PartiallyEvaluate(); ParameterInfo[] getterPars = this.getter.GetParameters(); ParameterInfo[] setterPars = this.setter.GetParameters(); int n = getterPars.Length; int m = setterPars.Length; if (n != m-1) return false; if (!((JSFieldMethod)this.getter).func.ReturnType(null).Equals(((ParameterDeclaration)setterPars[n]).type.ToIReflect())) return false; for (int i = 0; i < n; i++) if (((ParameterDeclaration)getterPars[i]).type.ToIReflect() != ((ParameterDeclaration)setterPars[i]).type.ToIReflect()) return false; return (this.getter.Attributes&~MethodAttributes.Abstract) == (this.setter.Attributes&~MethodAttributes.Abstract); } public override Type DeclaringType{ get{ if (this.getter != null) return this.getter.DeclaringType; else return this.setter.DeclaringType; } } public sealed override Object[] GetCustomAttributes(Type t, bool inherit){ return new Object[0]; } public sealed override Object[] GetCustomAttributes(bool inherit){ if (this.getter != null) return this.getter.GetCustomAttributes(true); if (this.setter != null) return this.setter.GetCustomAttributes(true); return new Object[0]; } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif internal static Object GetValue(PropertyInfo prop, Object obj, Object[] index){ JSProperty jsprop = prop as JSProperty; if (jsprop != null) return jsprop.GetValue(obj, BindingFlags.ExactBinding, null, index, null); JSWrappedProperty jswrappedprop = prop as JSWrappedProperty; if (jswrappedprop != null) return jswrappedprop.GetValue(obj, BindingFlags.ExactBinding, null, index, null); MethodInfo meth = JSProperty.GetGetMethod(prop, false); if (meth != null){ try { return meth.Invoke(obj, BindingFlags.ExactBinding, null, index, null); } catch (TargetInvocationException e) { throw e.InnerException; } } throw new MissingMethodException(); } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture){ MethodInfo getter = this.getter; JSObject jsOb = obj as JSObject; if (getter == null && jsOb != null){ getter = jsOb.GetMethod("get_"+this.name, BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic); JSWrappedMethod wrm = getter as JSWrappedMethod; if (wrm != null) getter = wrm.method; } if (getter == null) getter = this.GetGetMethod(false); if (getter != null) { try { return getter.Invoke(obj, invokeAttr, binder, index == null ? new Object[0] : index, culture); } catch (TargetInvocationException e) { throw e.InnerException; } } else return Missing.Value; } public override MethodInfo[] GetAccessors(bool nonPublic){ if (this.getter != null && (nonPublic || this.getter.IsPublic)) if (this.setter != null && (nonPublic || this.setter.IsPublic)) return new MethodInfo[]{this.getter, this.setter}; else return new MethodInfo[]{this.getter}; else if (this.setter != null && (nonPublic || this.setter.IsPublic)) return new MethodInfo[]{this.setter}; else return new MethodInfo[]{}; } internal static MethodInfo GetGetMethod(PropertyInfo prop, bool nonPublic){ if (prop == null) return null; JSProperty jsprop = prop as JSProperty; if (jsprop != null) return jsprop.GetGetMethod(nonPublic); MethodInfo meth = prop.GetGetMethod(nonPublic); if (meth != null) return meth; Type pdt = prop.DeclaringType; if (pdt == null) return null; Type bt = pdt.BaseType; if (bt == null) return null; meth = prop.GetGetMethod(nonPublic); if (meth == null) return null; BindingFlags flags = BindingFlags.Public; if (meth.IsStatic) flags |= BindingFlags.Static|BindingFlags.FlattenHierarchy; else flags |= BindingFlags.Instance; if (nonPublic) flags |= BindingFlags.NonPublic; String pname = prop.Name; prop = null; try{ prop = bt.GetProperty(pname, flags, null, null, new Type[]{}, null); }catch(AmbiguousMatchException){} if (prop != null) return JSProperty.GetGetMethod(prop, nonPublic); return null; } public override MethodInfo GetGetMethod(bool nonPublic){ if (this.getter == null){ try{ IReflect ir = ((ClassScope)this.setter.obj).GetSuperType(); BindingFlags flags = BindingFlags.Public; if (this.setter.IsStatic) flags |= BindingFlags.Static|BindingFlags.FlattenHierarchy; else flags |= BindingFlags.Instance; if (nonPublic) flags |= BindingFlags.NonPublic; PropertyInfo prop = ir.GetProperty(this.name, flags, null, null, new Type[]{}, null); if (prop is JSProperty) return prop.GetGetMethod(nonPublic); else return JSProperty.GetGetMethod(prop, nonPublic); }catch(AmbiguousMatchException){} } if (nonPublic || this.getter.IsPublic) return this.getter; else return null; } public override ParameterInfo[] GetIndexParameters(){ if (this.formal_parameters == null){ if (this.getter != null) this.formal_parameters = this.getter.GetParameters(); else{ ParameterInfo[] setterPars = this.setter.GetParameters(); int n = setterPars.Length; if (n <= 1) n = 1; this.formal_parameters = new ParameterInfo[n-1]; for (int i = 0; i < n-1; i++) this.formal_parameters[i] = setterPars[i]; } } return this.formal_parameters; } internal static MethodInfo GetSetMethod(PropertyInfo prop, bool nonPublic){ if (prop == null) return null; JSProperty jsProp = prop as JSProperty; if (jsProp != null) return jsProp.GetSetMethod(nonPublic); MethodInfo meth = prop.GetSetMethod(nonPublic); if (meth != null) return meth; Type pdt = prop.DeclaringType; if (pdt == null) return null; Type bt = pdt.BaseType; if (bt == null) return null; meth = prop.GetGetMethod(nonPublic); if (meth == null) return null; BindingFlags flags = BindingFlags.Public; if (meth.IsStatic) flags |= BindingFlags.Static|BindingFlags.FlattenHierarchy; else flags |= BindingFlags.Instance; if (nonPublic) flags |= BindingFlags.NonPublic; String pname = prop.Name; prop = null; try{ prop = bt.GetProperty(pname, flags, null, null, new Type[]{}, null); }catch(AmbiguousMatchException){} if (prop != null) return JSProperty.GetSetMethod(prop, nonPublic); return null; } public override MethodInfo GetSetMethod(bool nonPublic){ if (this.setter == null){ try{ IReflect ir = ((ClassScope)this.getter.obj).GetSuperType(); BindingFlags flags = BindingFlags.Public; if (this.getter.IsStatic) flags |= BindingFlags.Static|BindingFlags.FlattenHierarchy; else flags |= BindingFlags.Instance; if (nonPublic) flags |= BindingFlags.NonPublic; PropertyInfo prop = ir.GetProperty(this.name, flags, null, null, new Type[]{}, null); if (prop is JSProperty) return prop.GetSetMethod(nonPublic); else return JSProperty.GetSetMethod(prop, nonPublic); }catch(AmbiguousMatchException){} } if (nonPublic || this.setter.IsPublic) return this.setter; else return null; } public sealed override bool IsDefined(Type type, bool inherit){ return false; } public override MemberTypes MemberType{ get{ return MemberTypes.Property; } } public override String Name{ get{ return this.name; } } internal IReflect PropertyIR(){ if (this.getter is JSFieldMethod) return ((JSFieldMethod)this.getter).ReturnIR(); if (this.setter != null){ ParameterInfo[] pars = this.setter.GetParameters(); if (pars.Length > 0){ ParameterInfo par = pars[pars.Length-1]; if (par is ParameterDeclaration) return ((ParameterDeclaration)par).ParameterIReflect; else return par.ParameterType; } } return Typeob.Void; } public override Type PropertyType{ get{ if (this.getter != null) return this.getter.ReturnType; if (this.setter != null){ ParameterInfo[] pars = this.setter.GetParameters(); if (pars.Length > 0) return pars[pars.Length-1].ParameterType; } return Typeob.Void; } } public override Type ReflectedType{ get{ if (this.getter != null) return this.getter.ReflectedType; else return this.setter.ReflectedType; } } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif internal static void SetValue(PropertyInfo prop, Object obj, Object value, Object[] index){ JSProperty jsprop = prop as JSProperty; if (jsprop != null) {jsprop.SetValue(obj, value, BindingFlags.ExactBinding, null, index, null); return;} MethodInfo meth = JSProperty.GetSetMethod(prop, false); if (meth != null) { int n = (index == null ? 0 : index.Length); Object[] args = new Object[n+1]; if (n > 0) ArrayObject.Copy(index, 0, args, 0, n); args[n] = value; meth.Invoke(obj, BindingFlags.ExactBinding, null, args, null); return; } throw new MissingMethodException(); } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) { MethodInfo setter = this.setter; JSObject jsOb = obj as JSObject; if (setter == null && jsOb != null){ setter = jsOb.GetMethod("set_"+this.name, BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic); JSWrappedMethod wrm = setter as JSWrappedMethod; if (wrm != null) setter = wrm.method; } if (setter == null) setter = this.GetSetMethod(false); if (setter != null){ if (index == null || index.Length == 0) setter.Invoke(obj, invokeAttr, binder, new Object[]{value}, culture); else{ int n = index.Length; Object[] args = new Object[n+1]; ArrayObject.Copy(index, 0, args, 0, n); args[n] = value; setter.Invoke(obj, invokeAttr, binder, args, culture); } } } } }
/* * CP37.cs - IBM EBCDIC (US-Canada) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-37.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP37 : ByteEncoding { public CP37() : base(37, ToChars, "IBM EBCDIC (US-Canada)", "IBM037", "IBM037", "IBM037", false, false, false, false, 1252) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009', '\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087', '\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D', '\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007', '\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095', '\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B', '\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0', '\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5', '\u00E7', '\u00F1', '\u00A2', '\u002E', '\u003C', '\u0028', '\u002B', '\u007C', '\u0026', '\u00E9', '\u00EA', '\u00EB', '\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF', '\u0021', '\u0024', '\u002A', '\u0029', '\u003B', '\u00AC', '\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1', '\u00C3', '\u00C5', '\u00C7', '\u00D1', '\u00A6', '\u002C', '\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9', '\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF', '\u00CC', '\u0060', '\u003A', '\u0023', '\u0040', '\u0027', '\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1', '\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA', '\u00E6', '\u00B8', '\u00C6', '\u00A4', '\u00B5', '\u007E', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD', '\u00DE', '\u00AE', '\u005E', '\u00A3', '\u00A5', '\u00B7', '\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE', '\u005B', '\u005D', '\u00AF', '\u00A8', '\u00B4', '\u00D7', '\u007B', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4', '\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u007D', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00F9', '\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB', '\u00DC', '\u00D9', '\u00DA', '\u009F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x5A; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0x7B; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x7C; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0xBA; break; case 0x005C: ch = 0xE0; break; case 0x005D: ch = 0xBB; break; case 0x005E: ch = 0xB0; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x79; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0xC0; break; case 0x007C: ch = 0x4F; break; case 0x007D: ch = 0xD0; break; case 0x007E: ch = 0xA1; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0x4A; break; case 0x00A3: ch = 0xB1; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x6A; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0x5F; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0x48; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x5A; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0x7B; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x7C; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0xBA; break; case 0xFF3C: ch = 0xE0; break; case 0xFF3D: ch = 0xBB; break; case 0xFF3E: ch = 0xB0; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x79; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0xC0; break; case 0xFF5C: ch = 0x4F; break; case 0xFF5D: ch = 0xD0; break; case 0xFF5E: ch = 0xA1; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x5A; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0x7B; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x7C; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0xBA; break; case 0x005C: ch = 0xE0; break; case 0x005D: ch = 0xBB; break; case 0x005E: ch = 0xB0; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x79; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0xC0; break; case 0x007C: ch = 0x4F; break; case 0x007D: ch = 0xD0; break; case 0x007E: ch = 0xA1; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0x4A; break; case 0x00A3: ch = 0xB1; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x6A; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0x5F; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0x48; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x5A; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0x7B; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x7C; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0xBA; break; case 0xFF3C: ch = 0xE0; break; case 0xFF3D: ch = 0xBB; break; case 0xFF3E: ch = 0xB0; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x79; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0xC0; break; case 0xFF5C: ch = 0x4F; break; case 0xFF5D: ch = 0xD0; break; case 0xFF5E: ch = 0xA1; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP37 public class ENCibm037 : CP37 { public ENCibm037() : base() {} }; // class ENCibm037 }; // namespace I18N.Rare
using System.Collections; using UnityEngine; using UnityEngine.UI; using VRStandardAssets.Common; using VRStandardAssets.Utils; namespace VRStandardAssets.ShootingGallery { // This class controls the flow of the shooter games. It // includes the introduction, spawning of targets and // outro. Targets are spawned with a system that makes // spawnning more likely when there are fewer. public class ShootingGalleryController : MonoBehaviour { [SerializeField] private SessionData.GameType m_GameType; // Whether this is a 180 or 360 shooter. [SerializeField] private int m_IdealTargetNumber = 5; // How many targets aim to be on screen at once. [SerializeField] private float m_BaseSpawnProbability = 0.7f; // When there are the ideal number of targets, this is the probability another will spawn. [SerializeField] private float m_GameLength = 60f; // Time a game lasts in seconds. [SerializeField] private float m_SpawnInterval = 1f; // How frequently a target could spawn. [SerializeField] private float m_EndDelay = 1.5f; // The time the user needs to wait between the outro UI and being able to continue. [SerializeField] private float m_SphereSpawnInnerRadius = 5f; // For the 360 shooter, the nearest targets can spawn. [SerializeField] private float m_SphereSpawnOuterRadius = 10f; // For the 360 shooter, the furthest targets can spawn. [SerializeField] private float m_SphereSpawnMaxHeight = 15f; // For the 360 shooter, the highest targets can spawn. [SerializeField] private SelectionSlider m_SelectionSlider; // Used to confirm the user has understood the intro UI. [SerializeField] private Transform m_Camera; // Used to determine where targets can spawn. [SerializeField] private SelectionRadial m_SelectionRadial; // Used to continue past the outro. [SerializeField] private Reticle m_Reticle; // This is turned on and off when it is required and not. [SerializeField] private Image m_TimerBar; // The time remaining is shown on the UI for the gun, this is a reference to the image showing the time remaining. [SerializeField] private ObjectPool m_TargetObjectPool; // The object pool that stores all the targets. [SerializeField] private BoxCollider m_SpawnCollider; // For the 180 shooter, the volume that the targets can spawn within. [SerializeField] private UIController m_UIController; // Used to encapsulate the UI. [SerializeField] private InputWarnings m_InputWarnings; // Tap warnings need to be on for the intro and outro but off for the game itself. private float m_SpawnProbability; // The current probability that a target will spawn at the next interval. private float m_ProbabilityDelta; // The difference to the probability caused by a target spawning or despawning. public bool IsPlaying { get; private set; } // Whether or not the game is currently playing. private IEnumerator Start() { // Set the game type for the score to be recorded correctly. SessionData.SetGameType(m_GameType); // The probability difference for each spawn is difference between 100% and the base probabilty per the number or targets wanted. // That means that if the ideal number of targets was 5, the base probability was 0.7 then the delta is 0.06. // So if there are no targets, the probability of one spawning will be 1, then 0.94, then 0.88, etc. m_ProbabilityDelta = (1f - m_BaseSpawnProbability) / m_IdealTargetNumber; // Continue looping through all the phases. while (true) { yield return StartCoroutine (StartPhase ()); yield return StartCoroutine (PlayPhase ()); yield return StartCoroutine (EndPhase ()); } } private IEnumerator StartPhase () { // Wait for the intro UI to fade in. yield return StartCoroutine (m_UIController.ShowIntroUI ()); // Show the reticle (since there is now a selection slider) and hide the radial. m_Reticle.Show (); m_SelectionRadial.Hide (); // Turn on the tap warnings for the selection slider. m_InputWarnings.TurnOnDoubleTapWarnings (); m_InputWarnings.TurnOnSingleTapWarnings (); // Wait for the selection slider to finish filling. yield return StartCoroutine (m_SelectionSlider.WaitForBarToFill ()); // Turn off the tap warnings since it will now be tap to fire. m_InputWarnings.TurnOffDoubleTapWarnings (); m_InputWarnings.TurnOffSingleTapWarnings (); // Wait for the intro UI to fade out. yield return StartCoroutine (m_UIController.HideIntroUI ()); } private IEnumerator PlayPhase () { // Wait for the UI on the player's gun to fade in. yield return StartCoroutine(m_UIController.ShowPlayerUI()); // The game is now playing. IsPlaying = true; // Make sure the reticle is being shown. m_Reticle.Show (); // Reset the score. SessionData.Restart (); // Wait for the play updates to finish. yield return StartCoroutine (PlayUpdate ()); // Wait for the gun's UI to fade. yield return StartCoroutine(m_UIController.HidePlayerUI()); // The game is no longer playing. IsPlaying = false; } private IEnumerator EndPhase () { // Hide the reticle since the radial is about to be used. m_Reticle.Hide (); // In order, wait for the outro UI to fade in then wait for an additional delay. yield return StartCoroutine (m_UIController.ShowOutroUI ()); yield return new WaitForSeconds(m_EndDelay); // Turn on the tap warnings. m_InputWarnings.TurnOnDoubleTapWarnings(); m_InputWarnings.TurnOnSingleTapWarnings(); // Wait for the radial to fill (this will show and hide the radial automatically). yield return StartCoroutine(m_SelectionRadial.WaitForSelectionRadialToFill()); // The radial is now filled so stop the warnings. m_InputWarnings.TurnOffDoubleTapWarnings(); m_InputWarnings.TurnOffSingleTapWarnings(); // Wait for the outro UI to fade out. yield return StartCoroutine(m_UIController.HideOutroUI()); } private IEnumerator PlayUpdate () { // When the updates start, the probability of a target spawning is 100%. m_SpawnProbability = 1f; // The time remaining is the full length of the game length. float gameTimer = m_GameLength; // The amount of time before the next spawn is the full interval. float spawnTimer = m_SpawnInterval; // While there is still time remaining... while (gameTimer > 0f) { // ... check if the timer for spawning has reached zero. if (spawnTimer <= 0f) { // If it's time to spawn, check if a spawn should happen based on the probability. if (Random.value < m_SpawnProbability) { // If a spawn should happen, restart the timer for spawning. spawnTimer = m_SpawnInterval; // Decrease the probability of a spawn next time because there are now more targets. m_SpawnProbability -= m_ProbabilityDelta; // Spawn a target. Spawn (gameTimer); } } // Wait for the next frame. yield return null; // Decrease the timers by the time that was waited. gameTimer -= Time.deltaTime; spawnTimer -= Time.deltaTime; // Set the timer bar to be filled by the amount m_TimerBar.fillAmount = gameTimer / m_GameLength; } } private void Spawn (float timeRemaining) { // Get a reference to a target instance from the object pool. GameObject target = m_TargetObjectPool.GetGameObjectFromPool (); // Set the target's position to a random position. target.transform.position = SpawnPosition(); // Find a reference to the ShootingTarget script on the target gameobject and call it's Restart function. ShootingTarget shootingTarget = target.GetComponent<ShootingTarget>(); shootingTarget.Restart(timeRemaining); // Subscribe to the OnRemove event. shootingTarget.OnRemove += HandleTargetRemoved; } private Vector3 SpawnPosition () { // If this game is a 180 game then the random spawn position should be within the given collider. if (m_GameType == SessionData.GameType.SHOOTER180) { // Find the centre and extents of the spawn collider. Vector3 center = m_SpawnCollider.bounds.center; Vector3 extents = m_SpawnCollider.bounds.extents; // Get a random value between the extents on each axis. float x = Random.Range(center.x - extents.x, center.x + extents.x); float y = Random.Range(center.y - extents.y, center.y + extents.y); float z = Random.Range(center.z - extents.z, center.z + extents.z); // Return the point these random values make. return new Vector3(x, y, z); } // Otherwise the game is 360 and the spawn should be within a cylinder shape. // Find a random point on a unit circle and give it a radius between the inner and outer radii. Vector2 randomCirclePoint = Random.insideUnitCircle.normalized * Random.Range (m_SphereSpawnInnerRadius, m_SphereSpawnOuterRadius); // Find a random height between the camera's height and the maximum. float randomHeight = Random.Range (m_Camera.position.y, m_SphereSpawnMaxHeight); // The the random point on the circle is on the XZ plane and the random height is the Y axis. return new Vector3(randomCirclePoint.x, randomHeight, randomCirclePoint.y); } private void HandleTargetRemoved(ShootingTarget target) { // Now that the event has been hit, unsubscribe from it. target.OnRemove -= HandleTargetRemoved; // Return the target to it's object pool. m_TargetObjectPool.ReturnGameObjectToPool (target.gameObject); // Increase the likelihood of a spawn next time because there are fewer targets now. m_SpawnProbability += m_ProbabilityDelta; } } }
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/GUI/tk2dButton")] /// <summary> /// Simple gui button /// </summary> public class tk2dButton : MonoBehaviour { /// <summary> /// The camera this button is meant to be viewed from. /// Set this explicitly for best performance.\n /// The system will automatically traverse up the hierarchy to find a camera if this is not set.\n /// If nothing is found, it will fall back to the active <see cref="tk2dCamera"/>.\n /// Failing that, it will use Camera.main. /// </summary> public Camera viewCamera; // Button Up = normal state // Button Down = held down // Button Pressed = after it is pressed and activated /// <summary> /// The button down sprite. This is resolved by name from the sprite collection of the sprite component. /// </summary> public string buttonDownSprite = "button_down"; /// <summary> /// The button up sprite. This is resolved by name from the sprite collection of the sprite component. /// </summary> public string buttonUpSprite = "button_up"; /// <summary> /// The button pressed sprite. This is resolved by name from the sprite collection of the sprite component. /// </summary> public string buttonPressedSprite = "button_up"; int buttonDownSpriteId = -1, buttonUpSpriteId = -1, buttonPressedSpriteId = -1; /// <summary> /// Audio clip to play when the button transitions from up to down state. Requires an AudioSource component to be attached to work. /// </summary> public AudioClip buttonDownSound = null; /// <summary> /// Audio clip to play when the button transitions from down to up state. Requires an AudioSource component to be attached to work. /// </summary> public AudioClip buttonUpSound = null; /// <summary> /// Audio clip to play when the button is pressed. Requires an AudioSource component to be attached to work. /// </summary> public AudioClip buttonPressedSound = null; // Delegates /// <summary> /// Button event handler delegate. /// </summary> public delegate void ButtonHandlerDelegate(tk2dButton source); // Messaging /// <summary> /// Target object to send the message to. The event methods below are significantly more efficient. /// </summary> public GameObject targetObject = null; /// <summary> /// The message to send to the object. This should be the name of the method which needs to be called. /// </summary> public string messageName = ""; /// <summary> /// Occurs when button is pressed (tapped, and finger lifted while inside the button) /// </summary> public event ButtonHandlerDelegate ButtonPressedEvent; /// <summary> /// Occurs every frame for as long as the button is held down. /// </summary> public event ButtonHandlerDelegate ButtonAutoFireEvent; /// <summary> /// Occurs when button transition from up to down state /// </summary> public event ButtonHandlerDelegate ButtonDownEvent; /// <summary> /// Occurs when button transitions from down to up state /// </summary> public event ButtonHandlerDelegate ButtonUpEvent; tk2dBaseSprite sprite; bool buttonDown = false; /// <summary> /// How much to scale the sprite when the button is in the down state /// </summary> public float targetScale = 1.1f; /// <summary> /// The length of time the scale operation takes /// </summary> public float scaleTime = 0.05f; /// <summary> /// How long to wait before allowing the button to be pressed again, in seconds. /// </summary> public float pressedWaitTime = 0.3f; void OnEnable() { buttonDown = false; } // Use this for initialization void Start () { if (viewCamera == null) { // Find a camera parent Transform node = transform; while (node && node.camera == null) { node = node.parent; } if (node && node.camera != null) { viewCamera = node.camera; } // See if a tk2dCamera exists if (viewCamera == null && tk2dCamera.inst) { viewCamera = tk2dCamera.inst.mainCamera; } // ...otherwise, use the main camera if (viewCamera == null) { viewCamera = Camera.main; } } sprite = GetComponent<tk2dBaseSprite>(); // Further tests for sprite not being null aren't necessary, as the IDs will default to -1 in that case. Testing them will be sufficient if (sprite) { // Change this to use animated sprites if necessary // Same concept here, lookup Ids and call Play(xxx) instead of .spriteId = xxx UpdateSpriteIds(); } if (collider == null) { BoxCollider newCollider = gameObject.AddComponent<BoxCollider>(); Vector3 colliderExtents = newCollider.extents; colliderExtents.z = 0.2f; newCollider.extents = colliderExtents; } if ((buttonDownSound != null || buttonPressedSound != null || buttonUpSound != null) && audio == null) { AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.playOnAwake = false; } } /// <summary> /// Call this when the sprite names have changed /// </summary> public void UpdateSpriteIds() { buttonDownSpriteId = (buttonDownSprite.Length > 0)?sprite.GetSpriteIdByName(buttonDownSprite):-1; buttonUpSpriteId = (buttonUpSprite.Length > 0)?sprite.GetSpriteIdByName(buttonUpSprite):-1; buttonPressedSpriteId = (buttonPressedSprite.Length > 0)?sprite.GetSpriteIdByName(buttonPressedSprite):-1; } // Modify this to suit your audio solution // In our case, we have a global audio manager to play one shot sounds and pool them void PlaySound(AudioClip source) { if (audio && source) { audio.PlayOneShot(source); } } IEnumerator coScale(Vector3 defaultScale, float startScale, float endScale) { float t0 = Time.realtimeSinceStartup; Vector3 scale = defaultScale; float s = 0.0f; while (s < scaleTime) { float t = Mathf.Clamp01(s / scaleTime); float scl = Mathf.Lerp(startScale, endScale, t); scale = defaultScale * scl; transform.localScale = scale; yield return 0; s = (Time.realtimeSinceStartup - t0); } transform.localScale = defaultScale * endScale; } IEnumerator LocalWaitForSeconds(float seconds) { float t0 = Time.realtimeSinceStartup; float s = 0.0f; while (s < seconds) { yield return 0; s = (Time.realtimeSinceStartup - t0); } } IEnumerator coHandleButtonPress(int fingerId) { buttonDown = true; // inhibit processing in Update() bool buttonPressed = true; // the button is currently being pressed Vector3 defaultScale = transform.localScale; // Button has been pressed for the first time, cursor/finger is still on it if (targetScale != 1.0f) { // Only do this when the scale is actually enabled, to save one frame of latency when not needed yield return StartCoroutine( coScale(defaultScale, 1.0f, targetScale) ); } PlaySound(buttonDownSound); if (buttonDownSpriteId != -1) sprite.spriteId = buttonDownSpriteId; if (ButtonDownEvent != null) ButtonDownEvent(this); while (true) { Vector3 cursorPosition = Vector3.zero; bool cursorActive = true; // slightly akward arrangement to keep exact backwards compatibility #if !UNITY_FLASH if (Input.multiTouchEnabled) { bool found = false; for (int i = 0; i < Input.touchCount; ++i) { Touch touch = Input.GetTouch(i); if (touch.fingerId == fingerId) { if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) break; // treat as not found cursorPosition = touch.position; found = true; } } if (!found) cursorActive = false; } else #endif { if (!Input.GetMouseButton(0)) cursorActive = false; cursorPosition = Input.mousePosition; } // user is no longer pressing mouse or no longer touching button if (!cursorActive) break; Ray ray = viewCamera.ScreenPointToRay(cursorPosition); RaycastHit hitInfo; bool colliderHit = collider.Raycast(ray, out hitInfo, 1.0e8f); if (buttonPressed && !colliderHit) { if (targetScale != 1.0f) { // Finger is still on screen / button is still down, but the cursor has left the bounds of the button yield return StartCoroutine( coScale(defaultScale, targetScale, 1.0f) ); } PlaySound(buttonUpSound); if (buttonUpSpriteId != -1) sprite.spriteId = buttonUpSpriteId; if (ButtonUpEvent != null) ButtonUpEvent(this); buttonPressed = false; } else if (!buttonPressed & colliderHit) { if (targetScale != 1.0f) { // Cursor had left the bounds before, but now has come back in yield return StartCoroutine( coScale(defaultScale, 1.0f, targetScale) ); } PlaySound(buttonDownSound); if (buttonDownSpriteId != -1) sprite.spriteId = buttonDownSpriteId; if (ButtonDownEvent != null) ButtonDownEvent(this); buttonPressed = true; } if (buttonPressed && ButtonAutoFireEvent != null) { ButtonAutoFireEvent(this); } yield return 0; } if (buttonPressed) { if (targetScale != 1.0f) { // Handle case when cursor was in bounds when the button was released / finger lifted yield return StartCoroutine( coScale(defaultScale, targetScale, 1.0f) ); } PlaySound(buttonPressedSound); if (buttonPressedSpriteId != -1) sprite.spriteId = buttonPressedSpriteId; if (targetObject) { targetObject.SendMessage(messageName); } if (ButtonUpEvent != null) ButtonUpEvent(this); if (ButtonPressedEvent != null) ButtonPressedEvent(this); // Button may have been deactivated in ButtonPressed / Up event // Don't wait in that case #if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9 if (gameObject.active) #else if (gameObject.activeInHierarchy) #endif { yield return StartCoroutine(LocalWaitForSeconds(pressedWaitTime)); } if (buttonUpSpriteId != -1) sprite.spriteId = buttonUpSpriteId; } buttonDown = false; } // Update is called once per frame void Update () { if (buttonDown) // only need to process if button isn't down return; #if !UNITY_FLASH if (Input.multiTouchEnabled) { for (int i = 0; i < Input.touchCount; ++i) { Touch touch = Input.GetTouch(i); if (touch.phase != TouchPhase.Began) continue; Ray ray = viewCamera.ScreenPointToRay(touch.position); RaycastHit hitInfo; if (collider.Raycast(ray, out hitInfo, 1.0e8f)) { if (!Physics.Raycast(ray, hitInfo.distance - 0.01f)) { StartCoroutine(coHandleButtonPress(touch.fingerId)); break; // only one finger on a buton, please. } } } } else #endif { if (Input.GetMouseButtonDown(0)) { Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if (collider.Raycast(ray, out hitInfo, 1.0e8f)) { if (!Physics.Raycast(ray, hitInfo.distance - 0.01f)) StartCoroutine(coHandleButtonPress(-1)); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Runtime.Versioning; using EnvDTE; using NuGet.VisualStudio; using NuGet.VisualStudio.Resources; namespace NuGet.PowerShell.Commands { /// <summary> /// This class acts as the base class for InstallPackage, UninstallPackage and UpdatePackage commands. /// </summary> public abstract class ProcessPackageBaseCommand : NuGetBaseCommand { // If this command is executed by getting the project from the pipeline, then we need we keep track of all of the // project managers since the same cmdlet instance can be used across invocations. private readonly Dictionary<string, IProjectManager> _projectManagers = new Dictionary<string, IProjectManager>(); private readonly Dictionary<IProjectManager, Project> _projectManagerToProject = new Dictionary<IProjectManager, Project>(); private string _readmeFile; private readonly IVsCommonOperations _vsCommonOperations; private readonly IDeleteOnRestartManager _deleteOnRestartManager; private IDisposable _expandedNodesDisposable; protected ProcessPackageBaseCommand( ISolutionManager solutionManager, IVsPackageManagerFactory packageManagerFactory, IHttpClientEvents httpClientEvents, IVsCommonOperations vsCommonOperations, IDeleteOnRestartManager deleteOnRestartManager) : base(solutionManager, packageManagerFactory, httpClientEvents) { Debug.Assert(vsCommonOperations != null); _vsCommonOperations = vsCommonOperations; _deleteOnRestartManager = deleteOnRestartManager; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] public virtual string Id { get; set; } [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public virtual string ProjectName { get; set; } protected IProjectManager ProjectManager { get { // We take a snapshot of the default project, the first time it is accessed so if it changes during // the executing of this cmdlet we won't take it into consideration. (which is really an edge case anyway) string name = ProjectName ?? String.Empty; IProjectManager projectManager; if (!_projectManagers.TryGetValue(name, out projectManager)) { Tuple<IProjectManager, Project> tuple = GetProjectManager(); if (tuple != null) { projectManager = tuple.Item1; if (projectManager != null) { _projectManagers.Add(name, projectManager); } } } return projectManager; } } protected override void BeginProcessing() { base.BeginProcessing(); _readmeFile = null; if (PackageManager != null) { PackageManager.PackageInstalling += OnPackageInstalling; PackageManager.PackageInstalled += OnPackageInstalled; } // remember currently expanded nodes so that we can leave them expanded // after the operation has finished. SaveExpandedNodes(); } protected override void EndProcessing() { base.EndProcessing(); if (PackageManager != null) { PackageManager.PackageInstalling -= OnPackageInstalling; PackageManager.PackageInstalled -= OnPackageInstalled; } foreach (var projectManager in _projectManagers.Values) { projectManager.PackageReferenceAdded -= OnPackageReferenceAdded; projectManager.PackageReferenceRemoving -= OnPackageReferenceRemoving; } IList<string> packageDirectoriesMarkedForDeletion = _deleteOnRestartManager.GetPackageDirectoriesMarkedForDeletion(); if (packageDirectoriesMarkedForDeletion != null && packageDirectoriesMarkedForDeletion.Count != 0) { var message = string.Format( CultureInfo.CurrentCulture, VsResources.RequestRestartToCompleteUninstall, string.Join(", ", packageDirectoriesMarkedForDeletion)); WriteWarning(message); } WriteLine(); OpenReadMeFile(); CollapseNodes(); } private Tuple<IProjectManager, Project> GetProjectManager() { if (PackageManager == null) { return null; } Project project = GetProject(throwIfNotExists: true); if (project == null) { // No project specified and default project was null return null; } return GetProjectManager(project); } private Project GetProject(bool throwIfNotExists) { Project project = null; // If the user specified a project then use it if (!String.IsNullOrEmpty(ProjectName)) { project = SolutionManager.GetProject(ProjectName); // If that project was invalid then throw if (project == null && throwIfNotExists) { ErrorHandler.ThrowNoCompatibleProjectsTerminatingError(); } } else if (!String.IsNullOrEmpty(SolutionManager.DefaultProjectName)) { // If there is a default project then use it project = SolutionManager.GetProject(SolutionManager.DefaultProjectName); Debug.Assert(project != null, "default project should never be invalid"); } return project; } private Tuple<IProjectManager, Project> GetProjectManager(Project project) { IProjectManager projectManager = RegisterProjectEvents(project); return Tuple.Create(projectManager, project); } protected IProjectManager RegisterProjectEvents(Project project) { IProjectManager projectManager = PackageManager.GetProjectManager(project); if (!_projectManagerToProject.ContainsKey(projectManager)) { projectManager.PackageReferenceAdded += OnPackageReferenceAdded; projectManager.PackageReferenceRemoving += OnPackageReferenceRemoving; // Associate the project manager with this project _projectManagerToProject[projectManager] = project; } return projectManager; } private void OnPackageInstalling(object sender, PackageOperationEventArgs e) { // Write disclaimer text before a package is installed WriteDisclaimerText(e.Package); } private void OnPackageInstalled(object sender, PackageOperationEventArgs e) { AddToolsFolderToEnvironmentPath(e.InstallPath); ExecuteScript(e.InstallPath, PowerShellScripts.Init, e.Package, targetFramework: null, project: null); PrepareOpenReadMeFile(e); } private void PrepareOpenReadMeFile(PackageOperationEventArgs e) { // only open the read me file for the first package that initiates this operation. if (e.Package.Id.Equals(this.Id, StringComparison.OrdinalIgnoreCase) && e.Package.HasReadMeFileAtRoot()) { _readmeFile = Path.Combine(e.InstallPath, NuGetConstants.ReadmeFileName); } } private void OpenReadMeFile() { if (_readmeFile != null ) { _vsCommonOperations.OpenFile(_readmeFile); } } protected virtual void AddToolsFolderToEnvironmentPath(string installPath) { string toolsPath = Path.Combine(installPath, "tools"); if (Directory.Exists(toolsPath)) { var envPath = (string)GetVariableValue("env:path"); if (!envPath.EndsWith(";", StringComparison.OrdinalIgnoreCase)) { envPath = envPath + ";"; } envPath += toolsPath; SessionState.PSVariable.Set("env:path", envPath); } } private void OnPackageReferenceAdded(object sender, PackageOperationEventArgs e) { var projectManager = (ProjectManager)sender; Project project; if (!_projectManagerToProject.TryGetValue(projectManager, out project)) { throw new ArgumentException(Resources.Cmdlet_InvalidProjectManagerInstance, "sender"); } ExecuteScript(e.InstallPath, PowerShellScripts.Install, e.Package, project.GetTargetFrameworkName(), project); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void OnPackageReferenceRemoving(object sender, PackageOperationEventArgs e) { var projectManager = (ProjectManager)sender; Project project; if (!_projectManagerToProject.TryGetValue(projectManager, out project)) { throw new ArgumentException(Resources.Cmdlet_InvalidProjectManagerInstance, "sender"); } try { ExecuteScript( e.InstallPath, PowerShellScripts.Uninstall, e.Package, projectManager.GetTargetFrameworkForPackage(e.Package.Id), project); } catch (Exception ex) { LogCore(MessageLevel.Warning, ex.Message); } } protected void ExecuteScript( string rootPath, string scriptFileName, IPackage package, FrameworkName targetFramework, Project project) { string scriptPath, fullPath; if (package.FindCompatibleToolFiles(scriptFileName, targetFramework, out scriptPath)) { fullPath = Path.Combine(rootPath, scriptPath); } else { return; } if (File.Exists(fullPath)) { var psVariable = SessionState.PSVariable; string toolsPath = Path.GetDirectoryName(fullPath); // set temp variables to pass to the script psVariable.Set("__rootPath", rootPath); psVariable.Set("__toolsPath", toolsPath); psVariable.Set("__package", package); psVariable.Set("__project", project); string command = "& " + PathHelper.EscapePSPath(fullPath) + " $__rootPath $__toolsPath $__package $__project"; WriteVerbose(String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath)); InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null); // clear temp variables psVariable.Remove("__rootPath"); psVariable.Remove("__toolsPath"); psVariable.Remove("__package"); psVariable.Remove("__project"); } } protected virtual void WriteDisclaimerText(IPackageMetadata package) { if (package.RequireLicenseAcceptance) { string message = String.Format( CultureInfo.CurrentCulture, Resources.Cmdlet_InstallSuccessDisclaimerText, package.Id, String.Join(", ", package.Authors), package.LicenseUrl); WriteLine(message); } } private void SaveExpandedNodes() { // remember which nodes are currently open so that we can keep them open after the operation _expandedNodesDisposable = _vsCommonOperations.SaveSolutionExplorerNodeStates(SolutionManager); } private void CollapseNodes() { // collapse all nodes in solution explorer that we expanded during the operation if (_expandedNodesDisposable != null) { _expandedNodesDisposable.Dispose(); _expandedNodesDisposable = null; } } protected override void OnSendingRequest(object sender, WebRequestEventArgs e) { Project project = GetProject(throwIfNotExists: false); var projectGuids = project == null ? null : project.GetAllProjectTypeGuid(); HttpUtility.SetUserAgent(e.Request, DefaultUserAgent, projectGuids); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Dynamic; using System.Runtime.Serialization; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime.Types { // OldClass represents the type of old-style Python classes (which could not inherit from // built-in Python types). // // Object instances of old-style Python classes are represented by OldInstance. // // UserType is the equivalent of OldClass for new-style Python classes (which can inherit // from built-in types). [Flags] internal enum OldClassAttributes { None = 0x00, HasFinalizer = 0x01, HasSetAttr = 0x02, HasDelAttr = 0x04, } [PythonType("classobj"), DontMapGetMemberNamesToDir] [Serializable] [DebuggerTypeProxy(typeof(OldClass.OldClassDebugView)), DebuggerDisplay("old-style class {Name}")] public sealed class OldClass : #if FEATURE_CUSTOM_TYPE_DESCRIPTOR ICustomTypeDescriptor, #endif ICodeFormattable, IMembersList, IDynamicMetaObjectProvider, IPythonMembersList, IWeakReferenceable { [NonSerialized] private List<OldClass> _bases; private PythonType _type; internal PythonDictionary _dict; private int _attrs; // actually OldClassAttributes - losing type safety for thread safety internal object _name; private int _optimizedInstanceNamesVersion; private string[] _optimizedInstanceNames; private WeakRefTracker _tracker; public static string __doc__ = "classobj(name, bases, dict)"; public static object __new__(CodeContext/*!*/ context, [NotNull]PythonType cls, string name, PythonTuple bases, PythonDictionary/*!*/ dict) { if (dict == null) { throw PythonOps.TypeError("dict must be a dictionary"); } else if (cls != TypeCache.OldClass) { throw PythonOps.TypeError("{0} is not a subtype of classobj", cls.Name); } if (!dict.ContainsKey("__module__")) { object moduleValue; if (context.TryGetGlobalVariable("__name__", out moduleValue)) { dict["__module__"] = moduleValue; } } foreach (object o in bases) { if (o is PythonType) { return PythonOps.MakeClass(context, name, bases._data, String.Empty, dict); } } return new OldClass(name, bases, dict, String.Empty); } internal OldClass(string name, PythonTuple bases, PythonDictionary/*!*/ dict, string instanceNames) { _bases = ValidateBases(bases); Init(name, dict, instanceNames); } private void Init(string name, PythonDictionary/*!*/ dict, string instanceNames) { _name = name; InitializeInstanceNames(instanceNames); _dict = dict; if (!_dict._storage.Contains("__doc__")) { _dict._storage.Add(ref _dict._storage, "__doc__", null); } CheckSpecialMethods(_dict); } private void CheckSpecialMethods(PythonDictionary dict) { if (dict._storage.Contains("__del__")) { HasFinalizer = true; } if (dict._storage.Contains("__setattr__")) { HasSetAttr = true; } if (dict._storage.Contains("__delattr__")) { HasDelAttr = true; } foreach (OldClass oc in _bases) { if (oc.HasDelAttr) { HasDelAttr = true; } if (oc.HasSetAttr) { HasSetAttr = true; } if (oc.HasFinalizer) { HasFinalizer = true; } } } #if FEATURE_SERIALIZATION private OldClass(SerializationInfo info, StreamingContext context) { _bases = (List<OldClass>)info.GetValue("__class__", typeof(List<OldClass>)); _name = info.GetValue("__name__", typeof(object)); _dict = new PythonDictionary(); InitializeInstanceNames(""); //TODO should we serialize the optimization data List<object> keys = (List<object>)info.GetValue("keys", typeof(List<object>)); List<object> values = (List<object>)info.GetValue("values", typeof(List<object>)); for (int i = 0; i < keys.Count; i++) { _dict[keys[i]] = values[i]; } if (_dict.has_key("__del__")) HasFinalizer = true; } #pragma warning disable 169 // unused method - called via reflection from serialization [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] private void GetObjectData(SerializationInfo info, StreamingContext context) { ContractUtils.RequiresNotNull(info, "info"); info.AddValue("__bases__", _bases); info.AddValue("__name__", _name); List<object> keys = new List<object>(); List<object> values = new List<object>(); foreach (KeyValuePair<object, object> kvp in _dict._storage.GetItems()) { keys.Add(kvp.Key); values.Add(kvp.Value); } info.AddValue("keys", keys); info.AddValue("values", values); } #pragma warning restore 169 #endif private void InitializeInstanceNames(string instanceNames) { if (instanceNames.Length == 0) { _optimizedInstanceNames = ArrayUtils.EmptyStrings; _optimizedInstanceNamesVersion = 0; return; } string[] names = instanceNames.Split(','); _optimizedInstanceNames = new string[names.Length]; for (int i = 0; i < names.Length; i++) { _optimizedInstanceNames[i] = names[i]; } _optimizedInstanceNamesVersion = CustomInstanceDictionaryStorage.AllocateVersion(); } internal string[] OptimizedInstanceNames { get { return _optimizedInstanceNames; } } internal int OptimizedInstanceNamesVersion { get { return _optimizedInstanceNamesVersion; } } internal string Name { get { return _name.ToString(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] internal bool TryLookupSlot(string name, out object ret) { if (_dict._storage.TryGetValue(name, out ret)) { return true; } // bases only ever contains OldClasses (tuples are immutable, and when assigned // to we verify the types in the Tuple) foreach (OldClass c in _bases) { if (c.TryLookupSlot(name, out ret)) return true; } ret = null; return false; } internal bool TryLookupOneSlot(PythonType lookingType, string name, out object ret) { if (_dict._storage.TryGetValue(name, out ret)) { ret = GetOldStyleDescriptor(TypeObject.Context.SharedContext, ret, null, lookingType); return true; } return false; } internal string FullName { get { return _dict["__module__"].ToString() + '.' + _name; } } internal List<OldClass> BaseClasses { get { return _bases; } } internal object GetOldStyleDescriptor(CodeContext context, object self, object instance, object type) { PythonTypeSlot dts = self as PythonTypeSlot; object callable; if (dts != null && dts.TryGetValue(context, instance, TypeObject, out callable)) { return callable; } return PythonOps.GetUserDescriptor(self, instance, type); } internal static object GetOldStyleDescriptor(CodeContext context, object self, object instance, PythonType type) { PythonTypeSlot dts = self as PythonTypeSlot; object callable; if (dts != null && dts.TryGetValue(context, instance, type, out callable)) { return callable; } return PythonOps.GetUserDescriptor(self, instance, type); } internal bool HasFinalizer { get { return (_attrs & (int)OldClassAttributes.HasFinalizer) != 0; } set { int oldAttrs, newAttrs; do { oldAttrs = _attrs; newAttrs = value ? oldAttrs | ((int)OldClassAttributes.HasFinalizer) : oldAttrs & ((int)~OldClassAttributes.HasFinalizer); } while (Interlocked.CompareExchange(ref _attrs, newAttrs, oldAttrs) != oldAttrs); } } internal bool HasSetAttr { get { return (_attrs & (int)OldClassAttributes.HasSetAttr) != 0; } set { int oldAttrs, newAttrs; do { oldAttrs = _attrs; newAttrs = value ? oldAttrs | ((int)OldClassAttributes.HasSetAttr) : oldAttrs & ((int)~OldClassAttributes.HasSetAttr); } while (Interlocked.CompareExchange(ref _attrs, newAttrs, oldAttrs) != oldAttrs); } } internal bool HasDelAttr { get { return (_attrs & (int)OldClassAttributes.HasDelAttr) != 0; } set { int oldAttrs, newAttrs; do { oldAttrs = _attrs; newAttrs = value ? oldAttrs | ((int)OldClassAttributes.HasDelAttr) : oldAttrs & ((int)~OldClassAttributes.HasDelAttr); } while (Interlocked.CompareExchange(ref _attrs, newAttrs, oldAttrs) != oldAttrs); } } public override string ToString() { return FullName; } #region Calls // Calling an OldClass instance means instantiating that class and invoking the __init__() member if // it's defined. // OldClass impls IDynamicMetaObjectProvider. But May wind up here still if IDynamicObj doesn't provide a rule (such as for list sigs). // If our IDynamicMetaObjectProvider implementation is complete, we can then remove these Call methods. [SpecialName] public object Call(CodeContext context, [NotNull]params object[] args\u00F8) { OldInstance inst = new OldInstance(context, this); object value; // lookup the slot directly - we don't go through __getattr__ // until after the instance is created. if (TryLookupSlot("__init__", out value)) { PythonOps.CallWithContext(context, GetOldStyleDescriptor(context, value, inst, this), args\u00F8); } else if (args\u00F8.Length > 0) { MakeCallError(); } return inst; } [SpecialName] public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict\u00F8, [NotNull]params object[] args\u00F8) { OldInstance inst = new OldInstance(context, this); object meth; if (PythonOps.TryGetBoundAttr(inst, "__init__", out meth)) { PythonCalls.CallWithKeywordArgs(context, meth, args\u00F8, dict\u00F8); } else if (dict\u00F8.Count > 0 || args\u00F8.Length > 0) { MakeCallError(); } return inst; } #endregion // calls internal PythonType TypeObject { get { if (_type == null) { Interlocked.CompareExchange(ref _type, new PythonType(this), null); } return _type; } } private List<OldClass> ValidateBases(object value) { if (!(value is PythonTuple t)) throw PythonOps.TypeError("__bases__ must be a tuple object"); List<OldClass> res = new List<OldClass>(t.__len__()); foreach (object o in t) { if (!(o is OldClass oc)) throw PythonOps.TypeError("__bases__ items must be classes (got {0})", PythonTypeOps.GetName(o)); if (oc.IsSubclassOf(this)) { throw PythonOps.TypeError("a __bases__ item causes an inheritance cycle"); } res.Add(oc); } return res; } internal object GetMember(CodeContext context, string name) { object value; if (!TryGetBoundCustomMember(context, name, out value)) { throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'", Name, name); } return value; } internal bool TryGetBoundCustomMember(CodeContext context, string name, out object value) { if (name == "__bases__") { value = PythonTuple.Make(_bases); return true; } if (name == "__name__") { value = _name; return true; } if (name == "__dict__") { //!!! user code can modify __del__ property of __dict__ behind our back HasDelAttr = HasSetAttr = true; // pessimisticlly assume the user is setting __setattr__ in the dict value = _dict; return true; } if (TryLookupSlot(name, out value)) { value = GetOldStyleDescriptor(context, value, null, this); return true; } return false; } internal bool DeleteCustomMember(CodeContext context, string name) { if (!_dict._storage.Remove(ref _dict._storage, name)) { throw PythonOps.AttributeError("{0} is not a valid attribute", name); } if (name == "__del__") { HasFinalizer = false; } if (name == "__setattr__") { HasSetAttr = false; } if (name == "__delattr__") { HasDelAttr = false; } return true; } internal static void RecurseAttrHierarchy(OldClass oc, IDictionary<object, object> attrs) { foreach (KeyValuePair<object, object> kvp in oc._dict._storage.GetItems()) { if (!attrs.ContainsKey(kvp.Key)) { attrs.Add(kvp.Key, kvp.Key); } } // recursively get attrs in parent hierarchy if (oc._bases.Count != 0) { foreach (OldClass parent in oc._bases) { RecurseAttrHierarchy(parent, attrs); } } } #region IMembersList Members IList<string> IMembersList.GetMemberNames() { return PythonOps.GetStringMemberList(this); } IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { PythonDictionary attrs = new PythonDictionary(_dict); RecurseAttrHierarchy(this, attrs); return PythonOps.MakeListFromSequence(attrs); } #endregion internal bool IsSubclassOf(object other) { if (this == other) return true; if (!(other is OldClass dt)) return false; List<OldClass> bases = _bases; foreach (OldClass bc in bases) { if (bc.IsSubclassOf(other)) { return true; } } return false; } #region ICustomTypeDescriptor Members #if FEATURE_CUSTOM_TYPE_DESCRIPTOR AttributeCollection ICustomTypeDescriptor.GetAttributes() { return CustomTypeDescHelpers.GetAttributes(this); } string ICustomTypeDescriptor.GetClassName() { return CustomTypeDescHelpers.GetClassName(this); } string ICustomTypeDescriptor.GetComponentName() { return CustomTypeDescHelpers.GetComponentName(this); } TypeConverter ICustomTypeDescriptor.GetConverter() { return CustomTypeDescHelpers.GetConverter(this); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return CustomTypeDescHelpers.GetDefaultEvent(this); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return CustomTypeDescHelpers.GetDefaultProperty(this); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return CustomTypeDescHelpers.GetEditor(this, editorBaseType); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return CustomTypeDescHelpers.GetEvents(attributes); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return CustomTypeDescHelpers.GetEvents(this); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { return CustomTypeDescHelpers.GetProperties(attributes); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return CustomTypeDescHelpers.GetProperties(this); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return CustomTypeDescHelpers.GetPropertyOwner(this, pd); } #endif #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return string.Format("<class {0} at {1}>", FullName, PythonOps.HexId(this)); } #endregion #region Internal Member Accessors internal bool TryLookupInit(object inst, out object ret) { if (TryLookupSlot("__init__", out ret)) { ret = GetOldStyleDescriptor(DefaultContext.Default, ret, inst, this); return true; } return false; } internal static object MakeCallError() { // Normally, if we have an __init__ method, the method binder detects signature mismatches. // This can happen when a class does not define __init__ and therefore does not take any arguments. // Beware that calls like F(*(), **{}) have 2 arguments but they're empty and so it should still // match against def F(). throw PythonOps.TypeError("this constructor takes no arguments"); } internal void SetBases(object value) { _bases = ValidateBases(value); } internal void SetName(object value) { if (!(value is string n)) throw PythonOps.TypeError("TypeError: __name__ must be a string object"); _name = n; } internal void SetDictionary(object value) { if (!(value is PythonDictionary d)) throw PythonOps.TypeError("__dict__ must be set to dictionary"); _dict = d; } internal void SetNameHelper(string name, object value) { _dict._storage.Add(ref _dict._storage, name, value); if (name == "__del__") { HasFinalizer = true; } else if (name == "__setattr__") { HasSetAttr = true; } else if (name == "__delattr__") { HasDelAttr = true; } } internal object LookupValue(CodeContext context, string name) { object value; if (TryLookupValue(context, name, out value)) { return value; } throw PythonOps.AttributeErrorForMissingAttribute(this, name); } internal bool TryLookupValue(CodeContext context, string name, out object value) { if (TryLookupSlot(name, out value)) { value = GetOldStyleDescriptor(context, value, null, this); return true; } return false; } internal void DictionaryIsPublic() { HasDelAttr = true; HasSetAttr = true; } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) { return new Binding.MetaOldClass(parameter, BindingRestrictions.Empty, this); } #endregion internal class OldClassDebugView { private readonly OldClass _class; public OldClassDebugView(OldClass klass) { _class = klass; } public List<OldClass> __bases__ { get { return _class.BaseClasses; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal List<ObjectDebugView> Members { get { var res = new List<ObjectDebugView>(); if (_class._dict != null) { foreach (var v in _class._dict) { res.Add(new ObjectDebugView(v.Key, v.Value)); } } return res; } } } #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _tracker; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _tracker = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { _tracker = value; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// DeploymentsOperations operations. /// </summary> internal partial class DeploymentsOperations : IServiceOperations<ResourceManagementClient>, IDeploymentsOperations { /// <summary> /// Initializes a new instance of the DeploymentsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DeploymentsOperations(ResourceManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ResourceManagementClient /// </summary> public ResourceManagementClient Client { get; private set; } /// <summary> /// Delete deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, deploymentName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Delete deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Checks whether deployment exists. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to check. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<bool?>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckExistence", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 404) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; _result.Body = (_statusCode == HttpStatusCode.NoContent); 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> /// Create a named template deployment using a template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExtended>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<DeploymentExtended> _response = await BeginCreateOrUpdateWithHttpMessagesAsync( resourceGroupName, deploymentName, parameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExtended>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentExtended>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExtended>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExtended>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExtended>> GetWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentExtended>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExtended>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Cancel a currently running template deployment. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Cancel", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/cancel").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Validate a deployment template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Deployment to validate. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentValidateResult>> ValidateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Validate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/validate").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentValidateResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentValidateResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 400) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentValidateResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Exports a deployment template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<DeploymentExportResult>> ExportTemplateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deploymentName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("deploymentName", deploymentName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ExportTemplate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/exportTemplate").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DeploymentExportResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DeploymentExportResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to filter by. The name is case insensitive. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<DeploymentExtended>>> ListWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DeploymentExtendedFilter> odataQuery = default(ODataQuery<DeploymentExtendedFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<DeploymentExtended>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<DeploymentExtended>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<DeploymentExtended>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<DeploymentExtended>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<DeploymentExtended>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { public class ManagedPEBuilder : PEBuilder { private const string TextSectionName = ".text"; private const string ResourceSectionName = ".rsrc"; private const string RelocationSectionName = ".reloc"; private readonly PEDirectoriesBuilder _peDirectoriesBuilder; private readonly TypeSystemMetadataSerializer _metadataSerializer; private readonly BlobBuilder _ilStream; private readonly BlobBuilder _mappedFieldData; private readonly BlobBuilder _managedResourceData; private readonly Action<BlobBuilder, SectionLocation> _nativeResourceSectionSerializerOpt; private readonly int _strongNameSignatureSize; private readonly MethodDefinitionHandle _entryPoint; private readonly string _pdbPathOpt; private readonly ContentId _nativePdbContentId; private readonly ContentId _portablePdbContentId; private readonly CorFlags _corFlags; private int _lazyEntryPointAddress; private Blob _lazyStrongNameSignature; public ManagedPEBuilder( PEHeaderBuilder header, TypeSystemMetadataSerializer metadataSerializer, BlobBuilder ilStream, BlobBuilder mappedFieldData, BlobBuilder managedResourceData, Action<BlobBuilder, SectionLocation> nativeResourceSectionSerializer, // opt int strongNameSignatureSize, MethodDefinitionHandle entryPoint, string pdbPathOpt, // TODO: DebugTableBuilder ContentId nativePdbContentId, // TODO: DebugTableBuilder ContentId portablePdbContentId, // TODO: DebugTableBuilder CorFlags corFlags, Func<IEnumerable<Blob>, ContentId> deterministicIdProvider = null) : base(header, deterministicIdProvider) { _metadataSerializer = metadataSerializer; _ilStream = ilStream; _mappedFieldData = mappedFieldData; _managedResourceData = managedResourceData; _nativeResourceSectionSerializerOpt = nativeResourceSectionSerializer; _strongNameSignatureSize = strongNameSignatureSize; _entryPoint = entryPoint; _pdbPathOpt = pdbPathOpt; _nativePdbContentId = nativePdbContentId; _portablePdbContentId = portablePdbContentId; _corFlags = corFlags; _peDirectoriesBuilder = new PEDirectoriesBuilder(); } protected override ImmutableArray<Section> CreateSections() { var builder = ImmutableArray.CreateBuilder<Section>(3); builder.Add(new Section(TextSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode)); if (_nativeResourceSectionSerializerOpt != null) { builder.Add(new Section(ResourceSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData)); } if (Header.Machine == Machine.I386 || Header.Machine == 0) { builder.Add(new Section(RelocationSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemDiscardable | SectionCharacteristics.ContainsInitializedData)); } return builder.ToImmutable(); } protected override BlobBuilder SerializeSection(string name, SectionLocation location) { switch (name) { case TextSectionName: return SerializeTextSection(location); case ResourceSectionName: return SerializeResourceSection(location); case RelocationSectionName: return SerializeRelocationSection(location); default: throw new ArgumentException(SR.Format(SR.UnknownSectionName, name), nameof(name)); } } private BlobBuilder SerializeTextSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); var metadataBuilder = new BlobBuilder(); var metadataSizes = _metadataSerializer.MetadataSizes; var textSection = new ManagedTextSection( metadataSizes.MetadataSize, ilStreamSize: _ilStream.Count, mappedFieldDataSize: _mappedFieldData.Count, resourceDataSize: _managedResourceData.Count, strongNameSignatureSize: _strongNameSignatureSize, imageCharacteristics: Header.ImageCharacteristics, machine: Header.Machine, pdbPathOpt: _pdbPathOpt, isDeterministic: IsDeterministic); int methodBodyStreamRva = location.RelativeVirtualAddress + textSection.OffsetToILStream; int mappedFieldDataStreamRva = location.RelativeVirtualAddress + textSection.CalculateOffsetToMappedFieldDataStream(); _metadataSerializer.SerializeMetadata(metadataBuilder, methodBodyStreamRva, mappedFieldDataStreamRva); BlobBuilder debugTableBuilderOpt; if (_pdbPathOpt != null || IsDeterministic) { debugTableBuilderOpt = new BlobBuilder(); textSection.WriteDebugTable(debugTableBuilderOpt, location, _nativePdbContentId, _portablePdbContentId); } else { debugTableBuilderOpt = null; } _lazyEntryPointAddress = textSection.GetEntryPointAddress(location.RelativeVirtualAddress); textSection.Serialize( sectionBuilder, location.RelativeVirtualAddress, _entryPoint.IsNil ? 0 : MetadataTokens.GetToken(_entryPoint), _corFlags, Header.ImageBase, metadataBuilder, _ilStream, _mappedFieldData, _managedResourceData, debugTableBuilderOpt, out _lazyStrongNameSignature); _peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress; _peDirectoriesBuilder.DebugTable = textSection.GetDebugDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.ImportAddressTable = textSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.ImportTable = textSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.CorHeaderTable = textSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress); return sectionBuilder; } private BlobBuilder SerializeResourceSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); _nativeResourceSectionSerializerOpt(sectionBuilder, location); _peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private BlobBuilder SerializeRelocationSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); WriteRelocationSection(sectionBuilder, Header.Machine, _lazyEntryPointAddress); _peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress) { Debug.Assert(builder.Count == 0); builder.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000); builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u); uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000; uint relocType = (machine == Machine.Amd64 || machine == Machine.IA64) ? 10u : 3u; ushort s = (ushort)((relocType << 12) | offsetWithinPage); builder.WriteUInt16(s); if (machine == Machine.IA64) { builder.WriteUInt32(relocType << 12); } builder.WriteUInt16(0); // next chunk's RVA } protected internal override PEDirectoriesBuilder GetDirectories() { return _peDirectoriesBuilder; } private IEnumerable<Blob> GetContentToSign(BlobBuilder peImage) { // Signed content includes // - PE header without its alignment padding // - all sections including their alignment padding and excluding strong name signature blob int remainingHeader = Header.ComputeSizeOfPeHeaders(Sections.Length); foreach (var blob in peImage.GetBlobs()) { if (remainingHeader > 0) { int length = Math.Min(remainingHeader, blob.Length); yield return new Blob(blob.Buffer, blob.Start, length); remainingHeader -= length; } else if (blob.Buffer == _lazyStrongNameSignature.Buffer) { yield return new Blob(blob.Buffer, blob.Start, _lazyStrongNameSignature.Start - blob.Start); yield return new Blob(blob.Buffer, _lazyStrongNameSignature.Start + _lazyStrongNameSignature.Length, blob.Length - _lazyStrongNameSignature.Length); } else { yield return new Blob(blob.Buffer, blob.Start, blob.Length); } } } public void Sign(BlobBuilder peImage, Func<IEnumerable<Blob>, byte[]> signatureProvider) { if (peImage == null) { throw new ArgumentNullException(nameof(peImage)); } if (signatureProvider == null) { throw new ArgumentNullException(nameof(signatureProvider)); } var content = GetContentToSign(peImage); byte[] signature = signatureProvider(content); // signature may be shorter (the rest of the reserved space is padding): if (signature == null || signature.Length > _lazyStrongNameSignature.Length) { throw new InvalidOperationException(SR.SignatureProviderReturnedInvalidSignature); } // TODO: Native csc also calculates and fills checksum in the PE header // Using MapFileAndCheckSum() from imagehlp.dll. var writer = new BlobWriter(_lazyStrongNameSignature); writer.WriteBytes(signature); } } }
/* * 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.Services { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Services; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Services implementation. /// </summary> internal sealed class Services : PlatformTarget, IServices { /** */ private const int OpDeploy = 1; /** */ private const int OpDeployMultiple = 2; /** */ private const int OpDotnetServices = 3; /** */ private const int OpInvokeMethod = 4; /** */ private const int OpDescriptors = 5; /** */ private readonly IClusterGroup _clusterGroup; /** Invoker binary flag. */ private readonly bool _keepBinary; /** Server binary flag. */ private readonly bool _srvKeepBinary; /** Async instance. */ private readonly Lazy<Services> _asyncInstance; /// <summary> /// Initializes a new instance of the <see cref="Services" /> class. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="clusterGroup">Cluster group.</param> /// <param name="keepBinary">Invoker binary flag.</param> /// <param name="srvKeepBinary">Server binary flag.</param> public Services(IUnmanagedTarget target, Marshaller marsh, IClusterGroup clusterGroup, bool keepBinary, bool srvKeepBinary) : base(target, marsh) { Debug.Assert(clusterGroup != null); _clusterGroup = clusterGroup; _keepBinary = keepBinary; _srvKeepBinary = srvKeepBinary; _asyncInstance = new Lazy<Services>(() => new Services(this)); } /// <summary> /// Initializes a new async instance. /// </summary> /// <param name="services">The services.</param> private Services(Services services) : base(UU.ServicesWithAsync(services.Target), services.Marshaller) { _clusterGroup = services.ClusterGroup; _keepBinary = services._keepBinary; _srvKeepBinary = services._srvKeepBinary; } /** <inheritDoc /> */ public IServices WithKeepBinary() { if (_keepBinary) return this; return new Services(Target, Marshaller, _clusterGroup, true, _srvKeepBinary); } /** <inheritDoc /> */ public IServices WithServerKeepBinary() { if (_srvKeepBinary) return this; return new Services(UU.ServicesWithServerKeepBinary(Target), Marshaller, _clusterGroup, _keepBinary, true); } /** <inheritDoc /> */ public IClusterGroup ClusterGroup { get { return _clusterGroup; } } /// <summary> /// Gets the asynchronous instance. /// </summary> private Services AsyncInstance { get { return _asyncInstance.Value; } } /** <inheritDoc /> */ public void DeployClusterSingleton(string name, IService service) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); IgniteArgumentCheck.NotNull(service, "service"); DeployMultiple(name, service, 1, 1); } /** <inheritDoc /> */ public Task DeployClusterSingletonAsync(string name, IService service) { AsyncInstance.DeployClusterSingleton(name, service); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public void DeployNodeSingleton(string name, IService service) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); IgniteArgumentCheck.NotNull(service, "service"); DeployMultiple(name, service, 0, 1); } /** <inheritDoc /> */ public Task DeployNodeSingletonAsync(string name, IService service) { AsyncInstance.DeployNodeSingleton(name, service); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public void DeployKeyAffinitySingleton<TK>(string name, IService service, string cacheName, TK affinityKey) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); IgniteArgumentCheck.NotNull(service, "service"); IgniteArgumentCheck.NotNull(affinityKey, "affinityKey"); Deploy(new ServiceConfiguration { Name = name, Service = service, CacheName = cacheName, AffinityKey = affinityKey, TotalCount = 1, MaxPerNodeCount = 1 }); } /** <inheritDoc /> */ public Task DeployKeyAffinitySingletonAsync<TK>(string name, IService service, string cacheName, TK affinityKey) { AsyncInstance.DeployKeyAffinitySingleton(name, service, cacheName, affinityKey); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public void DeployMultiple(string name, IService service, int totalCount, int maxPerNodeCount) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); IgniteArgumentCheck.NotNull(service, "service"); DoOutOp(OpDeployMultiple, w => { w.WriteString(name); w.WriteObject(service); w.WriteInt(totalCount); w.WriteInt(maxPerNodeCount); }); } /** <inheritDoc /> */ public Task DeployMultipleAsync(string name, IService service, int totalCount, int maxPerNodeCount) { AsyncInstance.DeployMultiple(name, service, totalCount, maxPerNodeCount); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public void Deploy(ServiceConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); DoOutOp(OpDeploy, w => { w.WriteString(configuration.Name); w.WriteObject(configuration.Service); w.WriteInt(configuration.TotalCount); w.WriteInt(configuration.MaxPerNodeCount); w.WriteString(configuration.CacheName); w.WriteObject(configuration.AffinityKey); if (configuration.NodeFilter != null) w.WriteObject(configuration.NodeFilter); else w.WriteObject<object>(null); }); } /** <inheritDoc /> */ public Task DeployAsync(ServiceConfiguration configuration) { AsyncInstance.Deploy(configuration); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public void Cancel(string name) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); UU.ServicesCancel(Target, name); } /** <inheritDoc /> */ public Task CancelAsync(string name) { AsyncInstance.Cancel(name); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public void CancelAll() { UU.ServicesCancelAll(Target); } /** <inheritDoc /> */ public Task CancelAllAsync() { AsyncInstance.CancelAll(); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public ICollection<IServiceDescriptor> GetServiceDescriptors() { return DoInOp(OpDescriptors, stream => { var reader = Marshaller.StartUnmarshal(stream, _keepBinary); var size = reader.ReadInt(); var result = new List<IServiceDescriptor>(size); for (var i = 0; i < size; i++) { var name = reader.ReadString(); result.Add(new ServiceDescriptor(name, reader, this)); } return result; }); } /** <inheritDoc /> */ public T GetService<T>(string name) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var services = GetServices<T>(name); if (services == null) return default(T); return services.FirstOrDefault(); } /** <inheritDoc /> */ public ICollection<T> GetServices<T>(string name) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); return DoOutInOp<ICollection<T>>(OpDotnetServices, w => w.WriteString(name), r => { bool hasVal = r.ReadBool(); if (hasVal) { var count = r.ReadInt(); var res = new List<T>(count); for (var i = 0; i < count; i++) res.Add(Marshaller.Ignite.HandleRegistry.Get<T>(r.ReadLong())); return res; } return null; }); } /** <inheritDoc /> */ public T GetServiceProxy<T>(string name) where T : class { return GetServiceProxy<T>(name, false); } /** <inheritDoc /> */ public T GetServiceProxy<T>(string name, bool sticky) where T : class { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); IgniteArgumentCheck.Ensure(typeof(T).IsInterface, "T", "Service proxy type should be an interface: " + typeof(T)); // In local scenario try to return service instance itself instead of a proxy // Get as object because proxy interface may be different from real interface var locInst = GetService<object>(name) as T; if (locInst != null) return locInst; var javaProxy = UU.ServicesGetServiceProxy(Target, name, sticky); var platform = GetServiceDescriptors().Cast<ServiceDescriptor>().Single(x => x.Name == name).Platform; return new ServiceProxy<T>((method, args) => InvokeProxyMethod(javaProxy, method, args, platform)).GetTransparentProxy(); } /// <summary> /// Invokes the service proxy method. /// </summary> /// <param name="proxy">Unmanaged proxy.</param> /// <param name="method">Method to invoke.</param> /// <param name="args">Arguments.</param> /// <param name="platform">The platform.</param> /// <returns> /// Invocation result. /// </returns> private unsafe object InvokeProxyMethod(IUnmanagedTarget proxy, MethodBase method, object[] args, Platform platform) { return DoOutInOp(OpInvokeMethod, writer => ServiceProxySerializer.WriteProxyMethod(writer, method, args, platform), stream => ServiceProxySerializer.ReadInvocationResult(stream, Marshaller, _keepBinary), proxy.Target); } } }
using System; using System.Reflection; using System.Runtime.InteropServices; namespace Python.Runtime { /// <summary> /// Base class for Python types that reflect managed exceptions based on /// System.Exception /// </summary> /// <remarks> /// The Python wrapper for managed exceptions LIES about its inheritance /// tree. Although the real System.Exception is a subclass of /// System.Object the Python type for System.Exception does NOT claim that /// it subclasses System.Object. Instead TypeManager.CreateType() uses /// Python's exception.Exception class as base class for System.Exception. /// </remarks> internal class ExceptionClassObject : ClassObject { internal ExceptionClassObject(Type tp) : base(tp) { } internal static Exception ToException(IntPtr ob) { var co = GetManagedObject(ob) as CLRObject; if (co == null) { return null; } var e = co.inst as Exception; if (e == null) { return null; } return e; } /// <summary> /// Exception __str__ implementation /// </summary> public new static IntPtr tp_str(IntPtr ob) { Exception e = ToException(ob); if (e == null) { return Exceptions.RaiseTypeError("invalid object"); } string message = string.Empty; if (e.Message != string.Empty) { message = e.Message; } if (!string.IsNullOrEmpty(e.StackTrace)) { message = message + "\n" + e.StackTrace; } return Runtime.PyUnicode_FromString(message); } } /// <summary> /// Encapsulates the Python exception APIs. /// </summary> /// <remarks> /// Readability of the Exceptions class improvements as we look toward version 2.7 ... /// </remarks> public class Exceptions { internal static IntPtr warnings_module; internal static IntPtr exceptions_module; private Exceptions() { } /// <summary> /// Initialization performed on startup of the Python runtime. /// </summary> internal static void Initialize() { string exceptionsModuleName = Runtime.IsPython3 ? "builtins" : "exceptions"; exceptions_module = Runtime.PyImport_ImportModule(exceptionsModuleName); Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } else { fi.SetValue(type, IntPtr.Zero); DebugUtil.Print($"Unknown exception: {fi.Name}"); } } Runtime.PyErr_Clear(); } /// <summary> /// Cleanup resources upon shutdown of the Python runtime. /// </summary> internal static void Shutdown() { if (Runtime.Py_IsInitialized() != 0) { Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { var op = (IntPtr)fi.GetValue(type); if (op != IntPtr.Zero) { Runtime.XDecref(op); } } Runtime.XDecref(exceptions_module); Runtime.PyObject_HasAttrString(warnings_module, "xx"); Runtime.XDecref(warnings_module); } } /// <summary> /// Set the 'args' slot on a python exception object that wraps /// a CLR exception. This is needed for pickling CLR exceptions as /// BaseException_reduce will only check the slots, bypassing the /// __getattr__ implementation, and thus dereferencing a NULL /// pointer. /// </summary> /// <param name="ob">The python object wrapping </param> internal static void SetArgsAndCause(IntPtr ob) { // e: A CLR Exception Exception e = ExceptionClassObject.ToException(ob); if (e == null) { return; } IntPtr args; if (!string.IsNullOrEmpty(e.Message)) { args = Runtime.PyTuple_New(1); IntPtr msg = Runtime.PyUnicode_FromString(e.Message); Runtime.PyTuple_SetItem(args, 0, msg); } else { args = Runtime.PyTuple_New(0); } Marshal.WriteIntPtr(ob, ExceptionOffset.args, args); #if PYTHON3 if (e.InnerException != null) { IntPtr cause = CLRObject.GetInstHandle(e.InnerException); Marshal.WriteIntPtr(ob, ExceptionOffset.cause, cause); } #endif } /// <summary> /// Shortcut for (pointer == NULL) -&gt; throw PythonException /// </summary> /// <param name="pointer">Pointer to a Python object</param> internal static void ErrorCheck(IntPtr pointer) { if (pointer == IntPtr.Zero) { throw new PythonException(); } } /// <summary> /// Shortcut for (pointer == NULL or ErrorOccurred()) -&gt; throw PythonException /// </summary> internal static void ErrorOccurredCheck(IntPtr pointer) { if (pointer == IntPtr.Zero || ErrorOccurred()) { throw new PythonException(); } } /// <summary> /// ExceptionMatches Method /// </summary> /// <remarks> /// Returns true if the current Python exception matches the given /// Python object. This is a wrapper for PyErr_ExceptionMatches. /// </remarks> public static bool ExceptionMatches(IntPtr ob) { return Runtime.PyErr_ExceptionMatches(ob) != 0; } /// <summary> /// ExceptionMatches Method /// </summary> /// <remarks> /// Returns true if the given Python exception matches the given /// Python object. This is a wrapper for PyErr_GivenExceptionMatches. /// </remarks> public static bool ExceptionMatches(IntPtr exc, IntPtr ob) { int i = Runtime.PyErr_GivenExceptionMatches(exc, ob); return i != 0; } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a native string. /// This is a wrapper for the Python PyErr_SetString call. /// </remarks> public static void SetError(IntPtr ob, string value) { Runtime.PyErr_SetString(ob, value); } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a Python object. /// This is a wrapper for the Python PyErr_SetObject call. /// </remarks> public static void SetError(IntPtr ob, IntPtr value) { Runtime.PyErr_SetObject(ob, value); } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a CLR exception /// object. The CLR exception instance is wrapped as a Python /// object, allowing it to be handled naturally from Python. /// </remarks> public static void SetError(Exception e) { // Because delegates allow arbitrary nesting of Python calling // managed calling Python calling... etc. it is possible that we // might get a managed exception raised that is a wrapper for a // Python exception. In that case we'd rather have the real thing. var pe = e as PythonException; if (pe != null) { Runtime.PyErr_SetObject(pe.PyType, pe.PyValue); return; } IntPtr op = CLRObject.GetInstHandle(e); IntPtr etype = Runtime.PyObject_GetAttrString(op, "__class__"); Runtime.PyErr_SetObject(etype, op); Runtime.XDecref(etype); Runtime.XDecref(op); } /// <summary> /// ErrorOccurred Method /// </summary> /// <remarks> /// Returns true if an exception occurred in the Python runtime. /// This is a wrapper for the Python PyErr_Occurred call. /// </remarks> public static bool ErrorOccurred() { return Runtime.PyErr_Occurred() != 0; } /// <summary> /// Clear Method /// </summary> /// <remarks> /// Clear any exception that has been set in the Python runtime. /// </remarks> public static void Clear() { Runtime.PyErr_Clear(); } //==================================================================== // helper methods for raising warnings //==================================================================== /// <summary> /// Alias for Python's warnings.warn() function. /// </summary> public static void warn(string message, IntPtr exception, int stacklevel) { if (exception == IntPtr.Zero || (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1)) { Exceptions.RaiseTypeError("Invalid exception"); } Runtime.XIncref(warnings_module); IntPtr warn = Runtime.PyObject_GetAttrString(warnings_module, "warn"); Runtime.XDecref(warnings_module); Exceptions.ErrorCheck(warn); IntPtr args = Runtime.PyTuple_New(3); IntPtr msg = Runtime.PyString_FromString(message); Runtime.XIncref(exception); // PyTuple_SetItem steals a reference IntPtr level = Runtime.PyInt_FromInt32(stacklevel); Runtime.PyTuple_SetItem(args, 0, msg); Runtime.PyTuple_SetItem(args, 1, exception); Runtime.PyTuple_SetItem(args, 2, level); IntPtr result = Runtime.PyObject_CallObject(warn, args); Exceptions.ErrorCheck(result); Runtime.XDecref(warn); Runtime.XDecref(result); Runtime.XDecref(args); } public static void warn(string message, IntPtr exception) { warn(message, exception, 1); } public static void deprecation(string message, int stacklevel) { warn(message, Exceptions.DeprecationWarning, stacklevel); } public static void deprecation(string message) { deprecation(message, 1); } //==================================================================== // Internal helper methods for common error handling scenarios. //==================================================================== internal static IntPtr RaiseTypeError(string message) { Exceptions.SetError(Exceptions.TypeError, message); return IntPtr.Zero; } // 2010-11-16: Arranged in python (2.6 & 2.7) source header file order /* Predefined exceptions are puplic static variables on the Exceptions class filled in from the python class using reflection in Initialize() looked up by name, not posistion. */ public static IntPtr BaseException; public static IntPtr Exception; public static IntPtr StopIteration; public static IntPtr GeneratorExit; #if PYTHON2 public static IntPtr StandardError; #endif public static IntPtr ArithmeticError; public static IntPtr LookupError; public static IntPtr AssertionError; public static IntPtr AttributeError; public static IntPtr EOFError; public static IntPtr FloatingPointError; public static IntPtr EnvironmentError; public static IntPtr IOError; public static IntPtr OSError; public static IntPtr ImportError; public static IntPtr IndexError; public static IntPtr KeyError; public static IntPtr KeyboardInterrupt; public static IntPtr MemoryError; public static IntPtr NameError; public static IntPtr OverflowError; public static IntPtr RuntimeError; public static IntPtr NotImplementedError; public static IntPtr SyntaxError; public static IntPtr IndentationError; public static IntPtr TabError; public static IntPtr ReferenceError; public static IntPtr SystemError; public static IntPtr SystemExit; public static IntPtr TypeError; public static IntPtr UnboundLocalError; public static IntPtr UnicodeError; public static IntPtr UnicodeEncodeError; public static IntPtr UnicodeDecodeError; public static IntPtr UnicodeTranslateError; public static IntPtr ValueError; public static IntPtr ZeroDivisionError; //#ifdef MS_WINDOWS //public static IntPtr WindowsError; //#endif //#ifdef __VMS //public static IntPtr VMSError; //#endif //PyAPI_DATA(PyObject *) PyExc_BufferError; //PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst; //PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst; /* Predefined warning categories */ public static IntPtr Warning; public static IntPtr UserWarning; public static IntPtr DeprecationWarning; public static IntPtr PendingDeprecationWarning; public static IntPtr SyntaxWarning; public static IntPtr RuntimeWarning; public static IntPtr FutureWarning; public static IntPtr ImportWarning; public static IntPtr UnicodeWarning; //PyAPI_DATA(PyObject *) PyExc_BytesWarning; } }
// cassandra-sharp - high performance .NET driver for Apache Cassandra // Copyright (c) 2011-2013 Pierre Chalamet // // 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 cqlplus { using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; /// <summary> /// Used to control parsing of command line arguments. /// </summary> [Flags] public enum ArgumentType { /// <summary> /// Indicates that this field is required. An error will be displayed /// if it is not present when parsing arguments. /// </summary> Required = 0x01, /// <summary> /// Only valid in conjunction with Multiple. /// Duplicate values will result in an error. /// </summary> Unique = 0x02, /// <summary> /// Inidicates that the argument may be specified more than once. /// Only valid if the argument is a collection /// </summary> Multiple = 0x04, /// <summary> /// The default type for non-collection arguments. /// The argument is not required, but an error will be reported if it is specified more than once. /// </summary> AtMostOnce = 0x00, /// <summary> /// For non-collection arguments, when the argument is specified more than /// once no error is reported and the value of the argument is the last /// value which occurs in the argument list. /// </summary> LastOccurenceWins = Multiple, /// <summary> /// The default type for collection arguments. /// The argument is permitted to occur multiple times, but duplicate /// values will cause an error to be reported. /// </summary> MultipleUnique = Multiple | Unique, } /// <summary> /// Allows control of command line parsing. /// Attach this attribute to instance fields of types used /// as the destination of command line argument parsing. /// </summary> [AttributeUsage(AttributeTargets.Field)] public class ArgumentAttribute : Attribute { private readonly ArgumentType _type; private object _defaultValue; private string _helpText; private string _longName; private string _shortName; /// <summary> /// Allows control of command line parsing. /// </summary> /// <param name="type"> Specifies the error checking to be done on the argument. </param> public ArgumentAttribute(ArgumentType type) { _type = type; } /// <summary> /// The error checking to be done on the argument. /// </summary> public ArgumentType Type { get { return _type; } } /// <summary> /// Returns true if the argument did not have an explicit short name specified. /// </summary> public bool DefaultShortName { get { return null == _shortName; } } /// <summary> /// The short name of the argument. /// Set to null means use the default short name if it does not /// conflict with any other parameter name. /// Set to String.Empty for no short name. /// This property should not be set for DefaultArgumentAttributes. /// </summary> public string ShortName { get { return _shortName; } set { Debug.Assert(value == null || !(this is DefaultArgumentAttribute)); _shortName = value; } } /// <summary> /// Returns true if the argument did not have an explicit long name specified. /// </summary> public bool DefaultLongName { get { return null == _longName; } } /// <summary> /// The long name of the argument. /// Set to null means use the default long name. /// The long name for every argument must be unique. /// It is an error to specify a long name of String.Empty. /// </summary> public string LongName { get { Debug.Assert(!DefaultLongName); return _longName; } set { Debug.Assert(value != ""); _longName = value; } } /// <summary> /// The default value of the argument. /// </summary> public object DefaultValue { get { return _defaultValue; } set { _defaultValue = value; } } /// <summary> /// Returns true if the argument has a default value. /// </summary> public bool HasDefaultValue { get { return null != _defaultValue; } } /// <summary> /// Returns true if the argument has help text specified. /// </summary> public bool HasHelpText { get { return null != _helpText; } } /// <summary> /// The help text for the argument. /// </summary> public string HelpText { get { return _helpText; } set { _helpText = value; } } } /// <summary> /// Indicates that this argument is the default argument. /// '/' or '-' prefix only the argument value is specified. /// The ShortName property should not be set for DefaultArgumentAttribute /// instances. The LongName property is used for usage text only and /// does not affect the usage of the argument. /// </summary> [AttributeUsage(AttributeTargets.Field)] public class DefaultArgumentAttribute : ArgumentAttribute { /// <summary> /// Indicates that this argument is the default argument. /// </summary> /// <param name="type"> Specifies the error checking to be done on the argument. </param> public DefaultArgumentAttribute(ArgumentType type) : base(type) { } } /// <summary> /// A delegate used in error reporting. /// </summary> public delegate void ErrorReporter(string message); /// <summary> /// Parser for command line arguments. /// The parser specification is infered from the instance fields of the object /// specified as the destination of the parse. /// Valid argument types are: int, uint, string, bool, enums /// Also argument types of Array of the above types are also valid. /// Error checking options can be controlled by adding a ArgumentAttribute /// to the instance fields of the destination object. /// At most one field may be marked with the DefaultArgumentAttribute /// indicating that arguments without a '-' or '/' prefix will be parsed as that argument. /// If not specified then the parser will infer default options for parsing each /// instance field. The default long name of the argument is the field name. The /// default short name is the first character of the long name. Long names and explicitly /// specified short names must be unique. Default short names will be used provided that /// the default short name does not conflict with a long name or an explicitly /// specified short name. /// Arguments which are array types are collection arguments. Collection /// arguments can be specified multiple times. /// </summary> public sealed class CommandLineParser { /// <summary> /// The System Defined new line string. /// </summary> public const string NewLine = "\r\n"; private const int SpaceBeforeParam = 2; private readonly Hashtable _argumentMap; private readonly ArrayList _arguments; private readonly Argument _defaultArgument; private readonly ErrorReporter _reporter; /// <summary> /// Creates a new command line argument parser. /// </summary> /// <param name="argumentSpecification"> The type of object to parse. </param> /// <param name="reporter"> The destination for parse errors. </param> public CommandLineParser(Type argumentSpecification, ErrorReporter reporter) { _reporter = reporter; _arguments = new ArrayList(); _argumentMap = new Hashtable(); foreach (FieldInfo field in argumentSpecification.GetFields()) { if (!field.IsStatic && !field.IsInitOnly && !field.IsLiteral) { ArgumentAttribute attribute = GetAttribute(field); if (attribute is DefaultArgumentAttribute) { Debug.Assert(_defaultArgument == null); _defaultArgument = new Argument(attribute, field, reporter); } else { _arguments.Add(new Argument(attribute, field, reporter)); } } } // add explicit names to map foreach (Argument argument in _arguments) { Debug.Assert(!_argumentMap.ContainsKey(argument.LongName)); _argumentMap[argument.LongName] = argument; if (argument.ExplicitShortName) { if (!string.IsNullOrEmpty(argument.ShortName)) { Debug.Assert(!_argumentMap.ContainsKey(argument.ShortName)); _argumentMap[argument.ShortName] = argument; } else { argument.ClearShortName(); } } } // add implicit names which don't collide to map foreach (Argument argument in _arguments) { if (!argument.ExplicitShortName) { if (!string.IsNullOrEmpty(argument.ShortName) && !_argumentMap.ContainsKey(argument.ShortName)) { _argumentMap[argument.ShortName] = argument; } else { argument.ClearShortName(); } } } } /// <summary> /// Does this parser have a default argument. /// </summary> /// <value> Does this parser have a default argument. </value> public bool HasDefaultArgument { get { return _defaultArgument != null; } } /// <summary> /// Parses Command Line Arguments. Displays usage message to Console.Out /// if /?, /help or invalid arguments are encounterd. /// Errors are output on Console.Error. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="arguments"> The actual arguments. </param> /// <param name="destination"> The resulting parsed arguments. </param> /// <returns> true if no errors were detected. </returns> public static bool ParseArgumentsWithUsage(string[] arguments, object destination) { if (ParseHelp(arguments) || !ParseArguments(arguments, destination)) { // error encountered in arguments. Display usage message Console.Write(ArgumentsUsage(destination.GetType())); return false; } return true; } /// <summary> /// Parses Command Line Arguments. /// Errors are output on Console.Error. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="arguments"> The actual arguments. </param> /// <param name="destination"> The resulting parsed arguments. </param> /// <returns> true if no errors were detected. </returns> public static bool ParseArguments(string[] arguments, object destination) { return ParseArguments(arguments, destination, Console.Error.WriteLine); } /// <summary> /// Parses Command Line Arguments. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="arguments"> The actual arguments. </param> /// <param name="destination"> The resulting parsed arguments. </param> /// <param name="reporter"> The destination for parse errors. </param> /// <returns> true if no errors were detected. </returns> public static bool ParseArguments(string[] arguments, object destination, ErrorReporter reporter) { CommandLineParser parser = new CommandLineParser(destination.GetType(), reporter); return parser.Parse(arguments, destination); } private static void NullErrorReporter(string message) { } /// <summary> /// Checks if a set of arguments asks for help. /// </summary> /// <param name="args"> Args to check for help. </param> /// <returns> Returns true if args contains /? or /help. </returns> public static bool ParseHelp(string[] args) { CommandLineParser helpParser = new CommandLineParser(typeof(HelpArgument), NullErrorReporter); HelpArgument helpArgument = new HelpArgument(); helpParser.Parse(args, helpArgument); return HelpArgument.Help; } /// <summary> /// Returns a Usage string for command line argument parsing. /// Use ArgumentAttributes to control parsing behaviour. /// Formats the output to the width of the current console window. /// </summary> /// <param name="argumentType"> The type of the arguments to display usage for. </param> /// <returns> Printable string containing a user friendly description of command line arguments. </returns> public static string ArgumentsUsage(Type argumentType) { const int screenWidth = 80; return ArgumentsUsage(argumentType, screenWidth); } /// <summary> /// Returns a Usage string for command line argument parsing. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="argumentType"> The type of the arguments to display usage for. </param> /// <param name="columns"> The number of columns to format the output to. </param> /// <returns> Printable string containing a user friendly description of command line arguments. </returns> public static string ArgumentsUsage(Type argumentType, int columns) { return (new CommandLineParser(argumentType, null)).GetUsageString(columns); } /// <summary> /// Searches a StringBuilder for a character /// </summary> /// <param name="text"> The text to search. </param> /// <param name="value"> The character value to search for. </param> /// <param name="startIndex"> The index to stat searching at. </param> /// <returns> The index of the first occurence of value or -1 if it is not found. </returns> public static int IndexOf(StringBuilder text, char value, int startIndex) { for (int index = startIndex; index < text.Length; index++) { if (text[index] == value) { return index; } } return -1; } /// <summary> /// Searches a StringBuilder for a character in reverse /// </summary> /// <param name="text"> The text to search. </param> /// <param name="value"> The character to search for. </param> /// <param name="startIndex"> The index to start the search at. </param> /// <returns>The index of the last occurence of value in text or -1 if it is not found. </returns> public static int LastIndexOf(StringBuilder text, char value, int startIndex) { for (int index = Math.Min(startIndex, text.Length - 1); index >= 0; index --) { if (text[index] == value) { return index; } } return -1; } private static ArgumentAttribute GetAttribute(FieldInfo field) { object[] attributes = field.GetCustomAttributes(typeof(ArgumentAttribute), false); if (attributes.Length == 1) { return (ArgumentAttribute) attributes[0]; } Debug.Assert(attributes.Length == 0); return null; } private void ReportUnrecognizedArgument(string argument) { _reporter(string.Format("Unrecognized command line argument '{0}'", argument)); } /// <summary> /// Parses an argument list into an object /// </summary> /// <param name="args"></param> /// <param name="destination"></param> /// <returns> true if an error occurred </returns> private bool ParseArgumentList(string[] args, object destination) { bool hadError = false; if (args != null) { foreach (string argument in args) { if (argument.Length > 0) { switch (argument[0]) { case '-': case '/': int endIndex = argument.IndexOfAny(new[] {':', '+', '-'}, 1); string option = argument.Substring(1, endIndex == -1 ? argument.Length - 1 : endIndex - 1); string optionArgument; if (option.Length + 1 == argument.Length) { optionArgument = null; } else if (argument.Length > 1 + option.Length && argument[1 + option.Length] == ':') { optionArgument = argument.Substring(option.Length + 2); } else { optionArgument = argument.Substring(option.Length + 1); } Argument arg = (Argument) _argumentMap[option]; if (arg == null) { ReportUnrecognizedArgument(argument); hadError = true; } else { hadError |= !arg.SetValue(optionArgument, destination); } break; case '@': string[] nestedArguments; hadError |= LexFileArguments(argument.Substring(1), out nestedArguments); hadError |= ParseArgumentList(nestedArguments, destination); break; default: if (_defaultArgument != null) { hadError |= !_defaultArgument.SetValue(argument, destination); } else { ReportUnrecognizedArgument(argument); hadError = true; } break; } } } } return hadError; } /// <summary> /// Parses an argument list. /// </summary> /// <param name="args"> The arguments to parse. </param> /// <param name="destination"> The destination of the parsed arguments. </param> /// <returns> true if no parse errors were encountered. </returns> public bool Parse(string[] args, object destination) { bool hadError = ParseArgumentList(args, destination); // check for missing required arguments foreach (Argument arg in _arguments) { hadError |= arg.Finish(destination); } if (_defaultArgument != null) { hadError |= _defaultArgument.Finish(destination); } return !hadError; } /// <summary> /// A user firendly usage string describing the command line argument syntax. /// </summary> public string GetUsageString(int screenWidth) { ArgumentHelpStrings[] strings = GetAllHelpStrings(); int maxParamLen = 0; foreach (ArgumentHelpStrings helpString in strings) { maxParamLen = Math.Max(maxParamLen, helpString.Syntax.Length); } const int minimumNumberOfCharsForHelpText = 10; const int minimumHelpTextColumn = 5; const int minimumScreenWidth = minimumHelpTextColumn + minimumNumberOfCharsForHelpText; int helpTextColumn; int idealMinimumHelpTextColumn = maxParamLen + SpaceBeforeParam; screenWidth = Math.Max(screenWidth, minimumScreenWidth); if (screenWidth < (idealMinimumHelpTextColumn + minimumNumberOfCharsForHelpText)) { helpTextColumn = minimumHelpTextColumn; } else { helpTextColumn = idealMinimumHelpTextColumn; } const string newLine = "\n"; StringBuilder builder = new StringBuilder(); foreach (ArgumentHelpStrings helpStrings in strings) { // add syntax string int syntaxLength = helpStrings.Syntax.Length; builder.Append(helpStrings.Syntax); // start help text on new line if syntax string is too long int currentColumn = syntaxLength; if (syntaxLength >= helpTextColumn) { builder.Append(newLine); currentColumn = 0; } // add help text broken on spaces int charsPerLine = screenWidth - helpTextColumn; int index = 0; while (index < helpStrings.Help.Length) { // tab to start column builder.Append(' ', helpTextColumn - currentColumn); currentColumn = helpTextColumn; // find number of chars to display on this line int endIndex = index + charsPerLine; if (endIndex >= helpStrings.Help.Length) { // rest of text fits on this line endIndex = helpStrings.Help.Length; } else { endIndex = helpStrings.Help.LastIndexOf(' ', endIndex - 1, Math.Min(endIndex - index, charsPerLine)); if (endIndex <= index) { // no spaces on this line, append full set of chars endIndex = index + charsPerLine; } } // add chars builder.Append(helpStrings.Help, index, endIndex - index); index = endIndex; // do new line AddNewLine(newLine, builder, ref currentColumn); // don't start a new line with spaces while (index < helpStrings.Help.Length && helpStrings.Help[index] == ' ') { index ++; } } // add newline if there's no help text if (helpStrings.Help.Length == 0) { builder.Append(newLine); } } return builder.ToString(); } private static void AddNewLine(string newLine, StringBuilder builder, ref int currentColumn) { builder.Append(newLine); currentColumn = 0; } private ArgumentHelpStrings[] GetAllHelpStrings() { ArgumentHelpStrings[] strings = new ArgumentHelpStrings[NumberOfParametersToDisplay()]; int index = 0; foreach (Argument arg in _arguments) { strings[index] = GetHelpStrings(arg); index++; } strings[index++] = new ArgumentHelpStrings("@<file>", "Read response file for more options"); if (_defaultArgument != null) { strings[index++] = GetHelpStrings(_defaultArgument); } return strings; } private static ArgumentHelpStrings GetHelpStrings(Argument arg) { return new ArgumentHelpStrings(arg.SyntaxHelp, arg.FullHelpText); } private int NumberOfParametersToDisplay() { int numberOfParameters = _arguments.Count + 1; if (HasDefaultArgument) { numberOfParameters += 1; } return numberOfParameters; } private bool LexFileArguments(string fileName, out string[] arguments) { string args; try { using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) args = (new StreamReader(file)).ReadToEnd(); } catch (Exception e) { _reporter(string.Format("Error: Can't open command line argument file '{0}' : '{1}'", fileName, e.Message)); arguments = null; return false; } bool hadError = false; ArrayList argArray = new ArrayList(); StringBuilder currentArg = new StringBuilder(); bool inQuotes = false; int index = 0; // while (index < args.Length) try { while (true) { // skip whitespace while (char.IsWhiteSpace(args[index])) { index += 1; } // # - comment to end of line if (args[index] == '#') { index += 1; while (args[index] != '\n') { index += 1; } continue; } // do one argument do { if (args[index] == '\\') { int cSlashes = 1; index += 1; while (index == args.Length && args[index] == '\\') { cSlashes += 1; } if (index == args.Length || args[index] != '"') { currentArg.Append('\\', cSlashes); } else { currentArg.Append('\\', (cSlashes >> 1)); if (0 != (cSlashes & 1)) { currentArg.Append('"'); } else { inQuotes = !inQuotes; } } } else if (args[index] == '"') { inQuotes = !inQuotes; index += 1; } else { currentArg.Append(args[index]); index += 1; } } while (!char.IsWhiteSpace(args[index]) || inQuotes); argArray.Add(currentArg.ToString()); currentArg.Length = 0; } } catch (IndexOutOfRangeException) { // got EOF if (inQuotes) { _reporter(string.Format("Error: Unbalanced '\"' in command line argument file '{0}'", fileName)); hadError = true; } else if (currentArg.Length > 0) { // valid argument can be terminated by EOF argArray.Add(currentArg.ToString()); } } arguments = (string[]) argArray.ToArray(typeof(string)); return hadError; } private static string LongName(ArgumentAttribute attribute, FieldInfo field) { return (attribute == null || attribute.DefaultLongName) ? field.Name : attribute.LongName; } private static string ShortName(ArgumentAttribute attribute, FieldInfo field) { if (attribute is DefaultArgumentAttribute) { return null; } if (!ExplicitShortName(attribute)) { return LongName(attribute, field).Substring(0, 1); } return attribute.ShortName; } private static string HelpText(ArgumentAttribute attribute, FieldInfo field) { if (attribute == null) { return null; } return attribute.HelpText; } private static bool HasHelpText(ArgumentAttribute attribute) { return (attribute != null && attribute.HasHelpText); } private static bool ExplicitShortName(ArgumentAttribute attribute) { return (attribute != null && !attribute.DefaultShortName); } private static object DefaultValue(ArgumentAttribute attribute, FieldInfo field) { return (attribute == null || !attribute.HasDefaultValue) ? null : attribute.DefaultValue; } private static Type ElementType(FieldInfo field) { if (IsCollectionType(field.FieldType)) { return field.FieldType.GetElementType(); } return null; } private static ArgumentType Flags(ArgumentAttribute attribute, FieldInfo field) { if (attribute != null) { return attribute.Type; } if (IsCollectionType(field.FieldType)) { return ArgumentType.MultipleUnique; } return ArgumentType.AtMostOnce; } private static bool IsCollectionType(Type type) { return type.IsArray; } private static bool IsValidElementType(Type type) { return type != null && ( type == typeof(int) || type == typeof(uint) || type == typeof(string) || type == typeof(bool) || type.IsEnum); } [DebuggerDisplay("Name = {LongName}")] private class Argument { private readonly ArrayList _collectionValues; private readonly object _defaultValue; private readonly Type _elementType; private readonly bool _explicitShortName; private readonly FieldInfo _field; private readonly ArgumentType _flags; private readonly bool _hasHelpText; private readonly string _helpText; private readonly bool _isDefault; private readonly string _longName; private readonly ErrorReporter _reporter; private bool _seenValue; private string _shortName; public Argument(ArgumentAttribute attribute, FieldInfo field, ErrorReporter reporter) { _longName = CommandLineParser.LongName(attribute, field); _explicitShortName = CommandLineParser.ExplicitShortName(attribute); _shortName = CommandLineParser.ShortName(attribute, field); _hasHelpText = CommandLineParser.HasHelpText(attribute); _helpText = CommandLineParser.HelpText(attribute, field); _defaultValue = CommandLineParser.DefaultValue(attribute, field); _elementType = ElementType(field); _flags = Flags(attribute, field); _field = field; _seenValue = false; _reporter = reporter; _isDefault = attribute is DefaultArgumentAttribute; if (IsCollection) { _collectionValues = new ArrayList(); } Debug.Assert(!string.IsNullOrEmpty(_longName)); Debug.Assert(!_isDefault || !ExplicitShortName); Debug.Assert(!IsCollection || AllowMultiple, "Collection arguments must have allow multiple"); Debug.Assert(!Unique || IsCollection, "Unique only applicable to collection arguments"); Debug.Assert(IsValidElementType(Type) || IsCollectionType(Type)); Debug.Assert((IsCollection && IsValidElementType(_elementType)) || (!IsCollection && _elementType == null)); Debug.Assert(!(IsRequired && HasDefaultValue), "Required arguments cannot have default value"); Debug.Assert(!HasDefaultValue || (_defaultValue.GetType() == field.FieldType), "Type of default value must match field type"); } public Type ValueType { get { return IsCollection ? _elementType : Type; } } public string LongName { get { return _longName; } } public bool ExplicitShortName { get { return _explicitShortName; } } public string ShortName { get { return _shortName; } } public bool HasShortName { get { return _shortName != null; } } public bool HasHelpText { get { return _hasHelpText; } } public string HelpText { get { return _helpText; } } public object DefaultValue { get { return _defaultValue; } } public bool HasDefaultValue { get { return null != _defaultValue; } } public string FullHelpText { get { StringBuilder builder = new StringBuilder(); if (HasHelpText) { builder.Append(HelpText); } if (HasDefaultValue) { if (builder.Length > 0) { builder.Append(" "); } builder.Append("Default value:'"); AppendValue(builder, DefaultValue); builder.Append('\''); } if (HasShortName) { if (builder.Length > 0) { builder.Append(" "); } builder.Append("(short form /"); builder.Append(ShortName); builder.Append(")"); } return builder.ToString(); } } public string SyntaxHelp { get { StringBuilder builder = new StringBuilder(); if (IsDefault) { builder.Append("<"); builder.Append(LongName); builder.Append(">"); } else { builder.Append("/"); builder.Append(LongName); Type valueType = ValueType; if (valueType == typeof(int)) { builder.Append(":<int>"); } else if (valueType == typeof(uint)) { builder.Append(":<uint>"); } else if (valueType == typeof(bool)) { builder.Append("[+|-]"); } else if (valueType == typeof(string)) { builder.Append(":<string>"); } else { Debug.Assert(valueType.IsEnum); builder.Append(":{"); bool first = true; foreach (FieldInfo field in valueType.GetFields()) { if (field.IsStatic) { if (first) { first = false; } else { builder.Append('|'); } builder.Append(field.Name); } } builder.Append('}'); } } return builder.ToString(); } } public bool IsRequired { get { return 0 != (_flags & ArgumentType.Required); } } public bool SeenValue { get { return _seenValue; } } public bool AllowMultiple { get { return 0 != (_flags & ArgumentType.Multiple); } } public bool Unique { get { return 0 != (_flags & ArgumentType.Unique); } } public Type Type { get { return _field.FieldType; } } public bool IsCollection { get { return IsCollectionType(Type); } } public bool IsDefault { get { return _isDefault; } } public bool Finish(object destination) { if (SeenValue) { if (IsCollection) { _field.SetValue(destination, _collectionValues.ToArray(_elementType)); } } else { if (HasDefaultValue) { _field.SetValue(destination, DefaultValue); } } return ReportMissingRequiredArgument(); } private bool ReportMissingRequiredArgument() { if (IsRequired && !SeenValue) { if (IsDefault) { _reporter(string.Format("Missing required argument '<{0}>'.", LongName)); } else { _reporter(string.Format("Missing required argument '/{0}'.", LongName)); } return true; } return false; } private void ReportDuplicateArgumentValue(string value) { _reporter(string.Format("Duplicate '{0}' argument '{1}'", LongName, value)); } public bool SetValue(string value, object destination) { if (SeenValue && !AllowMultiple) { _reporter(string.Format("Duplicate '{0}' argument", LongName)); return false; } _seenValue = true; object newValue; if (!ParseValue(ValueType, value, out newValue)) { return false; } if (IsCollection) { if (Unique && _collectionValues.Contains(newValue)) { ReportDuplicateArgumentValue(value); return false; } else { _collectionValues.Add(newValue); } } else { _field.SetValue(destination, newValue); } return true; } private void ReportBadArgumentValue(string value) { _reporter(string.Format("'{0}' is not a valid value for the '{1}' command line option", value, LongName)); } private bool ParseValue(Type type, string stringData, out object value) { // null is only valid for bool variables // empty string is never valid if ((stringData != null || type == typeof(bool)) && (stringData == null || stringData.Length > 0)) { try { if (type == typeof(string)) { value = stringData; return true; } else if (type == typeof(bool)) { if (stringData == null || stringData == "+") { value = true; return true; } else if (stringData == "-") { value = false; return true; } } else if (type == typeof(int)) { value = int.Parse(stringData); return true; } else if (type == typeof(uint)) { value = int.Parse(stringData); return true; } else { Debug.Assert(type.IsEnum); bool valid = false; foreach (string name in Enum.GetNames(type)) { if (name == stringData) { valid = true; break; } } if (valid) { value = Enum.Parse(type, stringData, true); return true; } } } catch { // catch parse errors } } ReportBadArgumentValue(stringData); value = null; return false; } private void AppendValue(StringBuilder builder, object value) { if (value is string || value is int || value is uint || value.GetType().IsEnum) { builder.Append(value); } else if (value is bool) { builder.Append((bool) value ? "+" : "-"); } else { bool first = true; foreach (object o in (Array) value) { if (!first) { builder.Append(", "); } AppendValue(builder, o); first = false; } } } public void ClearShortName() { _shortName = null; } } private struct ArgumentHelpStrings { public readonly string Help; public readonly string Syntax; public ArgumentHelpStrings(string syntax, string help) { Syntax = syntax; Help = help; } } private class HelpArgument { [Argument(ArgumentType.AtMostOnce, ShortName = "?")] public const bool Help = false; } } }
// // GroupSelector.cs // // Author: // Larry Ewing <[email protected]> // Ruben Vermeersch <[email protected]> // // Copyright (C) 2004-2010 Novell, Inc. // Copyright (C) 2004-2007 Larry Ewing // Copyright (C) 2010 Ruben Vermeersch // // 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 Mono.Unix; using Gtk; using Gdk; using GLib; using FSpot.Core; using FSpot.Utils; using FSpot.Widgets; namespace FSpot { public class GroupSelector : Fixed { internal static GType groupSelectorGType; int border = 6; int box_spacing = 2; int box_top_padding = 6; public static int MIN_BOX_WIDTH = 20; private Glass glass; private Limit min_limit; private Limit max_limit; private Gtk.Button left; private Gtk.Button right; private DelayedOperation left_delay; private DelayedOperation right_delay; private Gdk.Window event_window; public Gdk.Rectangle background; public Gdk.Rectangle legend; public Gdk.Rectangle action; Pango.Layout [] tick_layouts; int [] box_counts = new int [0]; int box_count_max; int min_filled; int max_filled; bool has_limits; protected FSpot.GroupAdaptor adaptor; public FSpot.GroupAdaptor Adaptor { set { if (adaptor != null) { adaptor.Changed -= HandleAdaptorChanged; adaptor.Dispose (); } adaptor = value; HandleAdaptorChanged (adaptor); has_limits = adaptor is FSpot.ILimitable; if (has_limits) { min_limit.SetPosition (0, false); max_limit.SetPosition (adaptor.Count () - 1, false); } if (adaptor is TimeAdaptor) { left.TooltipText = Catalog.GetString ("More dates"); right.TooltipText = Catalog.GetString ("More dates"); } else { left.TooltipText = Catalog.GetString ("More"); right.TooltipText = Catalog.GetString ("More"); } adaptor.Changed += HandleAdaptorChanged; } get { return adaptor; } } public bool GlassUpdating { get { return glass.GlassUpdating; } set { glass.GlassUpdating = value; } } public int GlassPosition { get { return glass.Position; } } private void HandleAdaptorChanged (GroupAdaptor adaptor) { bool size_changed = box_counts.Length != adaptor.Count (); int [] box_values = new int [adaptor.Count ()]; if (tick_layouts != null) { foreach (Pango.Layout l in tick_layouts) { if (l != null) l.Dispose (); } } tick_layouts = new Pango.Layout [adaptor.Count ()]; int i = 0; while (i < adaptor.Count ()) { box_values [i] = adaptor.Value (i); string label = adaptor.TickLabel (i); if (label != null) { tick_layouts [i] = CreatePangoLayout (label); } i++; } if (glass.Position >= adaptor.Count()) glass.SetPosition (adaptor.Count() - 1); Counts = box_values; if (has_limits && size_changed) { min_limit.SetPosition (0, false); max_limit.SetPosition (adaptor.Count () - 1, false); } for (i = min_limit.Position; i < box_counts.Length; i++) if (box_counts [i] > 0) break; SetPosition (i < box_counts.Length ? i : min_limit.Position); ScrollTo (min_limit.Position); this.QueueDraw (); } private int [] Counts { set { bool min_found = false; box_count_max = 0; min_filled = 0; max_filled = 0; if (value != null) box_counts = value; else value = new int [0]; for (int i = 0; i < box_counts.Length; i++){ int count = box_counts [i]; box_count_max = Math.Max (count, box_count_max); if (count > 0) { if (!min_found) { min_filled = i; min_found = true; } max_filled = i; } } } } public enum RangeType { All, Fixed, Min } private RangeType mode = RangeType.Min; public RangeType Mode { get { return mode; } set { mode = value; if (Visible) GdkWindow.InvalidateRect (Allocation, false); } } private void ScrollTo (int position) { if (position == min_filled) position = 0; else if (position == max_filled) position = box_counts.Length - 1; Gdk.Rectangle box = new Box (this, position).Bounds; // Only scroll to position if we are not dragging if (!glass.Dragging) { if (box.Right > background.Right) Offset -= box.X + box.Width - (background.X + background.Width); else if (box.X < background.X) Offset += background.X - box.X; } } private int scroll_offset; public int Offset { get { return scroll_offset; } set { scroll_offset = value; int total_width = (int)(box_counts.Length * BoxWidth); if (total_width + scroll_offset < background.Width) scroll_offset = background.Width - total_width; if (total_width <= background.Width) scroll_offset = 0; UpdateButtons (); if (Visible) GdkWindow.InvalidateRect (Allocation, false); } } private void UpdateButtons () { left.Sensitive = (scroll_offset < 0); right.Sensitive = (box_counts.Length * BoxWidth > background.Width - scroll_offset); if (!left.Sensitive && left_delay.IsPending) left_delay.Stop (); if (!right.Sensitive && right_delay.IsPending) right_delay.Stop (); } private void BoxXHitFilled (double x, out int out_position) { x -= BoxX (0); double position = (x / BoxWidth); position = System.Math.Max (0, position); position = System.Math.Min (position, box_counts.Length - 1); if (box_counts [(int)position] > 0) { out_position = (int)position; } else { int upper = (int)position; while (upper < box_counts.Length && box_counts [upper] == 0) upper++; int lower = (int)position; while (lower >= 0 && box_counts [lower] == 0) lower--; if (lower == -1 && upper == box_counts.Length) { out_position = (int)position; } else if (lower == -1 && upper < box_counts.Length) { out_position = upper; } else if (upper == box_counts.Length && lower > -1){ out_position = lower; } else if (upper + 1 - position > position - lower) { out_position = lower; } else { out_position = upper; } } } private bool BoxXHit (double x, out int position) { x -= BoxX (0); position = (int) (x / BoxWidth); if (position < 0) { position = 0; return false; } else if (position >= box_counts.Length) { position = box_counts.Length -1; return false; } return true; } private bool BoxHit (double x, double y, out int position) { if (BoxXHit (x, out position)) { Box box = new Box (this, position); if (box.Bounds.Contains ((int) x, (int) y)) return true; position++; } return false; } public void SetPosition (int group) { if (!glass.Dragging) glass.SetPosition(group); } protected override bool OnButtonPressEvent (Gdk.EventButton args) { if (args.Button == 3) return DrawOrderMenu (args); double x = args.X + action.X; double y = args.Y + action.Y; if (glass.Contains (x, y)) { glass.StartDrag (x, y, args.Time); } else if (has_limits && min_limit.Contains (x, y)) { min_limit.StartDrag (x, y, args.Time); } else if (has_limits && max_limit.Contains (x, y)) { max_limit.StartDrag (x, y, args.Time); } else { int position; if (BoxHit (x, y, out position)) { BoxXHitFilled (x, out position); glass.UpdateGlass = true; glass.SetPosition (position); glass.UpdateGlass = false; return true; } } return base.OnButtonPressEvent (args); } protected override bool OnButtonReleaseEvent (Gdk.EventButton args) { double x = args.X + action.X; double y = args.Y + action.Y; if (glass.Dragging) { glass.EndDrag (x, y); } else if (min_limit.Dragging) { min_limit.EndDrag (x, y); } else if (max_limit.Dragging) { max_limit.EndDrag (x, y); } return base.OnButtonReleaseEvent (args); } public void UpdateLimits () { if (adaptor != null && has_limits && min_limit != null && max_limit != null) ((ILimitable)adaptor).SetLimits (min_limit.Position, max_limit.Position); } protected override bool OnMotionNotifyEvent (Gdk.EventMotion args) { double x = args.X + action.X; double y = args.Y + action.Y; //Rectangle box = glass.Bounds (); //Console.WriteLine ("please {0} and {1} in box {2}", x, y, box); if (glass == null) return base.OnMotionNotifyEvent (args); if (glass.Dragging) { glass.UpdateDrag (x, y); } else if (min_limit.Dragging) { min_limit.UpdateDrag (x, y); } else if (max_limit.Dragging) { max_limit.UpdateDrag (x, y); } else { glass.State = glass.Contains (x, y) ? StateType.Prelight : StateType.Normal; min_limit.State = min_limit.Contains (x, y) ? StateType.Prelight : StateType.Normal; max_limit.State = max_limit.Contains (x, y) ? StateType.Prelight : StateType.Normal; } return base.OnMotionNotifyEvent (args); } protected override void OnRealized () { SetFlag (WidgetFlags.Realized); GdkWindow = ParentWindow; base.OnRealized (); WindowAttr attr = WindowAttr.Zero; attr.WindowType = Gdk.WindowType.Child; attr.X = action.X; attr.Y = action.Y; attr.Width = action.Width; attr.Height = action.Height; attr.Wclass = WindowClass.InputOnly; attr.EventMask = (int) Events; attr.EventMask |= (int) (EventMask.ButtonPressMask | EventMask.KeyPressMask | EventMask.KeyReleaseMask | EventMask.ButtonReleaseMask | EventMask.PointerMotionMask); event_window = new Gdk.Window (GdkWindow, attr, (int) (WindowAttributesType.X | WindowAttributesType.Y)); event_window.UserData = this.Handle; } protected override void OnUnrealized () { event_window.Dispose (); event_window = null; base.OnUnrealized (); } private Double BoxWidth { get { switch (mode) { case RangeType.All: return Math.Max (1.0, background.Width / (double) box_counts.Length); case RangeType.Fixed: return background.Width / (double) 12; case RangeType.Min: return Math.Max (MIN_BOX_WIDTH, background.Width / (double) box_counts.Length); default: return (double) MIN_BOX_WIDTH; } } } private int BoxX (int item) { return scroll_offset + background.X + (int) Math.Round (BoxWidth * item); } private struct Box { Gdk.Rectangle bounds; Gdk.Rectangle bar; public Box (GroupSelector selector, int item) { bounds.Height = selector.background.Height; bounds.Y = selector.background.Y; bounds.X = selector.BoxX (item); bounds.Width = Math.Max (selector.BoxX (item + 1) - bounds.X, 1); if (item < 0 || item > selector.box_counts.Length - 1) return; double percent = selector.box_counts [item] / (double) Math.Max (selector.box_count_max, 1); bar = bounds; bar.Height = (int) Math.Ceiling ((bounds.Height - selector.box_top_padding) * percent); bar.Y += bounds.Height - bar.Height - 1; bar.Inflate (- selector.box_spacing, 0); } public Gdk.Rectangle Bounds { get { return bounds; } } public Gdk.Rectangle Bar { get { return bar; } } } private void DrawBox (Rectangle area, int item) { Box box = new Box (this, item); Rectangle bar = box.Bar; if (bar.Intersect (area, out area)) { if (item < min_limit.Position || item > max_limit.Position) { GdkWindow.DrawRectangle (Style.BackgroundGC (StateType.Active), true, area); } else { GdkWindow.DrawRectangle (Style.BaseGC (StateType.Selected), true, area); } } } public Rectangle TickBounds (int item) { Rectangle bounds = Rectangle.Zero; bounds.X = BoxX (item); bounds.Y = legend.Y + 3; bounds.Width = 1; bounds.Height = 6; return bounds; } public void DrawTick (Rectangle area, int item) { Rectangle tick = TickBounds (item); Pango.Layout layout = null; if (item < tick_layouts.Length) { layout = tick_layouts [item]; if (layout != null) { int width, height; layout.GetPixelSize (out width, out height); Style.PaintLayout (Style, GdkWindow, State, true, area, this, "GroupSelector:Tick", tick.X + 3, tick.Y + tick.Height, layout); } } if (layout == null) tick.Height /= 2; if (tick.Intersect (area, out area)) { GdkWindow.DrawRectangle (Style.ForegroundGC (State), true, area); } } protected override bool OnPopupMenu () { DrawOrderMenu (null); return true; } private bool DrawOrderMenu (Gdk.EventButton args) { Gtk.Menu order_menu = new Gtk.Menu(); order_menu.Append (App.Instance.Organizer.ReverseOrderAction.CreateMenuItem ()); GtkUtil.MakeMenuItem (order_menu, Catalog.GetString ("_Clear Date Range"), App.Instance.Organizer.HandleClearDateRange); if (args != null) order_menu.Popup (null, null, null, args.Button, args.Time); else order_menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime); return true; } public abstract class Manipulator { protected GroupSelector selector; protected DelayedOperation timer; public bool Dragging; public bool UpdateGlass; public bool GlassUpdating; public Point DragStart; public Manipulator (GroupSelector selector) { this.selector = selector; timer = new DelayedOperation (50, new GLib.IdleHandler (DragTimeout)); } protected int drag_offset; public int DragOffset { set { Rectangle then = Bounds (); drag_offset = value; Rectangle now = Bounds (); if (selector.Visible) { selector.GdkWindow.InvalidateRect (then, false); selector.GdkWindow.InvalidateRect (now, false); } } get { if (Dragging) return drag_offset; else return 0; } } public virtual void StartDrag (double x, double y, uint time) { State = StateType.Active; //timer.Start (); Dragging = true; DragStart.X = (int)x; DragStart.Y = (int)y; } private bool DragTimeout () { int x, y; selector.GetPointer (out x, out y); x += selector.Allocation.X; y += selector.Allocation.Y; UpdateDrag ((double) x, (double) y); return true; } protected bool PositionValid (int position) { if (position < 0 || position > selector.box_counts.Length - 1) return false; return true; } public virtual void UpdateDrag (double x, double y) { Rectangle bounds = Bounds (); double drag_lower_limit = (selector.background.Left) - (bounds.Width/2); double drag_upper_limit = (selector.background.Right) - (bounds.Width/2); double calX = DragStart.X + (x - DragStart.X); if (calX >= drag_lower_limit && calX <= drag_upper_limit) { if (selector.right_delay.IsPending) selector.right_delay.Stop(); if (selector.left_delay.IsPending) selector.left_delay.Stop(); DragOffset = (int)x - DragStart.X; } else if (calX >= drag_upper_limit && selector.right.Sensitive && !selector.right_delay.IsPending) { // Ensure selector is at the limit if (bounds.Left != drag_upper_limit) DragOffset = (int)drag_upper_limit - DragStart.X; selector.Offset -= 10; selector.right_delay.Start(); } else if (calX <= drag_lower_limit && selector.left.Sensitive && !selector.left_delay.IsPending) { // Ensure selector is at the limit if (bounds.Left != drag_lower_limit) DragOffset = (int)drag_lower_limit - DragStart.X; selector.Offset += 10; selector.left_delay.Start(); } } public virtual void EndDrag (double x, double y) { timer.Stop (); Rectangle box = Bounds (); double middle = box.X + (box.Width / 2.0); int position; DragOffset = 0; Dragging = false; if (selector.BoxXHit (middle, out position)) { this.SetPosition (position); State = StateType.Prelight; } else { State = selector.State; } } private StateType state; public StateType State { get { return state; } set { if (state != value) { selector.GdkWindow.InvalidateRect (Bounds (), false); } state = value; } } public void SetPosition (int position) { SetPosition (position, true); } public void SetPosition (int position, bool update) { if (! PositionValid (position)) return; Rectangle then = Bounds (); this.position = position; Rectangle now = Bounds (); if (selector.Visible) { then = now.Union (then); selector.GdkWindow.InvalidateRect (then, false); //selector.GdkWindow.InvalidateRect (now, false); } if (update) PositionChanged (); } private int position; public int Position { get { return position; } } public abstract void Draw (Rectangle area); public abstract void PositionChanged (); public abstract Rectangle Bounds (); public virtual bool Contains (double x, double y) { return Bounds ().Contains ((int)x, (int)y); } } private class Glass : Manipulator { Gtk.Window popup_window; Gtk.Label popup_label; int drag_position; public Glass (GroupSelector selector) : base (selector) { popup_window = new ToolTipWindow (); popup_label = new Gtk.Label (String.Empty); popup_label.Show (); popup_window.Add (popup_label); } public int handle_height = 15; private int border { get { return selector.box_spacing * 2; } } private void UpdatePopupPosition () { int x = 0, y = 0; Rectangle bounds = Bounds (); Requisition requisition = popup_window.SizeRequest (); popup_window.Resize (requisition.Width, requisition.Height); selector.GdkWindow.GetOrigin (out x, out y); x += bounds.X + (bounds.Width - requisition.Width) / 2; y += bounds.Y - requisition.Height; x = Math.Max (x, 0); x = Math.Min (x, selector.Screen.Width - requisition.Width); popup_window.Move (x, y); } public void MaintainPosition() { Rectangle box = Bounds (); double middle = box.X + (box.Width / 2.0); int current_position; if (selector.BoxXHit (middle, out current_position)) { if (current_position != drag_position) popup_label.Text = selector.Adaptor.GlassLabel (current_position); drag_position = current_position; } UpdatePopupPosition (); selector.ScrollTo (drag_position); } public override void StartDrag (double x, double y, uint time) { if (!PositionValid (Position)) return; base.StartDrag (x, y, time); popup_label.Text = selector.Adaptor.GlassLabel (this.Position); popup_window.Show (); UpdatePopupPosition (); drag_position = this.Position; } public override void UpdateDrag (double x, double y) { base.UpdateDrag (x, y); MaintainPosition(); } public override void EndDrag (double x, double y) { timer.Stop (); Rectangle box = Bounds (); double middle = box.X + (box.Width / 2.0); int position; DragOffset = 0; Dragging = false; selector.BoxXHitFilled (middle, out position); UpdateGlass = true; this.SetPosition (position); UpdateGlass = false; State = StateType.Prelight; popup_window.Hide (); } private Rectangle InnerBounds () { Rectangle box = new Box (selector, Position).Bounds; if (Dragging) { box.X = DragStart.X + DragOffset; } else { box.X += DragOffset; } return box; } public override Rectangle Bounds () { Rectangle box = InnerBounds (); box.Inflate (border, border); box.Height += handle_height; return box; } public override void Draw (Rectangle area) { if (! PositionValid (Position)) return; Rectangle inner = InnerBounds (); Rectangle bounds = Bounds (); if (! bounds.Intersect (area, out area)) return; int i = 0; Rectangle box = inner; box.Width -= 1; box.Height -= 1; while (i < border) { box.Inflate (1, 1); selector.Style.BackgroundGC (State).ClipRectangle = area; selector.GdkWindow.DrawRectangle (selector.Style.BackgroundGC (State), false, box); i++; } Style.PaintFlatBox (selector.Style, selector.GdkWindow, State, ShadowType.In, area, selector, "glass", bounds.X, inner.Y + inner.Height + border, bounds.Width, handle_height); Style.PaintHandle (selector.Style, selector.GdkWindow, State, ShadowType.In, area, selector, "glass", bounds.X, inner.Y + inner.Height + border, bounds.Width, handle_height, Orientation.Horizontal); Style.PaintShadow (selector.Style, selector.GdkWindow, State, ShadowType.Out, area, selector, null, bounds.X, bounds.Y, bounds.Width, bounds.Height); Style.PaintShadow (selector.Style, selector.GdkWindow, State, ShadowType.In, area, selector, null, inner.X, inner.Y, inner.Width, inner.Height); } public override void PositionChanged () { GlassUpdating = true; if (Dragging || UpdateGlass) selector.adaptor.SetGlass (Position); selector.ScrollTo (Position); GlassUpdating = false; } } public class Limit : Manipulator { int width = 10; int handle_height = 10; public enum LimitType { Min, Max } private LimitType limit_type; public override Rectangle Bounds () { int limit_offset = limit_type == LimitType.Max ? 1 : 0; Rectangle bounds = new Rectangle (0, 0, width, selector.background.Height + handle_height); if (Dragging) { bounds.X = DragStart.X + DragOffset; } else { bounds.X = DragOffset + selector.BoxX (Position + limit_offset) - bounds.Width /2; } bounds.Y = selector.background.Y - handle_height/2; return bounds; } public override void Draw (Rectangle area) { Rectangle bounds = Bounds (); Rectangle top = new Rectangle (bounds.X, bounds.Y, bounds.Width, handle_height); Rectangle bottom = new Rectangle (bounds.X, bounds.Y + bounds.Height - handle_height, bounds.Width, handle_height); Style.PaintBox (selector.Style, selector.GdkWindow, State, ShadowType.Out, area, selector, null, top.X, top.Y, top.Width, top.Height); Style.PaintBox (selector.Style, selector.GdkWindow, State, ShadowType.Out, area, selector, null, bottom.X, bottom.Y, bottom.Width, bottom.Height); } public Limit (GroupSelector selector, LimitType type) : base (selector) { limit_type = type; } public override void PositionChanged () { selector.UpdateLimits (); } } protected override void OnMapped () { base.OnMapped (); if (event_window != null) event_window.Show (); } protected override void OnUnmapped () { base.OnUnmapped (); if (event_window != null) event_window.Hide (); } protected override bool OnExposeEvent (Gdk.EventExpose args) { Rectangle area; //Console.WriteLine ("expose {0}", args.Area); foreach (Rectangle sub in args.Region.GetRectangles ()) { if (sub.Intersect (background, out area)) { Rectangle active = background; int min_x = BoxX (min_limit.Position); int max_x = BoxX (max_limit.Position + 1); active.X = min_x; active.Width = max_x - min_x; if (active.Intersect (area, out active)) GdkWindow.DrawRectangle (Style.BaseGC (State), true, active); int i; BoxXHit (area.X, out i); int end; BoxXHit (area.X + area.Width, out end); while (i <= end) DrawBox (area, i++); } Style.PaintShadow (this.Style, GdkWindow, State, ShadowType.In, area, this, null, background.X, background.Y, background.Width, background.Height); if (sub.Intersect (legend, out area)) { int i = 0; while (i < box_counts.Length) DrawTick (area, i++); } if (has_limits) { if (min_limit != null) { min_limit.Draw (sub); } if (max_limit != null) { max_limit.Draw (sub); } } if (glass != null) { glass.Draw (sub); } } return base.OnExposeEvent (args); } protected override void OnSizeRequested (ref Requisition requisition) { left.SizeRequest (); right.SizeRequest (); requisition.Width = 500; requisition.Height = (int) (LegendHeight () + glass.handle_height + 3 * border); } // FIXME I can't find a c# wrapper for the C PANGO_PIXELS () macro // So this Function is for that. public static int PangoPixels (int val) { return val >= 0 ? (val + 1024 / 2) / 1024 : (val - 1024 / 2) / 1024; } private int LegendHeight () { int max_height = 0; Pango.FontMetrics metrics = this.PangoContext.GetMetrics (this.Style.FontDescription, Pango.Language.FromString ("en_US")); max_height += PangoPixels (metrics.Ascent + metrics.Descent); foreach (Pango.Layout l in tick_layouts) { if (l != null) { int width, height; l.GetPixelSize (out width, out height); max_height = Math.Max (height, max_height); } } return (int) (max_height * 1.5); } private bool HandleScrollRight () { if (glass.Dragging) glass.MaintainPosition (); Offset -= 10; return true; } private bool HandleScrollLeft () { if (glass.Dragging) glass.MaintainPosition (); Offset += 10; return true; } private void HandleLeftPressed (object sender, System.EventArgs ars) { HandleScrollLeft (); left_delay.Start (); } private void HandleRightPressed (object sender, System.EventArgs ars) { HandleScrollRight (); right_delay.Start (); } [GLib.ConnectBefore] private void HandleScrollReleaseEvent (object sender, ButtonReleaseEventArgs args) { right_delay.Stop (); left_delay.Stop (); } protected override void OnSizeAllocated (Gdk.Rectangle alloc) { base.OnSizeAllocated (alloc); int legend_height = LegendHeight (); Gdk.Rectangle bar = new Rectangle (alloc.X + border, alloc.Y + border, alloc.Width - 2 * border, alloc.Height - 2 * border - glass.handle_height); if (left.Allocation.Y != bar.Y || left.Allocation.X != bar.X) { left.SetSizeRequest (-1, bar.Height); this.Move (left, bar.X - Allocation.X, bar.Y - Allocation.Y); } if (right.Allocation.Y != bar.Y || right.Allocation.X != bar.X + bar.Width - right.Allocation.Width) { right.SetSizeRequest (-1, bar.Height); this.Move (right, bar.X - Allocation.X + bar.Width - right.Allocation.Width, bar.Y - Allocation.Y); } background = new Rectangle (bar.X + left.Allocation.Width, bar.Y, bar.Width - left.Allocation.Width - right.Allocation.Width, bar.Height); legend = new Rectangle (background.X, background.Y, background.Width, legend_height); action = background.Union (glass.Bounds ()); if (event_window != null) event_window.MoveResize (action.X, action.Y, action.Width, action.Height); this.Offset = this.Offset; UpdateButtons (); } public void ResetLimits () { min_limit.SetPosition(0,false); max_limit.SetPosition(adaptor.Count () - 1, false); } public void SetLimitsToDates(DateTime start, DateTime stop) { if (((TimeAdaptor)adaptor).OrderAscending) { min_limit.SetPosition(((TimeAdaptor)adaptor).IndexFromDate(start),false); max_limit.SetPosition(((TimeAdaptor)adaptor).IndexFromDate(stop),false); } else { min_limit.SetPosition(((TimeAdaptor)adaptor).IndexFromDate(stop),false); max_limit.SetPosition(((TimeAdaptor)adaptor).IndexFromDate(start),false); } } public GroupSelector () : base () { SetFlag (WidgetFlags.NoWindow); background = Rectangle.Zero; glass = new Glass (this); min_limit = new Limit (this, Limit.LimitType.Min); max_limit = new Limit (this, Limit.LimitType.Max); left = new Gtk.Button (); //left.Add (new Gtk.Image (Gtk.Stock.GoBack, Gtk.IconSize.Button)); left.Add (new Gtk.Arrow (Gtk.ArrowType.Left, Gtk.ShadowType.None)); left.Relief = Gtk.ReliefStyle.None; //left.Clicked += HandleScrollLeft; left.Pressed += HandleLeftPressed; left.ButtonReleaseEvent += HandleScrollReleaseEvent; left_delay = new DelayedOperation (50, new GLib.IdleHandler (HandleScrollLeft)); right = new Gtk.Button (); //right.Add (new Gtk.Image (Gtk.Stock.GoForward, Gtk.IconSize.Button)); right.Add (new Gtk.Arrow (Gtk.ArrowType.Right, Gtk.ShadowType.None)); right.Relief = Gtk.ReliefStyle.None; right.Pressed += HandleRightPressed; right.ButtonReleaseEvent += HandleScrollReleaseEvent; right_delay = new DelayedOperation (50, new GLib.IdleHandler (HandleScrollRight)); //right.Clicked += HandleScrollRight; this.Put (left, 0, 0); this.Put (right, 100, 0); left.Show (); right.Show (); CanFocus = true; Mode = RangeType.Min; UpdateButtons (); } public GroupSelector (IntPtr raw) : base (raw) {} } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. using DataFactory.Tests.Utils; using Microsoft.Azure.Management.DataFactory; using Microsoft.Azure.Management.DataFactory.Models; using Microsoft.Azure.Management.ResourceManager; using System; using System.Linq; using System.Net; using System.Threading.Tasks; using Xunit; namespace DataFactory.Tests.ScenarioTests { public class IntegrationRuntimeScenarioTests : ScenarioTestBase<IntegrationRuntimeScenarioTests> { [Fact] [Trait(TraitName.TestType, TestType.Scenario)] public async Task SelfHostedIntegrationRuntimeScenarioTest() { var integrationRuntimeName = "selfhostedintegrationruntime"; var resource = new IntegrationRuntimeResource() { Properties = new SelfHostedIntegrationRuntime { Description = "Self-Hosted integration runtime." } }; Func<DataFactoryManagementClient, Task> action = async (client) => { var factory = new Factory(location: FactoryLocation); await client.Factories.CreateOrUpdateAsync(this.ResourceGroupName, this.DataFactoryName, factory); var createResponse = await client.IntegrationRuntimes.CreateOrUpdateAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName, resource); Assert.Equal(integrationRuntimeName, createResponse.Name); Assert.True(createResponse.Properties is SelfHostedIntegrationRuntime); var getResponse = await client.IntegrationRuntimes.GetAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); Assert.True(getResponse.Properties is SelfHostedIntegrationRuntime); var status = await client.IntegrationRuntimes.GetStatusAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); var selfHostedStatus = status.Properties as SelfHostedIntegrationRuntimeStatus; Assert.Equal(IntegrationRuntimeState.NeedRegistration, selfHostedStatus.State); var listByResourceGroupResponse = await client.IntegrationRuntimes.ListByFactoryAsync( this.ResourceGroupName, this.DataFactoryName); var item = listByResourceGroupResponse.First(); Assert.Equal(integrationRuntimeName, item.Name); Assert.True(item.Properties is SelfHostedIntegrationRuntime); }; Func<DataFactoryManagementClient, Task> finallyAction = async (client) => { await client.IntegrationRuntimes.DeleteAsync(this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); var deleteResponse = await client.IntegrationRuntimes.DeleteWithHttpMessagesAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); Assert.Equal(HttpStatusCode.NoContent, deleteResponse.Response.StatusCode); await client.Factories.DeleteAsync(this.ResourceGroupName, this.DataFactoryName); }; await this.RunTest(action, finallyAction); } [Fact] [Trait(TraitName.TestType, TestType.Scenario)] public async Task AzureIntegrationRuntimeScenarioTest() { var integrationRuntimeName = "azureintegrationruntime"; Func<DataFactoryManagementClient, Task> action = async (client) => { var factory = new Factory(location: FactoryLocation); await client.Factories.CreateOrUpdateAsync(this.ResourceGroupName, this.DataFactoryName, factory); var resource = new IntegrationRuntimeResource() { Properties = new ManagedIntegrationRuntime { Description = "Azure integration runtime." } }; var createResponse = await client.IntegrationRuntimes.CreateOrUpdateAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName, resource); Assert.Equal(integrationRuntimeName, createResponse.Name); Assert.True(createResponse.Properties is ManagedIntegrationRuntime); var getResponse = await client.IntegrationRuntimes.GetAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); Assert.True(getResponse.Properties is ManagedIntegrationRuntime); var status = await client.IntegrationRuntimes.GetStatusAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); var managedStatus = status.Properties as ManagedIntegrationRuntimeStatus; Assert.Equal(IntegrationRuntimeState.Online, managedStatus.State); var listByResourceGroupResponse = await client.IntegrationRuntimes.ListByFactoryAsync( this.ResourceGroupName, this.DataFactoryName); var item = listByResourceGroupResponse.First(); Assert.Equal(integrationRuntimeName, item.Name); Assert.True(item.Properties is ManagedIntegrationRuntime); }; Func<DataFactoryManagementClient, Task> finallyAction = async (client) => { await client.IntegrationRuntimes.DeleteAsync(this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); var deleteResponse = await client.IntegrationRuntimes.DeleteWithHttpMessagesAsync(this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); Assert.Equal(HttpStatusCode.NoContent, deleteResponse.Response.StatusCode); await client.Factories.DeleteAsync(this.ResourceGroupName, this.DataFactoryName); }; await this.RunTest(action, finallyAction); } [Fact] [Trait(TraitName.TestType, TestType.Scenario)] public async Task SsisAzureIntegrationRuntimeScenarioTest() { var integrationRuntimeName = "ssisazureintegrationruntime"; var resource = new IntegrationRuntimeResource() { Properties = new ManagedIntegrationRuntime { Description = "SSIS-Azure integration runtime.", ComputeProperties = new IntegrationRuntimeComputeProperties { NodeSize = "Standard_D1_v2", MaxParallelExecutionsPerNode = 1, NumberOfNodes = 1, Location = "WestUS", VNetProperties = new IntegrationRuntimeVNetProperties { SubnetId = "/subscriptions/1491d049-b7ce-4dc5-9833-d2947b0bd2e1/resourceGroups/Azure_SSIS_API/providers/Microsoft.Network/virtualNetworks/FirstVNetForAzureSSIS/subnets/TestVnetJoin" } }, SsisProperties = new IntegrationRuntimeSsisProperties { CatalogInfo = new IntegrationRuntimeSsisCatalogInfo { CatalogAdminUserName = Environment.GetEnvironmentVariable("CatalogAdminUsername"), CatalogAdminPassword = new SecureString(Environment.GetEnvironmentVariable("CatalogAdminPassword")), CatalogServerEndpoint = Environment.GetEnvironmentVariable("CatalogServerEndpoint"), CatalogPricingTier = "S1", DualStandbyPairName="Name" }, DataProxyProperties = new IntegrationRuntimeDataProxyProperties { ConnectVia = new EntityReference { ReferenceName = "selfHostedIRName" }, StagingLinkedService = new EntityReference { ReferenceName = "stagingLinkedService" }, Path = "fakedPath" }, Credential = new CredentialReference { ReferenceName= "credentialReference" } } } }; Func<DataFactoryManagementClient, Task> action = async (client) => { var factory = new Factory(location: FactoryLocation); await client.Factories.CreateOrUpdateAsync(this.ResourceGroupName, this.DataFactoryName, factory); var createResponse = await client.IntegrationRuntimes.CreateOrUpdateAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName, resource); Assert.Equal(integrationRuntimeName, createResponse.Name); Assert.True(createResponse.Properties is ManagedIntegrationRuntime); var startResponse = await client.IntegrationRuntimes.StartAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); var managedStatus = startResponse.Properties as ManagedIntegrationRuntimeStatus; Assert.Equal(IntegrationRuntimeState.Started, managedStatus.State); await client.IntegrationRuntimes.StopAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); var status = await client.IntegrationRuntimes.GetStatusAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); managedStatus = status.Properties as ManagedIntegrationRuntimeStatus; Assert.Equal(IntegrationRuntimeState.Stopped, managedStatus.State); await client.IntegrationRuntimes.ListOutboundNetworkDependenciesEndpointsWithHttpMessagesAsync( this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); }; Func<DataFactoryManagementClient, Task> finallyAction = async (client) => { await client.IntegrationRuntimes.DeleteAsync(this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); var deleteResponse = await client.IntegrationRuntimes.DeleteWithHttpMessagesAsync(this.ResourceGroupName, this.DataFactoryName, integrationRuntimeName); Assert.Equal(HttpStatusCode.NoContent, deleteResponse.Response.StatusCode); await client.Factories.DeleteAsync(this.ResourceGroupName, this.DataFactoryName); }; await this.RunTest(action, finallyAction); } } }
// ----- // GNU General Public License // The Forex Professional Analyzer 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 Forex Professional Analyzer 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. // ----- using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; using System.Collections.ObjectModel; using System.Windows.Forms; namespace fxpa { /// <summary> /// Thread safe. /// </summary> public class TradeChartSeries : SimpleChartSeries { public new enum ChartTypeEnum { CandleStick, BarChart, ColoredArea, Histogram, Line, } public override string[] ChartTypes { get { return Enum.GetNames(typeof(ChartTypeEnum)); } } public override string SelectedChartType { get { return Enum.GetName(typeof(ChartTypeEnum), _chartType); } } volatile ChartTypeEnum _chartType = ChartTypeEnum.BarChart; public new ChartTypeEnum ChartType { get { return _chartType; } set { _chartType = value; } } protected TimeSpan? _period; public TimeSpan? Period { get { return _period; } } /// <summary> /// Needed for proper rendering of volume (since it is uniform scaled). /// </summary> float _minVolume = 0; float _maxVolume = 0; protected List<BarData> _dataBars = new List<BarData>(); public ReadOnlyCollection<BarData> DataBars { get { lock (this) { return _dataBars.AsReadOnly(); } } } public int DataBarsCount { get { return _dataBars.Count; } } public override SeriesTypeEnum SeriesType { get { return SeriesTypeEnum.TimeBased; } } BarData.DataValueSourceEnum _simpleValuesType = BarData.DataValueSourceEnum.Close; /// <summary> /// Simple values are created when a bar data source is put in, or when you put them in manually. /// </summary> public BarData.DataValueSourceEnum SimpleValuesSourceType { get { return _simpleValuesType; } set { _simpleValuesType = value; if (_dataBars.Count > 0) {// Refresh the simple values array in this case. UpdateSimpleValues(); } } } // Harry -- MOD Brush _risingBarFill = null; public Brush RisingBarFill { set { _risingBarFill = value; } } Brush _fallingBarFill = Brushes.Green; public Brush FallingBarFill { set { _fallingBarFill = value; } } Pen _risingBarPen = Pens.Red; public Pen RisingBarPen { set { _risingBarPen = value; } } Pen _fallingBarPen = Pens.LightGreen; public Pen FallingBarPen { set { _fallingBarPen = value; } } Pen _timeGapsLinePen = new Pen(Color.DarkRed); /// <summary> /// Time gaps occur when there is space between one period and the next. /// </summary> public Pen TimeGapsLinePen { set { _timeGapsLinePen = value; } } volatile bool _showTimeGaps = false; /// <summary> /// If enabled, time gaps are shown but only on zoom 1 (units unification = 1). /// </summary> public bool ShowTimeGaps { get { return _showTimeGaps; } set { _showTimeGaps = value; } } bool _showVolume = true; public bool ShowVolume { get { return _showVolume; } set { _showVolume = value; } } Pen _volumePen = Pens.Gainsboro; public Pen VolumePen { get { return _volumePen; } set { _volumePen = value; } } Brush _volumeBrush = Brushes.Gainsboro; public Brush VolumeBrush { set { _volumeBrush = value; } } /// <summary> /// /// </summary> public TradeChartSeries() { _timeGapsLinePen.DashPattern = new float[] { 10, 10 }; _timeGapsLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom; ComponentResourceManager resources = new ComponentResourceManager(typeof(TradeChartSeries)); _imageDown = ((Image)(resources.GetObject("imageDown"))); _imageUp = ((Image)(resources.GetObject("imageUp"))); _imageCross = ((Image)(resources.GetObject("imageCross"))); _imageCross = ((Image)(resources.GetObject("imageStopLost"))); _imageCross = ((Image)(resources.GetObject("imageInfo"))); //_imageDown = ((Image)(resources.GetObject("imageStopLost"))); //_imageUp = ((Image)(resources.GetObject("imageInfo"))); } public TradeChartSeries(string name) { base.Name = name; } IDataProvider _dataProvider; public void Initialize(IDataProvider dataProvider) { lock (this) { _dataProvider = dataProvider; _dataProvider.ValuesUpdateEvent += new ValuesUpdatedDelegate(_provider_ValuesUpdateEvent); ComponentResourceManager resources = new ComponentResourceManager(typeof(TradeChartSeries)); //_imageDown = ((Image)(resources.GetObject("imageDown"))); //_imageUp = ((Image)(resources.GetObject("imageUp"))); //_imageCross = ((Image)(resources.GetObject("imageCross"))); //_imageStopGain = ((Image)(resources.GetObject("imageStopGain"))); //_imageGainTip = ((Image)(resources.GetObject("star4"))); _imageDown = ((Image)(resources.GetObject("arrow_down"))); _imageUp = ((Image)(resources.GetObject("arrow_up"))); _imageStopLoss = ((Image)(resources.GetObject("imageStopLost"))); //_imageStopLoss = ((Image)(resources.GetObject("tt"))); _imageStopGain = ((Image)(resources.GetObject("vv"))); _imageGainTip = ((Image)(resources.GetObject("dd"))); ////_imageTip = ((Image)(resources.GetObject("imageTip"))); //_imageUp = ((Image)(resources.GetObject("imageInfo"))); } } void _provider_ValuesUpdateEvent(IDataProvider dataProvider, UpdateType updateType, int updatedItemsCount, int stepsRemaining) { if (stepsRemaining == 0) { UpdateValues(); } } void UpdateValues() { lock (this) { BarData[] bars; lock (_dataProvider.DataUnits) { bars = new BarData[_dataProvider.DataUnits.Count]; _dataProvider.DataUnits.CopyTo(bars, 0); } if (null != bars && bars.Length > 0) { this.SetBarData(bars, _dataProvider.TimeInterval); RaiseValuesUpdated(true); } } } /// <summary> /// /// </summary> public TradeChartSeries(string name, ChartTypeEnum chartType) : base(name) { _chartType = chartType; } /// <summary> /// /// </summary> public TradeChartSeries(string name, ChartTypeEnum chartType, BarData[] bars, TimeSpan period) { _chartType = chartType; SetBarData(bars, period); } /// <summary> /// Establish the total minimum value of any item in this interval. /// </summary> /// <param name="startIndex">Inclusive starting index.</param> /// <param name="endIndex">Exclusive ending index.</param> public override float GetTotalMinimum(int startIndex, int endIndex) { float min = float.MaxValue; lock (this) { if (_dataBars.Count > 0) { for (int i = startIndex; i < endIndex && i < _dataBars.Count; i++) { // Modified due to mouse move if (i > 0 && _dataBars[i].HasDataValues) { //min = (float)Math.Min(_dataBars[i].Low, min); min = (float)Math.Min(_dataBars[i].ExLow, min); } } } else { min = base.GetTotalMinimum(startIndex, endIndex); } } return min; } /// <summary> /// Establish the total maximum value of any item in this interval. /// </summary> /// <param name="startIndex">Inclusive starting index.</param> /// <param name="endIndex">Exclusive ending index.</param> public override float GetTotalMaximum(int startIndex, int endIndex) { float max = float.MinValue; lock (this) { if (_dataBars.Count > 0) { for (int i = startIndex; i < endIndex && i < _dataBars.Count; i++) { if (i > 0 && _dataBars[i].HasDataValues) { //max = (float)Math.Max(_dataBars[i].High, max); max = (float)Math.Max(_dataBars[i].ExHigh, max); } } } else { base.GetTotalMaximum(startIndex, endIndex); } } return max; } public override DateTime GetTimeAtIndex(int index) { lock (this) { return _dataBars[index].DateTime; } } public override double GetOpenAtIndex(int index) { lock (this) { return _dataBars[index].Open; } } public override double GetCloseAtIndex(int index) { lock (this) { return _dataBars[index].Close; } } public override double GetLowAtIndex(int index) { lock (this) { return _dataBars[index].Low; } } public override double GetExLowAtIndex(int index) { lock (this) { return _dataBars[index].ExLow; } } public override double GetHightAtIndex(int index) { lock (this) { return _dataBars[index].High; } } public override double GetExHightAtIndex(int index) { lock (this) { return _dataBars[index].ExHigh; } } public override double GetSarAtIndex(int index) { lock (this) { return _dataBars[index].Sar; } } public override double GetCciAtIndex(int index) { lock (this) { return _dataBars[index].Cci; } } public override double GetCci2AtIndex(int index) { lock (this) { return _dataBars[index].Cci2; } } public override double GetCci3AtIndex(int index) { lock (this) { return _dataBars[index].Cci3; } } public override double GetWrAtIndex(int index) { lock (this) { return _dataBars[index].Wr; } } public override double GetWr2AtIndex(int index) { lock (this) { return _dataBars[index].Wr2; } } public override Dictionary<string, double> GetLwrAtIndex(int index) { lock (this) { return _dataBars[index].Lwr; } } public override Dictionary<string, double> GetBollAtIndex(int index) { lock (this) { return _dataBars[index].Boll; } } public override Dictionary<string, double> GetIndicatorsAtIndex(int index) { lock (this) { return _dataBars[index].Indicators; } } public override double GetRsiAtIndex(int index) { lock (this) { return _dataBars[index].Rsi; } } public override double GetRsi2AtIndex(int index) { lock (this) { return _dataBars[index].Rsi2; } } public override double GetRsi3AtIndex(int index) { lock (this) { return _dataBars[index].Rsi3; } } public override double GetRsi4AtIndex(int index) { lock (this) { return _dataBars[index].Rsi4; } } public override double GetArAtIndex(int index) { lock (this) { return _dataBars[index].Ar; } } public override double GetAr2AtIndex(int index) { lock (this) { return _dataBars[index].Ar2; } } public override double GetBrAtIndex(int index) { lock (this) { return _dataBars[index].Br; } } public override double GetCrAtIndex(int index) { lock (this) { return _dataBars[index].Cr; } } public override List<CandleSignal> GetSignalsAtIndex(int index) { lock (this) { return _dataBars[index].SignalList; } } public override BarData GetCandleAtIndex(int index) { lock (this) { return _dataBars[index]; } } //public override double GetRSIAtIndex(int index) //{ // lock (this) // { // return _dataBars[index].Rsi; // } //} public override void SaveToFile(string fileName) { BarData[] dataBars; lock (this) { dataBars = _dataBars.ToArray(); } BarDataHelper.SaveToFile(BarDataHelper.FileFormat.CVSDefault, fileName, dataBars); } /// <summary> /// To handle bar data properly it must have a regularly spread items over the period. /// </summary> public bool SetBarData(IEnumerable<BarData> datas, TimeSpan period) { lock (this) { _period = period; _dataBars.Clear(); _dataBars.AddRange(datas); _minVolume = float.MaxValue; _maxVolume = 0; UpdateSimpleValues(); } return true; } void UpdateSimpleValues() { // Harry -- Comment -- 2009.09.22 //Create corresponding simple values and calculate min and max volume. float[] simpleValues = new float[_dataBars.Count]; for (int i = 0; i < _dataBars.Count; i++) {// Empty values will have the value of double.NaN assigned. simpleValues[i] = (float)_dataBars[i].GetValue(_simpleValuesType); _minVolume = (float)Math.Min(_minVolume, _dataBars[i].Volume); _maxVolume = (float)Math.Max(_maxVolume, _dataBars[i].Volume); } if (_minVolume == float.MaxValue || float.IsPositiveInfinity(_minVolume)) { _minVolume = 0; } base.SetValues(new float[][] { simpleValues }); } /// <summary> /// /// </summary> /// <param name="g"></param> /// <param name="unitsUnification">Draw a few units as one. Used when zooming is too big to show each unit - so unify them. 1 means no unification, 10 means unify 10 units together</param> /// <param name="clippingRectangle"></param> /// <param name="itemWidth"></param> /// <param name="itemMargin"></param> public override void Draw(GraphicsWrapper g, int unitsUnification, RectangleF clippingRectangle, float itemWidth, float itemMargin) { if (Visible == false) { return; } PointF drawingPoint = new PointF(); lock (this) { if (_chartType == ChartTypeEnum.Line) { SetChartType(SimpleChartSeries.ChartTypeEnum.Line); base.Draw(g, unitsUnification, clippingRectangle, itemWidth, itemMargin); } else if (_chartType == ChartTypeEnum.Histogram) { SetChartType(SimpleChartSeries.ChartTypeEnum.Histogram); base.Draw(g, unitsUnification, clippingRectangle, itemWidth, itemMargin); } else if (_chartType == ChartTypeEnum.ColoredArea) { SetChartType(SimpleChartSeries.ChartTypeEnum.ColoredArea); base.Draw(g, unitsUnification, clippingRectangle, itemWidth, itemMargin); } else if (_chartType == ChartTypeEnum.CandleStick || _chartType == ChartTypeEnum.BarChart) {// Unit unification is done trough combining many bars together. List<BarData> combinationDatas = new List<BarData>(); bool timeGapFound = false; int startIndex, endIndex; GetDrawingRangeIndecesFromClippingRectange(clippingRectangle, drawingPoint, unitsUnification, out startIndex, out endIndex, itemWidth, itemMargin); float volumeDisplayRange = clippingRectangle.Height / 4f; double volumeDisplayMultiplicator = volumeDisplayRange / _maxVolume; for (int i = startIndex; i < endIndex && i < _dataBars.Count; i++) { combinationDatas.Add(_dataBars[i]); if (unitsUnification == 1 && ShowTimeGaps && i > 0 && _dataBars[i].DateTime - _dataBars[i - 1].DateTime != _period) { timeGapFound = true; } if (i % unitsUnification == 0) { BarData combinedData = BarData.CombinedBar(combinationDatas.ToArray()); if (i == _dataBars.Count - 1) Console.WriteLine(" LAST combinedData ###### " + combinedData); combinationDatas.Clear(); if (combinedData.HasDataValues) //&& drawingPoint.X >= clippingRectangle.X //&& drawingPoint.X <= clippingRectangle.X + clippingRectangle.Width) { if (timeGapFound && ShowTimeGaps && _timeGapsLinePen != null) {// Draw time gap. timeGapFound = false; g.DrawLine(_timeGapsLinePen, new PointF(drawingPoint.X, clippingRectangle.Y), new PointF(drawingPoint.X, clippingRectangle.Y + clippingRectangle.Height)); //g.DrawLine(_timeGapsLinePen, new PointF(drawingPoint.X, clippingRectangle.Y), new PointF(drawingPoint.X, (float)(data.High))); //g.DrawLine(_timeGapsLinePen, new PointF(drawingPoint.X, (float)(data.High + data.BarTotalLength / 2f)), new PointF(drawingPoint.X, clippingRectangle.Y + clippingRectangle.Height)); } if (_chartType == ChartTypeEnum.CandleStick) { if (i > 0 && combinedData.Open > _dataBars[i - 1].Close) combinedData.IsHigherPrev = true; DrawCandleStick(g, ref drawingPoint, combinedData, itemWidth, itemMargin, unitsUnification); } else { DrawBar(g, ref drawingPoint, combinedData, itemWidth, itemMargin, unitsUnification); } // Draw volume for this bar. if (_showVolume) { float actualHeight = (float)(combinedData.Volume * volumeDisplayMultiplicator); g.DrawLine(_volumePen, drawingPoint.X, clippingRectangle.Y, drawingPoint.X, clippingRectangle.Y + actualHeight); } if (combinedData.Sar != 0) { float dy = drawingPoint.Y; float y = (drawingPoint.Y + (float)combinedData.Sar); float yts = Math.Abs(g.DrawingSpaceTransform.Elements[0] / g.DrawingSpaceTransform.Elements[3]); float x = drawingPoint.X + (1 + yts) * itemWidth * 3f / 16f; //float x = drawingPoint.X + (1 + yts) * itemWidth * 3f / 8f; if (combinedData.Sar >= combinedData.Low && combinedData.High >= combinedData.Sar) g.DrawEllipse(new Pen(Color.White), x, y, yts * itemWidth / 2f, yts * itemWidth / 2f); else g.DrawEllipse(new Pen(Color.White), x, y, yts * itemWidth / 2f, yts * itemWidth / 2f); if (combinedData.Boll != null) { float uy = dy + (float)combinedData.Boll[BOLL.UPPER]; float my = dy + (float)combinedData.Boll[BOLL.MID]; float ly = dy + (float)combinedData.Boll[BOLL.LOWER]; g.DrawEllipse(new Pen(Color.Cyan), x, uy, yts * itemWidth / 2f, yts * itemWidth / 2f); g.DrawEllipse(new Pen(Color.Cyan), x, my, yts * itemWidth / 2f, yts * itemWidth / 2f); g.DrawEllipse(new Pen(Color.Cyan), x, ly, yts * itemWidth / 2f, yts * itemWidth / 2f); } } // Harry --- Draw Signal //_dataBars[i].RefreshExValues(); float actualImageHeight = _imageDown.Height / Math.Abs(g.DrawingSpaceTransform.Elements[3]); float yToXScaling = Math.Abs(g.DrawingSpaceTransform.Elements[0] / g.DrawingSpaceTransform.Elements[3]); PointF upImageDrawingPoint = drawingPoint; PointF downImageDrawingPoint = drawingPoint; Order order = new Order(); BarData orderBarData = _dataBars[i]; float lastBarX = (itemMargin + itemWidth) * _dataBars.Count; if (_dataBars[i].SignalList != null && _dataBars[i].SignalList.Count > 0) { foreach (CandleSignal cs in _dataBars[i].SignalList) { cs.BarData = orderBarData; if (cs.Code == 1) DrawSignal(g, ref downImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); if (cs.Code == -1) DrawSignal(g, ref upImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); if (cs.Code == 2) DrawGainTip(g, ref upImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); if (cs.Code == -2) DrawGainTip(g, ref downImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); if (cs.Code == 3) DrawStopLoss(g, ref downImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); if (cs.Code == -3) DrawStopLoss(g, ref upImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); if (cs.Code == 4) DrawStopGain(g, ref upImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); if (cs.Code == -4) DrawStopGain(g, ref downImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, cs, lastBarX, false); } } } drawingPoint.X = (i + 1) * (itemMargin + itemWidth); } } } } } /// <summary> /// Enter locked. /// </summary> void DrawBar(GraphicsWrapper g, ref PointF startingPoint, BarData barData, float itemWidth, float itemMargin, int itemUnitification) { float xMiddle = startingPoint.X + itemWidth / 2; float xHalfWidth = itemWidth / 2; Pen pen = _risingBarPen; if (barData.BarIsRising == false) { pen = _fallingBarPen; } if (pen == null) { return; } float yDisplacement = startingPoint.Y; g.DrawLine(pen, xMiddle, yDisplacement + (float)barData.Low, xMiddle, yDisplacement + (float)barData.High); g.DrawLine(pen, xMiddle, yDisplacement + (float)barData.Open, xMiddle - xHalfWidth, yDisplacement + (float)barData.Open); g.DrawLine(pen, xMiddle, yDisplacement + (float)barData.Close, xMiddle + xHalfWidth, yDisplacement + (float)barData.Close); } /// <summary> /// Enter locked. /// </summary> void DrawCandleStick(GraphicsWrapper g, ref PointF startingPoint, BarData barData, float itemWidth, float itemMargin, int itemUnitification) { if (barData.BarIsRising || (barData.IsHigherPrev && barData.BarBodyLength == 0)) { if (_risingBarFill != null) { g.FillRectangle(_risingBarFill, startingPoint.X, startingPoint.Y + (float)barData.Open, itemWidth, (float)barData.BarBodyLength); } if (_risingBarPen != null) { if (itemWidth > 4) { g.DrawRectangle(_risingBarPen, startingPoint.X, startingPoint.Y + (float)barData.Open, itemWidth, (float)barData.BarBodyLength); // Harry -- Draw a line for open = = close if ((float)barData.BarBodyLength <= 0) { g.DrawLine(_risingBarPen, startingPoint.X, startingPoint.Y + (float)barData.Close, startingPoint.X + itemWidth, startingPoint.Y + (float)barData.Close); } } else { g.FillRectangle(Brushes.Green, startingPoint.X, startingPoint.Y + (float)barData.Open, itemWidth, (float)barData.BarBodyLength); } // Lower shadow g.DrawLine(_risingBarPen, startingPoint.X + itemWidth / 2, startingPoint.Y + (float)barData.Low, startingPoint.X + itemWidth / 2, startingPoint.Y + (float)barData.Open); // Upper shadow g.DrawLine(_risingBarPen, startingPoint.X + itemWidth / 2, (float)(startingPoint.Y + barData.High), startingPoint.X + itemWidth / 2, (float)(startingPoint.Y + barData.Close)); //Console.WriteLine(" startingPoint.X " + startingPoint.X + " startingPoint.Y " + startingPoint.Y + " (float)barData.Low " + (float)barData.Low + " (float)barData.Close " + (float)barData.Close + " (float)barData.High " + (float)barData.High + " (float)barData.Open " + (float)barData.Open); } } else { if (_fallingBarFill != null) { g.FillRectangle(_fallingBarFill, startingPoint.X, startingPoint.Y + (float)barData.Close, itemWidth, (float)barData.BarBodyLength); // Harry -- Draw a line for open = = close if ((float)barData.BarBodyLength <= 0) { g.DrawLine(_fallingBarPen, startingPoint.X, startingPoint.Y + (float)barData.Close, startingPoint.X + itemWidth, startingPoint.Y + (float)barData.Close); } } if (_fallingBarPen != null) { if (itemWidth >= 4) {// Only if an item is clearly visible, show the border, otherwise, hide to improver overal visibility. // Showing this border adds nice detail on close zooming, but not useful otherwise. g.DrawRectangle(_fallingBarPen, startingPoint.X, startingPoint.Y + (float)barData.Close, itemWidth, (float)barData.BarBodyLength); } // Lower shadow g.DrawLine(_fallingBarPen, startingPoint.X + itemWidth / 2, startingPoint.Y + (float)barData.Low, startingPoint.X + itemWidth / 2, startingPoint.Y + (float)barData.Close); // Upper shadow g.DrawLine(_fallingBarPen, startingPoint.X + itemWidth / 2, (float)(startingPoint.Y + barData.High), startingPoint.X + itemWidth / 2, (float)(startingPoint.Y + barData.Open)); } } } public override void SetSelectedChartType(string chartType) { _chartType = (ChartTypeEnum)Enum.Parse(typeof(ChartTypeEnum), chartType); } Image _imageUp; Image _imageDown; Image _imageCross; Image _imageStopLoss; Image _imageStopGain; Image _imageGainTip; Pen _buyDashedPen = new Pen(Color.Green); Pen _sellDashedPen = new Pen(Color.Red); //void DrawSignal(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin, // float yToXScaling, BarData orderBarData, float lastBarX, bool drawOpening) void DrawSignal(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin, float yToXScaling, CandleSignal cs, float lastBarX, bool drawOpening) { Image image = _imageUp; Brush brush = Brushes.Green; Pen dashedPen = _buyDashedPen; Pen pen = Pens.GreenYellow; if (order.IsBuy == false) { image = _imageDown; brush = Brushes.Red; pen = Pens.Red; dashedPen = _sellDashedPen; } //if (drawOpening == false) //{ if (cs.Arrow == -1) image = _imageDown; else { image = _imageUp; } float imageHeight = 4 * (yToXScaling * itemWidth); if (cs.Arrow == -1) { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.High + (yToXScaling * itemWidth) + imageHeight, itemWidth, -imageHeight); updatedImageDrawingPoint.Y += 1.1f * imageHeight; } else { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.Low - (yToXScaling * itemWidth), itemWidth, -imageHeight); updatedImageDrawingPoint.Y -= 1.1f * imageHeight; } } void DrawGainTip(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin, float yToXScaling, CandleSignal cs, float lastBarX, bool drawOpening) { Image image = _imageUp; Brush brush = Brushes.Green; Pen dashedPen = _buyDashedPen; Pen pen = Pens.GreenYellow; image = _imageGainTip; float imageHeight = 2 * (yToXScaling * itemWidth); // Gain tip should occur on the opposite side of arrow if (cs.Arrow == 1) { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.High + (yToXScaling * itemWidth) + imageHeight, itemWidth, -imageHeight); updatedImageDrawingPoint.Y += 1.1f * imageHeight; } else { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.Low - (yToXScaling * itemWidth), itemWidth, -imageHeight); updatedImageDrawingPoint.Y -= 1.1f * imageHeight; } } void DrawStopLoss(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin, float yToXScaling, CandleSignal cs, float lastBarX, bool drawOpening) { Image image = _imageUp; Brush brush = Brushes.Green; Pen dashedPen = _buyDashedPen; Pen pen = Pens.GreenYellow; image = _imageStopLoss; float imageHeight = 2 * (yToXScaling * itemWidth); if (cs.Arrow == -1) { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.High + (yToXScaling * itemWidth) + imageHeight, itemWidth, -imageHeight); updatedImageDrawingPoint.Y += 1.1f * imageHeight; } else { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.Low - (yToXScaling * itemWidth), itemWidth, -imageHeight); updatedImageDrawingPoint.Y -= 1.1f * imageHeight; } } void DrawStopGain(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin, float yToXScaling, CandleSignal cs, float lastBarX, bool drawOpening) { Image image = _imageUp; Brush brush = Brushes.Green; Pen dashedPen = _buyDashedPen; Pen pen = Pens.GreenYellow; image = _imageStopGain; //itemWidth += itemMargin; float imageHeight = 2 * (yToXScaling * itemWidth); //float imageHeight = (yToXScaling * itemWidth); //imageHeight =itemWidth; Brush brushx = Brushes.Yellow; // Gain tip should occur on the opposite side of arrow if (cs.Arrow == 1) { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.High + (yToXScaling * itemWidth) + imageHeight, itemWidth, -imageHeight); updatedImageDrawingPoint.Y += 1.1f * imageHeight; } else { g.DrawImage(image, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)cs.BarData.Low - (yToXScaling * itemWidth), itemWidth, -imageHeight); updatedImageDrawingPoint.Y -= 1.1f * imageHeight; } } } }
// 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.Linq; using Internal.Metadata.NativeFormat.Writer; using ILCompiler.Metadata; using Cts = Internal.TypeSystem; using Xunit; namespace MetadataTransformTests { public class SimpleTests { private TestTypeSystemContext _context; private Cts.Ecma.EcmaModule _systemModule; public SimpleTests() { _context = new TestTypeSystemContext(); _systemModule = _context.CreateModuleForSimpleName("PrimaryMetadataAssembly"); _context.SetSystemModule(_systemModule); } [Fact] public void TestAllTypes() { var policy = new SingleFileMetadataPolicy(); var transformResult = MetadataTransform.Run(policy, new[] { _systemModule }); Assert.Equal(1, transformResult.Scopes.Count()); Assert.Equal( _systemModule.GetAllTypes().Count(x => !policy.IsBlocked(x)), transformResult.Scopes.Single().GetAllTypes().Count()); } [Fact] public void TestBlockedInterface() { // __ComObject implements ICastable, which is a metadata blocked type and should not show // up in the __ComObject interface list. var policy = new SingleFileMetadataPolicy(); var transformResult = MetadataTransform.Run(policy, new[] { _systemModule }); Cts.MetadataType icastable = _systemModule.GetType("System.Private.CompilerServices", "ICastable"); Cts.MetadataType comObject = _systemModule.GetType("System", "__ComObject"); Assert.Equal(1, comObject.ExplicitlyImplementedInterfaces.Length); Assert.Equal(icastable, comObject.ExplicitlyImplementedInterfaces[0]); Assert.Null(transformResult.GetTransformedTypeDefinition(icastable)); Assert.Null(transformResult.GetTransformedTypeReference(icastable)); TypeDefinition comObjectRecord = transformResult.GetTransformedTypeDefinition(comObject); Assert.NotNull(comObjectRecord); Assert.Equal(comObject.Name, comObjectRecord.Name.Value); Assert.Equal(0, comObjectRecord.Interfaces.Count); } [Fact] public void TestStandaloneSignatureGeneration() { var transformResult = MetadataTransform.Run(new SingleFileMetadataPolicy(), new[] { _systemModule }); var stringRecord = transformResult.GetTransformedTypeDefinition( (Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.String)); var singleRecord = transformResult.GetTransformedTypeDefinition( (Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.Single)); var sig = new Cts.MethodSignature( 0, 0, _context.GetWellKnownType(Cts.WellKnownType.String), new[] { _context.GetWellKnownType(Cts.WellKnownType.Single) }); var sigRecord = transformResult.Transform.HandleMethodSignature(sig); // Verify the signature is connected to the existing transformResult world Assert.Same(stringRecord, sigRecord.ReturnType.Type); Assert.Equal(1, sigRecord.Parameters.Count); Assert.Same(singleRecord, sigRecord.Parameters[0].Type); } [Fact] public void TestSampleMetadataGeneration() { var policy = new SingleFileMetadataPolicy(); var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly"); var transformResult = MetadataTransform.Run(policy, new[] { _systemModule, sampleMetadataModule }); Assert.Equal(2, transformResult.Scopes.Count); var systemScope = transformResult.Scopes.Single(s => s.Name.Value == "PrimaryMetadataAssembly"); var sampleScope = transformResult.Scopes.Single(s => s.Name.Value == "SampleMetadataAssembly"); Assert.Equal(_systemModule.GetAllTypes().Count(t => !policy.IsBlocked(t)), systemScope.GetAllTypes().Count()); Assert.Equal(sampleMetadataModule.GetAllTypes().Count(t => !policy.IsBlocked(t)), sampleScope.GetAllTypes().Count()); // TODO: check individual types } [Fact] public void TestMultifileSanity() { var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly"); var policy = new MultifileMetadataPolicy(sampleMetadataModule); var transformResult = MetadataTransform.Run(policy, new[] { _systemModule, sampleMetadataModule }); Assert.Equal(1, transformResult.Scopes.Count); var sampleScope = transformResult.Scopes.Single(); Assert.Equal(sampleMetadataModule.GetAllTypes().Count(t => !policy.IsBlocked(t)), sampleScope.GetAllTypes().Count()); var objectType = (Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.Object); var objectRecord = transformResult.GetTransformedTypeReference(objectType); Assert.Equal("Object", objectRecord.TypeName.Value); var stringType = (Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.String); var stringRecord = transformResult.GetTransformedTypeReference(stringType); Assert.Equal("String", stringRecord.TypeName.Value); Assert.Same(objectRecord.ParentNamespaceOrType, stringRecord.ParentNamespaceOrType); Assert.IsType<NamespaceReference>(objectRecord.ParentNamespaceOrType); var parentNamespace = objectRecord.ParentNamespaceOrType as NamespaceReference; Assert.Equal("System", parentNamespace.Name.Value); Assert.Null(transformResult.GetTransformedTypeDefinition(objectType)); Assert.Null(transformResult.GetTransformedTypeDefinition(stringType)); } [Fact] public void TestNestedTypeReference() { // A type reference nested under a type that has a definition record. The transform is required // to create a type reference for the containing type because a type *definition* can't be a parent // to a type *reference*. var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly"); Cts.MetadataType genericOutside = sampleMetadataModule.GetType("SampleMetadata", "GenericOutside`1"); Cts.MetadataType inside = genericOutside.GetNestedType("Inside"); { MockPolicy policy = new MockPolicy( type => { return type == genericOutside; }); var result = MetadataTransform.Run(policy, new[] { sampleMetadataModule }); Assert.Equal(1, result.Scopes.Count); Assert.Equal(1, result.Scopes.Single().GetAllTypes().Count()); var genericOutsideDefRecord = result.GetTransformedTypeDefinition(genericOutside); Assert.NotNull(genericOutsideDefRecord); Assert.Null(result.GetTransformedTypeReference(inside)); var insideRecord = result.Transform.HandleType(inside); Assert.IsType<TypeReference>(insideRecord); var genericOutsideRefRecord = ((TypeReference)insideRecord).ParentNamespaceOrType as TypeReference; Assert.NotNull(genericOutsideRefRecord); Assert.Equal(genericOutside.Name, genericOutsideRefRecord.TypeName.Value); Assert.Same(genericOutsideDefRecord, result.GetTransformedTypeDefinition(genericOutside)); } } [Fact] public void TestBlockedAttributes() { // Test that custom attributes referring to blocked types don't show up in metadata var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly"); Cts.MetadataType attributeHolder = sampleMetadataModule.GetType("BlockedMetadata", "AttributeHolder"); var policy = new SingleFileMetadataPolicy(); var transformResult = MetadataTransform.Run(policy, new[] { _systemModule, sampleMetadataModule }); int blockedCount = 0; int allowedCount = 0; foreach (var field in attributeHolder.GetFields()) { var transformedRecord = transformResult.GetTransformedFieldDefinition(field); Assert.NotNull(transformedRecord); if (field.Name.StartsWith("Blocked")) { blockedCount++; Assert.Equal(0, transformedRecord.CustomAttributes.Count); } else { allowedCount++; Assert.StartsWith("Allowed", field.Name); Assert.Equal(1, transformedRecord.CustomAttributes.Count); } } Assert.Equal(5, allowedCount); Assert.Equal(8, blockedCount); } [Fact] public void TestMethodImplMetadata() { // Test that custom attributes referring to blocked types don't show up in metadata var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly"); Cts.MetadataType iCloneable = sampleMetadataModule.GetType("SampleMetadataMethodImpl", "ICloneable"); Cts.MetadataType implementsICloneable = sampleMetadataModule.GetType("SampleMetadataMethodImpl", "ImplementsICloneable"); Cts.MethodDesc iCloneableDotClone = iCloneable.GetMethod("Clone", null); Cts.MethodDesc iCloneableImplementation = implementsICloneable.GetMethod("SampleMetadataMethodImpl.ICloneable.Clone", null); Cts.MethodDesc iCloneableDotGenericClone = iCloneable.GetMethod("GenericClone", null); Cts.MethodDesc iCloneableGenericImplementation = implementsICloneable.GetMethod("SampleMetadataMethodImpl.ICloneable.GenericClone", null); var policy = new SingleFileMetadataPolicy(); var transformResult = MetadataTransform.Run(policy, new[] { _systemModule, sampleMetadataModule }); var iCloneableType = transformResult.GetTransformedTypeDefinition(iCloneable); var implementsICloneableType = transformResult.GetTransformedTypeDefinition(implementsICloneable); Assert.Equal(2, implementsICloneableType.MethodImpls.Count); // non-generic MethodImpl Method iCloneableDotCloneMethod = transformResult.GetTransformedMethodDefinition(iCloneableDotClone); Method iCloneableImplementationMethod = transformResult.GetTransformedMethodDefinition(iCloneableImplementation); QualifiedMethod methodImplMethodDecl = (QualifiedMethod)implementsICloneableType.MethodImpls[0].MethodDeclaration; QualifiedMethod methodImplMethodBody = (QualifiedMethod)implementsICloneableType.MethodImpls[0].MethodBody; Assert.Equal(iCloneableDotCloneMethod, methodImplMethodDecl.Method); Assert.Equal(iCloneableType, methodImplMethodDecl.EnclosingType); Assert.Equal(iCloneableImplementationMethod, methodImplMethodBody.Method); Assert.Equal(implementsICloneableType, methodImplMethodBody.EnclosingType); // generic MethodImpl Method iCloneableDotGenericCloneMethod = transformResult.GetTransformedMethodDefinition(iCloneableDotGenericClone); Method iCloneableGenericImplementationMethod = transformResult.GetTransformedMethodDefinition(iCloneableGenericImplementation); QualifiedMethod methodImplGenericMethodDecl = (QualifiedMethod)implementsICloneableType.MethodImpls[1].MethodDeclaration; QualifiedMethod methodImplGenericMethodBody = (QualifiedMethod)implementsICloneableType.MethodImpls[1].MethodBody; Assert.Equal(iCloneableDotGenericCloneMethod, methodImplGenericMethodDecl.Method); Assert.Equal(iCloneableType, methodImplGenericMethodDecl.EnclosingType); Assert.Equal(iCloneableGenericImplementationMethod, methodImplGenericMethodBody.Method); Assert.Equal(implementsICloneableType, methodImplGenericMethodBody.EnclosingType); } } }
/* * 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; namespace OpenSim.Framework { // ACL Class // Modelled after the structure of the Zend ACL Framework Library // with one key difference - the tree will search for all matching // permissions rather than just the first. Deny permissions will // override all others. #region ACL Core Class /// <summary> /// Access Control List Engine /// </summary> public class ACL { private Dictionary<string, Resource> Resources = new Dictionary<string, Resource>(); private Dictionary<string, Role> Roles = new Dictionary<string, Role>(); /// <summary> /// Adds a new role /// </summary> /// <param name="role"></param> /// <returns></returns> public ACL AddRole(Role role) { if (Roles.ContainsKey(role.Name)) throw new AlreadyContainsRoleException(role); Roles.Add(role.Name, role); return this; } /// <summary> /// Adds a new resource /// </summary> /// <param name="resource"></param> /// <returns></returns> public ACL AddResource(Resource resource) { Resources.Add(resource.Name, resource); return this; } /// <summary> /// Permision for user/roll on a resource /// </summary> /// <param name="role"></param> /// <param name="resource"></param> /// <returns></returns> public Permission HasPermission(string role, string resource) { if (!Roles.ContainsKey(role)) throw new KeyNotFoundException(); if (!Resources.ContainsKey(resource)) throw new KeyNotFoundException(); return Roles[role].RequestPermission(resource); } public ACL GrantPermission(string role, string resource) { if (!Roles.ContainsKey(role)) throw new KeyNotFoundException(); if (!Resources.ContainsKey(resource)) throw new KeyNotFoundException(); Roles[role].GivePermission(resource, Permission.Allow); return this; } public ACL DenyPermission(string role, string resource) { if (!Roles.ContainsKey(role)) throw new KeyNotFoundException(); if (!Resources.ContainsKey(resource)) throw new KeyNotFoundException(); Roles[role].GivePermission(resource, Permission.Deny); return this; } public ACL ResetPermission(string role, string resource) { if (!Roles.ContainsKey(role)) throw new KeyNotFoundException(); if (!Resources.ContainsKey(resource)) throw new KeyNotFoundException(); Roles[role].GivePermission(resource, Permission.None); return this; } } #endregion #region Exceptions /// <summary> /// Thrown when an ACL attempts to add a duplicate role. /// </summary> public class AlreadyContainsRoleException : Exception { protected Role m_role; public AlreadyContainsRoleException(Role role) { m_role = role; } public Role ErrorRole { get { return m_role; } } public override string ToString() { return "This ACL already contains a role called '" + m_role.Name + "'."; } } #endregion #region Roles and Resources /// <summary> /// Does this Role have permission to access a specified Resource? /// </summary> public enum Permission { Deny, None, Allow } ; /// <summary> /// A role class, for use with Users or Groups /// </summary> public class Role { private string m_name; private Role[] m_parents; private Dictionary<string, Permission> m_resources = new Dictionary<string, Permission>(); public Role(string name) { m_name = name; m_parents = null; } public Role(string name, Role[] parents) { m_name = name; m_parents = parents; } public string Name { get { return m_name; } } public Permission RequestPermission(string resource) { return RequestPermission(resource, Permission.None); } public Permission RequestPermission(string resource, Permission current) { // Deny permissions always override any others if (current == Permission.Deny) return current; Permission temp = Permission.None; // Pickup non-None permissions if (m_resources.ContainsKey(resource) && m_resources[resource] != Permission.None) temp = m_resources[resource]; if (m_parents != null) { foreach (Role parent in m_parents) { temp = parent.RequestPermission(resource, temp); } } return temp; } public void GivePermission(string resource, Permission perm) { m_resources[resource] = perm; } } public class Resource { private string m_name; public Resource(string name) { m_name = name; } public string Name { get { return m_name; } } } #endregion #region Tests /// <summary> /// ACL Test class /// </summary> internal class ACLTester { public ACLTester() { ACL acl = new ACL(); Role Guests = new Role("Guests"); acl.AddRole(Guests); Role[] parents = new Role[0]; parents[0] = Guests; Role JoeGuest = new Role("JoeGuest", parents); acl.AddRole(JoeGuest); Resource CanBuild = new Resource("CanBuild"); acl.AddResource(CanBuild); acl.GrantPermission("Guests", "CanBuild"); acl.HasPermission("JoeGuest", "CanBuild"); } } #endregion }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans; namespace UnitTests.GrainInterfaces { public interface IGenericGrain<T, U> : IGrainWithIntegerKey { Task SetT(T a); Task<U> MapT2U(); } public interface ISimpleGenericGrain1<T> : IGrainWithIntegerKey { Task<T> GetA(); Task<string> GetAxB(); Task<string> GetAxB(T a, T b); Task SetA(T a); Task SetB(T b); } /// <summary> /// Long named grain type, which can cause issues in AzureTableStorage /// </summary> /// <typeparam name="T"></typeparam> public interface ISimpleGenericGrainUsingAzureTableStorage<T> : IGrainWithGuidKey { Task<T> EchoAsync(T entity); Task ClearState(); } /// <summary> /// Short named grain type, which shouldn't cause issues in AzureTableStorage /// </summary> /// <typeparam name="T"></typeparam> public interface ITinyNameGrain<T> : IGrainWithGuidKey { Task<T> EchoAsync(T entity); Task ClearState(); } public interface ISimpleGenericGrainU<U> : IGrainWithIntegerKey { Task<U> GetA(); Task<string> GetAxB(); Task<string> GetAxB(U a, U b); Task SetA(U a); Task SetB(U b); } public interface ISimpleGenericGrain2<T, in U> : IGrainWithIntegerKey { Task<T> GetA(); Task<string> GetAxB(); Task<string> GetAxB(T a, U b); Task SetA(T a); Task SetB(U b); } public interface IGenericGrainWithNoProperties<in T> : IGrainWithIntegerKey { Task<string> GetAxB(T a, T b); } public interface IGrainWithNoProperties : IGrainWithIntegerKey { Task<string> GetAxB(int a, int b); } public interface IGrainWithListFields : IGrainWithIntegerKey { Task AddItem(string item); Task<IList<string>> GetItems(); } public interface IGenericGrainWithListFields<T> : IGrainWithIntegerKey { Task AddItem(T item); Task<IList<T>> GetItems(); } public interface IGenericReader1<T> : IGrainWithIntegerKey { Task<T> GetValue(); } public interface IGenericWriter1<in T> : IGrainWithIntegerKey { Task SetValue(T value); } public interface IGenericReaderWriterGrain1<T> : IGenericWriter1<T>, IGenericReader1<T> { } public interface IGenericReader2<TOne, TTwo> : IGrainWithIntegerKey { Task<TOne> GetValue1(); Task<TTwo> GetValue2(); } public interface IGenericWriter2<in TOne, in TTwo> : IGrainWithIntegerKey { Task SetValue1(TOne value); Task SetValue2(TTwo value); } public interface IGenericReaderWriterGrain2<TOne, TTwo> : IGenericWriter2<TOne, TTwo>, IGenericReader2<TOne, TTwo> { } public interface IGenericReader3<TOne, TTwo, TThree> : IGenericReader2<TOne, TTwo> { Task<TThree> GetValue3(); } public interface IGenericWriter3<in TOne, in TTwo, in TThree> : IGenericWriter2<TOne, TTwo> { Task SetValue3(TThree value); } public interface IGenericReaderWriterGrain3<TOne, TTwo, TThree> : IGenericWriter3<TOne, TTwo, TThree>, IGenericReader3<TOne, TTwo, TThree> { } public interface IBasicGenericGrain<T, U> : IGrainWithIntegerKey { Task<T> GetA(); Task<string> GetAxB(); Task<string> GetAxB(T a, U b); Task SetA(T a); Task SetB(U b); } public interface IHubGrain<TKey, T1, T2> : IGrainWithIntegerKey { Task Bar(TKey key, T1 message1, T2 message2); } public interface IEchoHubGrain<TKey, TMessage> : IHubGrain<TKey, TMessage, TMessage> { Task Foo(TKey key, TMessage message, int x); Task<int> GetX(); } public interface IEchoGenericChainGrain<T> : IGrainWithIntegerKey { Task<T> Echo(T item); Task<T> Echo2(T item); Task<T> Echo3(T item); Task<T> Echo4(T item); Task<T> Echo5(T item); Task<T> Echo6(T item); } public interface INonGenericBase : IGrainWithGuidKey { Task Ping(); } public interface IGeneric1Argument<T> : IGrainWithGuidKey { Task<T> Ping(T t); } public interface IGeneric2Arguments<T, U> : IGrainWithIntegerKey { Task<Tuple<T, U>> Ping(T t, U u); } public interface IDbGrain<T> : IGrainWithIntegerKey { Task SetValue(T value); Task<T> GetValue(); } public interface IGenericPingSelf<T> : IGrainWithGuidKey { Task<T> Ping(T t); Task<T> PingSelf(T t); Task<T> PingOther(IGenericPingSelf<T> target, T t); Task<T> PingSelfThroughOther(IGenericPingSelf<T> target, T t); Task<T> GetLastValue(); Task ScheduleDelayedPing(IGenericPingSelf<T> target, T t, TimeSpan delay); Task ScheduleDelayedPingToSelfAndDeactivate(IGenericPingSelf<T> target, T t, TimeSpan delay); } public interface ILongRunningTaskGrain<T> : IGrainWithGuidKey { Task<string> GetRuntimeInstanceId(); Task LongWait(GrainCancellationToken tc, TimeSpan delay); Task<T> LongRunningTask(T t, TimeSpan delay); Task<T> CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, T t, TimeSpan delay); Task CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, GrainCancellationToken tc, TimeSpan delay); Task CallOtherLongRunningTaskWithLocalToken(ILongRunningTaskGrain<T> target, TimeSpan delay, TimeSpan delayBeforeCancel); Task<bool> CancellationTokenCallbackResolve(GrainCancellationToken tc); Task<bool> CallOtherCancellationTokenCallbackResolve(ILongRunningTaskGrain<T> target); Task CancellationTokenCallbackThrow(GrainCancellationToken tc); } public interface IGenericGrainWithConstraints<A, B, C> : IGrainWithStringKey where A : ICollection<B>, new() where B : struct where C : class { Task<int> GetCount(); Task Add(B item); Task<C> RoundTrip(C value); } public interface INonGenericCastableGrain : IGrainWithGuidKey { Task DoSomething(); } public interface IGenericCastableGrain<T> : IGrainWithGuidKey { } public interface IGrainSayingHello : IGrainWithGuidKey { Task<string> Hello(); } public interface ISomeGenericGrain<T> : IGrainSayingHello { } public interface INonGenericCastGrain : IGrainSayingHello { } public interface IIndependentlyConcretizedGrain : ISomeGenericGrain<string> { } public interface IIndependentlyConcretizedGenericGrain<T> : ISomeGenericGrain<T> { } namespace Generic.EdgeCases { public interface IBasicGrain : IGrainWithGuidKey { Task<string> Hello(); Task<string[]> ConcreteGenArgTypeNames(); } public interface IGrainWithTwoGenArgs<T1, T2> : IBasicGrain { } public interface IGrainWithThreeGenArgs<T1, T2, T3> : IBasicGrain { } public interface IGrainReceivingRepeatedGenArgs<T1, T2> : IBasicGrain { } public interface IPartiallySpecifyingInterface<T> : IGrainWithTwoGenArgs<T, int> { } public interface IReceivingRepeatedGenArgsAmongstOthers<T1, T2, T3> : IBasicGrain { } public interface IReceivingRepeatedGenArgsFromOtherInterface<T1, T2, T3> : IBasicGrain { } public interface ISpecifyingGenArgsRepeatedlyToParentInterface<T> : IReceivingRepeatedGenArgsFromOtherInterface<T, T, T> { } public interface IReceivingRearrangedGenArgs<T1, T2> : IBasicGrain { } public interface IReceivingRearrangedGenArgsViaCast<T1, T2> : IBasicGrain { } public interface ISpecifyingRearrangedGenArgsToParentInterface<T1, T2> : IReceivingRearrangedGenArgsViaCast<T2, T1> { } public interface IArbitraryInterface<T1, T2> : IBasicGrain { } public interface IInterfaceUnrelatedToConcreteGenArgs<T> : IBasicGrain { } public interface IInterfaceTakingFurtherSpecializedGenArg<T> : IBasicGrain { } public interface IAnotherReceivingFurtherSpecializedGenArg<T> : IBasicGrain { } public interface IYetOneMoreReceivingFurtherSpecializedGenArg<T> : IBasicGrain { } } }
/* * 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; using System.Collections.Generic; using System.Reflection; using Nwc.XmlRpc; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; private bool m_connectorEnabled = false; private string m_serviceURL = string.Empty; private bool m_disableKeepAlive = false; private string m_groupReadKey = string.Empty; private string m_groupWriteKey = string.Empty; #region IRegionModuleBase Members public string Name { get { return "XmlRpcGroupsServicesConnector"; } } // this module is not intended to be replaced, but there should only be 1 of them. public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("ServicesConnectorModule", "Default") != Name)) { m_connectorEnabled = false; return; } m_log.InfoFormat("[GROUPS-CONNECTOR]: Initializing {0}", this.Name); m_serviceURL = groupsConfig.GetString("XmlRpcServiceURL", string.Empty); if ((m_serviceURL == null) || (m_serviceURL == string.Empty)) { m_log.ErrorFormat("Please specify a valid URL for XmlRpcServiceURL in OpenSim.ini, [Groups]"); m_connectorEnabled = false; return; } m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false); m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty); m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty); // If we got all the config options we need, lets start'er'up m_connectorEnabled = true; } } public void Close() { m_log.InfoFormat("[GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (m_connectorEnabled) scene.RegisterModuleInterface<IGroupsServicesConnector>(this); } public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this) scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); } public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene) { // TODO: May want to consider listenning for Agent Connections so we can pre-cache group info // scene.EventManager.OnNewClient += OnNewClient; } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region IGroupsServicesConnector Members /// <summary> /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// </summary> public UUID CreateGroup(GroupRequestID requestID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { UUID GroupID = UUID.Random(); UUID OwnerRoleID = UUID.Random(); Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); param["Name"] = name; param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = 0; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; param["FounderID"] = founderID.ToString(); param["EveryonePowers"] = ((ulong)m_DefaultEveryonePowers).ToString(); param["OwnerRoleID"] = OwnerRoleID.ToString(); // Would this be cleaner as (GroupPowers)ulong.MaxValue; GroupPowers OwnerPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AllowSetHome | GroupPowers.AllowVoiceChat | GroupPowers.AssignMember | GroupPowers.AssignMemberLimited | GroupPowers.ChangeActions | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.CreateRole | GroupPowers.DeedObject | GroupPowers.DeleteRole | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.JoinChat | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReceiveNotices | GroupPowers.RemoveMember | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; param["OwnersPowers"] = ((ulong)OwnerPowers).ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.createGroup", param); if (respData.Contains("error")) { // UUID is not nullable return UUID.Zero; } return UUID.Parse((string)respData["GroupID"]); } public void UpdateGroup(GroupRequestID requestID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = membershipFee; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; XmlRpcCall(requestID, "groups.updateGroup", param); } public void AddGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); param["Name"] = name; param["Description"] = description; param["Title"] = title; param["Powers"] = powers.ToString(); XmlRpcCall(requestID, "groups.addRoleToGroup", param); } public void RemoveGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); XmlRpcCall(requestID, "groups.removeRoleFromGroup", param); } public void UpdateGroupRole(GroupRequestID requestID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); if (name != null) { param["Name"] = name; } if (description != null) { param["Description"] = description; } if (title != null) { param["Title"] = title; } param["Powers"] = powers.ToString(); XmlRpcCall(requestID, "groups.updateGroupRole", param); } public GroupRecord GetGroupRecord(GroupRequestID requestID, UUID GroupID, string GroupName) { Hashtable param = new Hashtable(); if (GroupID != UUID.Zero) { param["GroupID"] = GroupID.ToString(); } if ((GroupName != null) && (GroupName != string.Empty)) { param["Name"] = GroupName.ToString(); } Hashtable respData = XmlRpcCall(requestID, "groups.getGroup", param); if (respData.Contains("error")) { return null; } return GroupProfileHashtableToGroupRecord(respData); } public GroupProfileData GetMemberGroupProfile(GroupRequestID requestID, UUID GroupID, UUID AgentID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroup", param); if (respData.Contains("error")) { // GroupProfileData is not nullable return new GroupProfileData(); } GroupMembershipData MemberInfo = GetAgentGroupMembership(requestID, AgentID, GroupID); GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData); MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; return MemberGroupProfile; } public void SetAgentActiveGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestID, "groups.setAgentActiveGroup", param); } public void SetAgentActiveGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["SelectedRoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.setAgentGroupInfo", param); } public void SetAgentGroupInfo(GroupRequestID requestID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["AcceptNotices"] = AcceptNotices ? "1" : "0"; param["ListInProfile"] = ListInProfile ? "1" : "0"; XmlRpcCall(requestID, "groups.setAgentGroupInfo", param); } public void AddAgentToGroupInvite(GroupRequestID requestID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); param["AgentID"] = agentID.ToString(); param["RoleID"] = roleID.ToString(); param["GroupID"] = groupID.ToString(); XmlRpcCall(requestID, "groups.addAgentToGroupInvite", param); } public GroupInviteInfo GetAgentToGroupInvite(GroupRequestID requestID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentToGroupInvite", param); if (respData.Contains("error")) { return null; } GroupInviteInfo inviteInfo = new GroupInviteInfo(); inviteInfo.InviteID = inviteID; inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]); inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]); inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]); return inviteInfo; } public void RemoveAgentToGroupInvite(GroupRequestID requestID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); XmlRpcCall(requestID, "groups.removeAgentToGroupInvite", param); } public void AddAgentToGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.addAgentToGroup", param); } public void RemoveAgentFromGroup(GroupRequestID requestID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestID, "groups.removeAgentFromGroup", param); } public void AddAgentToGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.addAgentToGroupRole", param); } public void RemoveAgentFromGroupRole(GroupRequestID requestID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestID, "groups.removeAgentFromGroupRole", param); } public List<DirGroupsReplyData> FindGroups(GroupRequestID requestID, string search) { Hashtable param = new Hashtable(); param["Search"] = search; Hashtable respData = XmlRpcCall(requestID, "groups.findGroups", param); List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>(); if (!respData.Contains("error")) { Hashtable results = (Hashtable)respData["results"]; foreach (Hashtable groupFind in results.Values) { DirGroupsReplyData data = new DirGroupsReplyData(); data.groupID = new UUID((string)groupFind["GroupID"]); ; data.groupName = (string)groupFind["Name"]; data.members = int.Parse((string)groupFind["Members"]); // data.searchOrder = order; findings.Add(data); } } return findings; } public GroupMembershipData GetAgentGroupMembership(GroupRequestID requestID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentGroupMembership", param); if (respData.Contains("error")) { return null; } GroupMembershipData data = HashTableToGroupMembershipData(respData); return data; } public GroupMembershipData GetAgentActiveMembership(GroupRequestID requestID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentActiveMembership", param); if (respData.Contains("error")) { return null; } return HashTableToGroupMembershipData(respData); } public List<GroupMembershipData> GetAgentGroupMemberships(GroupRequestID requestID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentGroupMemberships", param); List<GroupMembershipData> memberships = new List<GroupMembershipData>(); if (!respData.Contains("error")) { foreach (object membership in respData.Values) { memberships.Add(HashTableToGroupMembershipData((Hashtable)membership)); } } return memberships; } public List<GroupRolesData> GetAgentGroupRoles(GroupRequestID requestID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getAgentRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.RoleID = new UUID((string)role["RoleID"]); data.Name = (string)role["Name"]; data.Description = (string)role["Description"]; data.Powers = ulong.Parse((string)role["Powers"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } public List<GroupRolesData> GetGroupRoles(GroupRequestID requestID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.Description = (string)role["Description"]; data.Members = int.Parse((string)role["Members"]); data.Name = (string)role["Name"]; data.Powers = ulong.Parse((string)role["Powers"]); data.RoleID = new UUID((string)role["RoleID"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } public List<GroupMembersData> GetGroupMembers(GroupRequestID requestID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupMembers", param); List<GroupMembersData> members = new List<GroupMembersData>(); if (respData.Contains("error")) { return members; } foreach (Hashtable membership in respData.Values) { GroupMembersData data = new GroupMembersData(); data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1"; data.AgentID = new UUID((string)membership["AgentID"]); data.Contribution = int.Parse((string)membership["Contribution"]); data.IsOwner = ((string)membership["IsOwner"]) == "1"; data.ListInProfile = ((string)membership["ListInProfile"]) == "1"; data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]); data.Title = (string)membership["Title"]; members.Add(data); } return members; } public List<GroupRoleMembersData> GetGroupRoleMembers(GroupRequestID requestID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupRoleMembers", param); List<GroupRoleMembersData> members = new List<GroupRoleMembersData>(); if (!respData.Contains("error")) { foreach (Hashtable membership in respData.Values) { GroupRoleMembersData data = new GroupRoleMembersData(); data.MemberID = new UUID((string)membership["AgentID"]); data.RoleID = new UUID((string)membership["RoleID"]); members.Add(data); } } return members; } public List<GroupNoticeData> GetGroupNotices(GroupRequestID requestID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupNotices", param); List<GroupNoticeData> values = new List<GroupNoticeData>(); if (!respData.Contains("error")) { foreach (Hashtable value in respData.Values) { GroupNoticeData data = new GroupNoticeData(); data.NoticeID = UUID.Parse((string)value["NoticeID"]); data.Timestamp = uint.Parse((string)value["Timestamp"]); data.FromName = (string)value["FromName"]; data.Subject = (string)value["Subject"]; data.HasAttachment = false; data.AssetType = 0; values.Add(data); } } return values; } public GroupNoticeInfo GetGroupNotice(GroupRequestID requestID, UUID noticeID) { Hashtable param = new Hashtable(); param["NoticeID"] = noticeID.ToString(); Hashtable respData = XmlRpcCall(requestID, "groups.getGroupNotice", param); if (respData.Contains("error")) { return null; } GroupNoticeInfo data = new GroupNoticeInfo(); data.GroupID = UUID.Parse((string)respData["GroupID"]); data.Message = (string)respData["Message"]; data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true); data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]); data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]); data.noticeData.FromName = (string)respData["FromName"]; data.noticeData.Subject = (string)respData["Subject"]; data.noticeData.HasAttachment = false; data.noticeData.AssetType = 0; if (data.Message == null) { data.Message = string.Empty; } return data; } public void AddGroupNotice(GroupRequestID requestID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket) { string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, ""); Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["NoticeID"] = noticeID.ToString(); param["FromName"] = fromName; param["Subject"] = subject; param["Message"] = message; param["BinaryBucket"] = binBucket; param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString(); XmlRpcCall(requestID, "groups.addGroupNotice", param); } #endregion #region XmlRpcHashtableMarshalling private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile) { GroupProfileData group = new GroupProfileData(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.Name = (string)groupProfile["Name"]; if (groupProfile["Charter"] != null) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]); group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]); group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]); return group; } private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile) { GroupRecord group = new GroupRecord(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.GroupName = groupProfile["Name"].ToString(); if (groupProfile["Charter"] != null) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]); return group; } private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData) { GroupMembershipData data = new GroupMembershipData(); data.AcceptNotices = ((string)respData["AcceptNotices"] == "1"); data.Contribution = int.Parse((string)respData["Contribution"]); data.ListInProfile = ((string)respData["ListInProfile"] == "1"); data.ActiveRole = new UUID((string)respData["SelectedRoleID"]); data.GroupTitle = (string)respData["Title"]; data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]); // Is this group the agent's active group data.GroupID = new UUID((string)respData["GroupID"]); UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]); data.Active = data.GroupID.Equals(ActiveGroup); data.AllowPublish = ((string)respData["AllowPublish"] == "1"); if (respData["Charter"] != null) { data.Charter = (string)respData["Charter"]; } data.FounderID = new UUID((string)respData["FounderID"]); data.GroupID = new UUID((string)respData["GroupID"]); data.GroupName = (string)respData["GroupName"]; data.GroupPicture = new UUID((string)respData["InsigniaID"]); data.MaturePublish = ((string)respData["MaturePublish"] == "1"); data.MembershipFee = int.Parse((string)respData["MembershipFee"]); data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1"); data.ShowInList = ((string)respData["ShowInList"] == "1"); return data; } #endregion /// <summary> /// Encapsulate the XmlRpc call to standardize security and error handling. /// </summary> private Hashtable XmlRpcCall(GroupRequestID requestID, string function, Hashtable param) { if (requestID == null) { requestID = new GroupRequestID(); } param.Add("RequestingAgentID", requestID.AgentID.ToString()); param.Add("RequestingAgentUserService", requestID.UserServiceURL); param.Add("RequestingSessionID", requestID.SessionID.ToString()); param.Add("ReadKey", m_groupReadKey); param.Add("WriteKey", m_groupWriteKey); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req; if (!m_disableKeepAlive) { req = new XmlRpcRequest(function, parameters); } else { // This seems to solve a major problem on some windows servers req = new NoKeepAliveXmlRpcRequest(function, parameters); } XmlRpcResponse resp = null; try { resp = req.Send(m_serviceURL, 10000); } catch (Exception e) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: An error has occured while attempting to access the XmlRpcGroups server method: {0}", function); m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} ", e.ToString()); foreach (string key in param.Keys) { m_log.WarnFormat("[XMLRPCGROUPDATA]: {0} :: {1}", key, param[key].ToString()); } Hashtable respData = new Hashtable(); respData.Add("error", e.ToString()); return respData; } if (resp.Value is Hashtable) { Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error") && !respData.Contains("succeed")) { LogRespDataToConsoleError(respData); } return respData; } m_log.ErrorFormat("[XMLRPCGROUPDATA]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString()); if (resp.Value is ArrayList) { ArrayList al = (ArrayList)resp.Value; m_log.ErrorFormat("[XMLRPCGROUPDATA]: Contains {0} elements", al.Count); foreach (object o in al) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} :: {1}", o.GetType().ToString(), o.ToString()); } } else { m_log.ErrorFormat("[XMLRPCGROUPDATA]: Function returned: {0}", resp.Value.ToString()); } Hashtable error = new Hashtable(); error.Add("error", "invalid return value"); return error; } private void LogRespDataToConsoleError(Hashtable respData) { m_log.Error("[XMLRPCGROUPDATA]: Error:"); foreach (string key in respData.Keys) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: Key: {0}", key); string[] lines = respData[key].ToString().Split(new char[] { '\n' }); foreach (string line in lines) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0}", line); } } } } public class GroupNoticeInfo { public GroupNoticeData noticeData = new GroupNoticeData(); public UUID GroupID = UUID.Zero; public string Message = string.Empty; public byte[] BinaryBucket = new byte[0]; } } namespace Nwc.XmlRpc { using System; using System.Collections; using System.IO; using System.Xml; using System.Net; using System.Text; using System.Reflection; /// <summary>Class supporting the request side of an XML-RPC transaction.</summary> public class NoKeepAliveXmlRpcRequest : XmlRpcRequest { private Encoding _encoding = new ASCIIEncoding(); private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer(); private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer(); /// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary> /// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request /// should be directed to.</param> /// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param> public NoKeepAliveXmlRpcRequest(String methodName, IList parameters) { MethodName = methodName; _params = parameters; } /// <summary>Send the request to the server.</summary> /// <param name="url"><c>String</c> The url of the XML-RPC server.</param> /// <returns><c>XmlRpcResponse</c> The response generated.</returns> public XmlRpcResponse Send(String url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (request == null) throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR, XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url); request.Method = "POST"; request.ContentType = "text/xml"; request.AllowWriteStreamBuffering = true; request.KeepAlive = false; Stream stream = request.GetRequestStream(); XmlTextWriter xml = new XmlTextWriter(stream, _encoding); _serializer.Serialize(xml, this); xml.Flush(); xml.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader input = new StreamReader(response.GetResponseStream()); XmlRpcResponse resp = (XmlRpcResponse)_deserializer.Deserialize(input); input.Close(); response.Close(); return resp; } } }
/* ----------------------------------------------------------------------------- * Rule_userinfo.cs * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Sat Dec 18 07:35:23 GMT 2021 * * ----------------------------------------------------------------------------- */ using System; using System.Collections.Generic; sealed internal class Rule_userinfo:Rule { private Rule_userinfo(String spelling, List<Rule> rules) : base(spelling, rules) { } internal override Object Accept(Visitor visitor) { return visitor.Visit(this); } public static Rule_userinfo Parse(ParserContext context) { context.Push("userinfo"); Rule rule; bool parsed = true; ParserAlternative b; int s0 = context.index; ParserAlternative a0 = new ParserAlternative(s0); List<ParserAlternative> as1 = new List<ParserAlternative>(); parsed = false; { int s1 = context.index; ParserAlternative a1 = new ParserAlternative(s1); parsed = true; if (parsed) { bool f1 = true; int c1 = 0; while (f1) { int g1 = context.index; List<ParserAlternative> as2 = new List<ParserAlternative>(); parsed = false; { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Rule_unreserved.Parse(context); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Rule_pct_encoded.Parse(context); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Rule_sub_delims.Parse(context); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { bool f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { rule = Terminal_StringValue.Parse(context, ":"); if ((f2 = rule != null)) { a2.Add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { as2.Add(a2); } context.index = s2; } b = ParserAlternative.GetBest(as2); parsed = b != null; if (parsed) { a1.Add(b.rules, b.end); context.index = b.end; } f1 = context.index > g1; if (parsed) c1++; } parsed = true; } if (parsed) { as1.Add(a1); } context.index = s1; } b = ParserAlternative.GetBest(as1); parsed = b != null; if (parsed) { a0.Add(b.rules, b.end); context.index = b.end; } rule = null; if (parsed) { rule = new Rule_userinfo(context.text.Substring(a0.start, a0.end - a0.start), a0.rules); } else { context.index = s0; } context.Pop("userinfo", parsed); return (Rule_userinfo)rule; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion //------------------------------------------------------------------------------------------------- // <auto-generated> // Marked as auto-generated so StyleCop will ignore BDD style tests // </auto-generated> //------------------------------------------------------------------------------------------------- #pragma warning disable 169 // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace RedBadger.Xpf.Specs.RectSpecs { using System; using Machine.Specifications; using RedBadger.Xpf.Internal; [Subject(typeof(Rect))] public class when_constructed { private static Rect subject; private Establish context = () => subject = new Rect(); private It should_have_a_position_at_zero_zero = () => subject.Location.ShouldEqual(new Point(0, 0)); private It should_have_a_size_of_zero_zero = () => subject.Size.ShouldEqual(new Size(0, 0)); private It should_not_be_equal_to_an_empty_rect = () => subject.ShouldNotEqual(Rect.Empty); private It should_not_say_it_is_empty = () => subject.IsEmpty.ShouldBeFalse(); } [Subject(typeof(Rect))] public class when_constructed_with_an_X_a_Y_a_Width_and_a_Height { private const double Height = 10; private const double Width = 20; private const double X = 5; private const double Y = 15; private static Rect subject; private Establish context = () => subject = new Rect(X, Y, Width, Height); private It should_1_have_a_correct_left_side = () => subject.Left.ShouldEqual(5); private It should_2_have_a_correct_top_side = () => subject.Top.ShouldEqual(15); private It should_3_have_a_correct_right_side = () => subject.Right.ShouldEqual(25); private It should_4_have_a_correct_bottom_side = () => subject.Bottom.ShouldEqual(25); private It should_have_the_expected_location = () => subject.Location.ShouldEqual(new Point(X, Y)); private It should_have_the_expected_size = () => subject.Size.ShouldEqual(new Size(Width, Height)); } [Subject(typeof(Rect))] public class when_constructed_with_a_size { private static readonly Size size = new Size(10, 20); private static Rect subject; private Because of = () => subject = new Rect(size); private It should_have_a_position_at_zero_zero = () => subject.Location.ShouldEqual(new Point(0, 0)); private It should_have_a_size_equal_to_the_specified_size = () => subject.Size.ShouldEqual(size); } [Subject(typeof(Rect))] public class when_constructed_with_a_position_and_a_size { private static readonly Point location = new Point(10, 20); private static readonly Size size = new Size(10, 20); private static Rect subject; private Because of = () => subject = new Rect(location, size); private It should_have_a_location_equal_to_the_specified_location = () => subject.Location.ShouldEqual(location); private It should_have_a_size_equal_to_the_specified_size = () => subject.Size.ShouldEqual(size); } [Subject(typeof(Rect))] public class when_a_rect_is_constructed_from_two_points { private static readonly Point point1 = new Point(10, 20); private static readonly Point point2 = new Point(30, 40); private static Rect subject; private Because of = () => subject = new Rect(point1, point2); private It should_contain_point_one = () => subject.Contains(point1).ShouldBeTrue(); private It should_contain_point_two = () => subject.Contains(point2).ShouldBeTrue(); private It should_encompass_the_two_points = () => subject.ShouldEqual(new Rect(10, 20, 20, 20)); } [Subject(typeof(Rect))] public class when_two_rects_are_equal { private static Rect rect; private static bool result; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); rect = new Rect(10, 20, 30, 40); }; private Because of = () => result = subject == rect; private It should_show_them_as_equal = () => result.ShouldBeTrue(); } [Subject(typeof(Rect))] public class when_two_rects_are_not_equal_in_the_x { private static Rect rect; private static bool result; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); rect = new Rect(11, 20, 30, 40); }; private Because of = () => result = subject == rect; private It should_show_them_as_not_equal = () => result.ShouldBeFalse(); } [Subject(typeof(Rect))] public class when_two_rects_are_not_equal_in_the_y { private static Rect rect; private static bool result; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); rect = new Rect(10, 21, 30, 40); }; private Because of = () => result = rect == subject; private It should_show_them_as_not_equal = () => result.ShouldBeFalse(); } [Subject(typeof(Rect))] public class when_two_rects_are_not_equal_in_the_width { private static Rect rect; private static bool result; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); rect = new Rect(10, 20, 31, 40); }; private Because of = () => result = rect == subject; private It should_show_them_as_not_equal = () => result.ShouldBeFalse(); } [Subject(typeof(Rect))] public class when_two_rects_are_not_equal_in_the_height { private static Rect rect; private static bool result; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); rect = new Rect(10, 20, 30, 41); }; private Because of = () => result = rect == subject; private It should_show_them_as_not_equal = () => result.ShouldBeFalse(); } [Subject(typeof(Rect))] public class when_a_Rect_is_displaced_by_a_vector { private static Rect subject; private static Vector vector; private Establish context = () => { subject = new Rect(10, 20, 30, 40); vector = new Vector(1, 2); }; private Because of = () => subject.Displace(vector); private It should_displace_the_rect_by_the_vector = () => subject.ShouldEqual(new Rect(11, 22, 30, 40)); } [Subject(typeof(Rect))] public class when_an_empty_Rect_is_displaced_by_a_vector { private static Rect subject; private static Vector vector; private Establish context = () => { subject = Rect.Empty; vector = new Vector(1, 2); }; private Because of = () => subject.Displace(vector); private It should_not_displace_the_rect = () => subject.IsEmpty.ShouldBeTrue(); } [Subject(typeof(Rect))] public class when_an_empty_rect_is_requested { private static Rect subject; private Because of = () => subject = Rect.Empty; private It should_have_a_height_of_negative_infinity = () => subject.Height.ShouldEqual(Double.NegativeInfinity); private It should_have_a_width_of_negative_infinity = () => subject.Width.ShouldEqual(Double.NegativeInfinity); private It should_have_an_x_location_of_infinity = () => subject.X.ShouldEqual(Double.PositiveInfinity); private It should_have_an_y_location_of_infinity = () => subject.Y.ShouldEqual(Double.PositiveInfinity); } [Subject(typeof(Rect))] public class when_an_empty_rect_is_asked_if_it_is_empty { private static Rect subject; private Because of = () => subject = Rect.Empty; private It should_return_true = () => subject.IsEmpty.ShouldBeTrue(); } [Subject(typeof(Rect))] public class when_a_rect_is_asked_if_it_contains_a_point_that_is_inside_its_boundary { private static bool result; private static Rect subject; private Establish context = () => subject = new Rect(0, 0, 100, 100); private Because of = () => result = subject.Contains(new Point(50, 50)); private It should_return_true = () => result.ShouldBeTrue(); } [Subject(typeof(Rect))] public class when_a_rect_is_asked_if_it_contains_a_point_that_is_outside_its_boundary { private static bool result; private static Rect subject; private Establish context = () => subject = new Rect(0, 0, 100, 100); private Because of = () => result = subject.Contains(new Point(150, 50)); private It should_return_true = () => result.ShouldBeFalse(); } [Subject(typeof(Rect))] public class when_a_rect_is_unioned_with_another_rect { private static Rect anotherRect; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); anotherRect = new Rect(20, 30, 40, 50); }; private Because of = () => subject.Union(anotherRect); private It should_encompass_both_rects = () => subject.ShouldEqual(new Rect(10, 20, 50, 60)); } [Subject(typeof(Rect))] public class when_a_rect_is_unioned_with_a_point { private static Point point; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); point = new Point(80, 100); }; private Because of = () => subject.Union(point); private It should_encompass_both_rects = () => subject.ShouldEqual(new Rect(10, 20, 70, 80)); } [Subject(typeof(Rect))] public class when_a_rect_is_asked_if_it_intersects_with_another_rect_that_it_instersects_with { private static Rect anotherRect; private static bool result; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); anotherRect = new Rect(30, 40, 50, 60); }; private Because of = () => result = subject.IntersectsWith(anotherRect); private It should_return_true = () => result.ShouldBeTrue(); } [Subject(typeof(Rect))] public class when_a_rect_is_asked_if_it_intersects_with_another_rect_that_it_doesnt_instersect_with { private static Rect anotherRect; private static bool result; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); anotherRect = new Rect(130, 140, 150, 160); }; private Because of = () => result = subject.IntersectsWith(anotherRect); private It should_return_true = () => result.ShouldBeFalse(); } [Subject(typeof(Rect))] public class when_a_rect_is_intersected_with_another_rect { private static Rect anotherRect; private static Rect subject; private Establish context = () => { subject = new Rect(10, 20, 30, 40); anotherRect = new Rect(30, 40, 50, 60); }; private Because of = () => subject.Intersect(anotherRect); private It should_return_true = () => subject.ShouldEqual(new Rect(30, 40, 10, 20)); } [Subject(typeof(Rect))] public class when_a_rect_is_deflated_by_a_thickness { private static readonly Thickness thickness = new Thickness(1, 2, 3, 4); private static Rect result; private static Rect subject; private Establish context = () => subject = new Rect(10, 20, 30, 40); private Because of = () => result = subject.Deflate(thickness); private It should_reduce_the_rect_by_the_correct_amount = () => result.ShouldEqual(new Rect(11, 22, 26, 34)); } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class MultiWayConditionalControlOperator : ConditionalControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private BasicBlock[] m_targets; // // Constructor Methods // private MultiWayConditionalControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static MultiWayConditionalControlOperator New( Debugging.DebugInfo debugInfo , Expression rhs , BasicBlock targetNotTaken , BasicBlock[] targets ) { MultiWayConditionalControlOperator res = new MultiWayConditionalControlOperator( debugInfo ); res.SetRhs( rhs ); res.m_targetBranchNotTaken = targetNotTaken; res.m_targets = targets; return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new MultiWayConditionalControlOperator( m_debugInfo ) ); } protected override void CloneState( CloningContext context , Operator clone ) { MultiWayConditionalControlOperator clone2 = (MultiWayConditionalControlOperator)clone; clone2.m_targets = context.Clone( m_targets ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_targets ); context.Pop(); } //--// protected override void UpdateSuccessorInformation() { base.UpdateSuccessorInformation(); foreach(BasicBlock target in m_targets) { m_basicBlock.LinkToNormalBasicBlock( target ); } } public override bool ShouldIncludeInScheduling( BasicBlock bbNext ) { if(base.ShouldIncludeInScheduling( bbNext ) == false) { return false; } return m_targetBranchNotTaken == bbNext; } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { bool fChanged = base.SubstituteTarget( oldBB, newBB ); BasicBlock[] targets = m_targets; for(int pos = targets.Length; --pos >=0; ) { if(targets[pos] == oldBB) { if(m_targets == targets) { targets = ArrayUtility.CopyNotNullArray( m_targets ); } targets[pos] = newBB; } } if(m_targets != targets) { BumpVersion(); m_targets = targets; fChanged = true; } return fChanged; } //--// public override bool Simplify( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { if(base.Simplify( defChains, useChains, properties )) { return true; } var exConst = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(exConst != null && exConst.IsValueInteger) { ulong val; if(exConst.GetAsRawUlong( out val )) { BasicBlock branch; if(val >= (ulong)m_targets.Length) { branch = m_targetBranchNotTaken; } else { branch = m_targets[(int)val]; } UnconditionalControlOperator opNew = UnconditionalControlOperator.New( this.DebugInfo, branch ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } } return false; } //--// // // Access Methods // public BasicBlock[] Targets { get { return m_targets; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "MultiWayConditionalControlOperator(" ); base.InnerToString( sb ); sb.Append( " Targets: ( " ); for(int i = 0; i < m_targets.Length; i++) { if(i != 0) sb.Append( ", " ); sb.Append( m_targets[i].SpanningTreeIndex ); } sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for(int i = 0; i < m_targets.Length; i++) { BasicBlock bb = m_targets[i]; if(i != 0) sb.Append( ", " ); sb.AppendFormat( "{0}", dumper.CreateLabel( bb ) ); } return dumper.FormatOutput( "switch {0} to {1}\n" + "goto {2}", this.FirstArgument, sb.ToString(), m_targetBranchNotTaken ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Security.Principal; namespace System.DirectoryServices.AccountManagement { [DirectoryRdnPrefix("CN")] public class UserPrincipal : AuthenticablePrincipal { // // Public constructors // public UserPrincipal(PrincipalContext context) : base(context) { if (context == null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; this.unpersisted = true; } public UserPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { if (samAccountName == null || password == null) throw new ArgumentException(SR.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) this.SamAccountName = samAccountName; this.Name = samAccountName; this.SetPassword(password); this.Enabled = enabled; } // // Public properties // // GivenName private string _givenName = null; // the actual property value private LoadState _givenNameChanged = LoadState.NotSet; // change-tracking public string GivenName { get { return HandleGet<string>(ref _givenName, PropertyNames.UserGivenName, ref _givenNameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserGivenName)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _givenName, value, ref _givenNameChanged, PropertyNames.UserGivenName); } } // MiddleName private string _middleName = null; // the actual property value private LoadState _middleNameChanged = LoadState.NotSet; // change-tracking public string MiddleName { get { return HandleGet<string>(ref _middleName, PropertyNames.UserMiddleName, ref _middleNameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserMiddleName)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _middleName, value, ref _middleNameChanged, PropertyNames.UserMiddleName); } } // Surname private string _surname = null; // the actual property value private LoadState _surnameChanged = LoadState.NotSet; // change-tracking public string Surname { get { return HandleGet<string>(ref _surname, PropertyNames.UserSurname, ref _surnameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserSurname)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _surname, value, ref _surnameChanged, PropertyNames.UserSurname); } } // EmailAddress private string _emailAddress = null; // the actual property value private LoadState _emailAddressChanged = LoadState.NotSet; // change-tracking public string EmailAddress { get { return HandleGet<string>(ref _emailAddress, PropertyNames.UserEmailAddress, ref _emailAddressChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmailAddress)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _emailAddress, value, ref _emailAddressChanged, PropertyNames.UserEmailAddress); } } // VoiceTelephoneNumber private string _voiceTelephoneNumber = null; // the actual property value private LoadState _voiceTelephoneNumberChanged = LoadState.NotSet; // change-tracking public string VoiceTelephoneNumber { get { return HandleGet<string>(ref _voiceTelephoneNumber, PropertyNames.UserVoiceTelephoneNumber, ref _voiceTelephoneNumberChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserVoiceTelephoneNumber)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _voiceTelephoneNumber, value, ref _voiceTelephoneNumberChanged, PropertyNames.UserVoiceTelephoneNumber); } } // EmployeeId private string _employeeID = null; // the actual property value private LoadState _employeeIDChanged = LoadState.NotSet; // change-tracking public string EmployeeId { get { return HandleGet<string>(ref _employeeID, PropertyNames.UserEmployeeID, ref _employeeIDChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmployeeID)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _employeeID, value, ref _employeeIDChanged, PropertyNames.UserEmployeeID); } } public override AdvancedFilters AdvancedSearchFilter { get { return rosf; } } public static UserPrincipal Current { get { PrincipalContext context; // Get the correct PrincipalContext to query against, depending on whether we're running // as a local or domain user if (Utils.IsSamUser()) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is local user"); #if PAPI_REGSAM context = new PrincipalContext(ContextType.Machine); #else // This implementation doesn't support Reg-SAM/MSAM (machine principals) throw new NotSupportedException(SR.UserLocalNotSupportedOnPlatform); #endif // PAPI_REGSAM } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is not local user"); #if PAPI_AD context = new PrincipalContext(ContextType.Domain); #else // This implementation doesn't support AD (domain principals) throw new NotSupportedException(SR.UserDomainNotSupportedOnPlatform); #endif // PAPI_AD } // Construct a query for the current user, using a SID IdentityClaim IntPtr pSid = IntPtr.Zero; UserPrincipal user = null; try { pSid = Utils.GetCurrentUserSid(); byte[] sid = Utils.ConvertNativeSidToByteArray(pSid); SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: using SID " + sidObj.ToString()); user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, sidObj.ToString()); } finally { if (pSid != IntPtr.Zero) System.Runtime.InteropServices.Marshal.FreeHGlobal(pSid); } // We're running as the user, we know they must exist, but perhaps we don't have access // to their user object if (user == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "User", "Current: found no user"); throw new NoMatchingPrincipalException(SR.UserCouldNotFindCurrent); } return user; } } // // Public methods // public static new PrincipalSearchResult<UserPrincipal> FindByLockoutTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLockoutTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLogonTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type) { return FindByExpirationTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type) { return FindByBadPasswordAttempt<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type) { return FindByPasswordSetTime<UserPrincipal>(context, time, type); } public static new UserPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityValue); } public static new UserPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityType, identityValue); } public PrincipalSearchResult<Principal> GetAuthorizationGroups() { return new PrincipalSearchResult<Principal>(GetAuthorizationGroupsHelper()); } // // Internal "constructor": Used for constructing Users returned by a query // internal static UserPrincipal MakeUser(PrincipalContext ctx) { UserPrincipal u = new UserPrincipal(ctx); u.unpersisted = false; return u; } // // Private implementation // private ResultSet GetAuthorizationGroupsHelper() { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); // Unpersisted principals are not members of any group if (this.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: unpersisted, using EmptySet"); return new EmptySet(); } StoreCtx storeCtx = GetStoreCtxToUse(); Debug.Assert(storeCtx != null); GlobalDebug.WriteLineIf( GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: retrieving AZ groups from StoreCtx of type=" + storeCtx.GetType().ToString() + ", base path=" + storeCtx.BasePath); ResultSet resultSet = storeCtx.GetGroupsMemberOfAZ(this); return resultSet; } // // Load/Store implementation // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { if (value == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value= null"); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString()); } switch (propertyName) { case (PropertyNames.UserGivenName): _givenName = (string)value; _givenNameChanged = LoadState.Loaded; break; case (PropertyNames.UserMiddleName): _middleName = (string)value; _middleNameChanged = LoadState.Loaded; break; case (PropertyNames.UserSurname): _surname = (string)value; _surnameChanged = LoadState.Loaded; break; case (PropertyNames.UserEmailAddress): _emailAddress = (string)value; _emailAddressChanged = LoadState.Loaded; break; case (PropertyNames.UserVoiceTelephoneNumber): _voiceTelephoneNumber = (string)value; _voiceTelephoneNumberChanged = LoadState.Loaded; break; case (PropertyNames.UserEmployeeID): _employeeID = (string)value; _employeeIDChanged = LoadState.Loaded; break; default: base.LoadValueIntoProperty(propertyName, value); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetChangeStatusForProperty: name=" + propertyName); return propertyName switch { PropertyNames.UserGivenName => _givenNameChanged == LoadState.Changed, PropertyNames.UserMiddleName => _middleNameChanged == LoadState.Changed, PropertyNames.UserSurname => _surnameChanged == LoadState.Changed, PropertyNames.UserEmailAddress => _emailAddressChanged == LoadState.Changed, PropertyNames.UserVoiceTelephoneNumber => _voiceTelephoneNumberChanged == LoadState.Changed, PropertyNames.UserEmployeeID => _employeeIDChanged == LoadState.Changed, _ => base.GetChangeStatusForProperty(propertyName), }; } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetValueForProperty: name=" + propertyName); return propertyName switch { PropertyNames.UserGivenName => _givenName, PropertyNames.UserMiddleName => _middleName, PropertyNames.UserSurname => _surname, PropertyNames.UserEmailAddress => _emailAddress, PropertyNames.UserVoiceTelephoneNumber => _voiceTelephoneNumber, PropertyNames.UserEmployeeID => _employeeID, _ => base.GetValueForProperty(propertyName), }; } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "ResetAllChangeStatus"); _givenNameChanged = (_givenNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _middleNameChanged = (_middleNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _surnameChanged = (_surnameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _emailAddressChanged = (_emailAddressChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _voiceTelephoneNumberChanged = (_voiceTelephoneNumberChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _employeeIDChanged = (_employeeIDChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; base.ResetAllChangeStatus(); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>AccessibleBiddingStrategy</c> resource.</summary> public sealed partial class AccessibleBiddingStrategyName : gax::IResourceName, sys::IEquatable<AccessibleBiddingStrategyName> { /// <summary>The possible contents of <see cref="AccessibleBiddingStrategyName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> CustomerBiddingStrategy = 1, } private static gax::PathTemplate s_customerBiddingStrategy = new gax::PathTemplate("customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}"); /// <summary> /// Creates a <see cref="AccessibleBiddingStrategyName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AccessibleBiddingStrategyName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AccessibleBiddingStrategyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AccessibleBiddingStrategyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AccessibleBiddingStrategyName"/> with the pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="AccessibleBiddingStrategyName"/> constructed from the provided ids. /// </returns> public static AccessibleBiddingStrategyName FromCustomerBiddingStrategy(string customerId, string biddingStrategyId) => new AccessibleBiddingStrategyName(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AccessibleBiddingStrategyName"/> with /// pattern <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AccessibleBiddingStrategyName"/> with pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </returns> public static string Format(string customerId, string biddingStrategyId) => FormatCustomerBiddingStrategy(customerId, biddingStrategyId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AccessibleBiddingStrategyName"/> with /// pattern <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AccessibleBiddingStrategyName"/> with pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </returns> public static string FormatCustomerBiddingStrategy(string customerId, string biddingStrategyId) => s_customerBiddingStrategy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId))); /// <summary> /// Parses the given resource name string into a new <see cref="AccessibleBiddingStrategyName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="AccessibleBiddingStrategyName"/> if successful.</returns> public static AccessibleBiddingStrategyName Parse(string accessibleBiddingStrategyName) => Parse(accessibleBiddingStrategyName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AccessibleBiddingStrategyName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AccessibleBiddingStrategyName"/> if successful.</returns> public static AccessibleBiddingStrategyName Parse(string accessibleBiddingStrategyName, bool allowUnparsed) => TryParse(accessibleBiddingStrategyName, allowUnparsed, out AccessibleBiddingStrategyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AccessibleBiddingStrategyName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AccessibleBiddingStrategyName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string accessibleBiddingStrategyName, out AccessibleBiddingStrategyName result) => TryParse(accessibleBiddingStrategyName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AccessibleBiddingStrategyName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AccessibleBiddingStrategyName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string accessibleBiddingStrategyName, bool allowUnparsed, out AccessibleBiddingStrategyName result) { gax::GaxPreconditions.CheckNotNull(accessibleBiddingStrategyName, nameof(accessibleBiddingStrategyName)); gax::TemplatedResourceName resourceName; if (s_customerBiddingStrategy.TryParseName(accessibleBiddingStrategyName, out resourceName)) { result = FromCustomerBiddingStrategy(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(accessibleBiddingStrategyName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AccessibleBiddingStrategyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string biddingStrategyId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; BiddingStrategyId = biddingStrategyId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AccessibleBiddingStrategyName"/> class from the component parts of /// pattern <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> public AccessibleBiddingStrategyName(string customerId, string biddingStrategyId) : this(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>BiddingStrategy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string BiddingStrategyId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerBiddingStrategy: return s_customerBiddingStrategy.Expand(CustomerId, BiddingStrategyId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AccessibleBiddingStrategyName); /// <inheritdoc/> public bool Equals(AccessibleBiddingStrategyName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AccessibleBiddingStrategyName a, AccessibleBiddingStrategyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AccessibleBiddingStrategyName a, AccessibleBiddingStrategyName b) => !(a == b); } public partial class AccessibleBiddingStrategy { /// <summary> /// <see cref="gagvr::AccessibleBiddingStrategyName"/>-typed view over the <see cref="ResourceName"/> resource /// name property. /// </summary> internal AccessibleBiddingStrategyName ResourceNameAsAccessibleBiddingStrategyName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::AccessibleBiddingStrategyName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::AccessibleBiddingStrategyName"/>-typed view over the <see cref="Name"/> resource name /// property. /// </summary> internal AccessibleBiddingStrategyName AccessibleBiddingStrategyName { get => string.IsNullOrEmpty(Name) ? null : gagvr::AccessibleBiddingStrategyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
namespace OpenKh.Tools.ItbEditor { partial class ItbEntry { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ITB_GBox = new System.Windows.Forms.GroupBox(); this.NumericReportID = new System.Windows.Forms.NumericUpDown(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.ItemKindComboBox = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.ItemIDComboBox = new System.Windows.Forms.ComboBox(); this.NumericTreasureBoxID = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.ITB_GBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericReportID)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericTreasureBoxID)).BeginInit(); this.SuspendLayout(); // // ITB_GBox // this.ITB_GBox.Controls.Add(this.NumericReportID); this.ITB_GBox.Controls.Add(this.label4); this.ITB_GBox.Controls.Add(this.label3); this.ITB_GBox.Controls.Add(this.ItemKindComboBox); this.ITB_GBox.Controls.Add(this.label2); this.ITB_GBox.Controls.Add(this.ItemIDComboBox); this.ITB_GBox.Controls.Add(this.NumericTreasureBoxID); this.ITB_GBox.Controls.Add(this.label1); this.ITB_GBox.Font = new System.Drawing.Font("Segoe UI Historic", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.ITB_GBox.Location = new System.Drawing.Point(4, 4); this.ITB_GBox.Name = "ITB_GBox"; this.ITB_GBox.Size = new System.Drawing.Size(562, 78); this.ITB_GBox.TabIndex = 0; this.ITB_GBox.TabStop = false; this.ITB_GBox.Text = "ITB Entry 1"; // // NumericReportID // this.NumericReportID.Location = new System.Drawing.Point(492, 37); this.NumericReportID.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.NumericReportID.Name = "NumericReportID"; this.NumericReportID.Size = new System.Drawing.Size(56, 23); this.NumericReportID.TabIndex = 7; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(492, 19); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(56, 15); this.label4.TabIndex = 6; this.label4.Text = "Report ID"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(87, 18); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(31, 15); this.label3.TabIndex = 5; this.label3.Text = "Kind"; // // ItemKindComboBox // this.ItemKindComboBox.FormattingEnabled = true; this.ItemKindComboBox.Items.AddRange(new object[] { "ITEM", "COMMAND"}); this.ItemKindComboBox.Location = new System.Drawing.Point(87, 37); this.ItemKindComboBox.Name = "ItemKindComboBox"; this.ItemKindComboBox.Size = new System.Drawing.Size(121, 23); this.ItemKindComboBox.TabIndex = 4; this.ItemKindComboBox.Text = "ITEM"; this.ItemKindComboBox.SelectedIndexChanged += new System.EventHandler(this.ItemKindComboBox_SelectedIndexChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(214, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(31, 15); this.label2.TabIndex = 3; this.label2.Text = "Item"; // // ItemIDComboBox // this.ItemIDComboBox.FormattingEnabled = true; this.ItemIDComboBox.Items.AddRange(new object[] { "Nothing", "Wayward Wind = 1", "Treasure Trove (Ventus)", "Stroke of Midnight (Ventus)", "Fairy Stars (Ventus)", "Victory Line (Ventus)", "Mark of a Hero (Ventus)", "Hyperdrive (Ventus)", "Pixie Petal (Ventus)", "Ultima Weapon (Ventus)", "Sweetstack (Ventus)", "Light Seeker (Ventus)", "it000c (Debug item)", "Frolic Flame (Ventus)", "Lost Memory (Ventus)", "Freeze (?)", "Void Gear (Ventus)", "No Name (Ventus)", "Crown Unlimit (Ventus)", "Freeze (?)", "Freeze (?)", "Freeze (?)", "Freeze (?)", "Freeze (?)", "Earth Shaker (Terra)", "Treasure Trove (Terra)", "Stroke of Midnight (Terra)", "Fairy Stars (Terra)", "Victory Line (Terra)", "Mark of a Hero (Terra)", "Hyperdrive (Terra)", "Pixie Petal (Terra)", "Ultima Weapon (Terra)", "Sweetstack (Terra)", "Darkgnaw (Terra)", "Ends of Earth (Terra)", "Chaos Ripper (Terra)", "Freeze (?)", "Freeze (?)", "Freeze (?)", "Void Gear (Terra)", "No Name (Terra)", "Crown Unlimit (Terra)", "Freeze (?)", "Rainfell", "Treasure Trove (Aqua)", "Stroke of Midnight (Aqua)", "Fairy Stars (Aqua)", "Victory Line (Aqua)", "Mark of a Hero (Aqua)", "Hyperdrive (Aqua)", "Pixie Petal (Aqua)", "Ultima Weapon (Aqua)", "Sweetstack (Aqua)", "Destiny\'s Embrace (Aqua)", "Stormfall (Aqua)", "Brightcrest (Aqua)", "Freeze (?)", "Freeze (?)", "Freeze (?)", "Void Gear (Aqua)", "No Name (Aqua)", "Crown Unlimit (Aqua)", "Master Keeper (Aqua)", "Map (Dwarf Woodlands)", "Map (Enchanted Dominion)", "Map (Radiant Garden)", "Map (Disney Town)", "Map (Deep Space)", "Map (Olympus Coliseum)", "Map (Neverland)", "Map (Keyblade Graveyard)", "Map (Land of Departure)", "Map (Castle of Dreams)", "Xehanort Letter", "Xehanort Report 12", "Xehanort Report 1", "Xehanort Report 2", "Xehanort Report 3", "Xehanort Report 4", "Xehanort Report 5", "Xehanort Report 6", "Xehanort Report 7", "Xehanort Report 8", "Xehanort Report 9", "Xehanort Report 10", "Xehanort Report 11", "Sticker (?)", "Mickey Sticker", "Minnie Sticker", "Huey Sticker", "Dewey Sticker", "Louie Sticker", "Rainbow Sticker", "Chip Sticker", "Dale Sticker", "Fireworks Sticker", "Fireworks Sticker", "Ice cream Sticker", "Ice cream Sticker", "Ice cream Sticker", "Ice cream Sticker", "Ice cream Sticker", "Ice cream Sticker", "Balloon Sticker", "UFO Sticker", "Confetti Sticker", "Confetti Sticker", "????", "Pete Sticker", "Huey Sticker", "Dewey Sticker", "Dewey Sticker", "Rainbow Sticker", "Airplane Sticker", "Chip Sticker", "Dale Sticker", "Flying Balloon Sticker", "Flying Balloon Sticker", "Bubble Sticker", "White Sash", "White Button", "Pink Fabric", "White Lace", "Pink Thread", "Pearl", "Risky Ticket", "Sentinel Ticket", "Ringer Ticket", "Threat Ticket", "Treasure Ticket", "Chill Ticket", "Versus Ticket G", "Versus Ticket H", "Versus Ticket I", "Versus Ticket J", "Block Recipe", "Action Recipe", "Magic Recipe", "Mega Magic Recipe", "Giga Magic Recipe", "Attack Recipe", "Mega Attack Recipe", "Giga Attack Recipe", "Unnamed item (?)", "Unnamed item (?)", "Star Shard", "Disney Town Pass", "Wayfinder (Ventus)", "Wayfinder (Stitch)", "Mirage Pass", "Wayfinder (Aqua)", "Wayfinder (Terra)", "Shimmering Crystal", "Shimmering Ore", "Fleeting Crystal", "Fleeting Ore", "Pulsing Crystal", "Pulsing Ore", "Wellspring Crystal", "Wellspring Ore", "Soothing Crystal", "Soothing Ore", "Hungry Crystal", "Hungry Ore", "Abounding Crystal", "Abounding Ore", "Chaos Crystal", "Secret Gem"}); this.ItemIDComboBox.Location = new System.Drawing.Point(214, 37); this.ItemIDComboBox.Name = "ItemIDComboBox"; this.ItemIDComboBox.Size = new System.Drawing.Size(272, 23); this.ItemIDComboBox.TabIndex = 2; this.ItemIDComboBox.Text = "DUMMY"; this.ItemIDComboBox.SelectedIndexChanged += new System.EventHandler(this.ItemIDComboBox_SelectedIndexChanged); // // NumericTreasureBoxID // this.NumericTreasureBoxID.Enabled = false; this.NumericTreasureBoxID.Location = new System.Drawing.Point(6, 37); this.NumericTreasureBoxID.Maximum = new decimal(new int[] { 65535, 0, 0, 0}); this.NumericTreasureBoxID.Name = "NumericTreasureBoxID"; this.NumericTreasureBoxID.Size = new System.Drawing.Size(75, 23); this.NumericTreasureBoxID.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 19); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(66, 15); this.label1.TabIndex = 0; this.label1.Text = "Treasure ID"; // // ItbEntry // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.ITB_GBox); this.Name = "ItbEntry"; this.Size = new System.Drawing.Size(573, 88); this.ITB_GBox.ResumeLayout(false); this.ITB_GBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericReportID)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericTreasureBoxID)).EndInit(); this.ResumeLayout(false); } #endregion public System.Windows.Forms.GroupBox ITB_GBox; public System.Windows.Forms.NumericUpDown NumericTreasureBoxID; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; public System.Windows.Forms.ComboBox ItemIDComboBox; public System.Windows.Forms.NumericUpDown NumericReportID; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; public System.Windows.Forms.ComboBox ItemKindComboBox; } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Swizzle { [TestFixture] public class UintSwizzleVec2Test { [Test] public void XYZW() { { var ov = new uvec2(4u, 9u); var v = ov.swizzle.xx; Assert.AreEqual(4u, v.x); Assert.AreEqual(4u, v.y); } { var ov = new uvec2(9u, 6u); var v = ov.swizzle.xxx; Assert.AreEqual(9u, v.x); Assert.AreEqual(9u, v.y); Assert.AreEqual(9u, v.z); } { var ov = new uvec2(1u, 3u); var v = ov.swizzle.xxxx; Assert.AreEqual(1u, v.x); Assert.AreEqual(1u, v.y); Assert.AreEqual(1u, v.z); Assert.AreEqual(1u, v.w); } { var ov = new uvec2(3u, 2u); var v = ov.swizzle.xxxy; Assert.AreEqual(3u, v.x); Assert.AreEqual(3u, v.y); Assert.AreEqual(3u, v.z); Assert.AreEqual(2u, v.w); } { var ov = new uvec2(8u, 2u); var v = ov.swizzle.xxy; Assert.AreEqual(8u, v.x); Assert.AreEqual(8u, v.y); Assert.AreEqual(2u, v.z); } { var ov = new uvec2(6u, 2u); var v = ov.swizzle.xxyx; Assert.AreEqual(6u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(2u, v.z); Assert.AreEqual(6u, v.w); } { var ov = new uvec2(9u, 4u); var v = ov.swizzle.xxyy; Assert.AreEqual(9u, v.x); Assert.AreEqual(9u, v.y); Assert.AreEqual(4u, v.z); Assert.AreEqual(4u, v.w); } { var ov = new uvec2(2u, 4u); var v = ov.swizzle.xy; Assert.AreEqual(2u, v.x); Assert.AreEqual(4u, v.y); } { var ov = new uvec2(8u, 7u); var v = ov.swizzle.xyx; Assert.AreEqual(8u, v.x); Assert.AreEqual(7u, v.y); Assert.AreEqual(8u, v.z); } { var ov = new uvec2(6u, 9u); var v = ov.swizzle.xyxx; Assert.AreEqual(6u, v.x); Assert.AreEqual(9u, v.y); Assert.AreEqual(6u, v.z); Assert.AreEqual(6u, v.w); } { var ov = new uvec2(2u, 8u); var v = ov.swizzle.xyxy; Assert.AreEqual(2u, v.x); Assert.AreEqual(8u, v.y); Assert.AreEqual(2u, v.z); Assert.AreEqual(8u, v.w); } { var ov = new uvec2(9u, 3u); var v = ov.swizzle.xyy; Assert.AreEqual(9u, v.x); Assert.AreEqual(3u, v.y); Assert.AreEqual(3u, v.z); } { var ov = new uvec2(1u, 8u); var v = ov.swizzle.xyyx; Assert.AreEqual(1u, v.x); Assert.AreEqual(8u, v.y); Assert.AreEqual(8u, v.z); Assert.AreEqual(1u, v.w); } { var ov = new uvec2(0u, 6u); var v = ov.swizzle.xyyy; Assert.AreEqual(0u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(6u, v.z); Assert.AreEqual(6u, v.w); } { var ov = new uvec2(3u, 4u); var v = ov.swizzle.yx; Assert.AreEqual(4u, v.x); Assert.AreEqual(3u, v.y); } { var ov = new uvec2(3u, 6u); var v = ov.swizzle.yxx; Assert.AreEqual(6u, v.x); Assert.AreEqual(3u, v.y); Assert.AreEqual(3u, v.z); } { var ov = new uvec2(9u, 6u); var v = ov.swizzle.yxxx; Assert.AreEqual(6u, v.x); Assert.AreEqual(9u, v.y); Assert.AreEqual(9u, v.z); Assert.AreEqual(9u, v.w); } { var ov = new uvec2(7u, 3u); var v = ov.swizzle.yxxy; Assert.AreEqual(3u, v.x); Assert.AreEqual(7u, v.y); Assert.AreEqual(7u, v.z); Assert.AreEqual(3u, v.w); } { var ov = new uvec2(1u, 6u); var v = ov.swizzle.yxy; Assert.AreEqual(6u, v.x); Assert.AreEqual(1u, v.y); Assert.AreEqual(6u, v.z); } { var ov = new uvec2(1u, 2u); var v = ov.swizzle.yxyx; Assert.AreEqual(2u, v.x); Assert.AreEqual(1u, v.y); Assert.AreEqual(2u, v.z); Assert.AreEqual(1u, v.w); } { var ov = new uvec2(5u, 4u); var v = ov.swizzle.yxyy; Assert.AreEqual(4u, v.x); Assert.AreEqual(5u, v.y); Assert.AreEqual(4u, v.z); Assert.AreEqual(4u, v.w); } { var ov = new uvec2(2u, 3u); var v = ov.swizzle.yy; Assert.AreEqual(3u, v.x); Assert.AreEqual(3u, v.y); } { var ov = new uvec2(1u, 5u); var v = ov.swizzle.yyx; Assert.AreEqual(5u, v.x); Assert.AreEqual(5u, v.y); Assert.AreEqual(1u, v.z); } { var ov = new uvec2(3u, 2u); var v = ov.swizzle.yyxx; Assert.AreEqual(2u, v.x); Assert.AreEqual(2u, v.y); Assert.AreEqual(3u, v.z); Assert.AreEqual(3u, v.w); } { var ov = new uvec2(1u, 5u); var v = ov.swizzle.yyxy; Assert.AreEqual(5u, v.x); Assert.AreEqual(5u, v.y); Assert.AreEqual(1u, v.z); Assert.AreEqual(5u, v.w); } { var ov = new uvec2(7u, 7u); var v = ov.swizzle.yyy; Assert.AreEqual(7u, v.x); Assert.AreEqual(7u, v.y); Assert.AreEqual(7u, v.z); } { var ov = new uvec2(0u, 4u); var v = ov.swizzle.yyyx; Assert.AreEqual(4u, v.x); Assert.AreEqual(4u, v.y); Assert.AreEqual(4u, v.z); Assert.AreEqual(0u, v.w); } { var ov = new uvec2(8u, 6u); var v = ov.swizzle.yyyy; Assert.AreEqual(6u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(6u, v.z); Assert.AreEqual(6u, v.w); } } [Test] public void RGBA() { { var ov = new uvec2(3u, 9u); var v = ov.swizzle.rr; Assert.AreEqual(3u, v.x); Assert.AreEqual(3u, v.y); } { var ov = new uvec2(9u, 8u); var v = ov.swizzle.rrr; Assert.AreEqual(9u, v.x); Assert.AreEqual(9u, v.y); Assert.AreEqual(9u, v.z); } { var ov = new uvec2(6u, 1u); var v = ov.swizzle.rrrr; Assert.AreEqual(6u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(6u, v.z); Assert.AreEqual(6u, v.w); } { var ov = new uvec2(8u, 8u); var v = ov.swizzle.rrrg; Assert.AreEqual(8u, v.x); Assert.AreEqual(8u, v.y); Assert.AreEqual(8u, v.z); Assert.AreEqual(8u, v.w); } { var ov = new uvec2(4u, 6u); var v = ov.swizzle.rrg; Assert.AreEqual(4u, v.x); Assert.AreEqual(4u, v.y); Assert.AreEqual(6u, v.z); } { var ov = new uvec2(5u, 8u); var v = ov.swizzle.rrgr; Assert.AreEqual(5u, v.x); Assert.AreEqual(5u, v.y); Assert.AreEqual(8u, v.z); Assert.AreEqual(5u, v.w); } { var ov = new uvec2(3u, 4u); var v = ov.swizzle.rrgg; Assert.AreEqual(3u, v.x); Assert.AreEqual(3u, v.y); Assert.AreEqual(4u, v.z); Assert.AreEqual(4u, v.w); } { var ov = new uvec2(3u, 2u); var v = ov.swizzle.rg; Assert.AreEqual(3u, v.x); Assert.AreEqual(2u, v.y); } { var ov = new uvec2(3u, 2u); var v = ov.swizzle.rgr; Assert.AreEqual(3u, v.x); Assert.AreEqual(2u, v.y); Assert.AreEqual(3u, v.z); } { var ov = new uvec2(9u, 4u); var v = ov.swizzle.rgrr; Assert.AreEqual(9u, v.x); Assert.AreEqual(4u, v.y); Assert.AreEqual(9u, v.z); Assert.AreEqual(9u, v.w); } { var ov = new uvec2(6u, 6u); var v = ov.swizzle.rgrg; Assert.AreEqual(6u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(6u, v.z); Assert.AreEqual(6u, v.w); } { var ov = new uvec2(5u, 3u); var v = ov.swizzle.rgg; Assert.AreEqual(5u, v.x); Assert.AreEqual(3u, v.y); Assert.AreEqual(3u, v.z); } { var ov = new uvec2(6u, 3u); var v = ov.swizzle.rggr; Assert.AreEqual(6u, v.x); Assert.AreEqual(3u, v.y); Assert.AreEqual(3u, v.z); Assert.AreEqual(6u, v.w); } { var ov = new uvec2(3u, 8u); var v = ov.swizzle.rggg; Assert.AreEqual(3u, v.x); Assert.AreEqual(8u, v.y); Assert.AreEqual(8u, v.z); Assert.AreEqual(8u, v.w); } { var ov = new uvec2(7u, 2u); var v = ov.swizzle.gr; Assert.AreEqual(2u, v.x); Assert.AreEqual(7u, v.y); } { var ov = new uvec2(6u, 9u); var v = ov.swizzle.grr; Assert.AreEqual(9u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(6u, v.z); } { var ov = new uvec2(6u, 5u); var v = ov.swizzle.grrr; Assert.AreEqual(5u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(6u, v.z); Assert.AreEqual(6u, v.w); } { var ov = new uvec2(7u, 3u); var v = ov.swizzle.grrg; Assert.AreEqual(3u, v.x); Assert.AreEqual(7u, v.y); Assert.AreEqual(7u, v.z); Assert.AreEqual(3u, v.w); } { var ov = new uvec2(3u, 8u); var v = ov.swizzle.grg; Assert.AreEqual(8u, v.x); Assert.AreEqual(3u, v.y); Assert.AreEqual(8u, v.z); } { var ov = new uvec2(7u, 7u); var v = ov.swizzle.grgr; Assert.AreEqual(7u, v.x); Assert.AreEqual(7u, v.y); Assert.AreEqual(7u, v.z); Assert.AreEqual(7u, v.w); } { var ov = new uvec2(4u, 9u); var v = ov.swizzle.grgg; Assert.AreEqual(9u, v.x); Assert.AreEqual(4u, v.y); Assert.AreEqual(9u, v.z); Assert.AreEqual(9u, v.w); } { var ov = new uvec2(8u, 9u); var v = ov.swizzle.gg; Assert.AreEqual(9u, v.x); Assert.AreEqual(9u, v.y); } { var ov = new uvec2(8u, 1u); var v = ov.swizzle.ggr; Assert.AreEqual(1u, v.x); Assert.AreEqual(1u, v.y); Assert.AreEqual(8u, v.z); } { var ov = new uvec2(2u, 1u); var v = ov.swizzle.ggrr; Assert.AreEqual(1u, v.x); Assert.AreEqual(1u, v.y); Assert.AreEqual(2u, v.z); Assert.AreEqual(2u, v.w); } { var ov = new uvec2(4u, 9u); var v = ov.swizzle.ggrg; Assert.AreEqual(9u, v.x); Assert.AreEqual(9u, v.y); Assert.AreEqual(4u, v.z); Assert.AreEqual(9u, v.w); } { var ov = new uvec2(7u, 0u); var v = ov.swizzle.ggg; Assert.AreEqual(0u, v.x); Assert.AreEqual(0u, v.y); Assert.AreEqual(0u, v.z); } { var ov = new uvec2(0u, 5u); var v = ov.swizzle.gggr; Assert.AreEqual(5u, v.x); Assert.AreEqual(5u, v.y); Assert.AreEqual(5u, v.z); Assert.AreEqual(0u, v.w); } { var ov = new uvec2(5u, 6u); var v = ov.swizzle.gggg; Assert.AreEqual(6u, v.x); Assert.AreEqual(6u, v.y); Assert.AreEqual(6u, v.z); Assert.AreEqual(6u, v.w); } } [Test] public void InlineXYZW() { { var v0 = new uvec2(1u, 1u); var v1 = new uvec2(5u, 9u); var v2 = v0.xy; v0.xy = v1; var v3 = v0.xy; Assert.AreEqual(v1, v3); Assert.AreEqual(5u, v0.x); Assert.AreEqual(9u, v0.y); Assert.AreEqual(1u, v2.x); Assert.AreEqual(1u, v2.y); } } [Test] public void InlineRGBA() { { var v0 = new uvec2(7u, 0u); var v1 = 1u; var v2 = v0.r; v0.r = v1; var v3 = v0.r; Assert.AreEqual(v1, v3); Assert.AreEqual(1u, v0.x); Assert.AreEqual(0u, v0.y); Assert.AreEqual(7u, v2); } { var v0 = new uvec2(2u, 3u); var v1 = 8u; var v2 = v0.g; v0.g = v1; var v3 = v0.g; Assert.AreEqual(v1, v3); Assert.AreEqual(2u, v0.x); Assert.AreEqual(8u, v0.y); Assert.AreEqual(3u, v2); } { var v0 = new uvec2(9u, 8u); var v1 = new uvec2(8u, 2u); var v2 = v0.rg; v0.rg = v1; var v3 = v0.rg; Assert.AreEqual(v1, v3); Assert.AreEqual(8u, v0.x); Assert.AreEqual(2u, v0.y); Assert.AreEqual(9u, v2.x); Assert.AreEqual(8u, v2.y); } } } }
//----------------------------------------------------------------------- // <copyright file="RiskBasedAuthenticationApi.cs" company="LoginRadius"> // Created by LoginRadius Development Team // Copyright 2019 LoginRadius Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using LoginRadiusSDK.V2.Common; using System.Threading.Tasks; using LoginRadiusSDK.V2.Util; using LoginRadiusSDK.V2.Models.ResponseModels; using LoginRadiusSDK.V2.Models.ResponseModels.UserProfile; using LoginRadiusSDK.V2.Models.RequestModels; namespace LoginRadiusSDK.V2.Api.Authentication { public class RiskBasedAuthenticationApi : LoginRadiusResource { /// <summary> /// This API retrieves a copy of the user data based on the Email /// </summary> /// <param name="emailAuthenticationModel">Model Class containing Definition of payload for Email Authentication API</param> /// <param name="emailTemplate">Email template name</param> /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param> /// <param name="loginUrl">Url where the user is logging from</param> /// <param name="passwordDelegation">Password Delegation Allows you to use a third-party service to store your passwords rather than LoginRadius Cloud storage.</param> /// <param name="passwordDelegationApp">RiskBased Authentication Password Delegation App</param> /// <param name="rbaBrowserEmailTemplate">Risk Based Authentication Browser EmailTemplate</param> /// <param name="rbaBrowserSmsTemplate">Risk Based Authentication Browser Sms Template</param> /// <param name="rbaCityEmailTemplate">Risk Based Authentication City Email Template</param> /// <param name="rbaCitySmsTemplate">Risk Based Authentication City SmsTemplate</param> /// <param name="rbaCountryEmailTemplate">Risk Based Authentication Country EmailTemplate</param> /// <param name="rbaCountrySmsTemplate">Risk Based Authentication Country SmsTemplate</param> /// <param name="rbaIpEmailTemplate">Risk Based Authentication Ip EmailTemplate</param> /// <param name="rbaIpSmsTemplate">Risk Based Authentication Ip SmsTemplate</param> /// <param name="rbaOneclickEmailTemplate">Risk Based Authentication Oneclick EmailTemplate</param> /// <param name="rbaOTPSmsTemplate">Risk Based Authentication Oneclick EmailTemplate</param> /// <param name="smsTemplate">SMS Template name</param> /// <param name="verificationUrl">Email verification url</param> /// <returns>Response containing User Profile Data and access token</returns> /// 9.2.4 public async Task<ApiResponse<AccessToken<Identity>>> RBALoginByEmail(EmailAuthenticationModel emailAuthenticationModel, string emailTemplate = null, string fields = "", string loginUrl = null, bool? passwordDelegation = null, string passwordDelegationApp = null, string rbaBrowserEmailTemplate = null, string rbaBrowserSmsTemplate = null, string rbaCityEmailTemplate = null, string rbaCitySmsTemplate = null, string rbaCountryEmailTemplate = null, string rbaCountrySmsTemplate = null, string rbaIpEmailTemplate = null, string rbaIpSmsTemplate = null, string rbaOneclickEmailTemplate = null, string rbaOTPSmsTemplate = null, string smsTemplate = null, string verificationUrl = null) { if (emailAuthenticationModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(emailAuthenticationModel)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] } }; if (!string.IsNullOrWhiteSpace(emailTemplate)) { queryParameters.Add("emailTemplate", emailTemplate); } if (!string.IsNullOrWhiteSpace(fields)) { queryParameters.Add("fields", fields); } if (!string.IsNullOrWhiteSpace(loginUrl)) { queryParameters.Add("loginUrl", loginUrl); } if (passwordDelegation != false) { queryParameters.Add("passwordDelegation", passwordDelegation.ToString()); } if (!string.IsNullOrWhiteSpace(passwordDelegationApp)) { queryParameters.Add("passwordDelegationApp", passwordDelegationApp); } if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate)) { queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaBrowserSmsTemplate)) { queryParameters.Add("rbaBrowserSmsTemplate", rbaBrowserSmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate)) { queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaCitySmsTemplate)) { queryParameters.Add("rbaCitySmsTemplate", rbaCitySmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate)) { queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaCountrySmsTemplate)) { queryParameters.Add("rbaCountrySmsTemplate", rbaCountrySmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate)) { queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaIpSmsTemplate)) { queryParameters.Add("rbaIpSmsTemplate", rbaIpSmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaOneclickEmailTemplate)) { queryParameters.Add("rbaOneclickEmailTemplate", rbaOneclickEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaOTPSmsTemplate)) { queryParameters.Add("rbaOTPSmsTemplate", rbaOTPSmsTemplate); } if (!string.IsNullOrWhiteSpace(smsTemplate)) { queryParameters.Add("smsTemplate", smsTemplate); } if (!string.IsNullOrWhiteSpace(verificationUrl)) { queryParameters.Add("verificationUrl", verificationUrl); } var resourcePath = "identity/v2/auth/login"; return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(emailAuthenticationModel)); } /// <summary> /// This API retrieves a copy of the user data based on the Username /// </summary> /// <param name="userNameAuthenticationModel">Model Class containing Definition of payload for Username Authentication API</param> /// <param name="emailTemplate">Email template name</param> /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param> /// <param name="loginUrl">Url where the user is logging from</param> /// <param name="passwordDelegation">Password Delegation Allows you to use a third-party service to store your passwords rather than LoginRadius Cloud storage.</param> /// <param name="passwordDelegationApp">RiskBased Authentication Password Delegation App</param> /// <param name="rbaBrowserEmailTemplate">Risk Based Authentication Browser EmailTemplate</param> /// <param name="rbaBrowserSmsTemplate">Risk Based Authentication Browser Sms Template</param> /// <param name="rbaCityEmailTemplate">Risk Based Authentication City Email Template</param> /// <param name="rbaCitySmsTemplate">Risk Based Authentication City SmsTemplate</param> /// <param name="rbaCountryEmailTemplate">Risk Based Authentication Country EmailTemplate</param> /// <param name="rbaCountrySmsTemplate">Risk Based Authentication Country SmsTemplate</param> /// <param name="rbaIpEmailTemplate">Risk Based Authentication Ip EmailTemplate</param> /// <param name="rbaIpSmsTemplate">Risk Based Authentication Ip SmsTemplate</param> /// <param name="rbaOneclickEmailTemplate">Risk Based Authentication Oneclick EmailTemplate</param> /// <param name="rbaOTPSmsTemplate">Risk Based Authentication OTPSmsTemplate</param> /// <param name="smsTemplate">SMS Template name</param> /// <param name="verificationUrl">Email verification url</param> /// <returns>Response containing User Profile Data and access token</returns> /// 9.2.5 public async Task<ApiResponse<AccessToken<Identity>>> RBALoginByUserName(UserNameAuthenticationModel userNameAuthenticationModel, string emailTemplate = null, string fields = "", string loginUrl = null, bool? passwordDelegation = null, string passwordDelegationApp = null, string rbaBrowserEmailTemplate = null, string rbaBrowserSmsTemplate = null, string rbaCityEmailTemplate = null, string rbaCitySmsTemplate = null, string rbaCountryEmailTemplate = null, string rbaCountrySmsTemplate = null, string rbaIpEmailTemplate = null, string rbaIpSmsTemplate = null, string rbaOneclickEmailTemplate = null, string rbaOTPSmsTemplate = null, string smsTemplate = null, string verificationUrl = null) { if (userNameAuthenticationModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(userNameAuthenticationModel)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] } }; if (!string.IsNullOrWhiteSpace(emailTemplate)) { queryParameters.Add("emailTemplate", emailTemplate); } if (!string.IsNullOrWhiteSpace(fields)) { queryParameters.Add("fields", fields); } if (!string.IsNullOrWhiteSpace(loginUrl)) { queryParameters.Add("loginUrl", loginUrl); } if (passwordDelegation != false) { queryParameters.Add("passwordDelegation", passwordDelegation.ToString()); } if (!string.IsNullOrWhiteSpace(passwordDelegationApp)) { queryParameters.Add("passwordDelegationApp", passwordDelegationApp); } if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate)) { queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaBrowserSmsTemplate)) { queryParameters.Add("rbaBrowserSmsTemplate", rbaBrowserSmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate)) { queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaCitySmsTemplate)) { queryParameters.Add("rbaCitySmsTemplate", rbaCitySmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate)) { queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaCountrySmsTemplate)) { queryParameters.Add("rbaCountrySmsTemplate", rbaCountrySmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate)) { queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaIpSmsTemplate)) { queryParameters.Add("rbaIpSmsTemplate", rbaIpSmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaOneclickEmailTemplate)) { queryParameters.Add("rbaOneclickEmailTemplate", rbaOneclickEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaOTPSmsTemplate)) { queryParameters.Add("rbaOTPSmsTemplate", rbaOTPSmsTemplate); } if (!string.IsNullOrWhiteSpace(smsTemplate)) { queryParameters.Add("smsTemplate", smsTemplate); } if (!string.IsNullOrWhiteSpace(verificationUrl)) { queryParameters.Add("verificationUrl", verificationUrl); } var resourcePath = "identity/v2/auth/login"; return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(userNameAuthenticationModel)); } /// <summary> /// This API retrieves a copy of the user data based on the Phone /// </summary> /// <param name="phoneAuthenticationModel">Model Class containing Definition of payload for PhoneAuthenticationModel API</param> /// <param name="emailTemplate">Email template name</param> /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param> /// <param name="loginUrl">Url where the user is logging from</param> /// <param name="passwordDelegation">Password Delegation Allows you to use a third-party service to store your passwords rather than LoginRadius Cloud storage.</param> /// <param name="passwordDelegationApp">RiskBased Authentication Password Delegation App</param> /// <param name="rbaBrowserEmailTemplate">Risk Based Authentication Browser EmailTemplate</param> /// <param name="rbaBrowserSmsTemplate">Risk Based Authentication Browser Sms Template</param> /// <param name="rbaCityEmailTemplate">Risk Based Authentication City Email Template</param> /// <param name="rbaCitySmsTemplate">Risk Based Authentication City SmsTemplate</param> /// <param name="rbaCountryEmailTemplate">Risk Based Authentication Country EmailTemplate</param> /// <param name="rbaCountrySmsTemplate">Risk Based Authentication Country SmsTemplate</param> /// <param name="rbaIpEmailTemplate">Risk Based Authentication Ip EmailTemplate</param> /// <param name="rbaIpSmsTemplate">Risk Based Authentication Ip SmsTemplate</param> /// <param name="rbaOneclickEmailTemplate">Risk Based Authentication Oneclick EmailTemplate</param> /// <param name="rbaOTPSmsTemplate">Risk Based Authentication OTPSmsTemplate</param> /// <param name="smsTemplate">SMS Template name</param> /// <param name="verificationUrl">Email verification url</param> /// <returns>Response containing User Profile Data and access token</returns> /// 9.2.6 public async Task<ApiResponse<AccessToken<Identity>>> RBALoginByPhone(PhoneAuthenticationModel phoneAuthenticationModel, string emailTemplate = null, string fields = "", string loginUrl = null, bool? passwordDelegation = null, string passwordDelegationApp = null, string rbaBrowserEmailTemplate = null, string rbaBrowserSmsTemplate = null, string rbaCityEmailTemplate = null, string rbaCitySmsTemplate = null, string rbaCountryEmailTemplate = null, string rbaCountrySmsTemplate = null, string rbaIpEmailTemplate = null, string rbaIpSmsTemplate = null, string rbaOneclickEmailTemplate = null, string rbaOTPSmsTemplate = null, string smsTemplate = null, string verificationUrl = null) { if (phoneAuthenticationModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phoneAuthenticationModel)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] } }; if (!string.IsNullOrWhiteSpace(emailTemplate)) { queryParameters.Add("emailTemplate", emailTemplate); } if (!string.IsNullOrWhiteSpace(fields)) { queryParameters.Add("fields", fields); } if (!string.IsNullOrWhiteSpace(loginUrl)) { queryParameters.Add("loginUrl", loginUrl); } if (passwordDelegation != false) { queryParameters.Add("passwordDelegation", passwordDelegation.ToString()); } if (!string.IsNullOrWhiteSpace(passwordDelegationApp)) { queryParameters.Add("passwordDelegationApp", passwordDelegationApp); } if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate)) { queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaBrowserSmsTemplate)) { queryParameters.Add("rbaBrowserSmsTemplate", rbaBrowserSmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate)) { queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaCitySmsTemplate)) { queryParameters.Add("rbaCitySmsTemplate", rbaCitySmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate)) { queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaCountrySmsTemplate)) { queryParameters.Add("rbaCountrySmsTemplate", rbaCountrySmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate)) { queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaIpSmsTemplate)) { queryParameters.Add("rbaIpSmsTemplate", rbaIpSmsTemplate); } if (!string.IsNullOrWhiteSpace(rbaOneclickEmailTemplate)) { queryParameters.Add("rbaOneclickEmailTemplate", rbaOneclickEmailTemplate); } if (!string.IsNullOrWhiteSpace(rbaOTPSmsTemplate)) { queryParameters.Add("rbaOTPSmsTemplate", rbaOTPSmsTemplate); } if (!string.IsNullOrWhiteSpace(smsTemplate)) { queryParameters.Add("smsTemplate", smsTemplate); } if (!string.IsNullOrWhiteSpace(verificationUrl)) { queryParameters.Add("verificationUrl", verificationUrl); } var resourcePath = "identity/v2/auth/login"; return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(phoneAuthenticationModel)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System; using System.IO; using System.Text; using System.Resources; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics; /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException"]/*' /> [Serializable] public class XmlSchemaException : SystemException { private string _res; private string[] _args; private string _sourceUri; private int _lineNumber; private int _linePosition; [NonSerialized] private XmlSchemaObject _sourceSchemaObject; // message != null for V1 exceptions deserialized in Whidbey // message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message) private string _message; /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException5"]/*' /> protected XmlSchemaException(SerializationInfo info, StreamingContext context) : base(info, context) { _res = (string) info.GetValue("res" , typeof(string)); _args = (string[]) info.GetValue("args", typeof(string[])); _sourceUri = (string) info.GetValue("sourceUri", typeof(string)); _lineNumber = (int) info.GetValue("lineNumber", typeof(int)); _linePosition = (int) info.GetValue("linePosition", typeof(int)); // deserialize optional members string version = null; foreach ( SerializationEntry e in info ) { if ( e.Name == "version" ) { version = (string)e.Value; } } if ( version == null ) { // deserializing V1 exception _message = CreateMessage( _res, _args ); } else { // deserializing V2 or higher exception -> exception message is serialized by the base class (Exception._message) _message = null; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.GetObjectData"]/*' /> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("res", _res); info.AddValue("args", _args); info.AddValue("sourceUri", _sourceUri); info.AddValue("lineNumber", _lineNumber); info.AddValue("linePosition", _linePosition); info.AddValue("version", "2.0"); } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException1"]/*' /> public XmlSchemaException() : this(null) { } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException2"]/*' /> public XmlSchemaException(String message) : this(message, ((Exception)null), 0, 0) { #if DEBUG Debug.Assert(message == null || !message.StartsWith("Sch_", StringComparison.Ordinal), "Do not pass a resource here!"); #endif } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException0"]/*' /> public XmlSchemaException(String message, Exception innerException) : this(message, innerException, 0, 0) { } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException3"]/*' /> public XmlSchemaException(String message, Exception innerException, int lineNumber, int linePosition) : this((message == null ? SR.Sch_DefaultException : SR.Xml_UserException), new string[] { message }, innerException, null, lineNumber, linePosition, null) { } internal XmlSchemaException(string res, string[] args) : this(res, args, null, null, 0, 0, null) { } internal XmlSchemaException(string res, string arg) : this(res, new string[] { arg }, null, null, 0, 0, null) { } internal XmlSchemaException(string res, string arg, string sourceUri, int lineNumber, int linePosition) : this(res, new string[] { arg }, null, sourceUri, lineNumber, linePosition, null) { } internal XmlSchemaException(string res, string sourceUri, int lineNumber, int linePosition) : this(res, (string[])null, null, sourceUri, lineNumber, linePosition, null) { } internal XmlSchemaException(string res, string[] args, string sourceUri, int lineNumber, int linePosition) : this(res, args, null, sourceUri, lineNumber, linePosition, null) { } internal XmlSchemaException(string res, XmlSchemaObject source) : this(res, (string[])null, source) { } internal XmlSchemaException(string res, string arg, XmlSchemaObject source) : this(res, new string[] { arg }, source) { } internal XmlSchemaException(string res, string[] args, XmlSchemaObject source) : this(res, args, null, source.SourceUri, source.LineNumber, source.LinePosition, source) { } internal XmlSchemaException(string res, string[] args, Exception innerException, string sourceUri, int lineNumber, int linePosition, XmlSchemaObject source) : base(CreateMessage(res, args), innerException) { HResult = HResults.XmlSchema; _res = res; _args = args; _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; _sourceSchemaObject = source; } internal static string CreateMessage(string res, string[] args) { try { if (args == null) { return res; } return string.Format(res, args); } catch (MissingManifestResourceException) { return "UNKNOWN(" + res + ")"; } } internal string GetRes { get { return _res; } } internal string[] Args { get { return _args; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceUri"]/*' /> public string SourceUri { get { return _sourceUri; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LineNumber"]/*' /> public int LineNumber { get { return _lineNumber; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LinePosition"]/*' /> public int LinePosition { get { return _linePosition; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceObject"]/*' /> public XmlSchemaObject SourceSchemaObject { get { return _sourceSchemaObject; } } /*internal static XmlSchemaException Create(string res) { //Since internal overload with res string will clash with public constructor that takes in a message return new XmlSchemaException(res, (string[])null, null, null, 0, 0, null); }*/ internal void SetSource(string sourceUri, int lineNumber, int linePosition) { _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; } internal void SetSchemaObject(XmlSchemaObject source) { _sourceSchemaObject = source; } internal void SetSource(XmlSchemaObject source) { _sourceSchemaObject = source; _sourceUri = source.SourceUri; _lineNumber = source.LineNumber; _linePosition = source.LinePosition; } internal void SetResourceId(string resourceId) { _res = resourceId; } public override string Message { get { return (_message == null) ? base.Message : _message; } } }; } // namespace System.Xml.Schema
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using metahub.logic.schema; using metahub.schema; namespace metahub.logic.nodes { public enum Dir { In, Out } public delegate bool Node_Filter(Node node); [DebuggerDisplay("{debug_string}")] public class Node { public Node_Type type; public List<Node> connections = new List<Node>(); public List<Node> inputs = new List<Node>(); public List<Node> outputs = new List<Node>(); public string stack_trace; public virtual string debug_string { get { return type + " node"; } } public Node(Node_Type type) { stack_trace = Environment.StackTrace; this.type = type; } virtual public Signature get_signature() { //throw new Exception(GetType().Name + " does not implement get_signature()."); return new Signature(Kind.unknown); } public List<Node> ports(Dir dir) { return dir == Dir.In ? inputs : outputs; } public List<Node> ports(int dir) { return dir == 0 ? inputs : outputs; } public void connect_input(Node other) { if (connections.Contains(other)) return; connections.Add(other); other.connections.Add(this); inputs.Add(other); other.outputs.Add(this); } public void connect(Node other, Dir dir) { if (dir == Dir.In) { connect_input(other); } else { connect_output(other); } } public void connect_many_inputs(IEnumerable<Node> inputs) { foreach (var input in inputs) { connect_input(input); } } public void connect_output(Node other) { if (connections.Contains(other)) return; if (other.connections.Contains(this)) return; connections.Add(other); other.connections.Add(this); other.inputs.Add(this); outputs.Add(other); } public List<Node> get_path() { var result = new List<Node>(); result.Add(this); var current = this; while (current.inputs.Count > 0) { current = current.inputs[0]; result.Add(current); } return result; } public Node get_last(Dir dir = Dir.In) { var current = this; while (current.ports(dir).Count > 0) { current = current.ports(dir)[0]; } return current; } public void disconnect(Node other) { if (!connections.Contains(other)) return; connections.Remove(other); inputs.Remove(other); outputs.Remove(other); other.connections.Remove(this); other.inputs.Remove(this); other.outputs.Remove(this); } public void replace_other(Node old_node, Node new_node) { if (!connections.Contains(old_node)) throw new Exception("Cannot replace node because there is no existing connection."); if (connections.Contains(new_node)) throw new Exception("Already connected to replacement node."); var index = inputs.IndexOf(old_node); if (index > -1) { disconnect(old_node); inputs.Insert(index, new_node); new_node.outputs.Add(this); } else { index = outputs.IndexOf(old_node); disconnect(old_node); outputs.Insert(index, new_node); new_node.inputs.Add(this); } connections.Add(new_node); new_node.connections.Add(this); } public void replace(Node new_node) { // Loop through both inputs and outputs for (int i = 0; i < 2; ++i) { var j = 1 - i; var port_list = ports(i).ToArray(); foreach (var port in port_list) { var index = port.ports(j).IndexOf(this); disconnect(port); port.ports(j).Insert(index, new_node); new_node.ports(i).Add(port); new_node.connections.Add(port); port.connections.Add(new_node); } } } public Node get_other_input(Node node) { if (inputs.Count != 2) throw new Exception("Not yet supported."); return inputs.First(n => n != node); } public Node get_other_output(Node node) { if (outputs.Count != 2) throw new Exception("Not yet supported."); return outputs.First(n => n != node); } public IEnumerable<Node> get_other_outputs(Node node) { if (outputs.Count != 2) throw new Exception("Not yet supported."); return outputs.Where(n => n != node); } public virtual Node clone() { if (type == Node_Type.bounce) return new Node(Node_Type.bounce); throw new Exception("Not implemented."); } public List<Node> aggregate(Dir dir, Node_Filter filter = null, bool exclude_self = false) { var result = new List<Node>(); if (filter == null || filter(this)) { if (!exclude_self) result.Add(this); foreach (var node in ports(dir)) { result.AddRange(node.aggregate(dir, filter)); } } return result; } public static void insert(Node left, Node middle, Node right) { var is_input = left.inputs.Contains(right); left.disconnect(right); if (is_input) { left.connect_input(middle); middle.connect_input(right); } else { left.connect_output(middle); middle.connect_output(right); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/logging/v2/logging_metrics.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Logging.V2 { /// <summary>Holder for reflection information generated from google/logging/v2/logging_metrics.proto</summary> public static partial class LoggingMetricsReflection { #region Descriptor /// <summary>File descriptor for google/logging/v2/logging_metrics.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static LoggingMetricsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cidnb29nbGUvbG9nZ2luZy92Mi9sb2dnaW5nX21ldHJpY3MucHJvdG8SEWdv", "b2dsZS5sb2dnaW5nLnYyGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3Rv", "Ghtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8ilgEKCUxvZ01ldHJpYxIM", "CgRuYW1lGAEgASgJEhMKC2Rlc2NyaXB0aW9uGAIgASgJEg4KBmZpbHRlchgD", "IAEoCRI4Cgd2ZXJzaW9uGAQgASgOMicuZ29vZ2xlLmxvZ2dpbmcudjIuTG9n", "TWV0cmljLkFwaVZlcnNpb24iHAoKQXBpVmVyc2lvbhIGCgJWMhAAEgYKAlYx", "EAEiTgoVTGlzdExvZ01ldHJpY3NSZXF1ZXN0Eg4KBnBhcmVudBgBIAEoCRIS", "CgpwYWdlX3Rva2VuGAIgASgJEhEKCXBhZ2Vfc2l6ZRgDIAEoBSJgChZMaXN0", "TG9nTWV0cmljc1Jlc3BvbnNlEi0KB21ldHJpY3MYASADKAsyHC5nb29nbGUu", "bG9nZ2luZy52Mi5Mb2dNZXRyaWMSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJ", "IioKE0dldExvZ01ldHJpY1JlcXVlc3QSEwoLbWV0cmljX25hbWUYASABKAki", "VgoWQ3JlYXRlTG9nTWV0cmljUmVxdWVzdBIOCgZwYXJlbnQYASABKAkSLAoG", "bWV0cmljGAIgASgLMhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmljIlsK", "FlVwZGF0ZUxvZ01ldHJpY1JlcXVlc3QSEwoLbWV0cmljX25hbWUYASABKAkS", "LAoGbWV0cmljGAIgASgLMhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmlj", "Ii0KFkRlbGV0ZUxvZ01ldHJpY1JlcXVlc3QSEwoLbWV0cmljX25hbWUYASAB", "KAky1AUKEE1ldHJpY3NTZXJ2aWNlVjISjgEKDkxpc3RMb2dNZXRyaWNzEigu", "Z29vZ2xlLmxvZ2dpbmcudjIuTGlzdExvZ01ldHJpY3NSZXF1ZXN0GikuZ29v", "Z2xlLmxvZ2dpbmcudjIuTGlzdExvZ01ldHJpY3NSZXNwb25zZSIngtPkkwIh", "Eh8vdjIve3BhcmVudD1wcm9qZWN0cy8qfS9tZXRyaWNzEoQBCgxHZXRMb2dN", "ZXRyaWMSJi5nb29nbGUubG9nZ2luZy52Mi5HZXRMb2dNZXRyaWNSZXF1ZXN0", "GhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmljIi6C0+STAigSJi92Mi97", "bWV0cmljX25hbWU9cHJvamVjdHMvKi9tZXRyaWNzLyp9EosBCg9DcmVhdGVM", "b2dNZXRyaWMSKS5nb29nbGUubG9nZ2luZy52Mi5DcmVhdGVMb2dNZXRyaWNS", "ZXF1ZXN0GhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmljIi+C0+STAiki", "Hy92Mi97cGFyZW50PXByb2plY3RzLyp9L21ldHJpY3M6Bm1ldHJpYxKSAQoP", "VXBkYXRlTG9nTWV0cmljEikuZ29vZ2xlLmxvZ2dpbmcudjIuVXBkYXRlTG9n", "TWV0cmljUmVxdWVzdBocLmdvb2dsZS5sb2dnaW5nLnYyLkxvZ01ldHJpYyI2", "gtPkkwIwGiYvdjIve21ldHJpY19uYW1lPXByb2plY3RzLyovbWV0cmljcy8q", "fToGbWV0cmljEoQBCg9EZWxldGVMb2dNZXRyaWMSKS5nb29nbGUubG9nZ2lu", "Zy52Mi5EZWxldGVMb2dNZXRyaWNSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVm", "LkVtcHR5Ii6C0+STAigqJi92Mi97bWV0cmljX25hbWU9cHJvamVjdHMvKi9t", "ZXRyaWNzLyp9QoIBChVjb20uZ29vZ2xlLmxvZ2dpbmcudjJCE0xvZ2dpbmdN", "ZXRyaWNzUHJvdG9QAVo4Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29v", "Z2xlYXBpcy9sb2dnaW5nL3YyO2xvZ2dpbmeqAhdHb29nbGUuQ2xvdWQuTG9n", "Z2luZy5WMmIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.LogMetric), global::Google.Cloud.Logging.V2.LogMetric.Parser, new[]{ "Name", "Description", "Filter", "Version" }, null, new[]{ typeof(global::Google.Cloud.Logging.V2.LogMetric.Types.ApiVersion) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.ListLogMetricsRequest), global::Google.Cloud.Logging.V2.ListLogMetricsRequest.Parser, new[]{ "Parent", "PageToken", "PageSize" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.ListLogMetricsResponse), global::Google.Cloud.Logging.V2.ListLogMetricsResponse.Parser, new[]{ "Metrics", "NextPageToken" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.GetLogMetricRequest), global::Google.Cloud.Logging.V2.GetLogMetricRequest.Parser, new[]{ "MetricName" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.CreateLogMetricRequest), global::Google.Cloud.Logging.V2.CreateLogMetricRequest.Parser, new[]{ "Parent", "Metric" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest), global::Google.Cloud.Logging.V2.UpdateLogMetricRequest.Parser, new[]{ "MetricName", "Metric" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest), global::Google.Cloud.Logging.V2.DeleteLogMetricRequest.Parser, new[]{ "MetricName" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Describes a logs-based metric. The value of the metric is the /// number of log entries that match a logs filter in a given time interval. /// </summary> public sealed partial class LogMetric : pb::IMessage<LogMetric> { private static readonly pb::MessageParser<LogMetric> _parser = new pb::MessageParser<LogMetric>(() => new LogMetric()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LogMetric> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogMetric() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogMetric(LogMetric other) : this() { name_ = other.name_; description_ = other.description_; filter_ = other.filter_; version_ = other.version_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogMetric Clone() { return new LogMetric(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. The client-assigned metric identifier. /// Examples: `"error_count"`, `"nginx/requests"`. /// /// Metric identifiers are limited to 100 characters and can include /// only the following characters: `A-Z`, `a-z`, `0-9`, and the /// special characters `_-.,+!*',()%/`. The forward-slash character /// (`/`) denotes a hierarchy of name pieces, and it cannot be the /// first character of the name. /// /// The metric identifier in this field must not be /// [URL-encoded](https://en.wikipedia.org/wiki/Percent-encoding). /// However, when the metric identifier appears as the `[METRIC_ID]` /// part of a `metric_name` API parameter, then the metric identifier /// must be URL-encoded. Example: /// `"projects/my-project/metrics/nginx%2Frequests"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 2; private string description_ = ""; /// <summary> /// Optional. A description of this metric, which is used in documentation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "filter" field.</summary> public const int FilterFieldNumber = 3; private string filter_ = ""; /// <summary> /// Required. An [advanced logs filter](/logging/docs/view/advanced_filters) /// which is used to match log entries. /// Example: /// /// "resource.type=gae_app AND severity>=ERROR" /// /// The maximum length of the filter is 20000 characters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Filter { get { return filter_; } set { filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "version" field.</summary> public const int VersionFieldNumber = 4; private global::Google.Cloud.Logging.V2.LogMetric.Types.ApiVersion version_ = 0; /// <summary> /// Output only. The API version that created or updated this metric. /// The version also dictates the syntax of the filter expression. When a value /// for this field is missing, the default value of V2 should be assumed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Logging.V2.LogMetric.Types.ApiVersion Version { get { return version_; } set { version_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LogMetric); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LogMetric other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Description != other.Description) return false; if (Filter != other.Filter) return false; if (Version != other.Version) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (Filter.Length != 0) hash ^= Filter.GetHashCode(); if (Version != 0) hash ^= Version.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Description.Length != 0) { output.WriteRawTag(18); output.WriteString(Description); } if (Filter.Length != 0) { output.WriteRawTag(26); output.WriteString(Filter); } if (Version != 0) { output.WriteRawTag(32); output.WriteEnum((int) Version); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (Filter.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter); } if (Version != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Version); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LogMetric other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Description.Length != 0) { Description = other.Description; } if (other.Filter.Length != 0) { Filter = other.Filter; } if (other.Version != 0) { Version = other.Version; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { Description = input.ReadString(); break; } case 26: { Filter = input.ReadString(); break; } case 32: { version_ = (global::Google.Cloud.Logging.V2.LogMetric.Types.ApiVersion) input.ReadEnum(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the LogMetric message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Stackdriver Logging API version. /// </summary> public enum ApiVersion { /// <summary> /// Stackdriver Logging API v2. /// </summary> [pbr::OriginalName("V2")] V2 = 0, /// <summary> /// Stackdriver Logging API v1. /// </summary> [pbr::OriginalName("V1")] V1 = 1, } } #endregion } /// <summary> /// The parameters to ListLogMetrics. /// </summary> public sealed partial class ListLogMetricsRequest : pb::IMessage<ListLogMetricsRequest> { private static readonly pb::MessageParser<ListLogMetricsRequest> _parser = new pb::MessageParser<ListLogMetricsRequest>(() => new ListLogMetricsRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListLogMetricsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListLogMetricsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListLogMetricsRequest(ListLogMetricsRequest other) : this() { parent_ = other.parent_; pageToken_ = other.pageToken_; pageSize_ = other.pageSize_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListLogMetricsRequest Clone() { return new ListLogMetricsRequest(this); } /// <summary>Field number for the "parent" field.</summary> public const int ParentFieldNumber = 1; private string parent_ = ""; /// <summary> /// Required. The name of the project containing the metrics: /// /// "projects/[PROJECT_ID]" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Parent { get { return parent_; } set { parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "page_token" field.</summary> public const int PageTokenFieldNumber = 2; private string pageToken_ = ""; /// <summary> /// Optional. If present, then retrieve the next batch of results from the /// preceding call to this method. `pageToken` must be the value of /// `nextPageToken` from the previous response. The values of other method /// parameters should be identical to those in the previous call. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PageToken { get { return pageToken_; } set { pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "page_size" field.</summary> public const int PageSizeFieldNumber = 3; private int pageSize_; /// <summary> /// Optional. The maximum number of results to return from this request. /// Non-positive values are ignored. The presence of `nextPageToken` in the /// response indicates that more results might be available. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PageSize { get { return pageSize_; } set { pageSize_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListLogMetricsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListLogMetricsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Parent != other.Parent) return false; if (PageToken != other.PageToken) return false; if (PageSize != other.PageSize) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Parent.Length != 0) hash ^= Parent.GetHashCode(); if (PageToken.Length != 0) hash ^= PageToken.GetHashCode(); if (PageSize != 0) hash ^= PageSize.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Parent.Length != 0) { output.WriteRawTag(10); output.WriteString(Parent); } if (PageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(PageToken); } if (PageSize != 0) { output.WriteRawTag(24); output.WriteInt32(PageSize); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Parent.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent); } if (PageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken); } if (PageSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListLogMetricsRequest other) { if (other == null) { return; } if (other.Parent.Length != 0) { Parent = other.Parent; } if (other.PageToken.Length != 0) { PageToken = other.PageToken; } if (other.PageSize != 0) { PageSize = other.PageSize; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Parent = input.ReadString(); break; } case 18: { PageToken = input.ReadString(); break; } case 24: { PageSize = input.ReadInt32(); break; } } } } } /// <summary> /// Result returned from ListLogMetrics. /// </summary> public sealed partial class ListLogMetricsResponse : pb::IMessage<ListLogMetricsResponse> { private static readonly pb::MessageParser<ListLogMetricsResponse> _parser = new pb::MessageParser<ListLogMetricsResponse>(() => new ListLogMetricsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListLogMetricsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListLogMetricsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListLogMetricsResponse(ListLogMetricsResponse other) : this() { metrics_ = other.metrics_.Clone(); nextPageToken_ = other.nextPageToken_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListLogMetricsResponse Clone() { return new ListLogMetricsResponse(this); } /// <summary>Field number for the "metrics" field.</summary> public const int MetricsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Logging.V2.LogMetric> _repeated_metrics_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Logging.V2.LogMetric.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogMetric> metrics_ = new pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogMetric>(); /// <summary> /// A list of logs-based metrics. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogMetric> Metrics { get { return metrics_; } } /// <summary>Field number for the "next_page_token" field.</summary> public const int NextPageTokenFieldNumber = 2; private string nextPageToken_ = ""; /// <summary> /// If there might be more results than appear in this response, then /// `nextPageToken` is included. To get the next set of results, call this /// method again using the value of `nextPageToken` as `pageToken`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NextPageToken { get { return nextPageToken_; } set { nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListLogMetricsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListLogMetricsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!metrics_.Equals(other.metrics_)) return false; if (NextPageToken != other.NextPageToken) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= metrics_.GetHashCode(); if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { metrics_.WriteTo(output, _repeated_metrics_codec); if (NextPageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(NextPageToken); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += metrics_.CalculateSize(_repeated_metrics_codec); if (NextPageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListLogMetricsResponse other) { if (other == null) { return; } metrics_.Add(other.metrics_); if (other.NextPageToken.Length != 0) { NextPageToken = other.NextPageToken; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { metrics_.AddEntriesFrom(input, _repeated_metrics_codec); break; } case 18: { NextPageToken = input.ReadString(); break; } } } } } /// <summary> /// The parameters to GetLogMetric. /// </summary> public sealed partial class GetLogMetricRequest : pb::IMessage<GetLogMetricRequest> { private static readonly pb::MessageParser<GetLogMetricRequest> _parser = new pb::MessageParser<GetLogMetricRequest>(() => new GetLogMetricRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetLogMetricRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetLogMetricRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetLogMetricRequest(GetLogMetricRequest other) : this() { metricName_ = other.metricName_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetLogMetricRequest Clone() { return new GetLogMetricRequest(this); } /// <summary>Field number for the "metric_name" field.</summary> public const int MetricNameFieldNumber = 1; private string metricName_ = ""; /// <summary> /// The resource name of the desired metric: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MetricName { get { return metricName_; } set { metricName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetLogMetricRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetLogMetricRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MetricName != other.MetricName) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (MetricName.Length != 0) hash ^= MetricName.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (MetricName.Length != 0) { output.WriteRawTag(10); output.WriteString(MetricName); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (MetricName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MetricName); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetLogMetricRequest other) { if (other == null) { return; } if (other.MetricName.Length != 0) { MetricName = other.MetricName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { MetricName = input.ReadString(); break; } } } } } /// <summary> /// The parameters to CreateLogMetric. /// </summary> public sealed partial class CreateLogMetricRequest : pb::IMessage<CreateLogMetricRequest> { private static readonly pb::MessageParser<CreateLogMetricRequest> _parser = new pb::MessageParser<CreateLogMetricRequest>(() => new CreateLogMetricRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CreateLogMetricRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateLogMetricRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateLogMetricRequest(CreateLogMetricRequest other) : this() { parent_ = other.parent_; Metric = other.metric_ != null ? other.Metric.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateLogMetricRequest Clone() { return new CreateLogMetricRequest(this); } /// <summary>Field number for the "parent" field.</summary> public const int ParentFieldNumber = 1; private string parent_ = ""; /// <summary> /// The resource name of the project in which to create the metric: /// /// "projects/[PROJECT_ID]" /// /// The new metric must be provided in the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Parent { get { return parent_; } set { parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "metric" field.</summary> public const int MetricFieldNumber = 2; private global::Google.Cloud.Logging.V2.LogMetric metric_; /// <summary> /// The new logs-based metric, which must not have an identifier that /// already exists. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Logging.V2.LogMetric Metric { get { return metric_; } set { metric_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CreateLogMetricRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CreateLogMetricRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Parent != other.Parent) return false; if (!object.Equals(Metric, other.Metric)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Parent.Length != 0) hash ^= Parent.GetHashCode(); if (metric_ != null) hash ^= Metric.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Parent.Length != 0) { output.WriteRawTag(10); output.WriteString(Parent); } if (metric_ != null) { output.WriteRawTag(18); output.WriteMessage(Metric); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Parent.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent); } if (metric_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metric); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CreateLogMetricRequest other) { if (other == null) { return; } if (other.Parent.Length != 0) { Parent = other.Parent; } if (other.metric_ != null) { if (metric_ == null) { metric_ = new global::Google.Cloud.Logging.V2.LogMetric(); } Metric.MergeFrom(other.Metric); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Parent = input.ReadString(); break; } case 18: { if (metric_ == null) { metric_ = new global::Google.Cloud.Logging.V2.LogMetric(); } input.ReadMessage(metric_); break; } } } } } /// <summary> /// The parameters to UpdateLogMetric. /// </summary> public sealed partial class UpdateLogMetricRequest : pb::IMessage<UpdateLogMetricRequest> { private static readonly pb::MessageParser<UpdateLogMetricRequest> _parser = new pb::MessageParser<UpdateLogMetricRequest>(() => new UpdateLogMetricRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UpdateLogMetricRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateLogMetricRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateLogMetricRequest(UpdateLogMetricRequest other) : this() { metricName_ = other.metricName_; Metric = other.metric_ != null ? other.Metric.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateLogMetricRequest Clone() { return new UpdateLogMetricRequest(this); } /// <summary>Field number for the "metric_name" field.</summary> public const int MetricNameFieldNumber = 1; private string metricName_ = ""; /// <summary> /// The resource name of the metric to update: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// /// The updated metric must be provided in the request and it's /// `name` field must be the same as `[METRIC_ID]` If the metric /// does not exist in `[PROJECT_ID]`, then a new metric is created. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MetricName { get { return metricName_; } set { metricName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "metric" field.</summary> public const int MetricFieldNumber = 2; private global::Google.Cloud.Logging.V2.LogMetric metric_; /// <summary> /// The updated metric. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Logging.V2.LogMetric Metric { get { return metric_; } set { metric_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UpdateLogMetricRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UpdateLogMetricRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MetricName != other.MetricName) return false; if (!object.Equals(Metric, other.Metric)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (MetricName.Length != 0) hash ^= MetricName.GetHashCode(); if (metric_ != null) hash ^= Metric.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (MetricName.Length != 0) { output.WriteRawTag(10); output.WriteString(MetricName); } if (metric_ != null) { output.WriteRawTag(18); output.WriteMessage(Metric); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (MetricName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MetricName); } if (metric_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metric); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UpdateLogMetricRequest other) { if (other == null) { return; } if (other.MetricName.Length != 0) { MetricName = other.MetricName; } if (other.metric_ != null) { if (metric_ == null) { metric_ = new global::Google.Cloud.Logging.V2.LogMetric(); } Metric.MergeFrom(other.Metric); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { MetricName = input.ReadString(); break; } case 18: { if (metric_ == null) { metric_ = new global::Google.Cloud.Logging.V2.LogMetric(); } input.ReadMessage(metric_); break; } } } } } /// <summary> /// The parameters to DeleteLogMetric. /// </summary> public sealed partial class DeleteLogMetricRequest : pb::IMessage<DeleteLogMetricRequest> { private static readonly pb::MessageParser<DeleteLogMetricRequest> _parser = new pb::MessageParser<DeleteLogMetricRequest>(() => new DeleteLogMetricRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DeleteLogMetricRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteLogMetricRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteLogMetricRequest(DeleteLogMetricRequest other) : this() { metricName_ = other.metricName_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteLogMetricRequest Clone() { return new DeleteLogMetricRequest(this); } /// <summary>Field number for the "metric_name" field.</summary> public const int MetricNameFieldNumber = 1; private string metricName_ = ""; /// <summary> /// The resource name of the metric to delete: /// /// "projects/[PROJECT_ID]/metrics/[METRIC_ID]" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MetricName { get { return metricName_; } set { metricName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DeleteLogMetricRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DeleteLogMetricRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MetricName != other.MetricName) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (MetricName.Length != 0) hash ^= MetricName.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (MetricName.Length != 0) { output.WriteRawTag(10); output.WriteString(MetricName); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (MetricName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MetricName); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DeleteLogMetricRequest other) { if (other == null) { return; } if (other.MetricName.Length != 0) { MetricName = other.MetricName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { MetricName = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { public class ConnectTest : ClientWebSocketTestBase { public ConnectTest(ITestOutputHelper output) : base(output) { } [ActiveIssue(20360, TargetFrameworkMonikers.NetFramework)] [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(UnavailableWebSocketServers))] public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server) { using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(server, cts.Token)); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task EchoBinaryMessage_Success(Uri server) { await WebSocketHelper.TestEcho(server, WebSocketMessageType.Binary, TimeOutMilliseconds, _output); } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task EchoTextMessage_Success(Uri server) { await WebSocketHelper.TestEcho(server, WebSocketMessageType.Text, TimeOutMilliseconds, _output); } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))] public async Task ConnectAsync_AddCustomHeaders_Success(Uri server) { using (var cws = new ClientWebSocket()) { cws.Options.SetRequestHeader("X-CustomHeader1", "Value1"); cws.Options.SetRequestHeader("X-CustomHeader2", "Value2"); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( (cws.State == WebSocketState.None) || (cws.State == WebSocketState.Connecting) || (cws.State == WebSocketState.Open), "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; var segment = new ArraySegment<byte>(buffer, 0, buffer.Length); WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await cws.ReceiveAsync(segment, cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(segment); Assert.True(headers.Contains("X-CustomHeader1:Value1")); Assert.True(headers.Contains("X-CustomHeader2:Value2")); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } [ActiveIssue(18784, TargetFrameworkMonikers.NetFramework)] [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))] public async Task ConnectAsync_AddHostHeader_Success(Uri server) { // Send via the physical address such as "corefx-net.cloudapp.net" // Set the Host header to logical address like "subdomain.corefx-net.cloudapp.net" // Verify the scenario works and the remote server received "Host: subdomain.corefx-net.cloudapp.net" string logicalHost = "subdomain." + server.Host; using (var cws = new ClientWebSocket()) { // Set the Host header to the logical address cws.Options.SetRequestHeader("Host", logicalHost); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { // Connect using the physical address Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( (cws.State == WebSocketState.None) || (cws.State == WebSocketState.Connecting) || (cws.State == WebSocketState.Open), "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; var segment = new ArraySegment<byte>(buffer, 0, buffer.Length); WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await cws.ReceiveAsync(segment, cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(segment); Assert.Contains($"Host:{logicalHost}", headers, StringComparison.Ordinal); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))] public async Task ConnectAsync_CookieHeaders_Success(Uri server) { using (var cws = new ClientWebSocket()) { Assert.Null(cws.Options.Cookies); cws.Options.Cookies = new CookieContainer(); cws.Options.Cookies.Add(server, new Cookie("Cookies", "Are Yummy")); cws.Options.Cookies.Add(server, new Cookie("Especially", "Chocolate Chip")); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( cws.State == WebSocketState.None || cws.State == WebSocketState.Connecting || cws.State == WebSocketState.Open, "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; var segment = new ArraySegment<byte>(buffer); WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await cws.ReceiveAsync(segment, cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(segment); Assert.True(headers.Contains("Cookies=Are Yummy")); Assert.True(headers.Contains("Especially=Chocolate Chip")); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task ConnectAsync_PassNoSubProtocol_ServerRequires_ThrowsWebSocketExceptionWithMessage(Uri server) { const string AcceptedProtocol = "CustomProtocol"; using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var ub = new UriBuilder(server); ub.Query = "subprotocol=" + AcceptedProtocol; WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(ub.Uri, cts.Token)); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task ConnectAsync_PassMultipleSubProtocols_ServerRequires_ConnectionUsesAgreedSubProtocol(Uri server) { const string AcceptedProtocol = "AcceptedProtocol"; const string OtherProtocol = "OtherProtocol"; using (var cws = new ClientWebSocket()) { cws.Options.AddSubProtocol(AcceptedProtocol); cws.Options.AddSubProtocol(OtherProtocol); var cts = new CancellationTokenSource(TimeOutMilliseconds); var ub = new UriBuilder(server); ub.Query = "subprotocol=" + AcceptedProtocol; await cws.ConnectAsync(ub.Uri, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); Assert.Equal(AcceptedProtocol, cws.SubProtocol); } } } }
using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Search { using Lucene.Net.Index; /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Bits = Lucene.Net.Util.Bits; using BytesRef = Lucene.Net.Util.BytesRef; using IndexReader = Lucene.Net.Index.IndexReader; using LongBitSet = Lucene.Net.Util.LongBitSet; using SortedDocValues = Lucene.Net.Index.SortedDocValues; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Rewrites MultiTermQueries into a filter, using the FieldCache for term enumeration. /// <p> /// this can be used to perform these queries against an unindexed docvalues field. /// @lucene.experimental /// </summary> public sealed class FieldCacheRewriteMethod : MultiTermQuery.RewriteMethod { public override Query Rewrite(IndexReader reader, MultiTermQuery query) { Query result = new ConstantScoreQuery(new MultiTermQueryFieldCacheWrapperFilter(query)); result.Boost = query.Boost; return result; } internal class MultiTermQueryFieldCacheWrapperFilter : Filter { protected internal readonly MultiTermQuery Query; /// <summary> /// Wrap a <seealso cref="MultiTermQuery"/> as a Filter. /// </summary> protected internal MultiTermQueryFieldCacheWrapperFilter(MultiTermQuery query) { this.Query = query; } public override string ToString() { // query.toString should be ok for the filter, too, if the query boost is 1.0f return Query.ToString(); } public override sealed bool Equals(object o) { if (o == this) { return true; } if (o == null) { return false; } if (this.GetType().Equals(o.GetType())) { return this.Query.Equals(((MultiTermQueryFieldCacheWrapperFilter)o).Query); } return false; } public override sealed int GetHashCode() { return Query.GetHashCode(); } /// <summary> /// Returns the field name for this query </summary> public string Field { get { return Query.Field; } } /// <summary> /// Returns a DocIdSet with documents that should be permitted in search /// results. /// </summary> public override DocIdSet GetDocIdSet(AtomicReaderContext context, Bits acceptDocs) { SortedDocValues fcsi = FieldCache.DEFAULT.GetTermsIndex((context.AtomicReader), Query.field); // Cannot use FixedBitSet because we require long index (ord): LongBitSet termSet = new LongBitSet(fcsi.ValueCount); TermsEnum termsEnum = Query.GetTermsEnum(new TermsAnonymousInnerClassHelper(this, fcsi)); Debug.Assert(termsEnum != null); if (termsEnum.Next() != null) { // fill into a bitset do { long ord = termsEnum.Ord(); if (ord >= 0) { termSet.Set(ord); } } while (termsEnum.Next() != null); } else { return null; } return new FieldCacheDocIdSetAnonymousInnerClassHelper(this, context.Reader.MaxDoc, acceptDocs, fcsi, termSet); } private class TermsAnonymousInnerClassHelper : Terms { private readonly MultiTermQueryFieldCacheWrapperFilter OuterInstance; private SortedDocValues Fcsi; public TermsAnonymousInnerClassHelper(MultiTermQueryFieldCacheWrapperFilter outerInstance, SortedDocValues fcsi) { this.OuterInstance = outerInstance; this.Fcsi = fcsi; } public override IComparer<BytesRef> Comparator { get { return BytesRef.UTF8SortedAsUnicodeComparer; } } public override TermsEnum Iterator(TermsEnum reuse) { return Fcsi.TermsEnum(); } public override long SumTotalTermFreq { get { return -1; } } public override long SumDocFreq { get { return -1; } } public override int DocCount { get { return -1; } } public override long Size() { return -1; } public override bool HasFreqs() { return false; } public override bool HasOffsets() { return false; } public override bool HasPositions() { return false; } public override bool HasPayloads() { return false; } } private class FieldCacheDocIdSetAnonymousInnerClassHelper : FieldCacheDocIdSet { private readonly MultiTermQueryFieldCacheWrapperFilter OuterInstance; private SortedDocValues Fcsi; private LongBitSet TermSet; public FieldCacheDocIdSetAnonymousInnerClassHelper(MultiTermQueryFieldCacheWrapperFilter outerInstance, int maxDoc, Bits acceptDocs, SortedDocValues fcsi, LongBitSet termSet) : base(maxDoc, acceptDocs) { this.OuterInstance = outerInstance; this.Fcsi = fcsi; this.TermSet = termSet; } protected internal override sealed bool MatchDoc(int doc) { int ord = Fcsi.GetOrd(doc); if (ord == -1) { return false; } return TermSet.Get(ord); } } } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } return true; } public override int GetHashCode() { return 641; } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using nzy3D.Plot3D.Rendering.Canvas; using nzy3D.Plot3D.Rendering.Scene; using nzy3D.Events; namespace nzy3D.Plot3D.Rendering.View { /// <summary> /// /// </summary> /// <remarks></remarks> public class Renderer3D : OpenTK.GLControl, ICanvas, IControllerEventListener { // TODO : add trace add debug capabilities internal View _view; internal int _width = 0; internal int _height = 0; internal bool _doScreenshotAtNextDisplay = false; internal bool _traceGL; internal bool _debugGL; internal System.Drawing.Bitmap _image; //Public Sub New(view As View) // Me.New(view, False, False) //End Sub //Public Sub New(view As View, traceGL As Boolean, debugGL As Boolean) // _view = view // _traceGL = traceGL // _debugGL = debugGL //End Sub //Private Sub Renderer3D_Load(sender As Object, e As System.EventArgs) Handles Me.Load //End Sub private void Renderer3D_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { if ((_view != null)) { _view.Clear(); _view.Render(); this.SwapBuffers(); if (_doScreenshotAtNextDisplay) { GrabScreenshot2(); _doScreenshotAtNextDisplay = false; } } } private void Renderer3D_Resize(object sender, System.EventArgs e) { _width = this.ClientSize.Width; _height = this.ClientSize.Height; if ((_view != null)) { _view.DimensionDirty = true; } } private void GrabScreenshot2() { if (_image == null || _image.Width != this.Width || _image.Height != this.Height) { _image = new System.Drawing.Bitmap(ClientSize.Width, ClientSize.Height); } System.Drawing.Imaging.BitmapData data = _image.LockBits(this.ClientRectangle, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); //OpenTK.Graphics.OpenGL.GL.ReadPixels(0, 0, ClientSize.Width, ClientSize.Height, OpenTK.Graphics.PixelFormat.Bgr, OpenTK.Graphics.PixelType.UnsignedByte, data.Scan0) OpenTK.Graphics.OpenGL.PixelFormat pxFormat = OpenTK.Graphics.OpenGL.PixelFormat.Bgr; OpenTK.Graphics.OpenGL.PixelType pxType = OpenTK.Graphics.OpenGL.PixelType.UnsignedByte; OpenTK.Graphics.OpenGL.GL.ReadPixels(0, 0, ClientSize.Width, ClientSize.Height, pxFormat, pxType, data.Scan0); _image.UnlockBits(data); _image.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY); } public void nextDisplayUpdateScreenshot() { _doScreenshotAtNextDisplay = true; } public System.Drawing.Bitmap LastScreenshot { get { return _image; } } public new int Width { get { return _width; } } public new int Height { get { return _height; } } public void addKeyListener(Events.Keyboard.IKeyListener listener) { KeyUp += listener.KeyReleased; KeyDown += listener.KeyPressed; // be cautious with cross-terminology (key_down / key_pressed / key_typed) KeyPress += listener.KeyTyped; // be cautious with cross-terminology (key_down / key_pressed / key_typed) } public void addMouseListener(Events.Mouse.IMouseListener listener) { MouseClick += listener.MouseClicked; MouseDown += listener.MousePressed; MouseUp += listener.MouseReleased; MouseDoubleClick += listener.MouseDoubleClicked; } public void addMouseMotionListener(Events.Mouse.IMouseMotionListener listener) { MouseMove += listener.MouseMoved; // NOT AVAILABLE IN WinForms : AddHandler ???, AddressOf listener.MouseDragged } public void addMouseWheelListener(Events.Mouse.IMouseWheelListener listener) { MouseWheel += listener.MouseWheelMoved; } public void Dispose1() { } void Canvas.ICanvas.Dispose() { Dispose1(); } public void ForceRepaint() { this.Invalidate(); } public void removeKeyListener(Events.Keyboard.IKeyListener listener) { KeyUp -= listener.KeyReleased; KeyDown -= listener.KeyPressed; // be cautious with cross-terminology (key_down / key_pressed / key_typed) KeyPress -= listener.KeyTyped; // be cautious with cross-terminology (key_down / key_pressed / key_typed) } public void removeMouseListener(Events.Mouse.IMouseListener listener) { MouseClick -= listener.MouseClicked; MouseDown -= listener.MousePressed; MouseUp -= listener.MouseReleased; } public void removeMouseMotionListener(Events.Mouse.IMouseMotionListener listener) { MouseMove -= listener.MouseMoved; // NOT AVAILABLE IN WinForms : RemoveHandler ???, AddressOf listener.MouseDragged } public void removeMouseWheelListener(Events.Mouse.IMouseWheelListener listener) { MouseWheel -= listener.MouseWheelMoved; } public int RendererHeight { get { return _height; } } public int RendererWidth { get { return _width; } } public System.Drawing.Bitmap Screenshot() { //Throw New NotImplementedException() this.GrabScreenshot2(); return _image; } public View View { //Throw New NotImplementedException("Property View is not implemented in nzy3D renderer, should not be necessary") get { return _view; } } public void setView(View value) { _view = value; _view.Init(); _view.Scene.Graph.MountAllGLBindedResources(); _view.BoundManual = _view.Scene.Graph.Bounds; } public void ControllerEventFired(Events.ControllerEventArgs e) { this.ForceRepaint(); } public Renderer3D() { Resize += Renderer3D_Resize; Paint += Renderer3D_Paint; } } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // IntersectQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Operator that yields the intersection of two data sources. /// </summary> /// <typeparam name="TInputOutput"></typeparam> internal sealed class IntersectQueryOperator<TInputOutput> : BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput> { private readonly IEqualityComparer<TInputOutput> _comparer; // An equality comparer. //--------------------------------------------------------------------------------------- // Constructs a new intersection operator. // internal IntersectQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput> comparer) : base(left, right) { Debug.Assert(left != null && right != null, "child data sources cannot be null"); _comparer = comparer; _outputOrdered = LeftChild.OutputOrdered; SetOrdinalIndex(OrdinalIndexState.Shuffled); } internal override QueryResults<TInputOutput> Open( QuerySettings settings, bool preferStriping) { // We just open our child operators, left and then right. Do not propagate the preferStriping value, but // instead explicitly set it to false. Regardless of whether the parent prefers striping or range // partitioning, the output will be hash-partititioned. QueryResults<TInputOutput> leftChildResults = LeftChild.Open(settings, false); QueryResults<TInputOutput> rightChildResults = RightChild.Open(settings, false); return new BinaryQueryOperatorResults(leftChildResults, rightChildResults, this, settings, false); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TInputOutput, TLeftKey> leftPartitionedStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings) { Debug.Assert(leftPartitionedStream.PartitionCount == rightPartitionedStream.PartitionCount); if (OutputOrdered) { WrapPartitionedStreamHelper<TLeftKey, TRightKey>( ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftPartitionedStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken); } else { WrapPartitionedStreamHelper<int, TRightKey>( ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftPartitionedStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken); } } //--------------------------------------------------------------------------------------- // This is a helper method. WrapPartitionedStream decides what type TLeftKey is going // to be, and then call this method with that key as a generic parameter. // private void WrapPartitionedStreamHelper<TLeftKey, TRightKey>( PartitionedStream<Pair, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, CancellationToken cancellationToken) { int partitionCount = leftHashStream.PartitionCount; PartitionedStream<Pair, int> rightHashStream = ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>( rightPartitionedStream, null, null, _comparer, cancellationToken); PartitionedStream<TInputOutput, TLeftKey> outputStream = new PartitionedStream<TInputOutput, TLeftKey>(partitionCount, leftHashStream.KeyComparer, OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { if (OutputOrdered) { outputStream[i] = new OrderedIntersectQueryOperatorEnumerator<TLeftKey>( leftHashStream[i], rightHashStream[i], _comparer, leftHashStream.KeyComparer, cancellationToken); } else { outputStream[i] = (QueryOperatorEnumerator<TInputOutput, TLeftKey>)(object) new IntersectQueryOperatorEnumerator<TLeftKey>(leftHashStream[i], rightHashStream[i], _comparer, cancellationToken); } } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // This enumerator performs the intersection operation incrementally. It does this by // maintaining a history -- in the form of a set -- of all data already seen. It then // only returns elements that are seen twice (returning each one only once). // class IntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, int> { private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair, int> _rightSource; // Right data source. private IEqualityComparer<TInputOutput> _comparer; // Comparer to use for equality/hash-coding. private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the intersection. private CancellationToken _cancellationToken; private Shared<int> _outputLoopCount; //--------------------------------------------------------------------------------------- // Instantiates a new intersection operator. // internal IntersectQueryOperatorEnumerator( QueryOperatorEnumerator<Pair, TLeftKey> leftSource, QueryOperatorEnumerator<Pair, int> rightSource, IEqualityComparer<TInputOutput> comparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _comparer = comparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the intersection. // internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey) { Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); // Build the set out of the right data source, if we haven't already. if (_hashLookup == null) { _outputLoopCount = new Shared<int>(0); _hashLookup = new Set<TInputOutput>(_comparer); Pair rightElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); int rightKeyUnused = default(int); int i = 0; while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); _hashLookup.Add((TInputOutput)rightElement.First); } } // Now iterate over the left data source, looking for matches. Pair leftElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); TLeftKey keyUnused = default(TLeftKey); while (_leftSource.MoveNext(ref leftElement, ref keyUnused)) { if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // If we found the element in our set, and if we haven't returned it yet, // we can yield it to the caller. We also mark it so we know we've returned // it once already and never will again. if (_hashLookup.Contains((TInputOutput)leftElement.First)) { _hashLookup.Remove((TInputOutput)leftElement.First); currentElement = (TInputOutput)leftElement.First; #if DEBUG currentKey = unchecked((int)0xdeadbeef); #endif return true; } } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.Dispose(); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token); IEnumerable<TInputOutput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token); return wrappedLeftChild.Intersect(wrappedRightChild, _comparer); } class OrderedIntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, TLeftKey> { private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair, int> _rightSource; // Right data source. private IEqualityComparer<Wrapper<TInputOutput>> _comparer; // Comparer to use for equality/hash-coding. private IComparer<TLeftKey> _leftKeyComparer; // Comparer to use to determine ordering of order keys. private Dictionary<Wrapper<TInputOutput>, Pair> _hashLookup; // The hash lookup, used to produce the intersection. private CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new intersection operator. // internal OrderedIntersectQueryOperatorEnumerator( QueryOperatorEnumerator<Pair, TLeftKey> leftSource, QueryOperatorEnumerator<Pair, int> rightSource, IEqualityComparer<TInputOutput> comparer, IComparer<TLeftKey> leftKeyComparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _comparer = new WrapperEqualityComparer<TInputOutput>(comparer); _leftKeyComparer = leftKeyComparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the intersection. // internal override bool MoveNext(ref TInputOutput currentElement, ref TLeftKey currentKey) { Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); // Build the set out of the left data source, if we haven't already. int i = 0; if (_hashLookup == null) { _hashLookup = new Dictionary<Wrapper<TInputOutput>, Pair>(_comparer); Pair leftElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); TLeftKey leftKey = default(TLeftKey); while (_leftSource.MoveNext(ref leftElement, ref leftKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // For each element, we track the smallest order key for that element that we saw so far Pair oldEntry; Wrapper<TInputOutput> wrappedLeftElem = new Wrapper<TInputOutput>((TInputOutput)leftElement.First); // If this is the first occurence of this element, or the order key is lower than all keys we saw previously, // update the order key for this element. if (!_hashLookup.TryGetValue(wrappedLeftElem, out oldEntry) || _leftKeyComparer.Compare(leftKey, (TLeftKey)oldEntry.Second) < 0) { // For each "elem" value, we store the smallest key, and the element value that had that key. // Note that even though two element values are "equal" according to the EqualityComparer, // we still cannot choose arbitrarily which of the two to yield. _hashLookup[wrappedLeftElem] = new Pair(leftElement.First, leftKey); } } } // Now iterate over the right data source, looking for matches. Pair rightElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); int rightKeyUnused = default(int); while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // If we found the element in our set, and if we haven't returned it yet, // we can yield it to the caller. We also mark it so we know we've returned // it once already and never will again. Pair entry; Wrapper<TInputOutput> wrappedRightElem = new Wrapper<TInputOutput>((TInputOutput)rightElement.First); if (_hashLookup.TryGetValue(wrappedRightElem, out entry)) { currentElement = (TInputOutput)entry.First; currentKey = (TLeftKey)entry.Second; _hashLookup.Remove(new Wrapper<TInputOutput>((TInputOutput)entry.First)); return true; } } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.Dispose(); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Nicolai.Utils.Composition.CompositionHelper; using System.Composition.Hosting; using System.Composition; using System.Linq; using System.Composition.Convention; using System; namespace UnitTests { [TestClass] public class SimpleUsageTests { [TestMethod] public void GetExport_StandardImpl_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act var instance = helper.GetExport<ICompositionTest>(); //Assert Assert.IsNotNull(instance); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] public void TryGetExport_StandardImpl_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act ICompositionTest instance; bool result = helper.TryGetExport(out instance); //Assert Assert.IsTrue(result); Assert.IsNotNull(instance); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] public void GetNamedExport_StandardImpl_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act var instance = helper.GetExport<ICompositionTest>("NamedImplementation"); //Assert Assert.IsNotNull(instance); Assert.AreEqual(typeof(NamedCompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] public void TryGetNamedExport_StandardImpl_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act ICompositionTest instance; bool result = helper.TryGetExport(out instance, "NamedImplementation"); // Assert Assert.IsTrue(result); Assert.IsNotNull(instance); Assert.AreEqual(typeof(NamedCompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] [ExpectedException(typeof(CompositionFailedException))] public void GetNamedExport_WrongContractName_Throws() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act and Assert helper.GetExport<ICompositionTest>("WrongName"); } [TestMethod] public void TryGetNamedExport_WrongContractName_Fails() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act ICompositionTest instance; var result = helper.TryGetExport(out instance, "WrongName"); // Assert Assert.IsFalse(result); Assert.IsNull(instance); } [TestMethod] public void GetExport_StubImpl_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act var instance = helper.GetExport<ICompositionTest>(); // Assert Assert.IsNotNull(instance); Assert.AreEqual(typeof(StubCompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] public void TryGetExport_StubImpl_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act ICompositionTest instance; var result = helper.TryGetExport(out instance); // Assert Assert.IsTrue(result); Assert.IsNotNull(instance); Assert.AreEqual(typeof(StubCompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] public void Dispose_StubDisposed_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); var instance = helper.GetExport<ICompositionTest>(); // Act helper.Dispose(true); // Assert Assert.IsNotNull(instance); Assert.AreEqual(typeof(StubCompositionTestImplementation).FullName, instance.GetType().FullName); Assert.IsTrue(instance.DisposeCalled); } [TestMethod] public void Dispose_StubNotDisposed_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); var instance = helper.GetExport<ICompositionTest>(); // Act helper.Dispose(false); // Assert Assert.IsNotNull(instance); Assert.AreEqual(typeof(StubCompositionTestImplementation).FullName, instance.GetType().FullName); Assert.IsFalse(instance.DisposeCalled); } [TestMethod] [ExpectedException(typeof(CompositionFailedException))] public void GetExport_MultipleImpl_Throws() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(NamedCompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act and Assert helper.GetExport<ICompositionTest>(); } [TestMethod] public void TryGetExport_MultipleImpl_Fails() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(NamedCompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act ICompositionTest instance; var result = helper.TryGetExport(out instance); // Assert Assert.IsFalse(result); Assert.IsNull(instance); } [TestMethod] public void GetExport_MultipleImplOneNamed_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act var instance = helper.GetExport<ICompositionTest>(); // Assert Assert.IsNotNull(instance); Assert.AreEqual(typeof(StubCompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] public void TryGetExport_MultipleImplOneNamed_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act ICompositionTest instance; var result = helper.TryGetExport(out instance); // Assert Assert.IsTrue(result); Assert.IsNotNull(instance); Assert.AreEqual(typeof(StubCompositionTestImplementation).FullName, instance.GetType().FullName); } [TestMethod] [ExpectedException(typeof(CompositionFailedException))] public void GetNamedExport_MultipleImplOneNamed_Throws() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act and Assert helper.GetExport<ICompositionTest>("NamedImplementation"); } [TestMethod] public void TryGetNamedExport_MultipleImplOneNamed_Fails() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTestImplementation)); ICompositionTest stub = new StubCompositionTestImplementation(); helper.ComposeExport(stub); // Act ICompositionTest instance; var result = helper.TryGetExport(out instance, "NamedImplementation"); // Assert Assert.IsFalse(result); Assert.IsNull(instance); } [TestMethod] public void GetExports_Generic_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act var types = helper.GetExports<ICompositionTest3>()?.ToList(); // Assert Assert.IsNotNull(types); Assert.AreEqual(2, types.Count); Assert.IsTrue(types.Where(t => t.GetType() == typeof(CompositionTest3Implementation1)).Any()); Assert.IsTrue(types.Where(t => t.GetType() == typeof(CompositionTest3Implementation2)).Any()); } [TestMethod] public void GetExports_NamedGeneric_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act var types = helper.GetExports<ICompositionTest3>("NamedImplementation")?.ToList(); // Assert Assert.IsNotNull(types); Assert.AreEqual(2, types.Count); Assert.IsTrue(types.Where(t => t.GetType() == typeof(NamedCompositionTest3Implementation1)).Any()); Assert.IsTrue(types.Where(t => t.GetType() == typeof(NamedCompositionTest3Implementation2)).Any()); } [TestMethod] public void GetExports_NonGeneric_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act var types = helper.GetExports(typeof(ICompositionTest3))?.ToList(); // Assert Assert.IsNotNull(types); Assert.AreEqual(2, types.Count); Assert.IsTrue(types.Where(t => t.GetType() == typeof(CompositionTest3Implementation1)).Any()); Assert.IsTrue(types.Where(t => t.GetType() == typeof(CompositionTest3Implementation2)).Any()); } [TestMethod] public void GetExports_NamedNonGeneric_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act var types = helper.GetExports(typeof(ICompositionTest3), "NamedImplementation")?.ToList(); // Assert Assert.IsNotNull(types); Assert.AreEqual(2, types.Count); Assert.IsTrue(types.Where(t => t.GetType() == typeof(NamedCompositionTest3Implementation1)).Any()); Assert.IsTrue(types.Where(t => t.GetType() == typeof(NamedCompositionTest3Implementation2)).Any()); } [TestMethod] public void ExportableTypes_All_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); PrivateObject po = new PrivateObject(helper); po.Invoke("CreateCompositionHost"); // Act var result = helper.ExportableTypes?.ToList(); // Assert Assert.IsNotNull(result); Assert.AreEqual(3, result.Count); Assert.IsTrue(result.Contains(typeof(ICompositionTest))); Assert.IsTrue(result.Contains(typeof(ICompositionTest2))); } [TestMethod] public void ExportableTypes_TypeExcluded_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, typeof(CompositionTest2Implementation)); PrivateObject po = new PrivateObject(helper); po.Invoke("CreateCompositionHost"); // Act var result = helper.ExportableTypes?.ToList(); // Assert Assert.IsNotNull(result); Assert.AreEqual(2, result.Count); Assert.IsTrue(result.Contains(typeof(ICompositionTest))); } [TestMethod] public void GetExport_NonShared_Success() { // Arrange var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }); // Act var instance1 = helper.GetExport<ICompositionTest>(); var instance2 = helper.GetExport<ICompositionTest>(); // Assert Assert.IsNotNull(instance1); Assert.IsNotNull(instance2); Assert.AreNotEqual(instance1, instance2); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance1.GetType().FullName); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance2.GetType().FullName); } [TestMethod] public void GetExport_NonSharedOverrideToShared_Success() { // Arrange var conventions = new ConventionBuilder(); conventions.ForTypesMatching(t => true).Shared(); var helper = new CompositionHelper().AddAssemblies(new[] { GetType().Assembly }, conventions); // Act var instance1 = helper.GetExport<ICompositionTest>(); var instance2 = helper.GetExport<ICompositionTest>(); // Assert Assert.IsNotNull(instance1); Assert.IsNotNull(instance2); Assert.AreEqual(instance1, instance2); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance1.GetType().FullName); } [TestMethod] public void GetExport_Shared_Success() { // Arrange var helper = new CompositionHelper(true).AddAssemblies(new[] { GetType().Assembly }); // Act var instance1 = helper.GetExport<ICompositionTest>(); var instance2 = helper.GetExport<ICompositionTest>(); // Assert Assert.IsNotNull(instance1); Assert.IsNotNull(instance2); Assert.AreEqual(instance1, instance2); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance1.GetType().FullName); } [TestMethod] public void GetExport_SharedOverrideToNonShared_Success() { // Arrange var helper = new CompositionHelper(true).AddAssemblies(new[] { GetType().Assembly }, new ConventionBuilder()); // Act var instance1 = helper.GetExport<ICompositionTest>(); var instance2 = helper.GetExport<ICompositionTest>(); // Assert Assert.IsNotNull(instance1); Assert.IsNotNull(instance2); Assert.AreNotEqual(instance1, instance2); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance1.GetType().FullName); Assert.AreEqual(typeof(CompositionTestImplementation).FullName, instance2.GetType().FullName); } } public interface ICompositionTest { bool DisposeCalled { get; } } public interface ICompositionTest2 { } public interface ICompositionTest3 { } [Export(typeof(ICompositionTest))] public class CompositionTestImplementation : ICompositionTest { public bool DisposeCalled => false; } [Export("NamedImplementation", typeof(ICompositionTest))] public class NamedCompositionTestImplementation : ICompositionTest { public bool DisposeCalled => false; } internal class StubCompositionTestImplementation : ICompositionTest, IDisposable { public bool DisposeCalled { get; private set; } public void Dispose() { DisposeCalled = true; } } [Export(typeof(ICompositionTest2))] public class CompositionTest2Implementation : ICompositionTest2 { } [Export(typeof(ICompositionTest3))] public class CompositionTest3Implementation1 : ICompositionTest3 { } [Export(typeof(ICompositionTest3))] public class CompositionTest3Implementation2 : ICompositionTest3 { } [Export("NamedImplementation", typeof(ICompositionTest3))] public class NamedCompositionTest3Implementation1 : ICompositionTest3 { } [Export("NamedImplementation", typeof(ICompositionTest3))] public class NamedCompositionTest3Implementation2 : ICompositionTest3 { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Linq; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableArray{T}"/>. /// </summary> public static class ImmutableArray { /// <summary> /// A two element array useful for throwing exceptions the way LINQ does. /// </summary> internal static readonly byte[] TwoElementArray = new byte[2]; /// <summary> /// Creates an empty <see cref="ImmutableArray{T}"/>. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <returns>An empty array.</returns> [Pure] public static ImmutableArray<T> Create<T>() { return ImmutableArray<T>.Empty; } /// <summary> /// Creates an <see cref="ImmutableArray{T}"/> with the specified element as its only member. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item">The element to store in the array.</param> /// <returns>A 1-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item) { T[] array = new[] { item }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an <see cref="ImmutableArray{T}"/> with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <returns>A 2-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2) { T[] array = new[] { item1, item2 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an <see cref="ImmutableArray{T}"/> with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <param name="item3">The third element to store in the array.</param> /// <returns>A 3-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2, T item3) { T[] array = new[] { item1, item2, item3 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an <see cref="ImmutableArray{T}"/> with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <param name="item3">The third element to store in the array.</param> /// <param name="item4">The fourth element to store in the array.</param> /// <returns>A 4-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4) { T[] array = new[] { item1, item2, item3, item4 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an <see cref="ImmutableArray{T}"/> populated with the contents of the specified sequence. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="items">The elements to store in the array.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items) { Requires.NotNull(items, nameof(items)); // As an optimization, if the provided enumerable is actually a // boxed ImmutableArray<T> instance, reuse the underlying array if possible. // Note that this allows for automatic upcasting and downcasting of arrays // where the CLR allows it. var immutableArray = items as IImmutableArray; if (immutableArray != null) { Array array = immutableArray.Array; if (array == null) { throw new InvalidOperationException(SR.InvalidOperationOnDefaultArray); } // `array` must not be null at this point, and we know it's an // ImmutableArray<T> or ImmutableArray<SomethingDerivedFromT> as they are // the only types that could be both IEnumerable<T> and IImmutableArray. // As such, we know that items is either an ImmutableArray<T> or // ImmutableArray<TypeDerivedFromT>, and we can cast the array to T[]. return new ImmutableArray<T>((T[])array); } // We don't recognize the source as an array that is safe to use. // So clone the sequence into an array and return an immutable wrapper. int count; if (items.TryGetCount(out count)) { // We know how long the sequence is. Linq's built-in ToArray extension method // isn't as comprehensive in finding the length as we are, so call our own method // to avoid reallocating arrays as the sequence is enumerated. return new ImmutableArray<T>(items.ToArray(count)); } else { return new ImmutableArray<T>(items.ToArray()); } } /// <summary> /// Creates an empty <see cref="ImmutableArray{T}"/>. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="items">The elements to store in the array.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<T> Create<T>(params T[] items) { if (items == null) { return Create<T>(); } // We can't trust that the array passed in will never be mutated by the caller. // The caller may have passed in an array explicitly (not relying on compiler params keyword) // and could then change the array after the call, thereby violating the immutable // guarantee provided by this struct. So we always copy the array to ensure it won't ever change. return CreateDefensiveCopy(items); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The array to initialize the array with. A defensive copy is made.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <remarks> /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant /// tax for copying an array when the new array is a segment of an existing array. /// </remarks> [Pure] public static ImmutableArray<T> Create<T>(T[] items, int start, int length) { Requires.NotNull(items, nameof(items)); Requires.Range(start >= 0 && start <= items.Length, nameof(start)); Requires.Range(length >= 0 && start + length <= items.Length, nameof(length)); if (length == 0) { // Avoid allocating an array. return Create<T>(); } var array = new T[length]; for (int i = 0; i < array.Length; i++) { array[i] = items[start + i]; } return new ImmutableArray<T>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The array to initialize the array with. /// The selected array segment may be copied into a new array.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <remarks> /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant /// tax for copying an array when the new array is a segment of an existing array. /// </remarks> [Pure] public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length) { Requires.Range(start >= 0 && start <= items.Length, nameof(start)); Requires.Range(length >= 0 && start + length <= items.Length, nameof(length)); if (length == 0) { return Create<T>(); } if (start == 0 && length == items.Length) { return items; } var array = new T[length]; Array.Copy(items.array, start, array, 0, length); return new ImmutableArray<T>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="selector">The function to apply to each element from the source array.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on an existing /// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from /// the source array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector) { Requires.NotNull(selector, nameof(selector)); int length = items.Length; if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i]); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on a slice of an existing /// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from the source array /// included in the resulting array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector) { int itemsLength = items.Length; Requires.Range(start >= 0 && start <= itemsLength, nameof(start)); Requires.Range(length >= 0 && start + length <= itemsLength, nameof(length)); Requires.NotNull(selector, nameof(selector)); if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i + start]); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="selector">The function to apply to each element from the source array.</param> /// <param name="arg">An argument to be passed to the selector mapping function.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on an existing /// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from /// the source array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg) { Requires.NotNull(selector, nameof(selector)); int length = items.Length; if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i], arg); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param> /// <param name="arg">An argument to be passed to the selector mapping function.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on a slice of an existing /// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from the source array /// included in the resulting array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg) { int itemsLength = items.Length; Requires.Range(start >= 0 && start <= itemsLength, nameof(start)); Requires.Range(length >= 0 && start + length <= itemsLength, nameof(length)); Requires.NotNull(selector, nameof(selector)); if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i + start], arg); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}.Builder"/> class. /// </summary> /// <typeparam name="T">The type of elements stored in the array.</typeparam> /// <returns>A new builder.</returns> [Pure] public static ImmutableArray<T>.Builder CreateBuilder<T>() { return Create<T>().ToBuilder(); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}.Builder"/> class. /// </summary> /// <typeparam name="T">The type of elements stored in the array.</typeparam> /// <param name="initialCapacity">The size of the initial array backing the builder.</param> /// <returns>A new builder.</returns> [Pure] public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity) { return new ImmutableArray<T>.Builder(initialCapacity); } /// <summary> /// Enumerates a sequence exactly once and produces an immutable array of its contents. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <param name="items">The sequence to enumerate.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items) { if (items is ImmutableArray<TSource>) { return (ImmutableArray<TSource>)items; } return CreateRange(items); } /// <summary> /// Searches an entire one-dimensional sorted <see cref="ImmutableArray{T}"/> for a specific element, /// using the <see cref="IComparable{T}"/> generic interface implemented by each element /// of the <see cref="ImmutableArray{T}"/> and by the specified object. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="value">The object to search for.</param> /// <returns> /// The index of the specified <paramref name="value"/> in the specified array, if <paramref name="value"/> is found. /// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="InvalidOperationException"> /// <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and /// the search encounters an element that does not implement the <see cref="IComparable{T}"/> /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, T value) { return Array.BinarySearch<T>(array.array, value); } /// <summary> /// Searches an entire one-dimensional sorted <see cref="ImmutableArray{T}"/> for a value using /// the specified <see cref="IComparer{T}"/> generic interface. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="value">The object to search for.</param> /// <param name="comparer"> /// The <see cref="IComparer{T}"/> implementation to use when comparing /// elements; or null to use the <see cref="IComparable{T}"/> implementation of each /// element. /// </param> /// <returns> /// The index of the specified <paramref name="value"/> in the specified array, if <paramref name="value"/> is found. /// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="InvalidOperationException"> /// <paramref name="comparer"/> is null, <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and /// the search encounters an element that does not implement the <see cref="IComparable{T}"/> /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T> comparer) { return Array.BinarySearch<T>(array.array, value, comparer); } /// <summary> /// Searches a range of elements in a one-dimensional sorted <see cref="ImmutableArray{T}"/> for /// a value, using the <see cref="IComparable{T}"/> generic interface implemented by /// each element of the <see cref="ImmutableArray{T}"/> and by the specified value. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="index">The starting index of the range to search.</param> /// <param name="length">The length of the range to search.</param> /// <param name="value">The object to search for.</param> /// <returns> /// The index of the specified <paramref name="value"/> in the specified <paramref name="array"/>, if <paramref name="value"/> is found. /// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in <paramref name="array"/>, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater /// than any of the elements in <paramref name="array"/>, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="InvalidOperationException"> /// <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and /// the search encounters an element that does not implement the <see cref="IComparable{T}"/> /// generic interface. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="index"/> and <paramref name="length"/> do not specify a valid range in <paramref name="array"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than the lower bound of <paramref name="array"/>. -or- <paramref name="length"/> is less than zero. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value) { return Array.BinarySearch<T>(array.array, index, length, value); } /// <summary> /// Searches a range of elements in a one-dimensional sorted <see cref="ImmutableArray{T}"/> for /// a value, using the specified <see cref="IComparer{T}"/> generic /// interface. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="index">The starting index of the range to search.</param> /// <param name="length">The length of the range to search.</param> /// <param name="value">The object to search for.</param> /// <param name="comparer"> /// The <see cref="IComparer{T}"/> implementation to use when comparing /// elements; or null to use the <see cref="IComparable{T}"/> implementation of each /// element. /// </param> /// <returns> /// The index of the specified <paramref name="value"/> in the specified <paramref name="array"/>, if <paramref name="value"/> is found. /// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in <paramref name="array"/>, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater /// than any of the elements in <paramref name="array"/>, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="InvalidOperationException"> /// <paramref name="comparer"/> is null, <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic /// interface, and the search encounters an element that does not implement the /// <see cref="IComparable{T}"/> generic interface. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="index"/> and <paramref name="length"/> do not specify a valid range in <paramref name="array"/>.-or-<paramref name="comparer"/> is null, /// and <paramref name="value"/> is of a type that is not compatible with the elements of <paramref name="array"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than the lower bound of <paramref name="array"/>. -or- <paramref name="length"/> is less than zero. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T> comparer) { return Array.BinarySearch<T>(array.array, index, length, value, comparer); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The array from which to copy.</param> internal static ImmutableArray<T> CreateDefensiveCopy<T>(T[] items) { Debug.Assert(items != null); if (items.Length == 0) { return ImmutableArray<T>.Empty; // use just a shared empty array, allowing the input array to be potentially GC'd } // defensive copy var tmp = new T[items.Length]; Array.Copy(items, 0, tmp, 0, items.Length); return new ImmutableArray<T>(tmp); } } }
// // TagDatabaseManager.cs // // Authors: // Marcos David Marin Amador <[email protected]> // Mitchell Wheeler <[email protected]> // // Copyright (C) 2007 Marcos David Marin Amador // // // This source code is licenced under The MIT License: // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Linq; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Threading; using MonoDevelop.Projects; using MonoDevelop.Core; using MonoDevelop.Core.Execution; using MonoDevelop.Ide.Gui; using CBinding.Navigation; // TODO // Generic, language independant 'TagDatabaseManager' // Parsing of ctags data into a Sqlite database, for easy/efficient access & updates. // namespace CBinding.Parser { /// <summary> /// Singleton class to manage tag databases /// </summary> class TagDatabaseManager { private static TagDatabaseManager instance; private Queue<ProjectFilePair> parsingJobs = new Queue<ProjectFilePair> (); private Thread parsingThread; private CTagsManager ctags; public event ClassPadEventHandler FileUpdated; bool ctagsInstalled = false; bool checkedCtagsInstalled = false; private TagDatabaseManager() { } public static TagDatabaseManager Instance { get { if (instance == null) instance = new TagDatabaseManager (); return instance; } } public bool DepsInstalled { get { if (!checkedCtagsInstalled) { checkedCtagsInstalled = true; try { var output = new StringWriter (); Runtime.ProcessService.StartProcess (CTagsManager.CTagsExecutable, "--version", null, output, null, null).WaitForExit (); if (Platform.IsMac && !output.ToString ().StartsWith ("Exuberant", StringComparison.Ordinal)) { System.Console.WriteLine ("Fallback to OSX ctags"); ctags = new BsdCTagsManager (); } else { ctags = new ExuberantCTagsManager (); } } catch { LoggingService.LogWarning ("Cannot update C/C++ tags database because exuberant ctags is not installed."); return false; } try { Runtime.ProcessService.StartProcess ("gcc", "--version", null, null).WaitForOutput (); } catch { LoggingService.LogWarning ("Cannot update C/C++ tags database because gcc is not installed."); return false; } lock (parsingJobs) { ctagsInstalled = true; } } return ctagsInstalled && ctags != null; } set { //don't assume that the caller is correct :-) if (value) checkedCtagsInstalled = false; //wil re-determine ctagsInstalled on next getting else ctagsInstalled = false; } } private string[] Headers (Project project, string filename, bool with_system) { List<string> headers = new List<string> (); CProject cproject = project as CProject; if (cproject == null){ return headers.ToArray(); } StringBuilder output = new StringBuilder (); StringBuilder option = new StringBuilder ("-M"); if (!with_system) { option.Append("M"); } option.Append (" -MG "); foreach (Package package in cproject.Packages) { package.ParsePackage (); option.AppendFormat ("{0} ", string.Join(" ", package.CFlags.ToArray ())); } ProcessWrapper p = null; try { p = Runtime.ProcessService.StartProcess ("gcc", option.ToString () + filename.Replace(@"\ ", " ").Replace(" ", @"\ "), null, null); p.WaitForOutput (); // Doing the below completely breaks header parsing // // Skip first two lines (.o & .c* files) - WARNING, sometimes this is compacted to 1 line... we need a better way of handling this. // if(p.StandardOutput.ReadLine () == null) return new string[0]; // object file // if(p.StandardOutput.ReadLine () == null) return new string[0]; // compile file string line; while ((line = p.StandardOutput.ReadLine ()) != null) output.Append (line); } catch (Exception ex) { LoggingService.LogError (ex.ToString ()); return new string [0]; } finally { if(p != null) p.Dispose(); } MatchCollection files = Regex.Matches(output.ToString().Replace(@" \", String.Empty), @" (?<file>([^ \\]|(\\ ))+)", RegexOptions.IgnoreCase); foreach (Match match in files) { string depfile = findFileInIncludes(project, match.Groups["file"].Value.Trim()); headers.Add (depfile.Replace(@"\ ", " ").Replace(" ", @"\ ")); } return headers.ToArray (); } /// <summary> /// Finds a file in a project's include path(s) /// </summary> /// <param name="project"> /// The project whose include path is to be searched /// <see cref="Project"/> /// </param> /// <param name="filename"> /// A portion of a full file path /// <see cref="System.String"/> /// </param> /// <returns> /// The full found path, or filename if not found /// <see cref="System.String"/> /// </returns> private static string findFileInIncludes (Project project, string filename) { CProjectConfiguration conf = project.DefaultConfiguration as CProjectConfiguration; string fullpath = string.Empty; if (!Path.IsPathRooted (filename)) { // Check against base directory fullpath = findFileInPath (filename, project.BaseDirectory); if (string.Empty != fullpath) return fullpath; if (conf != null) { // Check project's additional configuration includes foreach (string p in conf.Includes) { fullpath = findFileInPath (filename, p); if (string.Empty != fullpath) return fullpath; } } } return filename; } /// <summary> /// Finds a file in a subdirectory of a given path /// </summary> /// <param name="relativeFilename"> /// A portion of a full file path /// <see cref="System.String"/> /// </param> /// <param name="path"> /// The path beneath which to look for relativeFilename /// <see cref="System.String"/> /// </param> /// <returns> /// The full path, or string.Empty if not found /// <see cref="System.String"/> /// </returns> private static string findFileInPath (string relativeFilename, string path) { string tmp = Path.Combine (path, relativeFilename); if (Path.IsPathRooted (relativeFilename)) return relativeFilename; else if (File.Exists (tmp)) return tmp; if (Directory.Exists (path)) { foreach (string subdir in Directory.GetDirectories (path)) { tmp = findFileInPath (relativeFilename, subdir); if (string.Empty != tmp) return tmp; } } return string.Empty; } private void UpdateSystemTags (Project project, string filename, IEnumerable<string> includedFiles) { if (!DepsInstalled) return; ProjectInformation info = ProjectInformationManager.Instance.Get (project); List<FileInformation> files; lock (info) { if (!info.IncludedFiles.ContainsKey (filename)) { files = new List<FileInformation> (); info.IncludedFiles.Add (filename, files); } else { files = info.IncludedFiles[filename]; } foreach (string includedFile in includedFiles) { bool contains = false; foreach (FileInformation fi in files) { if (fi.FileName == includedFile) { contains = true; } } if (!contains) { FileInformation newFileInfo = new FileInformation (project, includedFile); files.Add (newFileInfo); ctags.FillFileInformation (newFileInfo); } contains = false; } } } private void ParsingThread () { try { while (parsingJobs.Count > 0) { ProjectFilePair p; lock (parsingJobs) { p = parsingJobs.Dequeue (); } string[] headers = Headers (p.Project, p.File, false); ctags.DoUpdateFileTags (p.Project, p.File, headers); OnFileUpdated (new ClassPadEventArgs (p.Project)); if (PropertyService.Get<bool> ("CBinding.ParseSystemTags", true)) UpdateSystemTags (p.Project, p.File, Headers (p.Project, p.File, true).Except (headers)); if (cache.Count > cache_size) cache.Clear (); } } catch (Exception ex) { LoggingService.LogError ("Unhandled error updating parser database. Disabling C/C++ parsing.", ex); DepsInstalled = false; return; } } public void UpdateFileTags (Project project, string filename) { if (!DepsInstalled) return; ProjectFilePair p = new ProjectFilePair (project, filename); lock (parsingJobs) { if (!parsingJobs.Contains (p)) parsingJobs.Enqueue (p); } if (parsingThread == null || !parsingThread.IsAlive) { parsingThread = new Thread (ParsingThread); parsingThread.Name = "Tag database parser"; parsingThread.IsBackground = true; parsingThread.Priority = ThreadPriority.Lowest; parsingThread.Start(); } } Tag BinarySearch (string[] ctags_lines, TagKind kind, string name) { int low; int high = ctags_lines.Length - 2; // last element is an empty string (because of the Split) int mid; int start_index = 0; // Skip initial comment lines while (ctags_lines[start_index].StartsWith ("!_")) start_index++; low = start_index; while (low <= high) { mid = (low + high) / 2; string entry = ctags_lines[mid]; string tag_name = entry.Substring (0, entry.IndexOf ('\t')); int res = string.CompareOrdinal (tag_name, name); if (res < 0) { low = mid + 1; } else if (res > 0) { high = mid - 1; } else { // The tag we are at has the same name than the one we are looking for // but not necessarily the same type, the actual tag we are looking // for might be higher up or down, so we try both, starting with going down. int save = mid; bool going_down = true; bool eof = false; while (true) { Tag tag = ctags.ParseTag (entry); if (tag == null) return null; if (tag.Kind == kind && tag_name == name) return tag; if (going_down) { mid++; if (mid >= ctags_lines.Length - 1) eof = true; if (!eof) { entry = ctags_lines[mid]; tag_name = entry.Substring (0, entry.IndexOf ('\t')); if (tag_name != name) { going_down = false; mid = save - 1; } } else { going_down = false; mid = save - 1; } } else { // going up mid--; if (mid < start_index) return null; entry = ctags_lines[mid]; tag_name = entry.Substring (0, entry.IndexOf ('\t')); if (tag_name != name) return null; } } } } return null; } private struct SemiTag { readonly internal string name; readonly internal TagKind kind; internal SemiTag (string name, TagKind kind) { this.name = name; this.kind = kind; } public override int GetHashCode () { return (name + kind.ToString ()).GetHashCode (); } } private const int cache_size = 10000; private Dictionary<SemiTag, Tag> cache = new Dictionary<SemiTag, Tag> (); public Tag FindTag (string name, TagKind kind, string ctags_output) { SemiTag semiTag = new SemiTag (name, kind); if (cache.ContainsKey (semiTag)) return cache[semiTag]; else { string[] ctags_lines = ctags_output.Split ('\n'); Tag tag = BinarySearch (ctags_lines, kind, name); cache.Add (semiTag, tag); return tag; } } /// <summary> /// Remove a file's parse information from the database. /// </summary> /// <param name="project"> /// A <see cref="Project"/>: The project to which the file belongs. /// </param> /// <param name="filename"> /// A <see cref="System.String"/>: The file. /// </param> public void RemoveFileInfo(Project project, string filename) { ProjectInformation info = ProjectInformationManager.Instance.Get (project); lock (info){ info.RemoveFileInfo(filename); } OnFileUpdated(new ClassPadEventArgs (project)); } /// <summary> /// Wrapper method for the FileUpdated event. /// </summary> void OnFileUpdated (ClassPadEventArgs args) { Runtime.RunInMainThread (() => { if (null != FileUpdated) FileUpdated(args); }); } private class ProjectFilePair { string file; Project project; public ProjectFilePair (Project project, string file) { this.project = project; this.file = file; } public string File { get { return file; } } public Project Project { get { return project; } } public override bool Equals (object other) { ProjectFilePair o = other as ProjectFilePair; if (o == null) return false; if (file == o.File && project == o.Project) return true; else return false; } public override int GetHashCode () { return (project.ToString() + file).GetHashCode (); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Graph.RBAC.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Graph.RBAC.Fluent.Models; using Microsoft.Azure.Management.Graph.RBAC.Fluent.CertificateCredential.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.PasswordCredential.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.ServicePrincipal.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.ServicePrincipal.Update; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System.Collections.Generic; using System; public partial class ServicePrincipalImpl { /// <summary> /// Gets the mapping from scopes to role assignments. /// </summary> System.Collections.Generic.ISet<Microsoft.Azure.Management.Graph.RBAC.Fluent.IRoleAssignment> Microsoft.Azure.Management.Graph.RBAC.Fluent.IServicePrincipal.RoleAssignments { get { return this.RoleAssignments(); } } /// <summary> /// Gets app id. /// </summary> string Microsoft.Azure.Management.Graph.RBAC.Fluent.IServicePrincipal.ApplicationId { get { return this.ApplicationId(); } } /// <summary> /// Gets the mapping of certificate credentials from their names. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.ICertificateCredential> Microsoft.Azure.Management.Graph.RBAC.Fluent.IServicePrincipal.CertificateCredentials { get { return this.CertificateCredentials(); } } /// <summary> /// Gets the list of names. /// </summary> System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Graph.RBAC.Fluent.IServicePrincipal.ServicePrincipalNames { get { return this.ServicePrincipalNames(); } } /// <summary> /// Gets the mapping of password credentials from their names. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.IPasswordCredential> Microsoft.Azure.Management.Graph.RBAC.Fluent.IServicePrincipal.PasswordCredentials { get { return this.PasswordCredentials(); } } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IWithCreate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IWithCreate>.WithCertificateCredential(CertificateCredentialImpl<IWithCreate> credential) { return this.WithCertificateCredential(credential); } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IUpdate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IUpdate>.WithCertificateCredential(CertificateCredentialImpl<IUpdate> credential) { return this.WithCertificateCredential(credential); } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IWithCreate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IWithCreate>.WithPasswordCredential(PasswordCredentialImpl<IWithCreate> credential) { return this.WithPasswordCredential(credential); } /// <summary> /// Attach a credential to this model. /// </summary> /// <param name="credential">The credential to attach to.</param> /// <return>The interface itself.</return> IUpdate Microsoft.Azure.Management.Graph.RBAC.Fluent.IHasCredential<IUpdate>.WithPasswordCredential(PasswordCredentialImpl<IUpdate> credential) { return this.WithPasswordCredential(credential); } /// <summary> /// Starts the definition of a certificate credential. /// </summary> /// <param name="name">The descriptive name of the certificate credential.</param> /// <return>The first stage in certificate credential definition.</return> CertificateCredential.UpdateDefinition.IBlank<ServicePrincipal.Update.IUpdate> ServicePrincipal.Update.IWithCredentialBeta.DefineCertificateCredential(string name) { return this.DefineCertificateCredential<IUpdate>(name); } /// <summary> /// Removes a key. /// </summary> /// <param name="name">The name of the key.</param> /// <return>The next stage of the application update.</return> ServicePrincipal.Update.IUpdate ServicePrincipal.Update.IWithCredentialBeta.WithoutCredential(string name) { return this.WithoutCredential(name); } /// <summary> /// Starts the definition of a password credential. /// </summary> /// <param name="name">The descriptive name of the password credential.</param> /// <return>The first stage in password credential definition.</return> PasswordCredential.UpdateDefinition.IBlank<ServicePrincipal.Update.IUpdate> ServicePrincipal.Update.IWithCredentialBeta.DefinePasswordCredential(string name) { return this.DefinePasswordCredential<IUpdate>(name); } /// <summary> /// Starts the definition of a certificate credential. /// </summary> /// <param name="name">The descriptive name of the certificate credential.</param> /// <return>The first stage in certificate credential definition.</return> CertificateCredential.Definition.IBlank<ServicePrincipal.Definition.IWithCreate> ServicePrincipal.Definition.IWithCredentialBeta.DefineCertificateCredential(string name) { return this.DefineCertificateCredential<IWithCreate>(name); } /// <summary> /// Starts the definition of a password credential. /// </summary> /// <param name="name">The descriptive name of the password credential.</param> /// <return>The first stage in password credential definition.</return> PasswordCredential.Definition.IBlank<ServicePrincipal.Definition.IWithCreate> ServicePrincipal.Definition.IWithCredentialBeta.DefinePasswordCredential(string name) { return this.DefinePasswordCredential<IWithCreate>(name); } /// <summary> /// Assigns a new role to the service principal. /// </summary> /// <param name="role">The role to assign to the service principal.</param> /// <param name="resourceGroup">The resource group the service principal can access.</param> /// <return>The next stage of the service principal update.</return> ServicePrincipal.Update.IUpdate ServicePrincipal.Update.IWithRoleAssignmentBeta.WithNewRoleInResourceGroup(BuiltInRole role, IResourceGroup resourceGroup) { return this.WithNewRoleInResourceGroup(role, resourceGroup); } /// <summary> /// Assigns a new role to the service principal. /// </summary> /// <param name="role">The role to assign to the service principal.</param> /// <param name="subscriptionId">The subscription the service principal can access.</param> /// <return>The next stage of the service principal update.</return> ServicePrincipal.Update.IUpdate ServicePrincipal.Update.IWithRoleAssignmentBeta.WithNewRoleInSubscription(BuiltInRole role, string subscriptionId) { return this.WithNewRoleInSubscription(role, subscriptionId); } /// <summary> /// Assigns a new role to the service principal. /// </summary> /// <param name="role">The role to assign to the service principal.</param> /// <param name="scope">The scope the service principal can access.</param> /// <return>The next stage of the service principal update.</return> ServicePrincipal.Update.IUpdate ServicePrincipal.Update.IWithRoleAssignmentBeta.WithNewRole(BuiltInRole role, string scope) { return this.WithNewRole(role, scope); } /// <summary> /// Removes a role from the service principal. /// </summary> /// <param name="roleAssignment">The role assignment to remove.</param> /// <return>The next stage of the service principal update.</return> ServicePrincipal.Update.IUpdate ServicePrincipal.Update.IWithRoleAssignmentBeta.WithoutRole(IRoleAssignment roleAssignment) { return this.WithoutRole(roleAssignment); } /// <summary> /// Assigns a new role to the service principal. /// </summary> /// <param name="role">The role to assign to the service principal.</param> /// <param name="resourceGroup">The resource group the service principal can access.</param> /// <return>The next stage of the service principal definition.</return> ServicePrincipal.Definition.IWithCreate ServicePrincipal.Definition.IWithRoleAssignmentBeta.WithNewRoleInResourceGroup(BuiltInRole role, IResourceGroup resourceGroup) { return this.WithNewRoleInResourceGroup(role, resourceGroup); } /// <summary> /// Assigns a new role to the service principal. /// </summary> /// <param name="role">The role to assign to the service principal.</param> /// <param name="subscriptionId">The subscription the service principal can access.</param> /// <return>The next stage of the service principal definition.</return> ServicePrincipal.Definition.IWithCreate ServicePrincipal.Definition.IWithRoleAssignmentBeta.WithNewRoleInSubscription(BuiltInRole role, string subscriptionId) { return this.WithNewRoleInSubscription(role, subscriptionId); } /// <summary> /// Assigns a new role to the service principal. /// </summary> /// <param name="role">The role to assign to the service principal.</param> /// <param name="scope">The scope the service principal can access.</param> /// <return>The next stage of the service principal definition.</return> ServicePrincipal.Definition.IWithCreate ServicePrincipal.Definition.IWithRoleAssignmentBeta.WithNewRole(BuiltInRole role, string scope) { return this.WithNewRole(role, scope); } /// <summary> /// Specifies an existing application by its app ID. /// </summary> /// <param name="id">The app ID of the application.</param> /// <return>The next stage of the service principal definition.</return> ServicePrincipal.Definition.IWithCreate ServicePrincipal.Definition.IWithApplicationBeta.WithExistingApplication(string id) { return this.WithExistingApplication(id); } /// <summary> /// Specifies an existing application to use by the service principal. /// </summary> /// <param name="application">The application.</param> /// <return>The next stage of the service principal definition.</return> ServicePrincipal.Definition.IWithCreate ServicePrincipal.Definition.IWithApplicationBeta.WithExistingApplication(IActiveDirectoryApplication application) { return this.WithExistingApplication(application); } /// <summary> /// Specifies a new application to create and use by the service principal. /// </summary> /// <param name="applicationCreatable">The new application's creatable.</param> /// <return>The next stage of the service principal definition.</return> ServicePrincipal.Definition.IWithCreate ServicePrincipal.Definition.IWithApplicationBeta.WithNewApplication(ICreatable<Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication> applicationCreatable) { return this.WithNewApplication(applicationCreatable); } /// <summary> /// Specifies a new application to create and use by the service principal. /// </summary> /// <param name="signOnUrl">The new application's sign on URL.</param> /// <return>The next stage of the service principal definition.</return> ServicePrincipal.Definition.IWithCreate ServicePrincipal.Definition.IWithApplicationBeta.WithNewApplication(string signOnUrl) { return this.WithNewApplication(signOnUrl); } } }
using Newtonsoft.Json; using StreamCompanionTypes; using StreamCompanionTypes.DataTypes; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using System.Windows.Media; using StreamCompanion.Common; using StreamCompanion.Common.Extensions; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces.Services; using Color = System.Drawing.Color; namespace LiveVisualizer { [SupportedOSPlatform("windows7.0")] public class LiveVisualizerPlugin : LiveVisualizerPluginBase { private MainWindow _visualizerWindow; private CancellationTokenSource cts = new CancellationTokenSource(); private List<KeyValuePair<string, IToken>> _liveTokens; private IToken _ppToken; private IToken _hit100Token; private IToken _hit50Token; private IToken _hitMissToken; private IToken _timeToken; private IToken _statusToken; private IToken _simulatedPpToken; private IToken _mapStrainsToken; private List<KeyValuePair<string, IToken>> Tokens { get => _liveTokens; set { _ppToken = value.FirstOrDefault(t => t.Key == "ppIfMapEndsNow").Value; _hit100Token = value.FirstOrDefault(t => t.Key == "c100").Value; _hit50Token = value.FirstOrDefault(t => t.Key == "c50").Value; _hitMissToken = value.FirstOrDefault(t => t.Key == "miss").Value; _timeToken = value.FirstOrDefault(t => t.Key == "time").Value; _statusToken = value.FirstOrDefault(t => t.Key == "status").Value; _simulatedPpToken = value.FirstOrDefault(t => t.Key == "simulatedPp").Value; _mapStrainsToken = value.FirstOrDefault(t => t.Key == "mapStrains").Value; _totalTimeToken = value.FirstOrDefault(t => t.Key == "totaltime").Value; _backgroundImageLocationToken = value.FirstOrDefault(t => t.Key == "backgroundImageLocation").Value; _liveTokens = value; } } private string _lastMapLocation = string.Empty; private string _lastMapHash = string.Empty; private IModsEx _lastMods = null; private IToken _totalTimeToken; private IToken _backgroundImageLocationToken; public LiveVisualizerPlugin(IContextAwareLogger logger, ISettings settings) : base(logger, settings) { VisualizerData = new VisualizerDataModel(); LoadConfiguration(); PrepareDataPlots(); EnableVisualizer(VisualizerData.Configuration.Enable); VisualizerData.Configuration.PropertyChanged += VisualizerConfigurationPropertyChanged; _ = UpdateLiveTokens(cts.Token).HandleExceptions(); } private void PrepareDataPlots() { foreach (var wpfPlot in new[] { VisualizerData.Display.MainDataPlot, VisualizerData.Display.BackgroundDataPlot }) { wpfPlot.Foreground = new SolidColorBrush(Colors.Transparent); wpfPlot.Background = new SolidColorBrush(Colors.Transparent); wpfPlot.plt.Style(Color.Transparent, Color.Transparent, Color.Transparent, Color.Green, Color.Aqua, Color.DarkOrange); wpfPlot.Configure(false, false, false, false, false, false, false, false, recalculateLayoutOnMouseUp: false, lowQualityOnScrollWheel: false); } } private void VisualizerConfigurationPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(IVisualizerConfiguration.Enable): EnableVisualizer(VisualizerData.Configuration.Enable); break; case nameof(IVisualizerConfiguration.AutoSizeAxisY): case nameof(IVisualizerConfiguration.ChartCutoffsSet): SetAxisValues(VisualizerData.Display.Strains?.ToList()); break; } _visualizerWindow?.UpdateChart(); SaveConfiguration(); } private void SaveConfiguration() { var serializedConfig = JsonConvert.SerializeObject(VisualizerData.Configuration); Settings.Add(ConfigEntrys.LiveVisualizerConfig.Name, serializedConfig, false); } private void LoadConfiguration(bool reset = false) { var rawConfig = Settings.Get<string>(ConfigEntrys.LiveVisualizerConfig); if (reset) { VisualizerData.Configuration.PropertyChanged -= VisualizerConfigurationPropertyChanged; //WPF window doesn't update its width when replacing configuration object - workaround var newConfiguration = new VisualizerConfiguration(); VisualizerData.Configuration.WindowWidth = newConfiguration.WindowWidth; VisualizerData.Configuration = newConfiguration; VisualizerData.Configuration.PropertyChanged += VisualizerConfigurationPropertyChanged; VisualizerConfigurationPropertyChanged(this, new PropertyChangedEventArgs("dummy")); } if (reset || rawConfig == ConfigEntrys.LiveVisualizerConfig.Default<string>()) { VisualizerData.Configuration.ChartCutoffsSet = new SortedSet<int>(new[] { 30, 60, 100, 200, 350 }); return; } var config = JsonConvert.DeserializeObject<VisualizerConfiguration>(rawConfig); config.AxisYStep = 100; config.MaxYValue = 200; VisualizerData.Configuration = config; } protected override void ResetSettings() { LoadConfiguration(true); } private void EnableVisualizer(bool enable) { if (enable) { if (_visualizerWindow == null || !_visualizerWindow.IsLoaded) _visualizerWindow = new MainWindow(VisualizerData); _visualizerWindow.Width = VisualizerData.Configuration.WindowWidth; _visualizerWindow.Height = VisualizerData.Configuration.WindowHeight; _visualizerWindow.Show(); } else { _visualizerWindow?.Hide(); } } protected override void ProcessNewMap(IMapSearchResult mapSearchResult) { var isValidBeatmap = false; var mapLocation = string.Empty; if (VisualizerData == null || !mapSearchResult.BeatmapsFound.Any() || !(isValidBeatmap = mapSearchResult.BeatmapsFound[0].IsValidBeatmap(Settings, out mapLocation)) || (mapLocation == _lastMapLocation && mapSearchResult.Mods == _lastMods && _lastMapHash == mapSearchResult.BeatmapsFound[0].Md5) ) { if (!isValidBeatmap) Logger.Log($"IsValidBeatmap check failed with mapLocation: \"{mapLocation ?? ""}\"", LogLevel.Trace); if (!mapSearchResult.BeatmapsFound.Any() && VisualizerData != null) { Logger.Log("Reseting view", LogLevel.Trace); VisualizerData.Display.ImageLocation = null; VisualizerData.Display.Artist = null; VisualizerData.Display.Title = null; VisualizerData.Display.Strains?.Clear(); _lastMapLocation = null; _lastMapHash = null; } else { Logger.Log("Not updating anything", LogLevel.Trace); } return; } Logger.Log("Updating live visualizer window", LogLevel.Trace); var strains = (Dictionary<int, double>)_mapStrainsToken?.Value; VisualizerData.Display.DisableChartAnimations = strains?.Count >= 400; //10min+ maps _lastMapLocation = mapLocation; _lastMods = mapSearchResult.Mods; _lastMapHash = mapSearchResult.BeatmapsFound[0].Md5; VisualizerData.Display.TotalTime = Convert.ToDouble(_totalTimeToken.Value); VisualizerData.Display.Title = Tokens.First(r => r.Key == "titleRoman").Value.Value?.ToString(); VisualizerData.Display.Artist = Tokens.First(r => r.Key == "artistRoman").Value.Value?.ToString(); if (VisualizerData.Display.Strains == null) VisualizerData.Display.Strains = new List<double>(); VisualizerData.Display.Strains.Clear(); var strainValues = strains?.Select(kv => kv.Value).ToList(); SetAxisValues(strainValues); VisualizerData.Display.Strains.AddRange(strainValues ?? Enumerable.Empty<double>()); var imageLocation = (string)_backgroundImageLocationToken.Value; VisualizerData.Display.ImageLocation = File.Exists(imageLocation) ? imageLocation : null; _visualizerWindow?.UpdateChart(); Logger.Log("Finished updating live visualizer window", LogLevel.Trace); } private void SetAxisValues(IReadOnlyList<double> strainValues) { if (strainValues != null && strainValues.Any()) { var strainsMax = strainValues.Max(); VisualizerData.Configuration.MaxYValue = getMaxY(strainsMax); VisualizerData.Configuration.AxisYStep = GetAxisYStep(double.IsNaN(VisualizerData.Configuration.MaxYValue) ? strainsMax : VisualizerData.Configuration.MaxYValue); } else { VisualizerData.Configuration.MaxYValue = 200; VisualizerData.Configuration.AxisYStep = 100; } } public override Task<List<IOutputPattern>> GetOutputPatterns(IMapSearchResult map, Tokens tokens, OsuStatus status) { Tokens = tokens.ToList(); return Task.FromResult<List<IOutputPattern>>(null); } private async Task UpdateLiveTokens(CancellationToken token) { while (true) { while (!VisualizerData.Configuration.Enable) { await Task.Delay(500, token); } try { if (Tokens != null) { //Blind casts :/ VisualizerData.Display.CurrentTime = (double)_timeToken.Value * 1000; var normalizedCurrentTime = VisualizerData.Display.CurrentTime < 0 ? 0 : VisualizerData.Display.CurrentTime; var progress = VisualizerData.Configuration.WindowWidth * (normalizedCurrentTime / VisualizerData.Display.TotalTime); VisualizerData.Display.PixelMapProgress = progress < VisualizerData.Configuration.WindowWidth ? progress : VisualizerData.Configuration.WindowWidth; var status = (OsuStatus)_statusToken.Value; if (VisualizerData.Configuration.SimulatePPWhenListening && (status == OsuStatus.Editing || status == OsuStatus.Listening)) { var pp = Math.Round((double)(_simulatedPpToken?.Value ?? 0d)); VisualizerData.Display.Pp = pp < 0 ? 0 : pp; } else { VisualizerData.Display.Pp = Math.Round((double)_ppToken.Value); VisualizerData.Display.Hit100 = (ushort)_hit100Token.Value; VisualizerData.Display.Hit50 = (ushort)_hit50Token.Value; VisualizerData.Display.HitMiss = (ushort)_hitMissToken.Value; } } } catch (Exception ex) { Logger.Log(ex, LogLevel.Error); } await Task.Delay(22); if (token.IsCancellationRequested) return; } } private bool AutomaticAxisControlIsEnabled => VisualizerData.Configuration.AutoSizeAxisY; private double getMaxY(double maxValue) { if (!AutomaticAxisControlIsEnabled) { foreach (var cutoff in VisualizerData.Configuration.ChartCutoffsSet) { if (maxValue < cutoff && cutoff > 0) return cutoff; } } var maxY = Math.Ceiling(maxValue); return maxY > 0 ? maxY : 200; } private double GetAxisYStep(double maxYValue) { if (double.IsNaN(maxYValue) || maxYValue <= 0) return 100; if (maxYValue < 10) maxYValue += 10; return RoundOff((int)(maxYValue / 3.1)); int RoundOff(int num) { return ((int)Math.Ceiling(num / 10.0)) * 10; } } public override void Dispose() { cts?.TryCancel(); _visualizerWindow?.Dispatcher.Invoke(() => { _visualizerWindow?.Close(); }); base.Dispose(); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Diagnostics; using Gallio.Common.Policies; using Gallio.Runtime.Debugging; using Gallio.Runtime.Logging; namespace Gallio.Runtime.Hosting { /// <summary> /// Base implementation of <see cref="IHost"/> that performs argument validation. /// </summary> public abstract class BaseHost : IHost { private readonly object syncRoot = new object(); private readonly HostSetup hostSetup; private readonly ILogger logger; private IHostService hostService; private event EventHandler disconnectedHandlers; private bool wasInitialized; private bool isDisposed; private IDebugger debugger; private Process debuggedProcess; /// <summary> /// Creates a host. /// </summary> /// <param name="hostSetup">The host setup.</param> /// <param name="logger">The logger for host message output.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="hostSetup"/> /// or <paramref name="logger"/> is null.</exception> protected BaseHost(HostSetup hostSetup, ILogger logger) { if (hostSetup == null) throw new ArgumentNullException("hostSetup"); if (logger == null) throw new ArgumentNullException("logger"); this.hostSetup = hostSetup; this.logger = logger; } /// <inheritdoc /> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <inheritdoc /> public event EventHandler Disconnected { add { lock (syncRoot) { ThrowIfDisposed(); if (hostService != null) { disconnectedHandlers += value; return; } } EventHandlerPolicy.SafeInvoke(value, this, EventArgs.Empty); } remove { lock (syncRoot) { ThrowIfDisposed(); disconnectedHandlers -= value; } } } /// <inheritdoc /> public abstract bool IsLocal { get; } /// <inheritdoc /> public bool IsConnected { get { lock (syncRoot) { ThrowIfDisposed(); return hostService != null; } } } /// <inheritdoc /> public HostSetup GetHostSetup() { lock (syncRoot) { ThrowIfDisposed(); return hostSetup.Copy(); } } /// <summary> /// Initializes the host and connects to the host service. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the host has already been initialized.</exception> /// <exception cref="ObjectDisposedException">Thrown if the host has been disposed.</exception> /// <exception cref="HostException">Thrown if an exception occurred while connecting to the host.</exception> public void Connect() { lock (syncRoot) { ThrowIfDisposed(); if (wasInitialized) throw new InvalidOperationException("The host has already been initialized."); wasInitialized = true; } try { hostService = AcquireHostService(); } catch (Exception ex) { throw new HostException("An exception occurred while connecting to the host service.", ex); } finally { if (hostService == null) NotifyDisconnected(); } } /// <inheritdoc /> public void Disconnect() { IHostService cachedHostService; lock (syncRoot) { ThrowIfDisposed(); if (hostService == null) return; cachedHostService = hostService; } if (cachedHostService != null) { try { ReleaseHostService(cachedHostService); } catch (Exception ex) { Logger.Log(LogSeverity.Warning, "An exception occurred while disconnecting from the host service.", ex); } } NotifyDisconnected(); } /// <inheritdoc /> public IHostService GetHostService() { lock (syncRoot) { ThrowIfDisposed(); if (hostService == null) throw new InvalidOperationException("The host has been disconnected."); return hostService; } } /// <summary> /// Gets an reference to the host service, or null if not connected. /// </summary> protected IHostService HostService { get { return hostService; } } /// <summary> /// Gets the internal host setup information without copying it. /// </summary> protected HostSetup HostSetup { get { return hostSetup; } } /// <summary> /// Gets the logger. /// </summary> protected ILogger Logger { get { return logger; } } /// <summary> /// Gets the host service. /// </summary> /// <returns>The host service, or null if the host service was not available.</returns> protected abstract IHostService AcquireHostService(); /// <summary> /// Releases the host service. /// </summary> /// <param name="hostService">The host service that is being released, not null.</param> protected virtual void ReleaseHostService(IHostService hostService) { } /// <summary> /// Disposes the host. /// </summary> /// <param name="disposing">True if disposing.</param> protected virtual void Dispose(bool disposing) { if (!isDisposed) { Disconnect(); isDisposed = true; } } /// <summary> /// Throws an exception if the host has been disposed. /// </summary> protected void ThrowIfDisposed() { if (isDisposed) throw new ObjectDisposedException(GetType().Name); } /// <summary> /// Sets the state of the host to disconnected and notifies clients. /// </summary> protected void NotifyDisconnected() { EventHandler cachedDisconnectedHandlers; lock (syncRoot) { if (hostService == null) return; cachedDisconnectedHandlers = disconnectedHandlers; disconnectedHandlers = null; hostService = null; } EventHandlerPolicy.SafeInvoke(cachedDisconnectedHandlers, this, EventArgs.Empty); } /// <summary> /// Attaches the debugger to a process if the host settings require it. /// </summary> protected void AttachDebuggerIfNeeded(IDebuggerManager debuggerManager, Process debuggedProcess) { if (HostSetup.DebuggerSetup != null) { IDebugger debugger = debuggerManager.GetDebugger(HostSetup.DebuggerSetup, Logger); if (! Debugger.IsAttached) { Logger.Log(LogSeverity.Important, "Attaching debugger to the host."); AttachDebuggerResult result = debugger.AttachToProcess(debuggedProcess); if (result == AttachDebuggerResult.Attached) { this.debugger = debugger; this.debuggedProcess = debuggedProcess; } else if (result == AttachDebuggerResult.CouldNotAttach) { Logger.Log(LogSeverity.Warning, "Could not attach debugger to the host."); } } } } /// <summary> /// Detaches the debugger from a process if the host settings require it. /// </summary> protected void DetachDebuggerIfNeeded() { if (debugger != null && debuggedProcess != null) { Logger.Log(LogSeverity.Important, "Detaching debugger from the host."); DetachDebuggerResult result = debugger.DetachFromProcess(debuggedProcess); if (result == DetachDebuggerResult.CouldNotDetach) Logger.Log(LogSeverity.Warning, "Could not detach debugger from the host."); debuggedProcess = null; debugger = null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Diagnostics; using System.Data.Common; using System.Threading; using System.Threading.Tasks; namespace System.Data.ProviderBase { internal abstract class DbConnectionFactory { private Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> _connectionPoolGroups; private readonly List<DbConnectionPool> _poolsToRelease; private readonly List<DbConnectionPoolGroup> _poolGroupsToRelease; private readonly Timer _pruningTimer; private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes private const int PruningPeriod = 30 * 1000; // thirty seconds // s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to // a maximum of Environment.ProcessorCount at a time. private static int s_pendingOpenNonPooledNext = 0; private static Task<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount]; private static Task<DbConnectionInternal> s_completedTask; protected DbConnectionFactory() { _connectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(); _poolsToRelease = new List<DbConnectionPool>(); _poolGroupsToRelease = new List<DbConnectionPoolGroup>(); _pruningTimer = CreatePruningTimer(); } abstract public DbProviderFactory ProviderFactory { get; } public void ClearAllPools() { Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups) { DbConnectionPoolGroup poolGroup = entry.Value; if (null != poolGroup) { poolGroup.Clear(); } } } public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); if (null != poolGroup) { poolGroup.Clear(); } } public void ClearPool(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); DbConnectionPoolGroup poolGroup; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; if (connectionPoolGroups.TryGetValue(key, out poolGroup)) { poolGroup.Clear(); } } internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions) { return null; } internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) { Debug.Assert(null != owningConnection, "null owningConnection?"); Debug.Assert(null != poolGroup, "null poolGroup?"); DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions; DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo; DbConnectionPoolKey poolKey = poolGroup.PoolKey; DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); if (null != newConnection) { newConnection.MakeNonPooledObject(owningConnection); } return newConnection; } internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) { Debug.Assert(null != pool, "null pool?"); DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo; DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); if (null != newConnection) { newConnection.MakePooledConnection(pool); } return newConnection; } virtual internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) { return null; } private Timer CreatePruningTimer() { TimerCallback callback = new TimerCallback(PruneConnectionPoolGroups); return new Timer(callback, null, PruningDueTime, PruningPeriod); } protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); if (!ADP.IsEmpty(key.ConnectionString)) { DbConnectionPoolGroup connectionPoolGroup; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) { return connectionPoolGroup.ConnectionOptions; } } return null; } // GetCompletedTask must be called from within s_pendingOpenPooled lock private static Task<DbConnectionInternal> GetCompletedTask() { if (s_completedTask == null) { TaskCompletionSource<DbConnectionInternal> source = new TaskCompletionSource<DbConnectionInternal>(); source.SetResult(null); s_completedTask = source.Task; } return s_completedTask; } internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection) { Debug.Assert(null != owningConnection, "null owningConnection?"); DbConnectionPoolGroup poolGroup; DbConnectionPool connectionPool; connection = null; // Work around race condition with clearing the pool between GetConnectionPool obtaining pool // and GetConnection on the pool checking the pool state. Clearing the pool in this window // will switch the pool into the ShuttingDown state, and GetConnection will return null. // There is probably a better solution involving locking the pool/group, but that entails a major // re-design of the connection pooling synchronization, so is post-poned for now. // Use retriesLeft to prevent CPU spikes with incremental sleep // start with one msec, double the time every retry // max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries) int retriesLeft = 10; int timeBetweenRetriesMilliseconds = 1; do { poolGroup = GetConnectionPoolGroup(owningConnection); // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); if (null == connectionPool) { // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool // or have a disabled pool entry. poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled if (retry != null) { Task<DbConnectionInternal> newTask; CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); lock (s_pendingOpenNonPooled) { // look for an available task slot (completed or empty) int idx; for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++) { Task task = s_pendingOpenNonPooled[idx]; if (task == null) { s_pendingOpenNonPooled[idx] = GetCompletedTask(); break; } else if (task.IsCompleted) { break; } } // if didn't find one, pick the next one in round-robbin fashion if (idx == s_pendingOpenNonPooled.Length) { idx = s_pendingOpenNonPooledNext++ % s_pendingOpenNonPooled.Length; } // now that we have an antecedent task, schedule our work when it is completed. // If it is a new slot or a compelted task, this continuation will start right away. newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) => { var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions); if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open)) { oldConnection.PrepareForReplaceConnection(); oldConnection.Dispose(); } return newConnection; }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default); // Place this new task in the slot so any future work will be queued behind it s_pendingOpenNonPooled[idx] = newTask; } // Set up the timeout (if needed) if (owningConnection.ConnectionTimeout > 0) { int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000; cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds); } // once the task is done, propagate the final results to the original caller newTask.ContinueWith((task) => { cancellationTokenSource.Dispose(); if (task.IsCanceled) { retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout())); } else if (task.IsFaulted) { retry.TrySetException(task.Exception.InnerException); } else { if (!retry.TrySetResult(task.Result)) { // The outer TaskCompletionSource was already completed // Which means that we don't know if someone has messed with the outer connection in the middle of creation // So the best thing to do now is to destroy the newly created connection task.Result.DoomThisConnection(); task.Result.Dispose(); } } }, TaskScheduler.Default); return false; } connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions); } else { if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection) { Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection"); connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection); } else { if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection)) { return false; } } if (connection == null) { // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { // If GetConnection failed while the pool is running, the pool timeout occurred. throw ADP.PooledOpenTimeout(); } else { // We've hit the race condition, where the pool was shut down after we got it from the group. // Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated // before retrying. Threading.Thread.Sleep(timeBetweenRetriesMilliseconds); timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration } } } } while (connection == null && retriesLeft-- > 0); if (connection == null) { // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); } return true; } private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup) { // if poolgroup is disabled, it will be replaced with a new entry Debug.Assert(null != owningObject, "null owningObject?"); Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); // It is possible that while the outer connection object has // been sitting around in a closed and unused state in some long // running app, the pruner may have come along and remove this // the pool entry from the master list. If we were to use a // pool entry in this state, we would create "unmanaged" pools, // which would be bad. To avoid this problem, we automagically // re-create the pool entry whenever it's disabled. // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; // get the string to hash on again DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions; Debug.Assert(null != connectionOptions, "prevent expansion of connectionString"); connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions); Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); SetConnectionPoolGroup(owningObject, connectionPoolGroup); } DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this); return connectionPool; } internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions) { if (ADP.IsEmpty(key.ConnectionString)) { return (DbConnectionPoolGroup)null; } DbConnectionPoolGroup connectionPoolGroup; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) { // If we can't find an entry for the connection string in // our collection of pool entries, then we need to create a // new pool entry and add it to our collection. DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions); if (null == connectionOptions) { throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing); } if (null == userConnectionOptions) { // we only allow one expansion on the connection string userConnectionOptions = connectionOptions; } // We don't support connection pooling on Win9x if (null == poolOptions) { if (null != connectionPoolGroup) { // reusing existing pool option in case user originally used SetConnectionPoolOptions poolOptions = connectionPoolGroup.PoolGroupOptions; } else { // Note: may return null for non-pooled connections poolOptions = CreateConnectionPoolGroupOptions(connectionOptions); } } DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions); newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions); lock (this) { connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) { // build new dictionary with space for new connection string Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(1 + connectionPoolGroups.Count); foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups) { newConnectionPoolGroups.Add(entry.Key, entry.Value); } // lock prevents race condition with PruneConnectionPoolGroups newConnectionPoolGroups.Add(key, newConnectionPoolGroup); connectionPoolGroup = newConnectionPoolGroup; _connectionPoolGroups = newConnectionPoolGroups; } else { Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered"); } } Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?"); Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?"); } else if (null == userConnectionOptions) { userConnectionOptions = connectionPoolGroup.ConnectionOptions; } return connectionPoolGroup; } private void PruneConnectionPoolGroups(object state) { // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the // pool isn't empty, it's because there are active connections or // distributed transactions that need it. lock (_poolsToRelease) { if (0 != _poolsToRelease.Count) { DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray(); foreach (DbConnectionPool pool in poolsToRelease) { if (null != pool) { pool.Clear(); if (0 == pool.Count) { _poolsToRelease.Remove(pool); } } } } } // Next, walk the pool entry release list and dispose of each // pool entry when it is finally empty. If the pool entry isn't // empty, it's because there are active pools that need it. lock (_poolGroupsToRelease) { if (0 != _poolGroupsToRelease.Count) { DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray(); foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease) { if (null != poolGroup) { int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); } } } } } // Finally, we walk through the collection of connection pool entries // and prune each one. This will cause any empty pools to be put // into the release list. lock (this) { Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(connectionPoolGroups.Count); foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups) { if (null != entry.Value) { Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered"); // entries start active and go idle during prune if all pools are gone // move idle entries from last prune pass to a queue for pending release // otherwise process entry which may move it from active to idle if (entry.Value.Prune()) { // may add entries to _poolsToRelease QueuePoolGroupForRelease(entry.Value); } else { newConnectionPoolGroups.Add(entry.Key, entry.Value); } } } _connectionPoolGroups = newConnectionPoolGroups; } } internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) { // Queue the pool up for release -- we'll clear it out and dispose // of it as the last part of the pruning timer callback so we don't // do it with the pool entry or the pool collection locked. Debug.Assert(null != pool, "null pool?"); // set the pool to the shutdown state to force all active // connections to be automatically disposed when they // are returned to the pool pool.Shutdown(); lock (_poolsToRelease) { if (clearing) { pool.Clear(); } _poolsToRelease.Add(pool); } } internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); lock (_poolGroupsToRelease) { _poolGroupsToRelease.Add(poolGroup); } } virtual protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) { return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection); } abstract protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection); abstract protected DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous); abstract protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options); abstract internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection); abstract internal DbConnectionInternal GetInnerConnection(DbConnection connection); abstract internal void PermissionDemand(DbConnection outerConnection); abstract internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup); abstract internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to); abstract internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from); abstract internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to); } }
namespace javax.microedition.khronos.opengles { [global::MonoJavaBridge.JavaClass()] public static partial class GL10Constants { public static int GL_ADD { get { return 260; } } public static int GL_ALIASED_LINE_WIDTH_RANGE { get { return 33902; } } public static int GL_ALIASED_POINT_SIZE_RANGE { get { return 33901; } } public static int GL_ALPHA { get { return 6406; } } public static int GL_ALPHA_BITS { get { return 3413; } } public static int GL_ALPHA_TEST { get { return 3008; } } public static int GL_ALWAYS { get { return 519; } } public static int GL_AMBIENT { get { return 4608; } } public static int GL_AMBIENT_AND_DIFFUSE { get { return 5634; } } public static int GL_AND { get { return 5377; } } public static int GL_AND_INVERTED { get { return 5380; } } public static int GL_AND_REVERSE { get { return 5378; } } public static int GL_BACK { get { return 1029; } } public static int GL_BLEND { get { return 3042; } } public static int GL_BLUE_BITS { get { return 3412; } } public static int GL_BYTE { get { return 5120; } } public static int GL_CCW { get { return 2305; } } public static int GL_CLAMP_TO_EDGE { get { return 33071; } } public static int GL_CLEAR { get { return 5376; } } public static int GL_COLOR_ARRAY { get { return 32886; } } public static int GL_COLOR_BUFFER_BIT { get { return 16384; } } public static int GL_COLOR_LOGIC_OP { get { return 3058; } } public static int GL_COLOR_MATERIAL { get { return 2903; } } public static int GL_COMPRESSED_TEXTURE_FORMATS { get { return 34467; } } public static int GL_CONSTANT_ATTENUATION { get { return 4615; } } public static int GL_COPY { get { return 5379; } } public static int GL_COPY_INVERTED { get { return 5388; } } public static int GL_CULL_FACE { get { return 2884; } } public static int GL_CW { get { return 2304; } } public static int GL_DECAL { get { return 8449; } } public static int GL_DECR { get { return 7683; } } public static int GL_DEPTH_BITS { get { return 3414; } } public static int GL_DEPTH_BUFFER_BIT { get { return 256; } } public static int GL_DEPTH_TEST { get { return 2929; } } public static int GL_DIFFUSE { get { return 4609; } } public static int GL_DITHER { get { return 3024; } } public static int GL_DONT_CARE { get { return 4352; } } public static int GL_DST_ALPHA { get { return 772; } } public static int GL_DST_COLOR { get { return 774; } } public static int GL_EMISSION { get { return 5632; } } public static int GL_EQUAL { get { return 514; } } public static int GL_EQUIV { get { return 5385; } } public static int GL_EXP { get { return 2048; } } public static int GL_EXP2 { get { return 2049; } } public static int GL_EXTENSIONS { get { return 7939; } } public static int GL_FALSE { get { return 0; } } public static int GL_FASTEST { get { return 4353; } } public static int GL_FIXED { get { return 5132; } } public static int GL_FLAT { get { return 7424; } } public static int GL_FLOAT { get { return 5126; } } public static int GL_FOG { get { return 2912; } } public static int GL_FOG_COLOR { get { return 2918; } } public static int GL_FOG_DENSITY { get { return 2914; } } public static int GL_FOG_END { get { return 2916; } } public static int GL_FOG_HINT { get { return 3156; } } public static int GL_FOG_MODE { get { return 2917; } } public static int GL_FOG_START { get { return 2915; } } public static int GL_FRONT { get { return 1028; } } public static int GL_FRONT_AND_BACK { get { return 1032; } } public static int GL_GEQUAL { get { return 518; } } public static int GL_GREATER { get { return 516; } } public static int GL_GREEN_BITS { get { return 3411; } } public static int GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES { get { return 35739; } } public static int GL_IMPLEMENTATION_COLOR_READ_TYPE_OES { get { return 35738; } } public static int GL_INCR { get { return 7682; } } public static int GL_INVALID_ENUM { get { return 1280; } } public static int GL_INVALID_OPERATION { get { return 1282; } } public static int GL_INVALID_VALUE { get { return 1281; } } public static int GL_INVERT { get { return 5386; } } public static int GL_KEEP { get { return 7680; } } public static int GL_LEQUAL { get { return 515; } } public static int GL_LESS { get { return 513; } } public static int GL_LIGHT_MODEL_AMBIENT { get { return 2899; } } public static int GL_LIGHT_MODEL_TWO_SIDE { get { return 2898; } } public static int GL_LIGHT0 { get { return 16384; } } public static int GL_LIGHT1 { get { return 16385; } } public static int GL_LIGHT2 { get { return 16386; } } public static int GL_LIGHT3 { get { return 16387; } } public static int GL_LIGHT4 { get { return 16388; } } public static int GL_LIGHT5 { get { return 16389; } } public static int GL_LIGHT6 { get { return 16390; } } public static int GL_LIGHT7 { get { return 16391; } } public static int GL_LIGHTING { get { return 2896; } } public static int GL_LINE_LOOP { get { return 2; } } public static int GL_LINE_SMOOTH { get { return 2848; } } public static int GL_LINE_SMOOTH_HINT { get { return 3154; } } public static int GL_LINE_STRIP { get { return 3; } } public static int GL_LINEAR { get { return 9729; } } public static int GL_LINEAR_ATTENUATION { get { return 4616; } } public static int GL_LINEAR_MIPMAP_LINEAR { get { return 9987; } } public static int GL_LINEAR_MIPMAP_NEAREST { get { return 9985; } } public static int GL_LINES { get { return 1; } } public static int GL_LUMINANCE { get { return 6409; } } public static int GL_LUMINANCE_ALPHA { get { return 6410; } } public static int GL_MAX_ELEMENTS_INDICES { get { return 33001; } } public static int GL_MAX_ELEMENTS_VERTICES { get { return 33000; } } public static int GL_MAX_LIGHTS { get { return 3377; } } public static int GL_MAX_MODELVIEW_STACK_DEPTH { get { return 3382; } } public static int GL_MAX_PROJECTION_STACK_DEPTH { get { return 3384; } } public static int GL_MAX_TEXTURE_SIZE { get { return 3379; } } public static int GL_MAX_TEXTURE_STACK_DEPTH { get { return 3385; } } public static int GL_MAX_TEXTURE_UNITS { get { return 34018; } } public static int GL_MAX_VIEWPORT_DIMS { get { return 3386; } } public static int GL_MODELVIEW { get { return 5888; } } public static int GL_MODULATE { get { return 8448; } } public static int GL_MULTISAMPLE { get { return 32925; } } public static int GL_NAND { get { return 5390; } } public static int GL_NEAREST { get { return 9728; } } public static int GL_NEAREST_MIPMAP_LINEAR { get { return 9986; } } public static int GL_NEAREST_MIPMAP_NEAREST { get { return 9984; } } public static int GL_NEVER { get { return 512; } } public static int GL_NICEST { get { return 4354; } } public static int GL_NO_ERROR { get { return 0; } } public static int GL_NOOP { get { return 5381; } } public static int GL_NOR { get { return 5384; } } public static int GL_NORMAL_ARRAY { get { return 32885; } } public static int GL_NORMALIZE { get { return 2977; } } public static int GL_NOTEQUAL { get { return 517; } } public static int GL_NUM_COMPRESSED_TEXTURE_FORMATS { get { return 34466; } } public static int GL_ONE { get { return 1; } } public static int GL_ONE_MINUS_DST_ALPHA { get { return 773; } } public static int GL_ONE_MINUS_DST_COLOR { get { return 775; } } public static int GL_ONE_MINUS_SRC_ALPHA { get { return 771; } } public static int GL_ONE_MINUS_SRC_COLOR { get { return 769; } } public static int GL_OR { get { return 5383; } } public static int GL_OR_INVERTED { get { return 5389; } } public static int GL_OR_REVERSE { get { return 5387; } } public static int GL_OUT_OF_MEMORY { get { return 1285; } } public static int GL_PACK_ALIGNMENT { get { return 3333; } } public static int GL_PALETTE4_R5_G6_B5_OES { get { return 35730; } } public static int GL_PALETTE4_RGB5_A1_OES { get { return 35732; } } public static int GL_PALETTE4_RGB8_OES { get { return 35728; } } public static int GL_PALETTE4_RGBA4_OES { get { return 35731; } } public static int GL_PALETTE4_RGBA8_OES { get { return 35729; } } public static int GL_PALETTE8_R5_G6_B5_OES { get { return 35735; } } public static int GL_PALETTE8_RGB5_A1_OES { get { return 35737; } } public static int GL_PALETTE8_RGB8_OES { get { return 35733; } } public static int GL_PALETTE8_RGBA4_OES { get { return 35736; } } public static int GL_PALETTE8_RGBA8_OES { get { return 35734; } } public static int GL_PERSPECTIVE_CORRECTION_HINT { get { return 3152; } } public static int GL_POINT_SMOOTH { get { return 2832; } } public static int GL_POINT_SMOOTH_HINT { get { return 3153; } } public static int GL_POINTS { get { return 0; } } public static int GL_POINT_FADE_THRESHOLD_SIZE { get { return 33064; } } public static int GL_POINT_SIZE { get { return 2833; } } public static int GL_POLYGON_OFFSET_FILL { get { return 32823; } } public static int GL_POLYGON_SMOOTH_HINT { get { return 3155; } } public static int GL_POSITION { get { return 4611; } } public static int GL_PROJECTION { get { return 5889; } } public static int GL_QUADRATIC_ATTENUATION { get { return 4617; } } public static int GL_RED_BITS { get { return 3410; } } public static int GL_RENDERER { get { return 7937; } } public static int GL_REPEAT { get { return 10497; } } public static int GL_REPLACE { get { return 7681; } } public static int GL_RESCALE_NORMAL { get { return 32826; } } public static int GL_RGB { get { return 6407; } } public static int GL_RGBA { get { return 6408; } } public static int GL_SAMPLE_ALPHA_TO_COVERAGE { get { return 32926; } } public static int GL_SAMPLE_ALPHA_TO_ONE { get { return 32927; } } public static int GL_SAMPLE_COVERAGE { get { return 32928; } } public static int GL_SCISSOR_TEST { get { return 3089; } } public static int GL_SET { get { return 5391; } } public static int GL_SHININESS { get { return 5633; } } public static int GL_SHORT { get { return 5122; } } public static int GL_SMOOTH { get { return 7425; } } public static int GL_SMOOTH_LINE_WIDTH_RANGE { get { return 2850; } } public static int GL_SMOOTH_POINT_SIZE_RANGE { get { return 2834; } } public static int GL_SPECULAR { get { return 4610; } } public static int GL_SPOT_CUTOFF { get { return 4614; } } public static int GL_SPOT_DIRECTION { get { return 4612; } } public static int GL_SPOT_EXPONENT { get { return 4613; } } public static int GL_SRC_ALPHA { get { return 770; } } public static int GL_SRC_ALPHA_SATURATE { get { return 776; } } public static int GL_SRC_COLOR { get { return 768; } } public static int GL_STACK_OVERFLOW { get { return 1283; } } public static int GL_STACK_UNDERFLOW { get { return 1284; } } public static int GL_STENCIL_BITS { get { return 3415; } } public static int GL_STENCIL_BUFFER_BIT { get { return 1024; } } public static int GL_STENCIL_TEST { get { return 2960; } } public static int GL_SUBPIXEL_BITS { get { return 3408; } } public static int GL_TEXTURE { get { return 5890; } } public static int GL_TEXTURE_2D { get { return 3553; } } public static int GL_TEXTURE_COORD_ARRAY { get { return 32888; } } public static int GL_TEXTURE_ENV { get { return 8960; } } public static int GL_TEXTURE_ENV_COLOR { get { return 8705; } } public static int GL_TEXTURE_ENV_MODE { get { return 8704; } } public static int GL_TEXTURE_MAG_FILTER { get { return 10240; } } public static int GL_TEXTURE_MIN_FILTER { get { return 10241; } } public static int GL_TEXTURE_WRAP_S { get { return 10242; } } public static int GL_TEXTURE_WRAP_T { get { return 10243; } } public static int GL_TEXTURE0 { get { return 33984; } } public static int GL_TEXTURE1 { get { return 33985; } } public static int GL_TEXTURE2 { get { return 33986; } } public static int GL_TEXTURE3 { get { return 33987; } } public static int GL_TEXTURE4 { get { return 33988; } } public static int GL_TEXTURE5 { get { return 33989; } } public static int GL_TEXTURE6 { get { return 33990; } } public static int GL_TEXTURE7 { get { return 33991; } } public static int GL_TEXTURE8 { get { return 33992; } } public static int GL_TEXTURE9 { get { return 33993; } } public static int GL_TEXTURE10 { get { return 33994; } } public static int GL_TEXTURE11 { get { return 33995; } } public static int GL_TEXTURE12 { get { return 33996; } } public static int GL_TEXTURE13 { get { return 33997; } } public static int GL_TEXTURE14 { get { return 33998; } } public static int GL_TEXTURE15 { get { return 33999; } } public static int GL_TEXTURE16 { get { return 34000; } } public static int GL_TEXTURE17 { get { return 34001; } } public static int GL_TEXTURE18 { get { return 34002; } } public static int GL_TEXTURE19 { get { return 34003; } } public static int GL_TEXTURE20 { get { return 34004; } } public static int GL_TEXTURE21 { get { return 34005; } } public static int GL_TEXTURE22 { get { return 34006; } } public static int GL_TEXTURE23 { get { return 34007; } } public static int GL_TEXTURE24 { get { return 34008; } } public static int GL_TEXTURE25 { get { return 34009; } } public static int GL_TEXTURE26 { get { return 34010; } } public static int GL_TEXTURE27 { get { return 34011; } } public static int GL_TEXTURE28 { get { return 34012; } } public static int GL_TEXTURE29 { get { return 34013; } } public static int GL_TEXTURE30 { get { return 34014; } } public static int GL_TEXTURE31 { get { return 34015; } } public static int GL_TRIANGLE_FAN { get { return 6; } } public static int GL_TRIANGLE_STRIP { get { return 5; } } public static int GL_TRIANGLES { get { return 4; } } public static int GL_TRUE { get { return 1; } } public static int GL_UNPACK_ALIGNMENT { get { return 3317; } } public static int GL_UNSIGNED_BYTE { get { return 5121; } } public static int GL_UNSIGNED_SHORT { get { return 5123; } } public static int GL_UNSIGNED_SHORT_4_4_4_4 { get { return 32819; } } public static int GL_UNSIGNED_SHORT_5_5_5_1 { get { return 32820; } } public static int GL_UNSIGNED_SHORT_5_6_5 { get { return 33635; } } public static int GL_VENDOR { get { return 7936; } } public static int GL_VERSION { get { return 7938; } } public static int GL_VERTEX_ARRAY { get { return 32884; } } public static int GL_XOR { get { return 5382; } } public static int GL_ZERO { get { return 0; } } } }
using Braintree; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using NUnit.Framework; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; #if netcore using System.Net.Http; #else using System.Web; #endif using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Params = System.Collections.Generic.Dictionary<string, object>; using Response = System.Collections.Generic.Dictionary<string, string>; using System.Diagnostics; namespace Braintree.TestUtil { public class TestHelper { public static Response SampleNotificationFromXml(BraintreeGateway gateway, string xml) { var response = new Response(); var service = new BraintreeService(gateway.Configuration); response["bt_payload"] = xml; response["bt_signature"] = $"{service.PublicKey}|{new Sha1Hasher().HmacHash(service.PrivateKey, xml).Trim().ToLower()}"; return response; } public static string GenerateDecodedClientToken(BraintreeGateway gateway, ClientTokenRequest request = null) { var encodedClientToken = gateway.ClientToken.Generate(request); var decodedClientToken = Encoding.UTF8.GetString(Convert.FromBase64String(encodedClientToken)); var unescapedClientToken = Regex.Unescape(decodedClientToken); return unescapedClientToken; } public static string GenerateValidUsBankAccountNonce(BraintreeGateway gateway, string accountNumber = "1000000000") { var clientToken = GenerateDecodedClientToken(gateway); var def = new { braintree_api = new { url = "", access_token = "", port = "", } }; var config = JsonConvert.DeserializeAnonymousType(clientToken, def); var url = config.braintree_api.url + "/graphql"; var accessToken = config.braintree_api.access_token; string query = @" mutation tokenizeUsBankAccount($input: TokenizeUsBankAccountInput!) { tokenizeUsBankAccount(input: $input) { paymentMethod { id } } }"; var variables = new Dictionary<string, object> { {"input", new Dictionary<string, object> { {"usBankAccount", new Dictionary<string, object> { {"accountNumber", accountNumber}, {"routingNumber", "021000021"}, {"accountType", "CHECKING"}, {"billingAddress", new Dictionary<string, object> { {"streetAddress", "123 Ave"}, {"city", "San Francisco"}, {"state", "CA"}, {"zipCode", "94112"} }}, {"individualOwner", new Dictionary<string, object> { {"firstName", "Dan"}, {"lastName", "Schulman"} }}, {"achMandate", "cl mandate text"} }} }} }; Dictionary<string, object> body = new Dictionary<string, object>(); body["query"] = query; body["variables"] = variables; string postData = JsonConvert.SerializeObject(body, Newtonsoft.Json.Formatting.None); #if netcore var request = new HttpRequestMessage(new HttpMethod("POST"), url); byte[] buffer = Encoding.UTF8.GetBytes(postData); request.Content = new StringContent(postData, Encoding.UTF8, "application/json"); request.Headers.Add("Braintree-Version", "2016-10-07"); request.Headers.Add("Authorization", "Bearer " + accessToken); var httpClientHandler = new HttpClientHandler{}; HttpResponseMessage response; using (var client = new HttpClient(httpClientHandler)) { response = client.SendAsync(request).GetAwaiter().GetResult(); } StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); string responseBody = reader.ReadToEnd(); #else string curlCommand = $@"-s -H ""Content-type: application/json"" -H ""Braintree-Version: 2016-10-07"" -H ""Authorization: Bearer {accessToken}"" -d '{postData}' -XPOST ""{url}"""; Process process = new Process { StartInfo = new ProcessStartInfo { FileName = "curl", Arguments = curlCommand, UseShellExecute = false, RedirectStandardOutput = true, } }; process.Start(); StringBuilder responseBodyBuilder = new StringBuilder(); while (!process.HasExited) { responseBodyBuilder.Append(process.StandardOutput.ReadToEnd()); } responseBodyBuilder.Append(process.StandardOutput.ReadToEnd()); string responseBody = responseBodyBuilder.ToString(); #endif var resDef = new { data = new { tokenizeUsBankAccount = new { paymentMethod = new { id = "", } } } }; var json = JsonConvert.DeserializeAnonymousType(responseBody, resDef); return json.data.tokenizeUsBankAccount.paymentMethod.id; } public static string GenerateInvalidUsBankAccountNonce() { var valid_characters = "bcdfghjkmnpqrstvwxyz23456789"; var token = "tokenusbankacct"; Random rnd = new Random(); for(int i=0; i<4; i++) { token += "_"; for(int j=0; j<6; j++) { token += valid_characters[rnd.Next(0,valid_characters.ToCharArray().Length)]; } } return token + "_xxx"; } public static int CompareModificationsById(Modification left, Modification right) { return left.Id.CompareTo(right.Id); } public static void AreDatesEqual(DateTime expected, DateTime actual) { Assert.AreEqual(expected.Day, actual.Day); Assert.AreEqual(expected.Month, actual.Month); Assert.AreEqual(expected.Year, actual.Year); } public static void AssertIncludes(string expected, string all) { Assert.IsTrue(all.IndexOf(expected) >= 0, "Expected:\n" + all + "\nto include:\n" + expected); } public static bool IncludesSubscription(ResourceCollection<Subscription> collection, Subscription subscription) { foreach (Subscription item in collection) { if (item.Id.Equals(subscription.Id)) { return true; } } return false; } public static void Escrow(BraintreeService service, string transactionId) { NodeWrapper response = new NodeWrapper(service.Put(service.MerchantPath() + "/transactions/" + transactionId + "/escrow")); Assert.IsTrue(response.IsSuccess()); } #if netcore public static string GetResponseContent(HttpResponseMessage response) { using (var reader = new StreamReader(response.Content.ReadAsStreamAsync().Result)) return reader.ReadToEnd(); } public static string extractParamFromJson(string keyName, HttpResponseMessage response) { var param = extractParamFromJson(keyName, GetResponseContent(response)); return param; } #else public static string GetResponseContent(HttpWebResponse response) { using (var reader = new StreamReader(response.GetResponseStream())) return reader.ReadToEnd(); } public static string extractParamFromJson(string keyName, HttpWebResponse response) { var param = extractParamFromJson(keyName, GetResponseContent(response)); response.Close(); return param; } #endif public static string extractParamFromJson(string keyName, string json) { string regex = $"\"{keyName}\":\\s?\"([^\"]+)\""; Match match = Regex.Match(json, regex); string keyValue = match.Groups[1].Value; return keyValue; } public static int extractIntParamFromJson(string keyName, string json) { string regex = $"\"{keyName}\":\\s?(\\d+)"; Match match = Regex.Match(json, regex); int keyValue = Convert.ToInt32(match.Groups[1].Value); return keyValue; } public static string GenerateAuthorizationFingerprint(BraintreeGateway gateway, string customerId = null) { var clientTokenRequest = customerId == null ? null : new ClientTokenRequest { CustomerId = customerId }; var clientToken = GenerateDecodedClientToken(gateway, clientTokenRequest); return extractParamFromJson("authorizationFingerprint", clientToken); } public static string GetNonceForPayPalAccount(BraintreeGateway gateway, Params paypalAccountDetails) { var authorizationFingerprint = GenerateAuthorizationFingerprint(gateway); var builder = new RequestBuilder(); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint); foreach (var param in paypalAccountDetails) builder.AddTopLevelElement($"paypal_account[{param.Key}]", param.Value.ToString()); var response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); string responseBody = reader.ReadToEnd(); return extractParamFromJson("nonce", responseBody); #else return extractParamFromJson("nonce", response); #endif } public static string GetNonceForNewCreditCard(BraintreeGateway gateway, Params creditCardDetails, string customerId = null) { var authorizationFingerprint = GenerateAuthorizationFingerprint(gateway, customerId); var builder = new RequestBuilder(); builder. AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("shared_customer_identifier_type", "testing"); foreach (var param in creditCardDetails) { var nested = param.Value as Params; if (null != nested) { foreach (var nestedParam in nested) { builder.AddTopLevelElement($"credit_card[{param.Key}][{nestedParam.Key}]", nestedParam.Value.ToString()); } } else builder.AddTopLevelElement($"credit_card[{param.Key}]", param.Value.ToString()); } var response = new BraintreeTestHttpService().Post( gateway.MerchantId, "v1/payment_methods/credit_cards", builder.ToQueryString()); return extractParamFromJson("nonce", response); } public static string GetNonceForNewPaymentMethod(BraintreeGateway gateway, Params @params, bool isCreditCard) { var authorizationFingerprint = GenerateAuthorizationFingerprint(gateway); var paymentMethodType = isCreditCard ? "credit_card" : "paypal_account"; var paymentMethodTypePlural = paymentMethodType + "s"; var builder = new RequestBuilder(); builder. AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("shared_customer_identifier_type", "testing"); foreach (var param in @params) builder.AddTopLevelElement($"{paymentMethodType}[{param.Key}]", param.Value.ToString()); var response = new BraintreeTestHttpService().Post( gateway.MerchantId, "v1/payment_methods/" + paymentMethodTypePlural, builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); string responseBody = reader.ReadToEnd(); return extractParamFromJson("nonce", responseBody); #else return extractParamFromJson("nonce", response); #endif } public static string GenerateUnlockedNonce(BraintreeGateway gateway, string creditCardNumber, string customerId) { var authorizationFingerprint = GenerateAuthorizationFingerprint(gateway, customerId); RequestBuilder builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("credit_card[number]", creditCardNumber). AddTopLevelElement("share", "true"). AddTopLevelElement("credit_card[expiration_month]", "11"). AddTopLevelElement("credit_card[expiration_year]", "2099"); var response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards", builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); #else StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); #endif string responseBody = reader.ReadToEnd(); reader.Close(); return extractParamFromJson("nonce", responseBody); } public static string GenerateUnlockedNonce(BraintreeGateway gateway) { return GenerateUnlockedNonce(gateway, "4111111111111111", null); } public static string GenerateOneTimePayPalNonce(BraintreeGateway gateway) { var authorizationFingerprint = GenerateAuthorizationFingerprint(gateway); RequestBuilder builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("paypal_account[access_token]", "access_token"). AddTopLevelElement("paypal_account[correlation_id]", Guid.NewGuid().ToString()). AddTopLevelElement("paypal_account[options][validate]", "false"); var response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); #else StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); #endif string responseBody = reader.ReadToEnd(); reader.Close(); Regex regex = new Regex("nonce\":\"(?<nonce>[a-f0-9\\-]+)\""); Match match = regex.Match(responseBody); return match.Groups["nonce"].Value; } public static string GenerateFuturePaymentPayPalNonce(BraintreeGateway gateway) { var authorizationFingerprint = GenerateAuthorizationFingerprint(gateway); RequestBuilder builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("paypal_account[consent_code]", "consent"). AddTopLevelElement("paypal_account[correlation_id]", Guid.NewGuid().ToString()). AddTopLevelElement("paypal_account[options][validate]", "false"); var response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); #else StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); #endif string responseBody = reader.ReadToEnd(); reader.Close(); Regex regex = new Regex("nonce\":\"(?<nonce>[a-f0-9\\-]+)\""); Match match = regex.Match(responseBody); return match.Groups["nonce"].Value; } public static string GenerateOrderPaymentPayPalNonce(BraintreeGateway gateway) { var authorizationFingerprint = GenerateAuthorizationFingerprint(gateway); RequestBuilder builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("paypal_account[intent]", "order"). AddTopLevelElement("paypal_account[payment_token]", Guid.NewGuid().ToString()). AddTopLevelElement("paypal_account[payer_id]", "false"); var response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); #else StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); #endif string responseBody = reader.ReadToEnd(); reader.Close(); Regex regex = new Regex("nonce\":\"(?<nonce>[a-f0-9\\-]+)\""); Match match = regex.Match(responseBody); return match.Groups["nonce"].Value; } public static string Create3DSVerification(BraintreeService service, string merchantAccountId, ThreeDSecureRequestForTests request) { string url = "/three_d_secure/create_verification/" + merchantAccountId; NodeWrapper response = new NodeWrapper(service.Post(service.MerchantPath() + url, request)); Assert.IsTrue(response.IsSuccess()); return response.GetString("three-d-secure-authentication-id"); } public static string Generate3DSNonce(BraintreeService service, CreditCardRequest request) { string url = "/three_d_secure/create_nonce/" + MerchantAccountIDs.THREE_D_SECURE_MERCHANT_ACCOUNT_ID; NodeWrapper response = new NodeWrapper(service.Post(service.MerchantPath() + url, request)); Assert.IsTrue(response.IsSuccess()); return response.GetString("nonce"); } } public class OAuthTestHelper { private class OAuthGrantRequest : Request { public string MerchantId { get; set; } public string Scope { get; set; } public override string ToXml() { return new RequestBuilder("grant") .AddElement("merchant_public_id", MerchantId) .AddElement("scope", Scope) .ToXml(); } } public static string CreateGrant(BraintreeGateway gateway, string merchantId, string scope) { var service = new BraintreeService(gateway.Configuration); XmlNode node = service.Post("/oauth_testing/grants", new OAuthGrantRequest { MerchantId = merchantId, Scope = scope }); return node["code"].InnerText; } } public class BraintreeTestHttpService { public string ApiVersion = "3"; #if netcore public HttpResponseMessage Get(string MerchantId, string URL) { return GetJsonResponse(MerchantId, URL, "GET", null); } public HttpResponseMessage Post(string MerchantId, string URL, string requestBody) { return GetJsonResponse(MerchantId, URL, "POST", requestBody); } private HttpResponseMessage GetJsonResponse(string MerchantId, string Path, string method, string requestBody) { try { var request = new HttpRequestMessage(new HttpMethod(method), Environment.DEVELOPMENT.GatewayURL + "/merchants/" + MerchantId + "/client_api/" + Path); request.Headers.Add("X-ApiVersion", ApiVersion); request.Headers.Add("Accept", "application/xml"); request.Headers.Add("UserAgent", "Braintree .NET " + typeof(TestHelper).GetTypeInfo().Assembly.GetName().Version.ToString()); request.Headers.Add("KeepAlive", "false"); request.Headers.Add("Timeout", "60000"); request.Headers.Add("ReadWriteTimeout", "60000"); if (requestBody != null) { var content = requestBody; var utf8_string = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(requestBody)); request.Content = new StringContent(utf8_string, Encoding.UTF8,"application/x-www-form-urlencoded"); request.Content.Headers.ContentLength = UTF8Encoding.UTF8.GetByteCount(utf8_string); } var httpClientHandler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, }; HttpResponseMessage response; using (var client = new HttpClient(httpClientHandler)) { response = client.SendAsync(request).GetAwaiter().GetResult(); } return response; } catch (WebException e) { var errorWebResponse = e.Response as HttpWebResponse; var errorResponseMessage = new HttpResponseMessage(errorWebResponse.StatusCode); errorResponseMessage.Content = new StringContent(e.Response.ToString(), Encoding.UTF8, "application/json"); if (errorWebResponse == null) throw e; return errorResponseMessage; } } #else public HttpWebResponse Get(string MerchantId, string URL) { return GetJsonResponse(MerchantId, URL, "GET", null); } public HttpWebResponse Post(string MerchantId, string URL, string requestBody) { return GetJsonResponse(MerchantId, URL, "POST", requestBody); } private HttpWebResponse GetJsonResponse(string MerchantId, string Path, string method, string requestBody) { try { var request = WebRequest.Create(Environment.DEVELOPMENT.GatewayURL + "/merchants/" + MerchantId + "/client_api/" + Path) as HttpWebRequest; request.Headers.Add("X-ApiVersion", ApiVersion); request.Accept = "application/json"; request.UserAgent = "Braintree .NET " + typeof(BraintreeService).Assembly.GetName().Version.ToString(); request.Method = method; request.KeepAlive = false; request.Timeout = 60000; request.ReadWriteTimeout = 60000; if (requestBody != null) { byte[] buffer = Encoding.UTF8.GetBytes(requestBody); request.ContentLength = buffer.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(buffer, 0, buffer.Length); requestStream.Close(); } var response = request.GetResponse() as HttpWebResponse; return response; } catch (WebException e) { var response = (HttpWebResponse)e.Response; if (response == null) throw e; return response; } } #endif } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Baseline.ImTools; using Marten.Events.Daemon; using Marten.Events.Operations; using Marten.Events.Projections; using Marten.Events.Schema; using Marten.Exceptions; using Marten.Internal; using Marten.Internal.Operations; using Marten.Internal.Sessions; using Weasel.Postgresql; using Marten.Schema.Identity; using Marten.Storage; using Marten.Util; using Weasel.Postgresql.Functions; namespace Marten.Events { public class EventGraph: IFeatureSchema, IEventStoreOptions, IReadOnlyEventStoreOptions { private readonly Cache<string, EventMapping> _byEventName = new Cache<string, EventMapping>(); private readonly Cache<Type, EventMapping> _events = new Cache<Type, EventMapping>(); private readonly Cache<string, Type> _aggregateTypeByName; private readonly Cache<Type, string> _aggregateNameByType = new Cache<Type, string>(type => type.Name.ToTableAlias()); private string _databaseSchemaName; private readonly Lazy<IProjection[]> _inlineProjections; private readonly Lazy<EstablishTombstoneStream> _establishTombstone; private DocumentStore _store; public EventGraph(StoreOptions options) { Options = options; _events.OnMissing = eventType => { var mapping = typeof(EventMapping<>).CloseAndBuildAs<EventMapping>(this, eventType); Options.Storage.AddMapping(mapping); return mapping; }; _byEventName.OnMissing = name => { return AllEvents().FirstOrDefault(x => x.EventTypeName == name); }; _inlineProjections = new Lazy<IProjection[]>(() => Projections.BuildInlineProjections(_store)); _establishTombstone = new Lazy<EstablishTombstoneStream>(() => new EstablishTombstoneStream(this)); Projections = new ProjectionCollection(options); _aggregateTypeByName = new Cache<string, Type>(name => findAggregateType(name)); } IReadOnlyDaemonSettings IReadOnlyEventStoreOptions.Daemon => Daemon; IReadOnlyList<IProjectionSource> IReadOnlyEventStoreOptions.Projections() { return Projections.Projections.OfType<IProjectionSource>().ToList(); } public IReadOnlyList<IEventType> AllKnownEventTypes() { return _events.OfType<IEventType>().ToList(); } IReadonlyMetadataConfig IReadOnlyEventStoreOptions.MetadataConfig => MetadataConfig; private Type findAggregateType(string name) { foreach (var aggregateType in Projections.AllAggregateTypes()) { var possibleName = _aggregateNameByType[aggregateType]; if (name.EqualsIgnoreCase(possibleName)) return aggregateType; } return null; } /// <summary> /// Advanced configuration for the asynchronous projection execution /// </summary> public DaemonSettings Daemon { get; } = new DaemonSettings(); /// <summary> /// Configure whether event streams are identified with Guid or strings /// </summary> public StreamIdentity StreamIdentity { get; set; } = StreamIdentity.AsGuid; /// <summary> /// Configure the event sourcing storage for multi-tenancy /// </summary> public TenancyStyle TenancyStyle { get; set; } = TenancyStyle.Single; /// <summary> /// Whether a "for update" (row exclusive lock) should be used when selecting out the event version to use from the streams table /// </summary> /// <remarks> /// Not using this can result in race conditions in a concurrent environment that lead to /// event version mismatches between the event and stream version numbers /// </remarks> public bool UseAppendEventForUpdateLock { get; set; } = false; /// <summary> /// Configure the meta data required to be stored for events. By default meta data fields are disabled /// </summary> public MetadataConfig MetadataConfig => new(Metadata); internal StoreOptions Options { get; } internal DbObjectName Table => new DbObjectName(DatabaseSchemaName, "mt_events"); internal EventMetadataCollection Metadata { get; } = new(); internal EventMapping EventMappingFor(Type eventType) { return _events[eventType]; } internal EventMapping EventMappingFor<T>() where T : class { return EventMappingFor(typeof(T)); } internal IEnumerable<EventMapping> AllEvents() { return _events; } internal EventMapping EventMappingFor(string eventType) { return _byEventName[eventType]; } /// <summary> /// Register an event type with Marten. This isn't strictly necessary for normal usage, /// but can help Marten with asynchronous projections where Marten hasn't yet encountered /// the event type /// </summary> /// <param name="eventType"></param> public void AddEventType(Type eventType) { _events.FillDefault(eventType); } /// <summary> /// Register an event type with Marten. This isn't strictly necessary for normal usage, /// but can help Marten with asynchronous projections where Marten hasn't yet encountered /// the event type /// </summary> /// <param name="types"></param> public void AddEventTypes(IEnumerable<Type> types) { types.Each(AddEventType); } internal bool IsActive(StoreOptions options) => _events.Any() || Projections.Any() ; /// <summary> /// Override the database schema name for event related tables. By default this /// is the same schema as the document storage /// </summary> public string DatabaseSchemaName { get { return _databaseSchemaName ?? Options.DatabaseSchemaName; } set { _databaseSchemaName = value; } } internal Type AggregateTypeFor(string aggregateTypeName) { return _aggregateTypeByName[aggregateTypeName]; } internal DbObjectName ProgressionTable => new DbObjectName(DatabaseSchemaName, "mt_event_progression"); internal DbObjectName StreamsTable => new DbObjectName(DatabaseSchemaName, "mt_streams"); internal string AggregateAliasFor(Type aggregateType) { var alias = _aggregateNameByType[aggregateType]; _aggregateTypeByName.Fill(alias, aggregateType); return alias; } IEnumerable<Type> IFeatureSchema.DependentTypes() { yield break; } ISchemaObject[] IFeatureSchema.Objects { get { var eventsTable = new EventsTable(this); var streamsTable = new StreamsTable(this); #region sample_using-sequence var sequence = new Sequence(new DbObjectName(DatabaseSchemaName, "mt_events_sequence")) { Owner = eventsTable.Identifier, OwnerColumn = "seq_id" }; #endregion sample_using-sequence // compute the args for mt_append_event function var streamIdTypeArg = StreamIdentity == StreamIdentity.AsGuid ? "uuid" : "varchar"; var appendEventFunctionArgs = $"{streamIdTypeArg}, varchar, varchar, uuid[], varchar[], varchar[], jsonb[]"; return new ISchemaObject[] { streamsTable, eventsTable, new EventProgressionTable(DatabaseSchemaName), sequence, new SystemFunction(DatabaseSchemaName, "mt_mark_event_progression", "varchar, bigint"), Function.ForRemoval(new DbObjectName(DatabaseSchemaName, "mt_append_event")) }; } } Type IFeatureSchema.StorageType => typeof(EventGraph); string IFeatureSchema.Identifier { get; } = "eventstore"; void IFeatureSchema.WritePermissions(DdlRules rules, TextWriter writer) { // Nothing } internal string GetStreamIdDBType() { return StreamIdentity == StreamIdentity.AsGuid ? "uuid" : "varchar"; } internal Type GetStreamIdType() { return StreamIdentity == StreamIdentity.AsGuid ? typeof(Guid) : typeof(string); } private readonly Ref<ImHashMap<string, Type>> _nameToType = Ref.Of(ImHashMap<string, Type>.Empty); internal Type TypeForDotNetName(string assemblyQualifiedName) { if (!_nameToType.Value.TryFind(assemblyQualifiedName, out var value)) { value = Type.GetType(assemblyQualifiedName); if (value == null) { throw new UnknownEventTypeException($"Unable to load event type '{assemblyQualifiedName}'."); } _nameToType.Swap(n => n.AddOrUpdate(assemblyQualifiedName, value)); } return value; } internal IEventStorage EnsureAsStringStorage(IMartenSession session) { if (StreamIdentity == StreamIdentity.AsGuid) throw new InvalidOperationException("This Marten event store is configured to identify streams with Guids"); return session.EventStorage(); } internal IEventStorage EnsureAsGuidStorage(IMartenSession session) { if (StreamIdentity == StreamIdentity.AsString) throw new InvalidOperationException("This Marten event store is configured to identify streams with strings"); return session.EventStorage(); } internal StreamAction Append(DocumentSessionBase session, Guid stream, params object[] events) { EnsureAsGuidStorage(session); if (stream == Guid.Empty) throw new ArgumentOutOfRangeException(nameof(stream), "Cannot use an empty Guid as the stream id"); var wrapped = events.Select(BuildEvent).ToArray(); if (session.WorkTracker.TryFindStream(stream, out var eventStream)) { eventStream.AddEvents(wrapped); } else { eventStream = StreamAction.Append(stream, wrapped); session.WorkTracker.Streams.Add(eventStream); } return eventStream; } internal StreamAction Append(DocumentSessionBase session, string stream, params object[] events) { EnsureAsStringStorage(session); if (stream.IsEmpty()) throw new ArgumentOutOfRangeException(nameof(stream), "The stream key cannot be null or empty"); var wrapped = events.Select(BuildEvent).ToArray(); if (session.WorkTracker.TryFindStream(stream, out var eventStream)) { eventStream.AddEvents(wrapped); } else { eventStream = StreamAction.Append(stream, wrapped); session.WorkTracker.Streams.Add(eventStream); } return eventStream; } internal StreamAction StartStream(DocumentSessionBase session, Guid id, params object[] events) { EnsureAsGuidStorage(session); if (id == Guid.Empty) throw new ArgumentOutOfRangeException(nameof(id), "Cannot use an empty Guid as the stream id"); var stream = StreamAction.Start(this, id, events); session.WorkTracker.Streams.Add(stream); return stream; } internal StreamAction StartStream(DocumentSessionBase session, string streamKey, params object[] events) { EnsureAsStringStorage(session); if (streamKey.IsEmpty()) throw new ArgumentOutOfRangeException(nameof(streamKey), "The stream key cannot be null or empty"); var stream = StreamAction.Start(this, streamKey, events); session.WorkTracker.Streams.Add(stream); return stream; } internal void ProcessEvents(DocumentSessionBase session) { if (!session.WorkTracker.Streams.Any()) { return; } var storage = session.EventStorage(); // TODO -- we'll optimize this later to batch up queries to the database var fetcher = new EventSequenceFetcher(this, session.WorkTracker.Streams.Sum(x => x.Events.Count)); var sequences = session.ExecuteHandler(fetcher); foreach (var stream in session.WorkTracker.Streams) { stream.TenantId ??= session.Tenant.TenantId; if (stream.ActionType == StreamActionType.Start) { stream.PrepareEvents(0, this, sequences, session); session.QueueOperation(storage.InsertStream(stream)); } else { var handler = storage.QueryForStream(stream); var state = session.ExecuteHandler(handler); if (state == null) { stream.PrepareEvents(0, this, sequences, session); session.QueueOperation(storage.InsertStream(stream)); } else { stream.PrepareEvents(state.Version, this, sequences, session); session.QueueOperation(storage.UpdateStreamVersion(stream)); } } foreach (var @event in stream.Events) { session.QueueOperation(storage.AppendEvent(this, session, stream, @event)); } } foreach (var projection in _inlineProjections.Value) { projection.Apply(session, session.WorkTracker.Streams.ToList()); } } internal async Task ProcessEventsAsync(DocumentSessionBase session, CancellationToken token) { if (!session._workTracker.Streams.Any()) { return; } // TODO -- we'll optimize this later to batch up queries to the database var fetcher = new EventSequenceFetcher(this, session.WorkTracker.Streams.Sum(x => x.Events.Count)); var sequences = await session.ExecuteHandlerAsync(fetcher, token); var storage = session.EventStorage(); foreach (var stream in session.WorkTracker.Streams) { stream.TenantId ??= session.Tenant.TenantId; if (stream.ActionType == StreamActionType.Start) { stream.PrepareEvents(0, this, sequences, session); session.QueueOperation(storage.InsertStream(stream)); } else { var handler = storage.QueryForStream(stream); var state = await session.ExecuteHandlerAsync(handler, token); if (state == null) { stream.PrepareEvents(0, this, sequences, session); session.QueueOperation(storage.InsertStream(stream)); } else { stream.PrepareEvents(state.Version, this, sequences, session); session.QueueOperation(storage.UpdateStreamVersion(stream)); } } foreach (var @event in stream.Events) { session.QueueOperation(storage.AppendEvent(this, session, stream, @event)); } } foreach (var projection in _inlineProjections.Value) { await projection.ApplyAsync(session, session.WorkTracker.Streams.ToList(), token); } } internal bool TryCreateTombstoneBatch(DocumentSessionBase session, out UpdateBatch batch) { if (session.WorkTracker.Streams.Any()) { var stream = StreamAction.ForTombstone(); var tombstone = new Tombstone(); var mapping = EventMappingFor<Tombstone>(); var operations = new List<IStorageOperation>(); var storage = session.EventStorage(); operations.Add(_establishTombstone.Value); var tombstones = session.WorkTracker.Streams .SelectMany(x => x.Events) .Select(x => new Event<Tombstone>(tombstone) { Sequence = x.Sequence, Version = x.Version, TenantId = x.TenantId, StreamId = EstablishTombstoneStream.StreamId, StreamKey = EstablishTombstoneStream.StreamKey, Id = CombGuidIdGeneration.NewGuid(), EventTypeName = mapping.EventTypeName, DotNetTypeName = mapping.DotNetTypeName }) .Select(e => storage.AppendEvent(this, session, stream, e)); operations.AddRange(tombstones); batch = new UpdateBatch(operations); return true; } batch = null; return false; } /// <summary> /// Configuration for all event store projections /// </summary> public ProjectionCollection Projections { get; } internal IEvent BuildEvent(object eventData) { if (eventData == null) throw new ArgumentNullException(nameof(eventData)); var mapping = EventMappingFor(eventData.GetType()); return mapping.Wrap(eventData); } internal void AssertValidity(DocumentStore store) { _store = store; Projections.AssertValidity(_store); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace LeaflyTest.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using Valve.VR; public class manipulator : MonoBehaviour { int controllerIndex = -1; public GameObject activeTip; public Transform tipL, tipR; public Transform triggerTrans; List<Transform> hitTransforms = new List<Transform>(); Transform selectedTransform; manipObject selectedObject; public Renderer[] oculusSprites; public GameObject oculusContextButtonGlow; menuspawn _menuspawn; public touchpad _touchpad; public GameObject[] tipTexts; public GameObject oculusObjects, viveObjects, oculusMenuButton, oculusTrigger; public Transform tipPackage, glowMenuTransform, oculusManipTarget, oculusParentTarget, viveMenuButtonTransform; public GameObject controllerRep; bool usingOculus = false; public Color onColor = Color.HSVToRGB(208 / 359f, 234 / 255f, 93 / 255f); void Awake() { _menuspawn = GetComponent<menuspawn>(); _touchpad.manip = this; activeTip.SetActive(false); glowMenuTransform.position = viveMenuButtonTransform.position; glowMenuTransform.rotation = viveMenuButtonTransform.rotation; oculusSprites[0].material.SetColor("_TintColor", onColor); oculusSprites[0].material.SetFloat("_EmissionGain", .5f); oculusSprites[0].gameObject.SetActive(true); for (int i = 1; i < oculusSprites.Length; i++) { oculusSprites[i].material.SetColor("_TintColor", onColor); oculusSprites[i].material.SetFloat("_EmissionGain", .5f); oculusSprites[i].gameObject.SetActive(false); } oculusContextButtonGlow.GetComponent<Renderer>().material.SetColor("_TintColor", onColor); oculusContextButtonGlow.SetActive(false); } bool controllerVisible = true; public void toggleController(bool on) { controllerVisible = on; controllerRep.SetActive(on); } public void SetDeviceIndex(int index) { controllerIndex = index; } bool grabbing; public bool emptyGrab; public bool isGrabbing() { return (selectedObject != null); } public void showTip() { if (!tipPackage.gameObject.activeSelf) tipPackage.gameObject.SetActive(true); } public void invertScale() { transform.parent.localScale = new Vector3(-1, 1, 1); Vector3 s = oculusSprites[0].gameObject.transform.localScale; s.x *= -1; oculusSprites[0].gameObject.transform.localScale = s; for (int i = 0; i < tipTexts.Length; i++) { s = tipTexts[i].gameObject.transform.localScale; s.x *= -1; tipTexts[i].gameObject.transform.localScale = s; } } void Grab(bool on) { grabbing = on; showTip(); if (selectedObject != null) { selectedObject.setGrab(grabbing, transform); if (!on) toggleController(true); else if (usingOculus) selectedObject.setTouch(true); } else emptyGrab = on; } public manipObject getSelection() { if (!grabbing) return null; return selectedObject; } public void ForceRelease() { showTip(); if (grabbing == true) { release(); grabbing = false; } } void release() { selectedObject.setState(manipObject.manipState.none); toggleController(true); } public void ForceGrab(manipObject o) { if (selectedObject != null) release(); grabbing = true; selectedObject = o; selectedObject.setGrab(grabbing, transform); emptyGrab = false; selectedTransform = o.transform; } void OnCollisionEnter(Collision coll) { manipObject o = coll.transform.GetComponent<manipObject>(); if (o != null) o.onTouch(true, this); } void OnCollisionExit(Collision coll) { manipObject o = coll.transform.GetComponent<manipObject>(); if (o != null) o.onTouch(false, this); } void OnCollisionStay(Collision coll) { hitTransforms.Add(coll.transform); } void FixedUpdate() { hitTransforms.Clear(); } Coroutine pulseCoroutine; public void constantPulse(bool on) { if (pulseCoroutine != null) StopCoroutine(pulseCoroutine); if (on) { pulseCoroutine = StartCoroutine(pulseRoutine()); } } IEnumerator pulseRoutine() { while (true) { hapticPulse(750); yield return new WaitForSeconds(0.3f); } } public void hapticPulse(ushort hapticPower = 750) { if (masterControl.instance.currentPlatform == masterControl.platform.Vive) SteamVR_Controller.Input(controllerIndex).TriggerHapticPulse(hapticPower); else if (masterControl.instance.currentPlatform == masterControl.platform.Oculus) bigHaptic(hapticPower, .05f); } Coroutine _hapticCoroutine; public void bigHaptic(ushort hapticPower = 750, float dur = .1f) { if (_hapticCoroutine != null) StopCoroutine(_hapticCoroutine); _hapticCoroutine = StartCoroutine(hapticCoroutine(hapticPower, dur)); } IEnumerator hapticCoroutine(ushort hapticPower, float dur) { if (masterControl.instance.currentPlatform == masterControl.platform.Vive) { float t = 0; while (t < dur) { t += Time.deltaTime; hapticPulse(hapticPower); yield return null; } } } void LateUpdate() { if (grabbing) return; Transform candidate = null; if (selectedObject != null) { if (hitTransforms.Contains(selectedTransform)) candidate = selectedTransform; } else { foreach (Transform t in hitTransforms) { if (t != null) { manipObject o = t.GetComponent<manipObject>(); if (o != null) { if (o.curState != manipObject.manipState.grabbed && o.curState != manipObject.manipState.selected) { candidate = t; break; } } } } } if (candidate != selectedTransform) { if (selectedObject != null) selectedObject.GetComponent<manipObject>().setSelect(false, transform); if (candidate != null) { candidate.GetComponent<manipObject>().setSelect(true, transform); if (candidate.GetComponent<handle>() != null) toggleCopy(true); else if (candidate.GetComponent<manipObject>().canBeDeleted) toggleDelete(true); hapticPulse(); selectedTransform = candidate; selectedObject = candidate.GetComponent<manipObject>(); } else { toggleCopy(false); toggleDelete(false); selectedTransform = null; selectedObject = null; } } } bool copyEnabled = false; void toggleCopy(bool on) { copyEnabled = on; if (!usingOculus) _touchpad.toggleCopy(on); else if (!copying) { oculusSprites[0].gameObject.SetActive(!on); oculusSprites[1].gameObject.SetActive(on); oculusSprites[2].gameObject.SetActive(false); oculusSprites[3].gameObject.SetActive(false); } } bool deleteEnabled = false; void toggleDelete(bool on) { if (multiselecting) return; deleteEnabled = on; if (!usingOculus) _touchpad.toggleDelete(on); else { oculusSprites[0].gameObject.SetActive(!on); oculusSprites[1].gameObject.SetActive(false); oculusSprites[2].gameObject.SetActive(on); oculusSprites[3].gameObject.SetActive(false); } } timelineGridUI multiselectGrid; bool multiselectEnabled = false; public void toggleMultiselect(bool on, timelineGridUI _grid) { if (!on && multiselecting) return; multiselectGrid = on ? _grid : null; multiselectEnabled = on; if (!usingOculus) _touchpad.toggleMultiselect(on); else { if (!deleteEnabled) oculusSprites[0].gameObject.SetActive(!on); oculusSprites[1].gameObject.SetActive(false); if (!deleteEnabled) oculusSprites[2].gameObject.SetActive(false); oculusSprites[3].gameObject.SetActive(on); } } public void SetTrigger(bool on) { triggerDown = on; if (selectedObject != null) { if (selectedObject.stickyGrip && selectedObject.curState == manipObject.manipState.grabbed) { if (on) Grab(!on); return; } } Grab(on); } bool multiselecting = false; public void MultiselectSelection(bool on) { multiselecting = on; if (multiselectGrid == null) { Debug.Log("HRM.."); return; } else { multiselectGrid.onMultiselect(on, transform); } } bool deleting = false; public void DeleteSelection(bool on) { deleting = on; if (on && selectedObject != null) { selectedObject.selfdelete(); } if (!on) { if (selectedObject == null) toggleDelete(false); else if (!selectedObject.canBeDeleted) toggleDelete(false); } } bool copying = false; public void SetCopy(bool on) { if (menuManager.instance.simple) return; copying = on; if (selectedObject != null) { if (on) { if (selectedObject.GetComponent<handle>() != null) SaveLoadInterface.instance.Copy(selectedObject.transform.parent.gameObject, this); } else if (selectedObject.GetComponent<handle>() != null && !triggerDown) Grab(false); } } void updateProngs() { float val = 0; if (masterControl.instance.currentPlatform == masterControl.platform.Vive) val = SteamVR_Controller.Input(controllerIndex).GetAxis(EVRButtonId.k_EButton_Axis1).x; if (!usingOculus) { triggerTrans.localRotation = Quaternion.Euler(Mathf.Lerp(0, 45, val), 180, 0); } else { triggerTrans.localRotation = Quaternion.Euler(Mathf.Lerp(0, -20, val), 0, 0); } tipL.localPosition = new Vector3(Mathf.Lerp(-.005f, 0, val), -.005f, -.018f); tipR.localPosition = new Vector3(Mathf.Lerp(.004f, -.001f, val), -.005f, -.018f); } bool showingTips = true; public void toggleTips(bool on) { showingTips = on; for (int i = 0; i < tipTexts.Length; i++) { tipTexts[i].SetActive(showingTips); } if (!usingOculus) _touchpad.setQuestionMark(showingTips); } public void changeHW(string s) { if (s == "oculus") { usingOculus = true; oculusObjects.SetActive(true); viveObjects.SetActive(false); glowMenuTransform.position = oculusMenuButton.transform.position; glowMenuTransform.rotation = oculusMenuButton.transform.rotation; glowMenuTransform.Translate(Vector3.up * .01f, Space.Self); tipPackage.localPosition = oculusManipTarget.localPosition; tipPackage.localRotation = oculusManipTarget.localRotation; triggerTrans = oculusTrigger.transform; } } public void setVerticalPosition(Transform t) { tipPackage.gameObject.SetActive(false); if (!usingOculus) return; else { t.localPosition = oculusParentTarget.localPosition; t.localRotation = oculusParentTarget.localRotation; } } bool touchpadActive = false; public void viveTouchpadUpdate() { bool tOn = SteamVR_Controller.Input(controllerIndex).GetTouchDown(SteamVR_Controller.ButtonMask.Touchpad); bool tOff = SteamVR_Controller.Input(controllerIndex).GetTouchUp(SteamVR_Controller.ButtonMask.Touchpad); bool pOn = SteamVR_Controller.Input(controllerIndex).GetPressDown(SteamVR_Controller.ButtonMask.Touchpad); bool pOff = SteamVR_Controller.Input(controllerIndex).GetPressUp(SteamVR_Controller.ButtonMask.Touchpad); bool activeManipObj = (grabbing && selectedObject != null); if (tOn) { touchpadActive = true; if (controllerVisible) _touchpad.setTouch(true); if (activeManipObj) selectedObject.setTouch(true); } if (tOff) { touchpadActive = false; if (controllerVisible) _touchpad.setTouch(false); if (activeManipObj) selectedObject.setTouch(false); } if (!touchpadActive) return; Vector2 pos = SteamVR_Controller.Input(controllerIndex).GetAxis(); if (controllerVisible) _touchpad.updateTouchPos(pos); if (activeManipObj) selectedObject.updateTouchPos(pos); if (pOn) { if (controllerVisible) _touchpad.setPress(true); if (activeManipObj) selectedObject.setPress(true); } if (pOff) { if (controllerVisible) _touchpad.setPress(false); if (activeManipObj) selectedObject.setPress(false); } } void secondaryOculusButtonUpdate() { bool secondaryDown = false; bool secondaryUp = false; if (masterControl.instance.currentPlatform == masterControl.platform.Vive) { secondaryDown = SteamVR_Controller.Input(controllerIndex).GetPressDown(SteamVR_Controller.ButtonMask.ApplicationMenu); secondaryUp = SteamVR_Controller.Input(controllerIndex).GetPressUp(SteamVR_Controller.ButtonMask.ApplicationMenu); } if (controllerVisible) { if (secondaryDown) { if (copyEnabled) SetCopy(true); else if (deleteEnabled) DeleteSelection(true); else if (multiselectEnabled) MultiselectSelection(true); else toggleTips(true); oculusContextButtonGlow.SetActive(true); } else if (secondaryUp) { toggleTips(false); if (copying) SetCopy(false); else if (deleting) DeleteSelection(false); else if (multiselectEnabled) MultiselectSelection(false); oculusContextButtonGlow.SetActive(false); } } else if (grabbing && selectedObject != null) { if (secondaryDown) selectedObject.setPress(true); if (secondaryUp) selectedObject.setPress(false); } } public bool triggerDown = false; void Update() { updateProngs(); bool triggerButtonDown, triggerButtonUp, menuButtonDown; if (masterControl.instance.currentPlatform == masterControl.platform.Vive) { triggerButtonDown = SteamVR_Controller.Input(controllerIndex).GetPressDown(SteamVR_Controller.ButtonMask.Trigger); triggerButtonUp = SteamVR_Controller.Input(controllerIndex).GetPressUp(SteamVR_Controller.ButtonMask.Trigger); if (!usingOculus) { viveTouchpadUpdate(); menuButtonDown = SteamVR_Controller.Input(controllerIndex).GetPressDown(SteamVR_Controller.ButtonMask.ApplicationMenu); } else { Vector2 pos = SteamVR_Controller.Input(controllerIndex).GetAxis(); if (grabbing && selectedObject != null) selectedObject.updateTouchPos(pos); secondaryOculusButtonUpdate(); menuButtonDown = SteamVR_Controller.Input(controllerIndex).GetPressDown(EVRButtonId.k_EButton_A); } } else { triggerButtonDown = triggerButtonUp = menuButtonDown = false; } if (triggerButtonDown) { activeTip.SetActive(true); tipL.gameObject.SetActive(false); tipR.gameObject.SetActive(false); SetTrigger(true); } if (triggerButtonUp) { activeTip.SetActive(false); tipL.gameObject.SetActive(true); tipR.gameObject.SetActive(true); SetTrigger(false); } if (menuButtonDown) _menuspawn.togglePad(); if (grabbing && selectedObject != null) selectedObject.grabUpdate(transform); else if (selectedObject != null) selectedObject.selectUpdate(transform); } }
// Bareplan (c) 2015-17 MIT License <[email protected]> namespace Bareplan.Core { using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using Pair = System.Collections.Generic.KeyValuePair<System.DateTime, Document.Task>; /// <summary> /// Base class for all document exporters. /// </summary> public abstract class DocumentExporter { public class RowInfo { /// <summary> /// Gets or sets the session. /// </summary> /// <value>The session.</value> public int Session { get; set; } /// <summary> /// Gets or sets the week number. /// </summary> /// <value>The week number.</value> public int WeekNumber { get; set; } /// <summary> /// Gets or sets a value indicating whether /// this <see cref="T:Bareplan.Core.DocumentExporter.RowInfo"/>'s week number changed. /// </summary> /// <value><c>true</c> if week number changed; otherwise, <c>false</c>.</value> public bool WeekNumberChanged { get; set; } /// <summary> /// Gets or sets the pair. /// </summary> /// <value>The pair of <see cref="T:System.DateTime"/> and task(string).</value> public Pair Pair { get; set; } } /// <summary> /// The base <see cref="Bareplan.Core.DocumentExporter"/> class for all exporters. /// </summary> /// <param name='info'> /// The <see cref="Bareplan.Core.ExportInfo"/> with the info to do the export. /// </param> protected DocumentExporter(ExportInfo info) { this.Info = info; this.Contents = ""; } /// <summary> /// Writes the header. /// </summary> /// <param name="txt">A <see cref="T:System.StringBuilder"/>Text.</param> protected virtual void WriteHeader(StringBuilder txt) { } /// <summary> /// Writes the header for the table of date/task's rows. /// </summary> /// <param name="txt">A <see cref="T:System.StringBuilder"/>Text.</param> protected virtual void WriteTableHeader(StringBuilder txt) { } /// <summary> /// Writes the footer for the table of date/task's rows. /// </summary> /// <param name="txt">A <see cref="T:System.StringBuilder"/>Text.</param> protected virtual void WriteTableFooter(StringBuilder txt) { } /// <summary> /// Writes the footer. /// </summary> /// <param name="txt">A <see cref="T:System.StringBuilder"/>Text.</param> protected virtual void WriteFooter(StringBuilder txt) { } /// <summary> /// Writes a given date/task row. /// </summary> /// <param name="txt">A <see cref="T:System.StringBuilder"/>Text.</param> /// <param name="rowInfo">A <see cref="T:RowInfo"/> containing all row's info.</param> protected virtual void WriteRow(StringBuilder txt, RowInfo rowInfo) { } /// <summary> /// Actually exports the document to an HTML string. /// </summary> public void Export() { Document doc = this.Info.Document; DateTimeFormatInfo dtfo = CultureInfo.CurrentCulture.DateTimeFormat; StringBuilder toret = new StringBuilder(); Trace.WriteLine( "Exporter.Export: Begin" ); Trace.Indent(); WriteHeader( toret ); WriteTableHeader( toret ); // Write each row Pair pair = doc.GotoFirst(); int weekCount = 1; int session = 1; bool showWeek = true; int weekNumber = GetWeekNumberFor( pair.Key ); while( !doc.IsEnd() ) { var rowInfo = new RowInfo { Session = session, WeekNumber = weekCount, Pair = pair, WeekNumberChanged = showWeek }; this.WriteRow( toret, rowInfo ); showWeek = false; // Next task/date pair toret.AppendLine(); pair = doc.Next(); ++session; int newWeekNumber = GetWeekNumberFor( pair.Key ); if ( newWeekNumber != weekNumber ) { ++weekCount; weekNumber = newWeekNumber; showWeek = true; } } // End WriteTableFooter( toret ); WriteFooter( toret ); this.Contents = toret.ToString(); Trace.Unindent(); Trace.WriteLine( "Exporter.Export: End" ); } /// <summary> /// Saves the Contents. Invokes Export() if Contents is empty. /// </summary> public void Save() { string fileName = this.Info.FileName; Trace.WriteLine( "Exporter.Save: Begin" ); Trace.Indent(); if ( string.IsNullOrWhiteSpace( this.Contents ) ) { this.Export(); } Trace.WriteLine( "Writing to: " + fileName ); Trace.WriteLine( "Writing " + this.Contents.Length + " chrs." ); using (StreamWriter outfile = new StreamWriter( fileName ) ) { outfile.WriteLine( this.Contents ); } Trace.Unindent(); Trace.WriteLine( "Exporter.Save: End" ); } /// <summary> /// Creates the specified exporter, given the export info. /// </summary> /// <returns>An appropriate <see cref="DocumentExporter"/>.</returns> /// <param name="info">The <see cref="ExportInfo"/>.</param> public static DocumentExporter Create(ExportInfo info) { DocumentExporter toret = null; switch( info.Type ) { case ExportInfo.FileType.Csv: toret = new CsvExporter( info ); break; case ExportInfo.FileType.Html: toret = new HtmlExporter( info ); break; case ExportInfo.FileType.Text: toret = new TextExporter( info ); break; case ExportInfo.FileType.GCal: toret = new GCalExporter( info ); break; } Debug.Assert( toret != null, "Exporter.Create: No exporter found for: " + info.Type ); return toret; } /// <summary> /// Gets the week number for the given date. /// </summary> /// <returns>The correpsonding week number.</returns> /// <param name="date">A <see cref="T:System.DateTime"/>.</param> protected static int GetWeekNumberFor(System.DateTime date) { DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; Calendar cal = dfi.Calendar; return cal.GetWeekOfYear( date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek ); } /// <summary> /// Gets the column info, converted into a string. /// </summary> /// <returns>The column, as a string.</returns> /// <param name="column">A <see cref="T:ExportInfo.Column"/>.</param> /// <param name="rowInfo">A <see cref="T:DocumentExporter.RowInfo"/>.</param> protected string GetColumn(ExportInfo.Column column, RowInfo rowInfo) { string toret = null; switch ( column ) { case ExportInfo.Column.Session: toret = rowInfo.Session.ToString(); break; case ExportInfo.Column.Week: toret = rowInfo.WeekNumber.ToString(); break; case ExportInfo.Column.Day: DateTimeFormatInfo dtfo = CultureInfo.CurrentCulture.DateTimeFormat; toret = dtfo.GetAbbreviatedDayName( rowInfo.Pair.Key.DayOfWeek ); break; case ExportInfo.Column.Date: toret = rowInfo.Pair.Key.ToShortDateString(); break; case ExportInfo.Column.Kind: toret = rowInfo.Pair.Value.Kind; break; case ExportInfo.Column.Contents: toret = rowInfo.Pair.Value.Contents; break; } Debug.Assert( toret != null, "no column's value for: " + column ); return toret; } /// <summary> /// The contents to be stored in the file. /// This is normally generated by <see cref="M:DocumentExporter.Export"/>. /// </summary> /// <value> /// The contents, as a string. /// </value> public string Contents { get; protected set; } /// <summary> /// Gets or sets the export info. /// </summary> /// <value>The <see cref="Info"/>.</value> public ExportInfo Info { get; private set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Security { // TODO: Issue #1387. // This implementation lacks encryption. We need to investigate adding such encryption support, at which point // we could potentially remove the current implementation's reliance on mlock and mprotect (mlock places additional // constraints on non-privileged processes due to RLIMIT_MEMLOCK), neither of which provides a guarantee that the // data-at-rest in memory can't be accessed; they just make it more difficult. If we don't encrypt, at least on Linux // we should consider also using madvise to set MADV_DONTDUMP and MADV_DONTFORK for the allocated pages. And we // should ensure the documentation gets updated appropriately. public sealed partial class SecureString { private ProtectedBuffer _buffer; [System.Security.SecurityCritical] // auto-generated internal unsafe SecureString(SecureString str) { // Allocate enough space to store the provided string EnsureCapacity(str._decryptedLength); _decryptedLength = str._decryptedLength; // Copy the string into the newly allocated space if (_decryptedLength > 0) using (str._buffer.Unprotect()) ProtectedBuffer.Copy(str._buffer, _buffer, (ulong)(str._decryptedLength * sizeof(char))); // Protect the buffer _buffer.Protect(); } [System.Security.SecurityCritical] // auto-generated private unsafe void InitializeSecureString(char* value, int length) { // Allocate enough space to store the provided string EnsureCapacity(length); _decryptedLength = length; if (length == 0) return; // Copy the string into the newly allocated space byte* ptr = null; try { _buffer.AcquirePointer(ref ptr); Buffer.MemoryCopy(value, ptr, _buffer.ByteLength, (ulong)(length * sizeof(char))); } finally { if (ptr != null) _buffer.ReleasePointer(); } // Protect the buffer _buffer.Protect(); } [System.Security.SecuritySafeCritical] // auto-generated private void DisposeCore() { if (_buffer != null && !_buffer.IsInvalid) { _buffer.Dispose(); _buffer = null; } } [System.Security.SecurityCritical] // auto-generated private void EnsureNotDisposed() { if (_buffer == null) throw new ObjectDisposedException(GetType().Name); } // clears the current contents. Only available if writable [System.Security.SecuritySafeCritical] // auto-generated private void ClearCore() { _decryptedLength = 0; using (_buffer.Unprotect()) _buffer.Clear(); } [System.Security.SecuritySafeCritical] // auto-generated private unsafe void AppendCharCore(char c) { // Make sure we have enough space for the new character, // then write it at the end. EnsureCapacity(_decryptedLength + 1); using (_buffer.Unprotect()) _buffer.Write((ulong)(_decryptedLength * sizeof(char)), c); _decryptedLength++; } [System.Security.SecuritySafeCritical] // auto-generated private unsafe void InsertAtCore(int index, char c) { // Make sure we have enough space for the new character, // then shift all of the characters above it and insert it. EnsureCapacity(_decryptedLength + 1); byte* ptr = null; try { _buffer.AcquirePointer(ref ptr); char* charPtr = (char*)ptr; using (_buffer.Unprotect()) { for (int i = _decryptedLength; i > index; i--) charPtr[i] = charPtr[i - 1]; charPtr[index] = c; } ++_decryptedLength; } finally { if (ptr != null) _buffer.ReleasePointer(); } } [System.Security.SecuritySafeCritical] // auto-generated private unsafe void RemoveAtCore(int index) { // Shift down all values above the specified index, // then null out the empty space at the end. byte* ptr = null; try { _buffer.AcquirePointer(ref ptr); char* charPtr = (char*)ptr; using (_buffer.Unprotect()) { for (int i = index; i < _decryptedLength - 1; i++) charPtr[i] = charPtr[i + 1]; charPtr[--_decryptedLength] = (char)0; } } finally { if (ptr != null) _buffer.ReleasePointer(); } } [System.Security.SecuritySafeCritical] // auto-generated private void SetAtCore(int index, char c) { // Overwrite the character at the specified index using (_buffer.Unprotect()) _buffer.Write((ulong)(index * sizeof(char)), c); } [System.Security.SecurityCritical] // auto-generated internal unsafe IntPtr ToUniStrCore() { int length = _decryptedLength; byte* bufferPtr = null; IntPtr stringPtr = IntPtr.Zero, result = IntPtr.Zero; try { // Allocate space for the string to be returned, including space for a null terminator stringPtr = Marshal.AllocCoTaskMem((length + 1) * sizeof(char)); _buffer.AcquirePointer(ref bufferPtr); // Copy all of our data into it using (_buffer.Unprotect()) Buffer.MemoryCopy( source: bufferPtr, destination: (byte*)stringPtr.ToPointer(), destinationSizeInBytes: ((length + 1) * sizeof(char)), sourceBytesToCopy: length * sizeof(char)); // Add the null termination *(length + (char*)stringPtr.ToPointer()) = '\0'; // Finally store the string pointer into our result. We maintain // a separate result variable to make clean up in the finally easier. result = stringPtr; } finally { // If there was a failure, such that result isn't initialized, // release the string if we had one. if (stringPtr != IntPtr.Zero && result == IntPtr.Zero) { ProtectedBuffer.ZeroMemory((byte*)stringPtr, (ulong)(length * sizeof(char))); Marshal.FreeCoTaskMem(stringPtr); } if (bufferPtr != null) _buffer.ReleasePointer(); } return result; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private void EnsureCapacity(int capacity) { // Make sure the requested capacity doesn't exceed SecureString's defined limit if (capacity > MaxLength) throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); // If we already have enough space allocated, we're done if (_buffer != null && (capacity * sizeof(char)) <= (int)_buffer.ByteLength) return; // We need more space, so allocate a new buffer, copy all our data into it, // and then swap the new for the old. ProtectedBuffer newBuffer = ProtectedBuffer.Allocate(capacity * sizeof(char)); if (_buffer != null) { using (_buffer.Unprotect()) ProtectedBuffer.Copy(_buffer, newBuffer, _buffer.ByteLength); newBuffer.Protect(); _buffer.Dispose(); } _buffer = newBuffer; } /// <summary>SafeBuffer for managing memory meant to be kept confidential.</summary> private sealed class ProtectedBuffer : SafeBuffer { private static readonly long s_pageSize = Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_PAGESIZE); internal ProtectedBuffer() : base(true) { } internal static ProtectedBuffer Allocate(int bytes) { Debug.Assert(bytes >= 0); // Round the number of bytes up to the next page size boundary. mmap // is going to allocate pages, anyway, and we lock/protect entire pages, // so we might as well benefit from being able to use all of that space, // rather than allocating it and having it be unusable. As a SecureString // grows, this will significantly help in avoiding unnecessary recreations // of the buffer. Debug.Assert(s_pageSize > 0); ulong nativeBytes = RoundUpToPageSize(bytes); Debug.Assert((long)nativeBytes % s_pageSize == 0); ProtectedBuffer buffer = new ProtectedBuffer(); IntPtr ptr = IntPtr.Zero; try { // Allocate the page(s) for the buffer. ptr = Interop.Sys.MMap( IntPtr.Zero, nativeBytes, Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE, Interop.Sys.MemoryMappedFlags.MAP_ANONYMOUS | Interop.Sys.MemoryMappedFlags.MAP_PRIVATE, 0, 0); if (ptr == IntPtr.Zero) // note that shim uses null pointer, not non-null MAP_FAILED sentinel throw CreateExceptionFromErrno(); // Lock the pages into memory to minimize the chances that the pages get // swapped out, making the contents available on disk. if (Interop.Sys.MLock(ptr, nativeBytes) != 0) throw CreateExceptionFromErrno(); } catch { // Something failed; release the allocation if (ptr != IntPtr.Zero) Interop.Sys.MUnmap(ptr, nativeBytes); // ignore any errors throw; } // The memory was allocated; initialize the buffer with it. buffer.SetHandle(ptr); buffer.Initialize((ulong)bytes); return buffer; } internal void Protect() { // Make the pages unreadable/writable; attempts to read/write this memory will result in seg faults. ChangeProtection(Interop.Sys.MemoryMappedProtections.PROT_NONE); } internal ProtectOnDispose Unprotect() { // Make the pages readable/writable; attempts to read/write this memory will succeed. // Then return a disposable that will re-protect the memory when done with it. ChangeProtection(Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE); return new ProtectOnDispose(this); } internal struct ProtectOnDispose : IDisposable { private readonly ProtectedBuffer _buffer; internal ProtectOnDispose(ProtectedBuffer buffer) { Debug.Assert(buffer != null); _buffer = buffer; } public void Dispose() { _buffer.Protect(); } } private unsafe void ChangeProtection(Interop.Sys.MemoryMappedProtections prots) { byte* ptr = null; try { AcquirePointer(ref ptr); if (Interop.Sys.MProtect((IntPtr)ptr, ByteLength, prots) != 0) throw CreateExceptionFromErrno(); } finally { if (ptr != null) ReleasePointer(); } } internal unsafe void Clear() { byte* ptr = null; try { AcquirePointer(ref ptr); ZeroMemory(ptr, ByteLength); } finally { if (ptr != null) ReleasePointer(); } } internal static unsafe void Copy(ProtectedBuffer source, ProtectedBuffer destination, ulong bytesLength) { if (bytesLength == 0) return; byte* srcPtr = null, dstPtr = null; try { source.AcquirePointer(ref srcPtr); destination.AcquirePointer(ref dstPtr); Buffer.MemoryCopy(srcPtr, dstPtr, destination.ByteLength, bytesLength); } finally { if (dstPtr != null) destination.ReleasePointer(); if (srcPtr != null) source.ReleasePointer(); } } protected override unsafe bool ReleaseHandle() { bool success = true; IntPtr h = handle; if (h != IntPtr.Zero) { ulong len = ByteLength; success &= Interop.Sys.MProtect(h, len, Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE) == 0; if (success) { ZeroMemory((byte*)h, len); success &= (Interop.Sys.MUnlock(h, len) == 0); } success &= (Interop.Sys.MUnmap(h, len) == 0); } return success; } internal static unsafe void ZeroMemory(byte* ptr, ulong len) { for (ulong i = 0; i < len; i++) *ptr++ = 0; } private static Exception CreateExceptionFromErrno() { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); return (errorInfo.Error == Interop.Error.ENOMEM || errorInfo.Error == Interop.Error.EPERM) ? (Exception)new OutOfMemoryException(SR.OutOfMemory_MemoryResourceLimits) : (Exception)new InvalidOperationException(errorInfo.GetErrorMessage()); } private static ulong RoundUpToPageSize(int bytes) { long nativeBytes = bytes > 0 ? (bytes + (s_pageSize - 1)) & ~(s_pageSize - 1) : s_pageSize; Debug.Assert(nativeBytes > 0 && nativeBytes <= uint.MaxValue); Debug.Assert((nativeBytes % s_pageSize) == 0); return (ulong)nativeBytes; } } } }
// Copyright 2022, Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/events/firebase/database/v1/data.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Events.Protobuf.Firebase.Database.V1 { /// <summary>Holder for reflection information generated from google/events/firebase/database/v1/data.proto</summary> public static partial class DataReflection { #region Descriptor /// <summary>File descriptor for google/events/firebase/database/v1/data.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DataReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci1nb29nbGUvZXZlbnRzL2ZpcmViYXNlL2RhdGFiYXNlL3YxL2RhdGEucHJv", "dG8SImdvb2dsZS5ldmVudHMuZmlyZWJhc2UuZGF0YWJhc2UudjEaHGdvb2ds", "ZS9wcm90b2J1Zi9zdHJ1Y3QucHJvdG8iYQoSUmVmZXJlbmNlRXZlbnREYXRh", "EiQKBGRhdGEYASABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSJQoFZGVs", "dGEYAiABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWVCLqoCK0dvb2dsZS5F", "dmVudHMuUHJvdG9idWYuRmlyZWJhc2UuRGF0YWJhc2UuVjFiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Events.Protobuf.Firebase.Database.V1.ReferenceEventData), global::Google.Events.Protobuf.Firebase.Database.V1.ReferenceEventData.Parser, new[]{ "Data", "Delta" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// The data within all Firebase Real Time Database reference events. /// </summary> public sealed partial class ReferenceEventData : pb::IMessage<ReferenceEventData> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ReferenceEventData> _parser = new pb::MessageParser<ReferenceEventData>(() => new ReferenceEventData()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ReferenceEventData> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Events.Protobuf.Firebase.Database.V1.DataReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ReferenceEventData() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ReferenceEventData(ReferenceEventData other) : this() { data_ = other.data_ != null ? other.data_.Clone() : null; delta_ = other.delta_ != null ? other.delta_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ReferenceEventData Clone() { return new ReferenceEventData(this); } /// <summary>Field number for the "data" field.</summary> public const int DataFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Value data_; /// <summary> /// The original data for the reference. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Value Data { get { return data_; } set { data_ = value; } } /// <summary>Field number for the "delta" field.</summary> public const int DeltaFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Value delta_; /// <summary> /// The change in the reference data. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Value Delta { get { return delta_; } set { delta_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ReferenceEventData); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ReferenceEventData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Data, other.Data)) return false; if (!object.Equals(Delta, other.Delta)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (data_ != null) hash ^= Data.GetHashCode(); if (delta_ != null) hash ^= Delta.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (data_ != null) { output.WriteRawTag(10); output.WriteMessage(Data); } if (delta_ != null) { output.WriteRawTag(18); output.WriteMessage(Delta); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (data_ != null) { output.WriteRawTag(10); output.WriteMessage(Data); } if (delta_ != null) { output.WriteRawTag(18); output.WriteMessage(Delta); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (data_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Data); } if (delta_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Delta); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ReferenceEventData other) { if (other == null) { return; } if (other.data_ != null) { if (data_ == null) { Data = new global::Google.Protobuf.WellKnownTypes.Value(); } Data.MergeFrom(other.Data); } if (other.delta_ != null) { if (delta_ == null) { Delta = new global::Google.Protobuf.WellKnownTypes.Value(); } Delta.MergeFrom(other.Delta); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (data_ == null) { Data = new global::Google.Protobuf.WellKnownTypes.Value(); } input.ReadMessage(Data); break; } case 18: { if (delta_ == null) { Delta = new global::Google.Protobuf.WellKnownTypes.Value(); } input.ReadMessage(Delta); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (data_ == null) { Data = new global::Google.Protobuf.WellKnownTypes.Value(); } input.ReadMessage(Data); break; } case 18: { if (delta_ == null) { Delta = new global::Google.Protobuf.WellKnownTypes.Value(); } input.ReadMessage(Delta); break; } } } } #endif } #endregion } #endregion Designer generated code
using System; using System.Linq; using Nop.Core; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Customers; using Nop.Services.Common; using Nop.Services.Events; using Nop.Services.Messages; namespace Nop.Services.Catalog { /// <summary> /// Back in stock subscription service /// </summary> public partial class BackInStockSubscriptionService : IBackInStockSubscriptionService { #region Fields private readonly IRepository<BackInStockSubscription> _backInStockSubscriptionRepository; private readonly IWorkflowMessageService _workflowMessageService; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="backInStockSubscriptionRepository">Back in stock subscription repository</param> /// <param name="workflowMessageService">Workflow message service</param> /// <param name="eventPublisher">Event publisher</param> public BackInStockSubscriptionService(IRepository<BackInStockSubscription> backInStockSubscriptionRepository, IWorkflowMessageService workflowMessageService, IEventPublisher eventPublisher) { this._backInStockSubscriptionRepository = backInStockSubscriptionRepository; this._workflowMessageService = workflowMessageService; this._eventPublisher = eventPublisher; } #endregion #region Methods /// <summary> /// Delete a back in stock subscription /// </summary> /// <param name="subscription">Subscription</param> public virtual void DeleteSubscription(BackInStockSubscription subscription) { if (subscription == null) throw new ArgumentNullException("subscription"); _backInStockSubscriptionRepository.Delete(subscription); //event notification _eventPublisher.EntityDeleted(subscription); } /// <summary> /// Gets all subscriptions /// </summary> /// <param name="customerId">Customer identifier</param> /// <param name="storeId">Store identifier; pass 0 to load all records</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns>Subscriptions</returns> public virtual IPagedList<BackInStockSubscription> GetAllSubscriptionsByCustomerId(int customerId, int storeId, int pageIndex, int pageSize) { var query = _backInStockSubscriptionRepository.Table; //customer query = query.Where(biss => biss.CustomerId == customerId); //store if (storeId > 0) query = query.Where(biss => biss.StoreId == storeId); //product query = query.Where(biss => !biss.Product.Deleted); query = query.OrderByDescending(biss => biss.CreatedOnUtc); return new PagedList<BackInStockSubscription>(query, pageIndex, pageSize); } /// <summary> /// Gets all subscriptions /// </summary> /// <param name="productId">Product identifier</param> /// <param name="storeId">Store identifier; pass 0 to load all records</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns>Subscriptions</returns> public virtual IPagedList<BackInStockSubscription> GetAllSubscriptionsByProductId(int productId, int storeId, int pageIndex, int pageSize) { var query = _backInStockSubscriptionRepository.Table; //product query = query.Where(biss => biss.ProductId == productId); //store if (storeId > 0) query = query.Where(biss => biss.StoreId == storeId); //customer query = query.Where(biss => !biss.Customer.Deleted && biss.Customer.Active); query = query.OrderByDescending(biss => biss.CreatedOnUtc); return new PagedList<BackInStockSubscription>(query, pageIndex, pageSize); } /// <summary> /// Gets all subscriptions /// </summary> /// <param name="customerId">Customer id</param> /// <param name="productId">Product identifier</param> /// <param name="storeId">Store identifier</param> /// <returns>Subscriptions</returns> public virtual BackInStockSubscription FindSubscription(int customerId, int productId, int storeId) { var query = from biss in _backInStockSubscriptionRepository.Table orderby biss.CreatedOnUtc descending where biss.CustomerId == customerId && biss.ProductId == productId && biss.StoreId == storeId select biss; var subscription = query.FirstOrDefault(); return subscription; } /// <summary> /// Gets a subscription /// </summary> /// <param name="subscriptionId">Subscription identifier</param> /// <returns>Subscription</returns> public virtual BackInStockSubscription GetSubscriptionById(int subscriptionId) { if (subscriptionId == 0) return null; var subscription = _backInStockSubscriptionRepository.GetById(subscriptionId); return subscription; } /// <summary> /// Inserts subscription /// </summary> /// <param name="subscription">Subscription</param> public virtual void InsertSubscription(BackInStockSubscription subscription) { if (subscription == null) throw new ArgumentNullException("subscription"); _backInStockSubscriptionRepository.Insert(subscription); //event notification _eventPublisher.EntityInserted(subscription); } /// <summary> /// Updates subscription /// </summary> /// <param name="subscription">Subscription</param> public virtual void UpdateSubscription(BackInStockSubscription subscription) { if (subscription == null) throw new ArgumentNullException("subscription"); _backInStockSubscriptionRepository.Update(subscription); //event notification _eventPublisher.EntityUpdated(subscription); } /// <summary> /// Send notification to subscribers /// </summary> /// <param name="product">Product</param> /// <returns>Number of sent email</returns> public virtual int SendNotificationsToSubscribers(Product product) { if (product == null) throw new ArgumentNullException("product"); int result = 0; var subscriptions = GetAllSubscriptionsByProductId(product.Id, 0, 0, int.MaxValue); foreach (var subscription in subscriptions) { //ensure that customer is registered (simple and fast way) if (CommonHelper.IsValidEmail(subscription.Customer.Email)) { var customer = subscription.Customer; var customerLanguageId = customer.GetAttribute<int>(SystemCustomerAttributeNames.LanguageId, subscription.StoreId); _workflowMessageService.SendBackInStockNotification(subscription, customerLanguageId); result++; } } for (int i = 0; i <= subscriptions.Count - 1; i++) DeleteSubscription(subscriptions[i]); return result; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Add_Vector128_UInt32() { var test = new SimpleBinaryOpTest__Add_Vector128_UInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.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 (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 SimpleBinaryOpTest__Add_Vector128_UInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Add_Vector128_UInt32 testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Add_Vector128_UInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Add_Vector128_UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SimpleBinaryOpTest__Add_Vector128_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Add( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Add_Vector128_UInt32(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__Add_Vector128_UInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Add( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((uint)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((uint)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights { using Azure; using Management; using Rest; using 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> /// ProfilesOperations operations. /// </summary> internal partial class ProfilesOperations : IServiceOperations<CustomerInsightsManagementClient>, IProfilesOperations { /// <summary> /// Initializes a new instance of the ProfilesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProfilesOperations(CustomerInsightsManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the CustomerInsightsManagementClient /// </summary> public CustomerInsightsManagementClient Client { get; private set; } /// <summary> /// Creates a profile within a Hub, or updates an existing profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete Profile type operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ProfileResourceFormat>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, ProfileResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ProfileResourceFormat> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, profileName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets information about the specified profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<ProfileResourceFormat>> GetWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (hubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hubName"); } if (profileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "profileName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("hubName", hubName); tracingParameters.Add("profileName", profileName); tracingParameters.Add("localeCode", localeCode); 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.CustomerInsights/hubs/{hubName}/profiles/{profileName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName)); _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (localeCode != null) { _queryParameters.Add(string.Format("locale-code={0}", System.Uri.EscapeDataString(localeCode))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProfileResourceFormat>(); _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<ProfileResourceFormat>(_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> /// Deletes a profile within a hub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, hubName, profileName, localeCode, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all profile in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<IPage<ProfileResourceFormat>>> ListByHubWithHttpMessagesAsync(string resourceGroupName, string hubName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (hubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hubName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("hubName", hubName); tracingParameters.Add("localeCode", localeCode); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByHub", 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.CustomerInsights/hubs/{hubName}/profiles").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (localeCode != null) { _queryParameters.Add(string.Format("locale-code={0}", System.Uri.EscapeDataString(localeCode))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ProfileResourceFormat>>(); _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<Page<ProfileResourceFormat>>(_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> /// Creates a profile within a Hub, or updates an existing profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete Profile type operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<ProfileResourceFormat>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, ProfileResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (hubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hubName"); } if (profileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "profileName"); } if (profileName != null) { if (profileName.Length > 128) { throw new ValidationException(ValidationRules.MaxLength, "profileName", 128); } if (profileName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "profileName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(profileName, "^[a-zA-Z][a-zA-Z0-9_]+$")) { throw new ValidationException(ValidationRules.Pattern, "profileName", "^[a-zA-Z][a-zA-Z0-9_]+$"); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("hubName", hubName); tracingParameters.Add("profileName", profileName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.CustomerInsights/hubs/{hubName}/profiles/{profileName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName)); _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("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(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.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 != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProfileResourceFormat>(); _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<ProfileResourceFormat>(_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> /// Deletes a profile within a hub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (hubName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hubName"); } if (profileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "profileName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("hubName", hubName); tracingParameters.Add("profileName", profileName); tracingParameters.Add("localeCode", localeCode); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.CustomerInsights/hubs/{hubName}/profiles/{profileName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName)); _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (localeCode != null) { _queryParameters.Add(string.Format("locale-code={0}", System.Uri.EscapeDataString(localeCode))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("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 != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all profile in the hub. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<IPage<ProfileResourceFormat>>> ListByHubNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByHubNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ProfileResourceFormat>>(); _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<Page<ProfileResourceFormat>>(_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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable CS0067 // events are declared but not used using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.ExceptionServices; using System.Runtime.Loader; using System.Runtime.Remoting; using System.Security; using System.Security.Permissions; using System.Security.Principal; using System.Threading; namespace System { #if PROJECTN [Internal.Runtime.CompilerServices.RelocatedType("System.Runtime.Extensions")] #endif public sealed partial class AppDomain : MarshalByRefObject { private static readonly AppDomain s_domain = new AppDomain(); private readonly object _forLock = new object(); private IPrincipal? _defaultPrincipal; private PrincipalPolicy _principalPolicy = PrincipalPolicy.NoPrincipal; private Func<IPrincipal>? s_getWindowsPrincipal; private Func<IPrincipal>? s_getUnauthenticatedPrincipal; private AppDomain() { } public static AppDomain CurrentDomain => s_domain; public string? BaseDirectory => AppContext.BaseDirectory; public string? RelativeSearchPath => null; public AppDomainSetup SetupInformation => new AppDomainSetup(); public PermissionSet PermissionSet => new PermissionSet(PermissionState.Unrestricted); public event UnhandledExceptionEventHandler? UnhandledException { add { AppContext.UnhandledException += value; } remove { AppContext.UnhandledException -= value; } } public string? DynamicDirectory => null; [ObsoleteAttribute("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetDynamicBase(string? path) { } public string FriendlyName { get { Assembly? assembly = Assembly.GetEntryAssembly(); return assembly != null ? assembly.GetName().Name! : "DefaultDomain"; } } public int Id => 1; public bool IsFullyTrusted => true; public bool IsHomogenous => true; public event EventHandler? DomainUnload; public event EventHandler<FirstChanceExceptionEventArgs>? FirstChanceException { add { AppContext.FirstChanceException += value; } remove { AppContext.FirstChanceException -= value; } } public event EventHandler? ProcessExit { add { AppContext.ProcessExit += value; } remove { AppContext.ProcessExit -= value; } } public string ApplyPolicy(string assemblyName) { if (assemblyName == null) { throw new ArgumentNullException(nameof(assemblyName)); } if (assemblyName.Length == 0 || assemblyName[0] == '\0') { throw new ArgumentException(SR.Argument_StringZeroLength, nameof(assemblyName)); } return assemblyName; } public static AppDomain CreateDomain(string friendlyName) { if (friendlyName == null) throw new ArgumentNullException(nameof(friendlyName)); throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomains); } public int ExecuteAssembly(string assemblyFile) => ExecuteAssembly(assemblyFile, null); public int ExecuteAssembly(string assemblyFile, string?[]? args) { if (assemblyFile == null) { throw new ArgumentNullException(nameof(assemblyFile)); } string fullPath = Path.GetFullPath(assemblyFile); Assembly assembly = Assembly.LoadFile(fullPath); return ExecuteAssembly(assembly, args); } public int ExecuteAssembly(string assemblyFile, string?[]? args, byte[]? hashValue, Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // This api is only meaningful for very specific partial trust/CAS scenarios } private int ExecuteAssembly(Assembly assembly, string?[]? args) { MethodInfo? entry = assembly.EntryPoint; if (entry == null) { throw new MissingMethodException(SR.Arg_EntryPointNotFoundException); } object? result = entry.Invoke( obj: null, invokeAttr: BindingFlags.DoNotWrapExceptions, binder: null, parameters: entry.GetParameters().Length > 0 ? new object?[] { args } : null, culture: null); return result != null ? (int)result : 0; } public int ExecuteAssemblyByName(AssemblyName assemblyName, params string?[]? args) => ExecuteAssembly(Assembly.Load(assemblyName), args); public int ExecuteAssemblyByName(string assemblyName) => ExecuteAssemblyByName(assemblyName, null); public int ExecuteAssemblyByName(string assemblyName, params string?[]? args) => ExecuteAssembly(Assembly.Load(assemblyName), args); public object? GetData(string name) => AppContext.GetData(name); public void SetData(string name, object? data) => AppContext.SetData(name, data); public bool? IsCompatibilitySwitchSet(string value) { bool result; return AppContext.TryGetSwitch(value, out result) ? result : default(bool?); } public bool IsDefaultAppDomain() => true; public bool IsFinalizingForUnload() => false; public override string ToString() => SR.AppDomain_Name + FriendlyName + Environment.NewLine + SR.AppDomain_NoContextPolicies; public static void Unload(AppDomain domain) { if (domain == null) { throw new ArgumentNullException(nameof(domain)); } throw new CannotUnloadAppDomainException(SR.Arg_PlatformNotSupported); } public Assembly Load(byte[] rawAssembly) => Assembly.Load(rawAssembly); public Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) => Assembly.Load(rawAssembly, rawSymbolStore); public Assembly Load(AssemblyName assemblyRef) => Assembly.Load(assemblyRef); public Assembly Load(string assemblyString) => Assembly.Load(assemblyString); public Assembly[] ReflectionOnlyGetAssemblies() => Array.Empty<Assembly>(); public static bool MonitoringIsEnabled { get { return true; } set { if (!value) { throw new ArgumentException(SR.Arg_MustBeTrue); } } } public long MonitoringSurvivedMemorySize => MonitoringSurvivedProcessMemorySize; public static long MonitoringSurvivedProcessMemorySize { get { GCMemoryInfo mi = GC.GetGCMemoryInfo(); return mi.HeapSizeBytes - mi.FragmentedBytes; } } public long MonitoringTotalAllocatedMemorySize => GC.GetTotalAllocatedBytes(precise: false); [ObsoleteAttribute("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. https://go.microsoft.com/fwlink/?linkid=14202", false)] public static int GetCurrentThreadId() => Environment.CurrentManagedThreadId; public bool ShadowCopyFiles => false; [ObsoleteAttribute("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void AppendPrivatePath(string? path) { } [ObsoleteAttribute("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void ClearPrivatePath() { } [ObsoleteAttribute("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void ClearShadowCopyPath() { } [ObsoleteAttribute("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetCachePath(string? path) { } [ObsoleteAttribute("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetShadowCopyFiles() { } [ObsoleteAttribute("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetShadowCopyPath(string? path) { } public Assembly[] GetAssemblies() => AssemblyLoadContext.GetLoadedAssemblies(); public event AssemblyLoadEventHandler? AssemblyLoad { add { AssemblyLoadContext.AssemblyLoad += value; } remove { AssemblyLoadContext.AssemblyLoad -= value; } } public event ResolveEventHandler? AssemblyResolve { add { AssemblyLoadContext.AssemblyResolve += value; } remove { AssemblyLoadContext.AssemblyResolve -= value; } } public event ResolveEventHandler? ReflectionOnlyAssemblyResolve; public event ResolveEventHandler? TypeResolve { add { AssemblyLoadContext.TypeResolve += value; } remove { AssemblyLoadContext.TypeResolve -= value; } } public event ResolveEventHandler? ResourceResolve { add { AssemblyLoadContext.ResourceResolve += value; } remove { AssemblyLoadContext.ResourceResolve -= value; } } public void SetPrincipalPolicy(PrincipalPolicy policy) { _principalPolicy = policy; } public void SetThreadPrincipal(IPrincipal principal) { if (principal == null) { throw new ArgumentNullException(nameof(principal)); } lock (_forLock) { // Check that principal has not been set previously. if (_defaultPrincipal != null) { throw new SystemException(SR.AppDomain_Policy_PrincipalTwice); } _defaultPrincipal = principal; } } public ObjectHandle? CreateInstance(string assemblyName, string typeName) { if (assemblyName == null) { throw new ArgumentNullException(nameof(assemblyName)); } return Activator.CreateInstance(assemblyName, typeName); } public ObjectHandle? CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { if (assemblyName == null) { throw new ArgumentNullException(nameof(assemblyName)); } return Activator.CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); } public ObjectHandle? CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) { if (assemblyName == null) { throw new ArgumentNullException(nameof(assemblyName)); } return Activator.CreateInstance(assemblyName, typeName, activationAttributes); } public object? CreateInstanceAndUnwrap(string assemblyName, string typeName) { ObjectHandle? oh = CreateInstance(assemblyName, typeName); return oh?.Unwrap(); } public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { ObjectHandle? oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); return oh?.Unwrap(); } public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, object?[]? activationAttributes) { ObjectHandle? oh = CreateInstance(assemblyName, typeName, activationAttributes); return oh?.Unwrap(); } public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName) { return Activator.CreateInstanceFrom(assemblyFile, typeName); } public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { return Activator.CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); } public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, object?[]? activationAttributes) { return Activator.CreateInstanceFrom(assemblyFile, typeName, activationAttributes); } public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName) { ObjectHandle? oh = CreateInstanceFrom(assemblyFile, typeName); return oh?.Unwrap(); } public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { ObjectHandle? oh = CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); return oh?.Unwrap(); } public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object?[]? activationAttributes) { ObjectHandle? oh = CreateInstanceFrom(assemblyFile, typeName, activationAttributes); return oh?.Unwrap(); } internal IPrincipal? GetThreadPrincipal() { IPrincipal? principal = _defaultPrincipal; if (principal == null) { switch (_principalPolicy) { case PrincipalPolicy.UnauthenticatedPrincipal: if (s_getUnauthenticatedPrincipal == null) { Type type = Type.GetType("System.Security.Principal.GenericPrincipal, System.Security.Claims", throwOnError: true)!; MethodInfo? mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); Debug.Assert(mi != null); // Don't throw PNSE if null like for WindowsPrincipal as UnauthenticatedPrincipal should // be available on all platforms. Volatile.Write(ref s_getUnauthenticatedPrincipal, (Func<IPrincipal>)mi.CreateDelegate(typeof(Func<IPrincipal>))); } principal = s_getUnauthenticatedPrincipal(); break; case PrincipalPolicy.WindowsPrincipal: if (s_getWindowsPrincipal == null) { Type type = Type.GetType("System.Security.Principal.WindowsPrincipal, System.Security.Principal.Windows", throwOnError: true)!; MethodInfo? mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); if (mi == null) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Principal); } Volatile.Write(ref s_getWindowsPrincipal, (Func<IPrincipal>)mi.CreateDelegate(typeof(Func<IPrincipal>))); } principal = s_getWindowsPrincipal(); break; } } return principal; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using Utils; using DevExpress.Utils; using DevExpress.XtraGrid; using DevExpress.XtraGrid.Views.Base; using DevExpress.XtraGrid.Views.Grid.ViewInfo; namespace KabMan.Client { public partial class frmServerDetailListe : DevExpress.XtraEditors.XtraForm { private int sid; WaitDialogForm dlgWait; private RefreshHelper helper; private Common com; ModifyRegistry reg; public frmServerDetailListe(int sid) { this.sid = sid; InitializeComponent(); } private int RecordId { get { return (int)gridView1.DataController.GetCurrentRowValue("Id"); } } private void frmServerDetailListe_Load(object sender, EventArgs e) { reg = new ModifyRegistry(); com = new Common(); com.LoadViewCols(gridView1, "ServerList"); com.LoadViewCols(gridView2, "SNMP"); helper = new RefreshHelper(gridView1, "Id"); FormText(); RestoreView(); Liste(false); } private void FormText() { SqlDataReader dr; DatabaseLib data = new DatabaseLib(); data.RunSqlQuery(string.Format("SELECT Room + Coordinate AS Server FROM tblReck WHERE Id={0}", sid), out dr); if (dr.Read()) { this.Text = dr["Server"].ToString(); this.Tag = sid.ToString(); } data.Dispose(); } public void Liste(bool savePos) { Cursor = Cursors.WaitCursor; dlgWait = new WaitDialogForm("Loading Data..."); dlgWait.StartPosition = FormStartPosition.CenterParent; // grid pozisyonu kayit ediliyor if (savePos) helper.SaveViewInfo(); DataSet ds; DatabaseLib data = new DatabaseLib(); SqlParameter[] prm = { data.MakeInParam("@Id", sid) }; data.RunProc("sp_selServer", prm, out ds); data.Dispose(); gridControl1.DataSource = ds.Tables[0]; if (ds.Tables[0].DefaultView.Count > 0) { btnDetail.Enabled = true; btnLoeschen.Enabled = true; } else { btnDetail.Enabled = false; btnLoeschen.Enabled = false; } // grid pozisyonu yukleniyor if (savePos) helper.LoadViewInfo(); dlgWait.Close(); Cursor = Cursors.Default; } private void SaveView() { reg.Write("grdSMTPView", btnCheckSNMPView.Down.ToString()); } private void RestoreView() { if (reg.Read("grdSMTPView") != null) { btnCheckSNMPView.Down = Convert.ToBoolean(reg.Read("grdSMTPView")); Status(); } } private void btnCheckSNMPView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { Status(); } private void Status() { if (btnCheckSNMPView.Down) splitterItem1.Visibility = layoutControlGroup2.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always; else splitterItem1.Visibility = layoutControlGroup2.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never; } private void btnSchliessen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { Close(); } private void btnNeu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmServerDetailListeDetail f = new frmServerDetailListeDetail(this, 0, sid); f.ShowDialog(); } private void gridView1_ColumnWidthChanged(object sender, DevExpress.XtraGrid.Views.Base.ColumnEventArgs e) { com.SaveViewCols(gridView1, "ServerList"); } private void gridView2_ColumnWidthChanged(object sender, DevExpress.XtraGrid.Views.Base.ColumnEventArgs e) { com.SaveViewCols(gridView2, "SNMP"); } private void frmServerDetailListe_FormClosing(object sender, FormClosingEventArgs e) { SaveView(); } private void btnDetail_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { frmServerDetailListeDetail f = new frmServerDetailListeDetail(this, RecordId, sid); f.ShowDialog(); } private void gridControl1_MouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { GridControl grid = sender as GridControl; BaseView view = grid.FocusedView; GridHitInfo hitInfo = view.CalcHitInfo(e.Location) as GridHitInfo; if (hitInfo.InRow) btnDetail_ItemClick(sender, null); } } private void btnLoeschen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (XtraMessageBox.Show( "Are you sure you want to delete this information?", Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) { // eger kayitid > 0 dan buyuk ise database dan siliniyor if (RecordId > 0) { DatabaseLib data = new DatabaseLib(); SqlParameter[] prm = { data.MakeInParam("@Id", RecordId) }; data.RunProc("sp_delServer", prm); data.Dispose(); } Liste(false); } } private void gridControl1_Click(object sender, EventArgs e) { } private void barCheckItem1_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (barCheckItem1.Checked == true) { KabelURMLC.Visible = true; } else { KabelURMLC.Visible = false; } } private void barCheckItem2_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (barCheckItem2.Checked == true) { Blech.Visible = true; } else { Blech.Visible = false; } } private void barCheckItem3_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (barCheckItem3.Checked == true) { CableTrunkMulti.Visible = true; } else { CableTrunkMulti.Visible = false; } } private void barCheckItem4_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (barCheckItem4.Checked == true) { VTPort.Visible = true; } else { VTPort.Visible = false; } } private void barCheckItem5_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (barCheckItem5.Checked == true) { PatchCableURM_URM.Visible = true; } else { PatchCableURM_URM.Visible = false; } } private void barCheckItem6_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (barCheckItem6.Checked == true) { SAN.Visible = true; } else { SAN.Visible = false; } } } }
// Copyright 2013, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: [email protected] (Anash P. Oommen) using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201306; using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201306 { /// <summary> /// This code example shows how to handle RateExceededError in your /// application. To trigger the rate exceeded error, this code example runs /// 100 threads in parallel, each thread attempting to validate 100 keywords /// in a single request. Note that spawning 100 parallel threads is for /// illustrative purposes only, you shouldn't do this in your application. /// /// Tags: AdGroupAdService.mutate /// </summary> public class HandleRateExceededError: ExampleBase { /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { HandleRateExceededError codeExample = new HandleRateExceededError(); Console.WriteLine(codeExample.Description); try { long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE"); codeExample.Run(new AdWordsUser(), adGroupId); } catch (Exception ex) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(ex)); } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example shows how to handle RateExceededError in your application. " + "To trigger the rate exceeded error, this code example runs 100 threads in " + "parallel, each thread attempting to validate 100 keywords in a single request. " + "Note that spawning 100 parallel threads is for illustrative purposes only, you " + "shouldn't do this in your application."; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which keywords are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { const int NUM_THREADS = 100; // Increase the maximum number of parallel HTTP connections that .NET // framework allows. By default, this is set to 2 by the .NET framework. System.Net.ServicePointManager.DefaultConnectionLimit = NUM_THREADS; List<Thread> threads = new List<Thread>(); for (int i = 0; i < NUM_THREADS; i++) { Thread thread = new Thread(new KeywordThread(user, i, adGroupId).Run); threads.Add(thread); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].Start(i); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].Join(); } } /// <summary> /// Thread class for validating keywords. /// </summary> class KeywordThread { /// <summary> /// Index of this thread, for identifying and debugging. /// </summary> int threadIndex; /// <summary> /// The ad group id to which keywords are added. /// </summary> long adGroupId; /// <summary> /// The AdWords user who owns this ad group. /// </summary> AdWordsUser user; /// <summary> /// Number of keywords to be validated in each API call. /// </summary> const int NUM_KEYWORDS = 100; /// <summary> /// Initializes a new instance of the <see cref="KeywordThread" /> class. /// </summary> /// <param name="threadIndex">Index of the thread.</param> /// <param name="adGroupId">The ad group id.</param> /// <param name="user">The AdWords user who owns the ad group.</param> public KeywordThread(AdWordsUser user, int threadIndex, long adGroupId) { this.user = user; this.threadIndex = threadIndex; this.adGroupId = adGroupId; } /// <summary> /// Main method for the thread. /// </summary> /// <param name="obj">The thread parameter.</param> public void Run(Object obj) { // Create the operations. List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>(); for (int j = 0; j < NUM_KEYWORDS; j++) { // Create the keyword. Keyword keyword = new Keyword(); keyword.text = "mars cruise thread " + threadIndex.ToString() + " seed " + j.ToString(); keyword.matchType = KeywordMatchType.BROAD; // Create the biddable ad group criterion. AdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion(); keywordCriterion.adGroupId = adGroupId; keywordCriterion.criterion = keyword; // Create the operations. AdGroupCriterionOperation keywordOperation = new AdGroupCriterionOperation(); keywordOperation.@operator = Operator.ADD; keywordOperation.operand = keywordCriterion; operations.Add(keywordOperation); } // Get the AdGroupCriterionService. This should be done within the // thread, since a service can only handle one outgoing HTTP request // at a time. AdGroupCriterionService service = (AdGroupCriterionService) user.GetService( AdWordsService.v201306.AdGroupCriterionService); service.RequestHeader.validateOnly = true; int retryCount = 0; const int NUM_RETRIES = 3; try { while (retryCount < NUM_RETRIES) { try { // Validate the keywords. AdGroupCriterionReturnValue retval = service.mutate(operations.ToArray()); break; } catch (AdWordsApiException ex) { // Handle API errors. ApiException innerException = ex.ApiException as ApiException; if (innerException == null) { throw new Exception("Failed to retrieve ApiError. See inner exception for more " + "details.", ex); } foreach (ApiError apiError in innerException.errors) { if (!(apiError is RateExceededError)) { // Rethrow any errors other than RateExceededError. throw; } // Handle rate exceeded errors. RateExceededError rateExceededError = (RateExceededError) apiError; Console.WriteLine("Got Rate exceeded error - rate name = '{0}', scope = '{1}', " + "retry After {2} seconds.", rateExceededError.rateScope, rateExceededError.rateName, rateExceededError.retryAfterSeconds); Thread.Sleep(rateExceededError.retryAfterSeconds * 1000); retryCount = retryCount + 1; } } finally { if (retryCount == NUM_RETRIES) { throw new Exception(String.Format("Could not recover after making {0} attempts.", retryCount)); } } } } catch (Exception ex) { throw new System.ApplicationException("Failed to validate keywords.", ex); } } } } }
// 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.Security; using System.Threading; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Text { public abstract class DecoderFallback { internal bool bIsMicrosoftBestFitFallback = false; private static DecoderFallback s_replacementFallback; // Default fallback, uses no best fit & "?" private static DecoderFallback s_exceptionFallback; // Get each of our generic fallbacks. public static DecoderFallback ReplacementFallback { get { if (s_replacementFallback == null) Interlocked.CompareExchange<DecoderFallback>(ref s_replacementFallback, new DecoderReplacementFallback(), null); return s_replacementFallback; } } public static DecoderFallback ExceptionFallback { get { if (s_exceptionFallback == null) Interlocked.CompareExchange<DecoderFallback>(ref s_exceptionFallback, new DecoderExceptionFallback(), null); return s_exceptionFallback; } } // Fallback // // Return the appropriate unicode string alternative to the character that need to fall back. // Most implimentations will be: // return new MyCustomDecoderFallbackBuffer(this); public abstract DecoderFallbackBuffer CreateFallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public abstract int MaxCharCount { get; } internal bool IsMicrosoftBestFitFallback { get { return bIsMicrosoftBestFitFallback; } } } public abstract class DecoderFallbackBuffer { // Most implimentations will probably need an implimenation-specific constructor // internal methods that cannot be overriden that let us do our fallback thing // These wrap the internal methods so that we can check for people doing stuff that's incorrect public abstract bool Fallback(byte[] bytesUnknown, int index); // Get next character public abstract char GetNextChar(); // Back up a character public abstract bool MovePrevious(); // How many chars left in this fallback? public abstract int Remaining { get; } // Clear the buffer public virtual void Reset() { while (GetNextChar() != (char)0) ; } // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally internal unsafe byte* byteStart; internal unsafe char* charEnd; // Internal Reset internal unsafe void InternalReset() { byteStart = null; Reset(); } // Set the above values // This can't be part of the constructor because DecoderFallbacks would have to know how to impliment these. internal unsafe void InternalInitialize(byte* byteStart, char* charEnd) { this.byteStart = byteStart; this.charEnd = charEnd; } // Fallback the current byte by sticking it into the remaining char buffer. // This can only be called by our encodings (other have to use the public fallback methods), so // we can use our DecoderNLS here too (except we don't). // Returns true if we are successful, false if we can't fallback the character (no buffer space) // So caller needs to throw buffer space if return false. // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* // Don't touch ref chars unless we succeed internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { // Copy the chars to our output char ch; char* charTemp = chars; bool bHighSurrogate = false; while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates if (Char.IsSurrogate(ch)) { if (Char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); bHighSurrogate = true; } else { // Low surrogate if (bHighSurrogate == false) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); bHighSurrogate = false; } } if (charTemp >= charEnd) { // No buffer space return false; } *(charTemp++) = ch; } // Need to make sure that bHighSurrogate isn't true if (bHighSurrogate) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); // Now we aren't going to be false, so its OK to update chars chars = charTemp; } return true; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { int count = 0; char ch; bool bHighSurrogate = false; while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates if (Char.IsSurrogate(ch)) { if (Char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); bHighSurrogate = true; } else { // Low surrogate if (bHighSurrogate == false) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); bHighSurrogate = false; } } count++; } // Need to make sure that bHighSurrogate isn't true if (bHighSurrogate) throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); return count; } // If no fallback return 0 return 0; } // private helper methods internal void ThrowLastBytesRecursive(byte[] bytesUnknown) { // Create a string representation of our bytes. StringBuilder strBytes = new StringBuilder(bytesUnknown.Length * 3); int i; for (i = 0; i < bytesUnknown.Length && i < 20; i++) { if (strBytes.Length > 0) strBytes.Append(' '); strBytes.AppendFormat(FormatProvider.InvariantCulture, "\\x{0:X2}", bytesUnknown[i]); } // In case the string's really long if (i == 20) strBytes.Append(" ..."); // Throw it, using our complete bytes throw new ArgumentException( SR.Format(SR.Argument_RecursiveFallbackBytes, strBytes.ToString()), "bytesUnknown"); } } }
using UnityEngine; using Pathfinding.Serialization; namespace Pathfinding { /** Node used for the PointGraph. * This is just a simple point with a list of connections (and associated costs) to other nodes. * It does not have any concept of a surface like many other node types. * * \see PointGraph */ public class PointNode : GraphNode { public Connection[] connections; /** GameObject this node was created from (if any). * \warning When loading a graph from a saved file or from cache, this field will be null. */ public GameObject gameObject; public void SetPosition (Int3 value) { position = value; } public PointNode (AstarPath astar) : base(astar) { } public override void GetConnections (System.Action<GraphNode> action) { if (connections == null) return; for (int i = 0; i < connections.Length; i++) action(connections[i].node); } public override void ClearConnections (bool alsoReverse) { if (alsoReverse && connections != null) { for (int i = 0; i < connections.Length; i++) { connections[i].node.RemoveConnection(this); } } connections = null; } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG(path, pathNode); handler.heap.Add(pathNode); for (int i = 0; i < connections.Length; i++) { GraphNode other = connections[i].node; PathNode otherPN = handler.GetPathNode(other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) { other.UpdateRecursiveG(path, otherPN, handler); } } } public override bool ContainsConnection (GraphNode node) { for (int i = 0; i < connections.Length; i++) if (connections[i].node == node) return true; return false; } /** Add a connection from this node to the specified node. * If the connection already exists, the cost will simply be updated and * no extra connection added. * * \note Only adds a one-way connection. Consider calling the same function on the other node * to get a two-way connection. */ public override void AddConnection (GraphNode node, uint cost) { if (node == null) throw new System.ArgumentNullException(); if (connections != null) { for (int i = 0; i < connections.Length; i++) { if (connections[i].node == node) { connections[i].cost = cost; return; } } } int connLength = connections != null ? connections.Length : 0; var newconns = new Connection[connLength+1]; for (int i = 0; i < connLength; i++) { newconns[i] = connections[i]; } newconns[connLength] = new Connection { node = node, cost = cost }; connections = newconns; } /** Removes any connection from this node to the specified node. * If no such connection exists, nothing will be done. * * \note This only removes the connection from this node to the other node. * You may want to call the same function on the other node to remove its eventual connection * to this node. */ public override void RemoveConnection (GraphNode node) { if (connections == null) return; for (int i = 0; i < connections.Length; i++) { if (connections[i].node == node) { int connLength = connections.Length; var newconns = new Connection[connLength-1]; for (int j = 0; j < i; j++) { newconns[j] = connections[j]; } for (int j = i+1; j < connLength; j++) { newconns[j-1] = connections[j]; } connections = newconns; return; } } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; for (int i = 0; i < connections.Length; i++) { GraphNode other = connections[i].node; if (path.CanTraverse(other)) { PathNode pathOther = handler.GetPathNode(other); if (pathOther.pathID != handler.PathID) { pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = connections[i].cost; pathOther.H = path.CalculateHScore(other); other.UpdateG(path, pathOther); handler.heap.Add(pathOther); } else { //If not we can test if the path from this node to the other one is a better one then the one already used uint tmpCost = connections[i].cost; if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = tmpCost; pathOther.parent = pathNode; other.UpdateRecursiveG(path, pathOther, handler); } else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection(this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = tmpCost; UpdateRecursiveG(path, pathNode, handler); } } } } } public override int GetGizmoHashCode () { var hash = base.GetGizmoHashCode(); if (connections != null) { for (int i = 0; i < connections.Length; i++) { hash ^= 17 * connections[i].GetHashCode(); } } return hash; } public override void SerializeNode (GraphSerializationContext ctx) { base.SerializeNode(ctx); ctx.SerializeInt3(position); } public override void DeserializeNode (GraphSerializationContext ctx) { base.DeserializeNode(ctx); position = ctx.DeserializeInt3(); } public override void SerializeReferences (GraphSerializationContext ctx) { if (connections == null) { ctx.writer.Write(-1); } else { ctx.writer.Write(connections.Length); for (int i = 0; i < connections.Length; i++) { ctx.SerializeNodeReference(connections[i].node); ctx.writer.Write(connections[i].cost); } } } public override void DeserializeReferences (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { connections = null; } else { connections = new Connection[count]; for (int i = 0; i < count; i++) { connections[i] = new Connection { node = ctx.DeserializeNodeReference(), cost = ctx.reader.ReadUInt32() }; } } } } }
// 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 ShiftLeftLogical128BitLaneInt321() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321(); 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(); // 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector256<Int32> _clsVar; private Vector256<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321(); var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != 2048) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical128BitLane)}<Int32>(Vector256<Int32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace agile9.outlook.context.db.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.Win32; namespace Microsoft.PythonTools.Profiling { using Infrastructure; using IServiceProvider = System.IServiceProvider; /// <summary> /// Represents an individual profiling session. We have nodes: /// 0 - the configuration for what to profile /// 1 - a folder, sessions that have been run /// 2+ - the sessions themselves. /// /// This looks like: /// Root /// Target /// Sessions /// Session #1 /// Session #2 /// </summary> class SessionNode : BaseHierarchyNode, IVsHierarchyDeleteHandler, IVsPersistHierarchyItem { private readonly string _filename; private readonly uint _docCookie; internal bool _isDirty, _neverSaved; private bool _isReportsExpanded; private readonly SessionsNode _parent; internal readonly IServiceProvider _serviceProvider; private ProfilingTarget _target; private AutomationSession _automationSession; internal readonly uint ItemId; //private const int ConfigItemId = 0; private const int ReportsItemId = 1; internal const uint StartingReportId = 2; public SessionNode(IServiceProvider serviceProvider, SessionsNode parent, ProfilingTarget target, string filename) { _serviceProvider = serviceProvider; _parent = parent; _target = target; _filename = filename; // Register this with the running document table. This will prompt // for save when the file is dirty and by responding to GetProperty // for VSHPROPID_ItemDocCookie we will support Ctrl-S when one of // our files is dirty. // http://msdn.microsoft.com/en-us/library/bb164600(VS.80).aspx var rdt = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable)); Debug.Assert(rdt != null, "_serviceProvider has no RDT service"); uint cookie; IntPtr punkDocData = Marshal.GetIUnknownForObject(this); try { ErrorHandler.ThrowOnFailure(rdt.RegisterAndLockDocument( (uint)(_VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_EditLock | _VSRDTFLAGS.RDT_CanBuildFromMemory), filename, this, VSConstants.VSITEMID_ROOT, punkDocData, out cookie )); } finally { if (punkDocData != IntPtr.Zero) { Marshal.Release(punkDocData); } } _docCookie = cookie; ItemId = parent._sessionsCollection.Add(this); } public IPythonProfileSession GetAutomationObject() { if (_automationSession == null) { _automationSession = new AutomationSession(this); } return _automationSession; } public SortedDictionary<uint, Report> Reports { get { if (_target.Reports == null) { _target.Reports = new Reports(); } if (_target.Reports.AllReports == null) { _target.Reports.AllReports = new SortedDictionary<uint, Report>(); } return _target.Reports.AllReports; } } public string Caption { get { string name = Name; if (_isDirty) { return Strings.CaptionDirty.FormatUI(name); } return name; } } public ProfilingTarget Target { get { return _target; } } public override int SetProperty(uint itemid, int propid, object var) { var prop = (__VSHPROPID)propid; switch (prop) { case __VSHPROPID.VSHPROPID_Expanded: if (itemid == ReportsItemId) { _isReportsExpanded = Convert.ToBoolean(var); break; } break; } return base.SetProperty(itemid, propid, var); } public override int GetProperty(uint itemid, int propid, out object pvar) { // GetProperty is called many many times for this particular property pvar = null; var prop = (__VSHPROPID)propid; switch (prop) { case __VSHPROPID.VSHPROPID_Parent: if (itemid == ReportsItemId) { pvar = VSConstants.VSITEMID_ROOT; } else if (IsReportItem(itemid)) { pvar = ReportsItemId; } break; case __VSHPROPID.VSHPROPID_FirstChild: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = ReportsItemId; } else if (itemid == ReportsItemId && Reports.Count > 0) { pvar = (int)Reports.First().Key; } else { pvar = VSConstants.VSITEMID_NIL; } break; case __VSHPROPID.VSHPROPID_NextSibling: pvar = VSConstants.VSITEMID_NIL; if (IsReportItem(itemid)) { var items = Reports.Keys.ToArray(); for (int i = 0; i < items.Length; i++) { if (items[i] > (int)itemid) { pvar = (int)(itemid + 1); break; } } } break; case __VSHPROPID.VSHPROPID_ItemDocCookie: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = (int)_docCookie; } break; case __VSHPROPID.VSHPROPID_Expandable: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = true; } else if (itemid == ReportsItemId && Reports.Count > 0) { pvar = true; } else { pvar = false; } break; case __VSHPROPID.VSHPROPID_ExpandByDefault: pvar = true; break; case __VSHPROPID.VSHPROPID_IconImgList: case __VSHPROPID.VSHPROPID_OpenFolderIconHandle: pvar = (int)SessionsNode._imageList.Handle; break; case __VSHPROPID.VSHPROPID_IconIndex: case __VSHPROPID.VSHPROPID_OpenFolderIconIndex: if (itemid == ReportsItemId) { if (_isReportsExpanded) { pvar = (int)TreeViewIconIndex.OpenFolder; } else { pvar = (int)TreeViewIconIndex.CloseFolder; } } else if (IsReportItem(itemid)) { pvar = (int)TreeViewIconIndex.GreenNotebook; } break; case __VSHPROPID.VSHPROPID_Caption: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = Caption; } else if (itemid == ReportsItemId) { pvar = Strings.Reports; } else if (IsReportItem(itemid)) { pvar = Path.GetFileNameWithoutExtension(GetReport(itemid).Filename); } break; case __VSHPROPID.VSHPROPID_ParentHierarchy: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = _parent as IVsHierarchy; } break; } if (pvar != null) return VSConstants.S_OK; return VSConstants.DISP_E_MEMBERNOTFOUND; } public override int ExecCommand(uint itemid, ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup == VsMenus.guidVsUIHierarchyWindowCmds) { switch ((VSConstants.VsUIHierarchyWindowCmdIds)nCmdID) { case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_DoubleClick: case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_EnterKey: if (itemid == VSConstants.VSITEMID_ROOT) { OpenTargetProperties(); // S_FALSE: don't process the double click to expand the item return VSConstants.S_FALSE; } else if (IsReportItem(itemid)) { OpenProfile(itemid); } return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_RightClick: int? ctxMenu = null; if (itemid == VSConstants.VSITEMID_ROOT) { ctxMenu = (int)PkgCmdIDList.menuIdPerfContext; } else if (itemid == ReportsItemId) { ctxMenu = (int)PkgCmdIDList.menuIdPerfReportsContext; } else if (IsReportItem(itemid)) { ctxMenu = (int)PkgCmdIDList.menuIdPerfSingleReportContext; } if (ctxMenu != null) { var uishell = (IVsUIShell)_serviceProvider.GetService(typeof(SVsUIShell)); if (uishell != null) { var pt = System.Windows.Forms.Cursor.Position; var pnts = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } }; var guid = GuidList.guidPythonProfilingCmdSet; int hr = uishell.ShowContextMenu( 0, ref guid, ctxMenu.Value, pnts, new ContextCommandTarget(this, itemid)); ErrorHandler.ThrowOnFailure(hr); } } break; } } return base.ExecCommand(itemid, ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } internal ProfilingTarget OpenTargetProperties() { var targetView = new ProfilingTargetView(_serviceProvider, _target); var dialog = new LaunchProfiling(_serviceProvider, targetView); var res = dialog.ShowModal() ?? false; if (res && targetView.IsValid) { var target = targetView.GetTarget(); if (target != null && !ProfilingTarget.IsSame(target, _target)) { _target = target; MarkDirty(); return _target; } } return null; } private void OpenProfile(uint itemid) { var item = GetReport(itemid); if (!File.Exists(item.Filename)) { MessageBox.Show(Strings.PerformanceReportNotFound.FormatUI(item.Filename), Strings.ProductTitle); } else { var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE)); dte.ItemOperations.OpenFile(item.Filename); } } class ContextCommandTarget : IOleCommandTarget { private readonly SessionNode _node; private readonly uint _itemid; public ContextCommandTarget(SessionNode node, uint itemid) { _node = node; _itemid = itemid; } #region IOleCommandTarget Members public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup == GuidList.guidPythonProfilingCmdSet) { switch (nCmdID) { case PkgCmdIDList.cmdidOpenReport: _node.OpenProfile(_itemid); return VSConstants.S_OK; case PkgCmdIDList.cmdidPerfCtxSetAsCurrent: _node._parent.SetActiveSession(_node); return VSConstants.S_OK; case PkgCmdIDList.cmdidPerfCtxStartProfiling: _node.StartProfiling(); return VSConstants.S_OK; case PkgCmdIDList.cmdidReportsCompareReports: { CompareReportsView compareView; if (_node.IsReportItem(_itemid)) { var report = _node.GetReport(_itemid); compareView = new CompareReportsView(report.Filename); } else { compareView = new CompareReportsView(); } var dialog = new CompareReportsWindow(compareView); var res = dialog.ShowModal() ?? false; if (res && compareView.IsValid) { IVsUIShellOpenDocument sod = _node._serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (sod == null) { return VSConstants.E_FAIL; } Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame frame = null; Guid guid = new Guid("{9C710F59-984F-4B83-B781-B6356C363B96}"); // performance diff guid Guid guidNull = Guid.Empty; sod.OpenSpecificEditor( (uint)(_VSRDTFLAGS.RDT_CantSave | _VSRDTFLAGS.RDT_DontAddToMRU | _VSRDTFLAGS.RDT_NonCreatable | _VSRDTFLAGS.RDT_NoLock), compareView.GetComparisonUri(), ref guid, null, ref guidNull, Strings.PerformanceComparisonTitle, _node, _itemid, IntPtr.Zero, null, out frame ); if (frame != null) { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.Show()); } } return VSConstants.S_OK; } case PkgCmdIDList.cmdidReportsAddReport: { var dialog = new OpenFileDialog(); dialog.Filter = PythonProfilingPackage.PerformanceFileFilter; dialog.CheckFileExists = true; var res = dialog.ShowDialog() ?? false; if (res) { _node.AddProfile(dialog.FileName); } return VSConstants.S_OK; } } } else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { switch((VSConstants.VSStd97CmdID)nCmdID) { case VSConstants.VSStd97CmdID.PropSheetOrProperties: _node.OpenTargetProperties(); return VSConstants.S_OK; } } return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; } #endregion } internal void MarkDirty() { _isDirty = true; OnPropertyChanged(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Caption, 0); } public override int QueryStatusCommand(uint itemid, ref Guid pguidCmdGroup, uint cCmds, VisualStudio.OLE.Interop.OLECMD[] prgCmds, IntPtr pCmdText) { return base.QueryStatusCommand(itemid, ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } private bool IsReportItem(uint itemid) { return itemid >= StartingReportId && Reports.ContainsKey(itemid); } private Report GetReport(uint itemid) { return Reports[itemid]; } public void AddProfile(string filename) { if (_target.Reports == null) { _target.Reports = new Reports(new[] { new Report(filename) }); } else { if (_target.Reports.Report == null) { _target.Reports.Report = new Report[0]; } uint prevSibling, newId; if (Reports.Count > 0) { prevSibling = (uint)Reports.Last().Key; newId = prevSibling + 1; } else { prevSibling = VSConstants.VSITEMID_NIL; newId = StartingReportId; } Reports[newId] = new Report(filename); OnItemAdded( ReportsItemId, prevSibling, newId ); } MarkDirty(); } public void Save(VSSAVEFLAGS flags, out int pfCanceled) { pfCanceled = 0; switch (flags) { case VSSAVEFLAGS.VSSAVE_Save: if (_neverSaved) { goto case VSSAVEFLAGS.VSSAVE_SaveAs; } Save(_filename); break; case VSSAVEFLAGS.VSSAVE_SaveAs: case VSSAVEFLAGS.VSSAVE_SaveCopyAs: SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.FileName = _filename; if (saveDialog.ShowDialog() == true) { Save(saveDialog.FileName); _neverSaved = false; } else { pfCanceled = 1; } break; } } internal void Removed() { IVsRunningDocumentTable rdt = _serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_EditLock, _docCookie)); } #region IVsHierarchyDeleteHandler Members public int DeleteItem(uint dwDelItemOp, uint itemid) { Debug.Assert(_target.Reports != null && _target.Reports.Report != null && _target.Reports.Report.Length > 0); var report = GetReport(itemid); Reports.Remove(itemid); OnItemDeleted(itemid); OnInvalidateItems(ReportsItemId); if (File.Exists(report.Filename) && dwDelItemOp == (uint)__VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) { // close the file if it's open before deleting it... var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE)); if (dte.ItemOperations.IsFileOpen(report.Filename)) { var doc = dte.Documents.Item(report.Filename); doc.Close(); } File.Delete(report.Filename); } return VSConstants.S_OK; } public int QueryDeleteItem(uint dwDelItemOp, uint itemid, out int pfCanDelete) { if (IsReportItem(itemid)) { pfCanDelete = 1; return VSConstants.S_OK; } pfCanDelete = 0; return VSConstants.S_OK; } #endregion internal void StartProfiling(bool openReport = true) { PythonProfilingPackage.Instance.StartProfiling(_target, this, openReport); } public void Save(string filename = null) { if (filename == null) { filename = _filename; } using (var stream = new FileStream(filename, FileMode.Create)) { ProfilingTarget.Serializer.Serialize( stream, _target ); _isDirty = false; stream.Close(); OnPropertyChanged(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Caption, 0); } } public string Filename { get { return _filename; } } public string Name { get { return Path.GetFileNameWithoutExtension(_filename); } } public bool IsSaved { get { return !_isDirty && !_neverSaved; } } #region IVsPersistHierarchyItem Members public int IsItemDirty(uint itemid, IntPtr punkDocData, out int pfDirty) { if (itemid == VSConstants.VSITEMID_ROOT) { pfDirty = _isDirty ? 1 : 0; return VSConstants.S_OK; } else { pfDirty = 0; return VSConstants.E_FAIL; } } public int SaveItem(VSSAVEFLAGS dwSave, string pszSilentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCanceled) { if (itemid == VSConstants.VSITEMID_ROOT) { Save(dwSave, out pfCanceled); return VSConstants.S_OK; } pfCanceled = 0; return VSConstants.E_FAIL; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Timers; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Encapsulate the asynchronous requests for the assets required for an archive operation /// </summary> class AssetsRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Method called when all the necessary assets for an archive request have been received. /// </summary> public delegate void AssetsRequestCallback( ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut); enum RequestState { Initial, Running, Completed, Aborted }; /// <value> /// Timeout threshold if we still need assets or missing asset notifications but have stopped receiving them /// from the asset service /// </value> protected const int TIMEOUT = 60 * 1000; /// <value> /// If a timeout does occur, limit the amount of UUID information put to the console. /// </value> protected const int MAX_UUID_DISPLAY_ON_TIMEOUT = 3; protected System.Timers.Timer m_requestCallbackTimer; /// <value> /// State of this request /// </value> private RequestState m_requestState = RequestState.Initial; /// <value> /// uuids to request /// </value> protected IDictionary<UUID, sbyte> m_uuids; /// <value> /// Callback used when all the assets requested have been received. /// </value> protected AssetsRequestCallback m_assetsRequestCallback; /// <value> /// List of assets that were found. This will be passed back to the requester. /// </value> protected List<UUID> m_foundAssetUuids = new List<UUID>(); /// <value> /// Maintain a list of assets that could not be found. This will be passed back to the requester. /// </value> protected List<UUID> m_notFoundAssetUuids = new List<UUID>(); /// <value> /// Record the number of asset replies required so we know when we've finished /// </value> private int m_repliesRequired; /// <value> /// Asset service used to request the assets /// </value> protected IAssetService m_assetService; protected IUserAccountService m_userAccountService; protected UUID m_scopeID; // the grid ID protected AssetsArchiver m_assetsArchiver; protected Dictionary<string, object> m_options; protected internal AssetsRequest( AssetsArchiver assetsArchiver, IDictionary<UUID, sbyte> uuids, IAssetService assetService, IUserAccountService userService, UUID scope, Dictionary<string, object> options, AssetsRequestCallback assetsRequestCallback) { m_assetsArchiver = assetsArchiver; m_uuids = uuids; m_assetsRequestCallback = assetsRequestCallback; m_assetService = assetService; m_userAccountService = userService; m_scopeID = scope; m_options = options; m_repliesRequired = uuids.Count; // FIXME: This is a really poor way of handling the timeout since it will always leave the original requesting thread // hanging. Need to restructure so an original request thread waits for a ManualResetEvent on asset received // so we can properly abort that thread. Or request all assets synchronously, though that would be a more // radical change m_requestCallbackTimer = new System.Timers.Timer(TIMEOUT); m_requestCallbackTimer.AutoReset = false; m_requestCallbackTimer.Elapsed += new ElapsedEventHandler(OnRequestCallbackTimeout); } protected internal void Execute() { m_requestState = RequestState.Running; m_log.DebugFormat("[ARCHIVER]: AssetsRequest executed looking for {0} possible assets", m_repliesRequired); // We can stop here if there are no assets to fetch if (m_repliesRequired == 0) { m_requestState = RequestState.Completed; PerformAssetsRequestCallback(false); return; } m_requestCallbackTimer.Enabled = true; foreach (KeyValuePair<UUID, sbyte> kvp in m_uuids) { // m_log.DebugFormat("[ARCHIVER]: Requesting asset {0}", kvp.Key); // m_assetService.Get(kvp.Key.ToString(), kvp.Value, PreAssetRequestCallback); AssetBase asset = m_assetService.Get(kvp.Key.ToString()); PreAssetRequestCallback(kvp.Key.ToString(), kvp.Value, asset); } } protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args) { bool timedOut = true; try { lock (this) { // Take care of the possibilty that this thread started but was paused just outside the lock before // the final request came in (assuming that such a thing is possible) if (m_requestState == RequestState.Completed) { timedOut = false; return; } m_requestState = RequestState.Aborted; } // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure // case anyway. List<UUID> uuids = new List<UUID>(); foreach (UUID uuid in m_uuids.Keys) { uuids.Add(uuid); } foreach (UUID uuid in m_foundAssetUuids) { uuids.Remove(uuid); } foreach (UUID uuid in m_notFoundAssetUuids) { uuids.Remove(uuid); } m_log.ErrorFormat( "[ARCHIVER]: Asset service failed to return information about {0} requested assets", uuids.Count); int i = 0; foreach (UUID uuid in uuids) { m_log.ErrorFormat("[ARCHIVER]: No information about asset {0} received", uuid); if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT) break; } if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT) m_log.ErrorFormat( "[ARCHIVER]: (... {0} more not shown)", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT); m_log.Error("[ARCHIVER]: Archive save aborted. PLEASE DO NOT USE THIS ARCHIVE, IT WILL BE INCOMPLETE."); } catch (Exception e) { m_log.ErrorFormat("[ARCHIVER]: Timeout handler exception {0}{1}", e.Message, e.StackTrace); } finally { if (timedOut) WorkManager.RunInThread(PerformAssetsRequestCallback, true, "Archive Assets Request Callback"); } } protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset) { // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown) { m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, SLUtil.AssetTypeFromCode((sbyte)assetType)); fetchedAsset.Type = (sbyte)assetType; } AssetRequestCallback(fetchedAssetID, this, fetchedAsset); } /// <summary> /// Called back by the asset cache when it has the asset /// </summary> /// <param name="assetID"></param> /// <param name="asset"></param> public void AssetRequestCallback(string id, object sender, AssetBase asset) { Culture.SetCurrentCulture(); try { lock (this) { //m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id); m_requestCallbackTimer.Stop(); if ((m_requestState == RequestState.Aborted) || (m_requestState == RequestState.Completed)) { m_log.WarnFormat( "[ARCHIVER]: Received information about asset {0} while in state {1}. Ignoring.", id, m_requestState); return; } if (asset != null) { // m_log.DebugFormat("[ARCHIVER]: Writing asset {0}", id); m_foundAssetUuids.Add(asset.FullID); m_assetsArchiver.WriteAsset(PostProcess(asset)); } else { // m_log.DebugFormat("[ARCHIVER]: Recording asset {0} as not found", id); m_notFoundAssetUuids.Add(new UUID(id)); } if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count >= m_repliesRequired) { m_requestState = RequestState.Completed; if(m_notFoundAssetUuids.Count == 0) m_log.DebugFormat( "[ARCHIVER]: Successfully added {0} assets", m_foundAssetUuids.Count); else m_log.DebugFormat( "[ARCHIVER]: Successfully added {0} assets ({1} assets not found but these may be expected invalid references)", m_foundAssetUuids.Count, m_notFoundAssetUuids.Count); // We want to stop using the asset cache thread asap // as we now need to do the work of producing the rest of the archive WorkManager.RunInThread(PerformAssetsRequestCallback, false, "Archive Assets Request Callback"); } else { m_requestCallbackTimer.Start(); } } } catch (Exception e) { m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e); } } /// <summary> /// Perform the callback on the original requester of the assets /// </summary> protected void PerformAssetsRequestCallback(object o) { Culture.SetCurrentCulture(); Boolean timedOut = (Boolean)o; try { m_assetsRequestCallback(m_foundAssetUuids, m_notFoundAssetUuids, timedOut); } catch (Exception e) { m_log.ErrorFormat( "[ARCHIVER]: Terminating archive creation since asset requster callback failed with {0}", e); } } protected AssetBase PostProcess(AssetBase asset) { if (asset.Type == (sbyte)AssetType.Object && asset.Data != null && m_options.ContainsKey("home")) { //m_log.DebugFormat("[ARCHIVER]: Rewriting object data for {0}", asset.ID); string xml = ExternalRepresentationUtils.RewriteSOP(Utils.BytesToString(asset.Data), string.Empty, m_options["home"].ToString(), m_userAccountService, m_scopeID); asset.Data = Utils.StringToBytes(xml); } return asset; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Utilities { internal static class BufferUtils { public static char[] RentBuffer(IArrayPool<char> bufferPool, int minSize) { if (bufferPool == null) { return new char[minSize]; } char[] buffer = bufferPool.Rent(minSize); return buffer; } public static void ReturnBuffer(IArrayPool<char> bufferPool, char[] buffer) { if (bufferPool == null) { return; } bufferPool.Return(buffer); } public static char[] EnsureBufferSize(IArrayPool<char> bufferPool, int size, char[] buffer) { if (bufferPool == null) { return new char[size]; } if (buffer != null) { bufferPool.Return(buffer); } return bufferPool.Rent(size); } } internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; private const int UnicodeTextLength = 6; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (var escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) { return HtmlCharEscapeFlags; } if (quoteChar == '"') { return DoubleQuoteCharEscapeFlags; } return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) { return false; } foreach (char c in s) { if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; } } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); if (i > lastWritePosition) { int length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0); int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) { Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } BufferUtils.ReturnBuffer(bufferPool, writeBuffer); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { writer.Write(escapedValue); } else { writer.Write(writeBuffer, 0, UnicodeTextLength); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { int length = s.Length - lastWritePosition; if (writeBuffer == null || writeBuffer.Length < length) { writeBuffer = new char[length]; } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters) { return ToEscapedJavaScriptString(value, delimiter, appendDelimiters, StringEscapeHandling.Default); } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16)) { char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Archimedes.Geometry.Primitives { /// <summary> /// Composition of several single IGeometryBase Elements to a common Interface /// </summary> public class ComplexGeometry : IGeometry { #region Fields readonly List<IGeometry> _geometries = new List<IGeometry>(); Vertices _verticesCache = null; readonly object _verticesCacheLock = new object(); AARectangle _boundingbox; Rectangle2 _boundingboxsmall; bool _boundingboxInvalidated = true; bool _boundingboxsmallInvalidated = true; #endregion #region Constructor public ComplexGeometry() { } #endregion #region Geometry Access Methods public void AddGeometry(IGeometry geometry) { _geometries.Add(geometry); Invalidate(); } public void AddGeometries(IEnumerable<IGeometry> geometries) { _geometries.AddRange(geometries); Invalidate(); } public void RemoveGeometry(IGeometry geometry) { _geometries.Remove(geometry); Invalidate(); } public int Count() { return _geometries.Count(); } public IGeometry this[int index]{ get { return _geometries[index]; } set { _geometries[index] = value; Invalidate(); } } #endregion #region Public Properties public Vector2 FirstPoint { get { return ToPath().FirstPoint; } } public Vector2 LastPoint { get { return ToPath().LastPoint; } } private void Invalidate() { lock (_verticesCacheLock) { _verticesCache = null; } _boundingboxInvalidated = true; _boundingboxsmallInvalidated = true; } public Vector2 Location { get { return MiddlePoint; } set { MiddlePoint = value; } } public Vector2 MiddlePoint { get { double mpointX = 0; double mpointY = 0; var middlepoints = (from g in _geometries select g.MiddlePoint).ToList(); foreach (var pnt in middlepoints){ mpointX += pnt.X; mpointY += pnt.Y; } return new Vector2( mpointX / middlepoints.Count, mpointY / middlepoints.Count); } set { var mov = new Vector2(MiddlePoint, value); this.Translate(mov); } } #endregion #region Public Methods public void Translate(Vector2 mov) { foreach (var g in _geometries) g.Translate(mov); Invalidate(); } public void Scale(double fact) { foreach (var g in _geometries) g.Scale(fact); Invalidate(); } /// <summary> /// Gets a deep copy of this Object /// </summary> /// <returns></returns> public IGeometry Clone() { var nuv = new ComplexGeometry(); foreach (var g in _geometries) nuv.AddGeometry(g.Clone()); return nuv; } public void Prototype(IGeometry iprototype) { var prototype = iprototype as ComplexGeometry; if (prototype == null) throw new NotSupportedException(); _geometries.Clear(); _geometries.AddRange(prototype.GetGeometries()); } public bool Contains(Vector2 point, double tolerance = GeometrySettings.DEFAULT_TOLERANCE) { foreach (var g in _geometries) { if (g.Contains(point, tolerance)) { return true; } } return false; } public bool Contains(Vector2 point, ref IGeometry subGeometry, double tolerance = GeometrySettings.DEFAULT_TOLERANCE) { subGeometry = null; foreach (var g in _geometries) { if (g.Contains(point, tolerance)) { subGeometry = g; return true; } } return false; } #endregion #region Bounding Boxes public AARectangle BoundingBox { get { if (_boundingboxInvalidated) { _boundingbox = ToVertices().BoundingBox; _boundingboxInvalidated = false; } return _boundingbox; } } public Rectangle2 SmallestBoundingBox { get { if (_boundingboxsmallInvalidated) { _boundingboxsmall = ToPolygon2().FindSmallestBoundingBox(); _boundingboxsmallInvalidated = false; } return _boundingboxsmall; } } public Rectangle2 SmallestWidthBoundingBox { get { return ToPolygon2().FindSmallestWidthBoundingBox(); } } public Circle2 BoundingCircle { get { return this.ToPolygon2().BoundingCircle; } } #endregion #region Intersection Methods public IEnumerable<Vector2> Intersect(IGeometry other, double tolerance = GeometrySettings.DEFAULT_TOLERANCE) { var intercepts = new List<Vector2>(); foreach (var g in _geometries) { intercepts.AddRange(g.Intersect(other, tolerance)); } return intercepts; } public bool HasCollision(IGeometry geometry, double tolerance = GeometrySettings.DEFAULT_TOLERANCE) { foreach (var g in _geometries) { if (g.HasCollision(geometry, tolerance)) { return true; } } return false; } #endregion #region To -> Transformer Methods /// <summary> /// Returns vertices of this geometry /// </summary> /// <returns></returns> public Vertices ToVertices() { lock (_verticesCacheLock) { if (_verticesCache == null) { var vertices = ToPath().ToVertices().Distinct(); _verticesCache = new Vertices(vertices); } return new Vertices(_verticesCache); } } public IEnumerable<IGeometry> GetGeometries() { return new List<IGeometry>(_geometries); } public Polygon2 ToPolygon2() { return new Polygon2(ToVertices()); } /// <summary> /// Creates a docked path from this geometries. /// </summary> /// <returns></returns> public LineString ToPath() { var path = new LineString(); foreach (var g in _geometries) path.DockGeometry(g); return path; } #endregion } }
namespace Economy.scripts.EconStructures { using System; using System.Collections.Generic; using System.Globalization; using System.Xml.Serialization; [XmlType("EconConfig")] public class EconConfigStruct { public EconConfigStruct() { // Set defaults. CurrencyName = EconomyConsts.CurrencyName; TradeNetworkName = EconomyConsts.TradeNetworkName; DefaultStartingBalance = EconomyConsts.DefaultStartingBalance; LimitedRange = EconomyConsts.DefaultLimitedRange; LimitedSupply = EconomyConsts.LimitedSupply; TradeTimeout = EconomyConsts.TradeTimeout; AccountExpiry = EconomyConsts.AccountExpiry; NPCStartingBalance = EconomyConsts.NPCStartingBalance; NpcMerchantName = EconomyConsts.NpcMerchantName; DefaultTradeRange = EconomyConsts.DefaultTradeRange; Language = (int)VRage.MyLanguagesEnum.English; EnableLcds = true; EnablePlayerPayments = true; EnableNpcTradezones = true; EnablePlayerTradezones = true; MaximumPlayerTradeZones = 1; TradeZoneLicenceCostMin = 20000; TradeZoneLicenceCostMax = 20000000; TradeZoneRelinkRatio = 0.5m; TradeZoneMinRadius = 20; TradeZoneMaxRadius = 5000; PriceScaling = EconomyConsts.DefaultPriceScaling; ShipTrading = true; MinimumLcdDisplayInterval = 1; } #region properties /// <summary> /// Name our money. This is NOT the symbol (ie., $). /// </summary> public string CurrencyName; /// <summary> /// Name our Trading Network. /// </summary> public string TradeNetworkName; /// <summary> /// The starting balance for all new players. /// </summary> public decimal DefaultStartingBalance; /// <summary> /// The cost to create a Player trade zone when the zone size is at its Minimum allowed radius. /// </summary> public decimal TradeZoneLicenceCostMin; /// <summary> /// The cost to create a Player trade zone when the zone size is at its Maximum allowed radius. /// </summary> public decimal TradeZoneLicenceCostMax; /// <summary> /// The cost to create a Player trade zone Minimum allowed radius. /// </summary> public decimal TradeZoneMinRadius; /// <summary> /// The cost to create a Player trade zone Maximum allowed radius. /// </summary> public decimal TradeZoneMaxRadius; /// <summary> /// The cost ratio for Relink/Reestablishing a broken trade zone. /// </summary> public decimal TradeZoneRelinkRatio; /// <summary> /// The maximum number of trade zones a player an create. /// </summary> public int MaximumPlayerTradeZones; /// <summary> /// Should players be near each other to trade or should it be unlimited distance. /// </summary> public bool LimitedRange; /// <summary> /// Should the NPC market be limited or unlimited supply. /// </summary> public bool LimitedSupply; /// <summary> /// The starting balance for NPC Bankers. /// </summary> public decimal NPCStartingBalance; /// <summary> /// The name that will used to identify the Merchant's server account. /// </summary> public string NpcMerchantName; /// <summary> /// Default range of trade zones. /// </summary> public double DefaultTradeRange; /// <summary> /// Indicates what language the Servre uses for text in game. /// Mapped aginst: VRage.MyLanguagesEnum /// Typically retrieved via: MyAPIGateway.Session.Config.Language /// </summary> public int Language; /// <summary> /// Indicates the LCD panels can be used to display Trade zone information. /// </summary> public bool EnableLcds; /// <summary> /// Indicates that Npc Tradezones can be used. /// They can still be created and managed by the Admin, allowing an admin to take the tradezones offline temporarily to fix any issue. /// </summary> public bool EnableNpcTradezones; // TODO: split buy and sell? https://github.com/jpcsupplies/Economy_mod/issues/88 /// <summary> /// Indicates the Player Tradezone can be created and used. /// </summary> public bool EnablePlayerTradezones; // TODO: split buy and sell? https://github.com/jpcsupplies/Economy_mod/issues/88 /// <summary> /// Indicates that Players can send payments to one another. /// </summary> public bool EnablePlayerPayments; ///// <summary> ///// Indicates that Players can Trade with on another. ///// </summary> //public bool EnablePlayerTrades; /// <summary> /// This sets if prices should react to available supply. /// </summary> public bool PriceScaling; /// <summary> /// This sets if players can buy and sell ships. /// </summary> public bool ShipTrading; /// <summary> /// Users can specify the LCD display refresh interval, but this will restrict /// the minimum LCD display refresh server wide for all Economy tagged lcds. /// This should never be set less than 1. /// </summary> public decimal MinimumLcdDisplayInterval; #endregion #region TradeTimeout // Local Variable private TimeSpan _tradeTimeout; /// <summary> /// The time to timeout a player to player trade offer. /// </summary> /// <remarks>The TimeSpan data type cannot be natively serialized, so we cheat by using /// a proxy property to store it in another acceptable (and human readable) format.</remarks> [XmlIgnore] public TimeSpan TradeTimeout { get { return _tradeTimeout; } set { _tradeTimeout = value; } } /// <summary> /// Serialization property for TradeTimeout. /// </summary> [XmlElement("TradeTimeout")] public string TradeTimeoutTicks { get { return _tradeTimeout.ToString("c"); } set { try { _tradeTimeout = TimeSpan.Parse(value, CultureInfo.InvariantCulture); } catch (Exception) { _tradeTimeout = EconomyConsts.TradeTimeout; EconomyScript.Instance.ServerLogger.WriteWarning("TradeTimeout has been reset, as the stored value '{0}' was invalid.", value); } } } #endregion #region AccountExpiry // Local Variable private TimeSpan _accountExpiry; /// <summary> /// The time to timeout a player to player trade offer. /// </summary> /// <remarks>The TimeSpan data type cannot be natively serialized, so we cheat by using /// a proxy property to store it in another acceptable (and human readable) format.</remarks> [XmlIgnore] public TimeSpan AccountExpiry { get { return _accountExpiry; } set { _accountExpiry = value; } } /// <summary> /// Serialization property for AccountExpiry. /// </summary> [XmlElement("AccountExpiry")] public string AccountExpiryTicks { get { return _accountExpiry.ToString("c"); } set { try { _accountExpiry = TimeSpan.Parse(value, CultureInfo.InvariantCulture); } catch (Exception) { _accountExpiry = EconomyConsts.AccountExpiry; EconomyScript.Instance.ServerLogger.WriteWarning("AccountExpiry has been reset, as the stored value '{0}' was invalid.", value); } } } #endregion public List<MarketItemStruct> DefaultPrices; public decimal CalculateZoneCost(decimal radius, bool relink) { // linear cost on radius. return (relink ? TradeZoneRelinkRatio : 1m) * (((radius - TradeZoneMinRadius) / (TradeZoneMaxRadius - TradeZoneMinRadius) * (TradeZoneLicenceCostMax - TradeZoneLicenceCostMin)) + TradeZoneLicenceCostMin); } } }
//----------------------------------------------------------------------- // <copyright file="FlowThrottleSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.IO; using Akka.Streams.Actors; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class FlowThrottleSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowThrottleSpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(1, 1); Materializer = ActorMaterializer.Create(Sys, settings); } private static ByteString GenerateByteString(int length) { var random = new Random(); var bytes = Enumerable.Range(0, 255) .Select(_ => random.Next(0, 255)) .Take(length) .Select(Convert.ToByte) .ToArray(); return ByteString.FromBytes(bytes); } [Fact] public void Throttle_for_single_cost_elements_must_work_for_the_happy_case() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 5)) .Throttle(1, TimeSpan.FromMilliseconds(100), 0, ThrottleMode.Shaping) .RunWith(this.SinkProbe<int>(), Materializer) .Request(5) .ExpectNext(1, 2, 3, 4, 5) .ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_accept_very_high_rates() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 5)) .Throttle(1, TimeSpan.FromTicks(1), 0, ThrottleMode.Shaping) .RunWith(this.SinkProbe<int>(), Materializer) .Request(5) .ExpectNext(1, 2, 3, 4, 5) .ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_accept_very_low_rates() { this.AssertAllStagesStopped(() => { var probe = Source.From(Enumerable.Range(1, 5)) .Throttle(1, TimeSpan.FromDays(100), 1, ThrottleMode.Shaping) .RunWith(this.SinkProbe<int>(), Materializer); probe.Request(5) .ExpectNext(1) .ExpectNoMsg(TimeSpan.FromMilliseconds(100)); probe.Cancel(); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_() { var sharedThrottle = Flow.Create<int>().Throttle(1, TimeSpan.FromDays(1), 1, ThrottleMode.Enforcing); // If there is accidental shared state then we would not be able to pass through the single element var t = Source.Single(1) .Via(sharedThrottle) .Via(sharedThrottle) .RunWith(Sink.First<int>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.Should().Be(1); // It works with a new stream, too t = Source.Single(2) .Via(sharedThrottle) .Via(sharedThrottle) .RunWith(Sink.First<int>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.Should().Be(2); } [Fact] public void Throttle_for_single_cost_elements_must_emit_single_element_per_tick() { this.AssertAllStagesStopped(() => { var upstream = this.CreatePublisherProbe<int>(); var downstream = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstream) .Throttle(1, TimeSpan.FromMilliseconds(300), 0, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); downstream.Request(2); upstream.SendNext(1); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(150)); downstream.ExpectNext(1); upstream.SendNext(2); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(150)); downstream.ExpectNext(2); upstream.SendComplete(); downstream.ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_not_send_downstream_if_upstream_does_not_emit_element() { this.AssertAllStagesStopped(() => { var upstream = this.CreatePublisherProbe<int>(); var downstream = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstream) .Throttle(1, TimeSpan.FromMilliseconds(300), 0, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); downstream.Request(2); upstream.SendNext(1); downstream.ExpectNext(1); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); upstream.SendNext(2); downstream.ExpectNext(2); upstream.SendComplete(); downstream.ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_cancel_when_downstream_cancels() { this.AssertAllStagesStopped(() => { var downstream = this.CreateSubscriberProbe<int>(); Source.From(Enumerable.Range(1, 10)) .Throttle(1, TimeSpan.FromMilliseconds(300), 0, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); downstream.Cancel(); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_send_elements_downstream_as_soon_as_time_comes() { this.AssertAllStagesStopped(() => { var probe = Source.From(Enumerable.Range(1, 10)) .Throttle(2, TimeSpan.FromMilliseconds(750), 0, ThrottleMode.Shaping) .RunWith(this.SinkProbe<int>(), Materializer); probe.Request(5); var result = probe.ReceiveWhile(TimeSpan.FromMilliseconds(900), filter: x => x); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(150)) .ExpectNext(3) .ExpectNoMsg(TimeSpan.FromMilliseconds(150)) .ExpectNext(4); probe.Cancel(); // assertion may take longer then the throttle and therefore the next assertion fails result.ShouldAllBeEquivalentTo(new[] { new OnNext(1), new OnNext(2) }); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_burst_according_to_its_maximum_if_enough_time_passed() { this.AssertAllStagesStopped(() => { var ms = TimeSpan.FromMilliseconds(300); var upstream = this.CreatePublisherProbe<int>(); var downstream = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstream) .Throttle(1, TimeSpan.FromMilliseconds(200), 5, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); // Exhaust bucket first downstream.Request(5); Enumerable.Range(1, 5).ForEach(i => upstream.SendNext(i)); // Check later, takes to long var exhaustElements = downstream.ReceiveWhile(ms, ms, msg => msg is TestSubscriber.OnNext<int> ? msg : null, 5); downstream.Request(1); upstream.SendNext(6); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); downstream.ExpectNext(6); downstream.Request(5); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1200)); var expected = new List<OnNext>(); for (var i = 7; i < 12; i++) { upstream.SendNext(i); expected.Add(new OnNext(i)); } downstream.ReceiveWhile(TimeSpan.FromMilliseconds(300), filter: x => x, msgs: 5) .ShouldAllBeEquivalentTo(expected); downstream.Cancel(); exhaustElements.Cast<TestSubscriber.OnNext<int>>() .Select(n => n.Element) .ShouldAllBeEquivalentTo(Enumerable.Range(1, 5)); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_burst_some_elements_if_have_enough_time() { this.AssertAllStagesStopped(() => { var upstream = this.CreatePublisherProbe<int>(); var downstream = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstream) .Throttle(1, TimeSpan.FromMilliseconds(200), 5, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); // Exhaust bucket first downstream.Request(5); Enumerable.Range(1, 5).ForEach(i => upstream.SendNext(i)); // Check later, takes too long var exhaustElements = downstream.ReceiveWhile(filter: o => o, max: TimeSpan.FromMilliseconds(300), msgs: 5); downstream.Request(1); upstream.SendNext(6); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); downstream.ExpectNext(6); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); downstream.Request(5); var expected = new List<OnNext>(); for (var i = 7; i < 11; i++) { upstream.SendNext(i); if (i < 9) expected.Add(new OnNext(i)); } downstream.ReceiveWhile(TimeSpan.FromMilliseconds(100), filter: x => x, msgs: 2) .ShouldAllBeEquivalentTo(expected); downstream.Cancel(); exhaustElements .Cast<TestSubscriber.OnNext<int>>() .Select(n => n.Element) .ShouldAllBeEquivalentTo(Enumerable.Range(1, 5)); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_throw_exception_when_exceeding_throughtput_in_enforced_mode() { this.AssertAllStagesStopped(() => { var t1 = Source.From(Enumerable.Range(1, 5)) .Throttle(1, TimeSpan.FromMilliseconds(200), 5, ThrottleMode.Enforcing) .RunWith(Sink.Seq<int>(), Materializer); // Burst is 5 so this will not fail t1.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t1.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 5)); var t2 = Source.From(Enumerable.Range(1, 6)) .Throttle(1, TimeSpan.FromMilliseconds(200), 5, ThrottleMode.Enforcing) .RunWith(Sink.Ignore<int>(), Materializer); t2.Invoking(task => task.Wait(TimeSpan.FromSeconds(2))).ShouldThrow<OverflowException>(); }, Materializer); } [Fact] public void Throttle_for_single_cost_elements_must_properly_combine_shape_and_throttle_modes() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 5)) .Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Shaping) .Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Enforcing) .RunWith(this.SinkProbe<int>(), Materializer) .Request(5) .ExpectNext(1, 2, 3, 4, 5) .ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_work_for_the_happy_case() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 5)) .Throttle(1, TimeSpan.FromMilliseconds(100), 0, _ => 1, ThrottleMode.Shaping) .RunWith(this.SinkProbe<int>(), Materializer) .Request(5) .ExpectNext(1, 2, 3, 4, 5) .ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_emit_elements_according_to_cost() { this.AssertAllStagesStopped(() => { var list = Enumerable.Range(1, 4).Select(x => x*2).Select(GenerateByteString).ToList(); Source.From(list) .Throttle(2, TimeSpan.FromMilliseconds(200), 0, x => x.Count, ThrottleMode.Shaping) .RunWith(this.SinkProbe<ByteString>(), Materializer) .Request(4) .ExpectNext(list[0]) .ExpectNoMsg(TimeSpan.FromMilliseconds(300)) .ExpectNext(list[1]) .ExpectNoMsg(TimeSpan.FromMilliseconds(500)) .ExpectNext(list[2]) .ExpectNoMsg(TimeSpan.FromMilliseconds(700)) .ExpectNext(list[3]) .ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_not_send_downstream_if_upstream_does_not_emit_element() { this.AssertAllStagesStopped(() => { var upstream = this.CreatePublisherProbe<int>(); var downstream = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstream) .Throttle(1, TimeSpan.FromMilliseconds(300), 0, x => x, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); downstream.Request(2); upstream.SendNext(1); downstream.ExpectNext(1); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); upstream.SendNext(2); downstream.ExpectNext(2); upstream.SendComplete(); downstream.ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_cancel_when_downstream_cancels() { this.AssertAllStagesStopped(() => { var downstream = this.CreateSubscriberProbe<int>(); Source.From(Enumerable.Range(1, 10)) .Throttle(2, TimeSpan.FromMilliseconds(200), 0, x => x, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); downstream.Cancel(); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_send_elements_downstream_as_soon_as_time_comes() { this.AssertAllStagesStopped(() => { var probe = Source.From(Enumerable.Range(1, 10)) .Throttle(4, TimeSpan.FromMilliseconds(500), 0, _ => 2, ThrottleMode.Shaping) .RunWith(this.SinkProbe<int>(), Materializer); probe.Request(5); var result = probe.ReceiveWhile(TimeSpan.FromMilliseconds(600), filter: x => x); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(100)) .ExpectNext(3) .ExpectNoMsg(TimeSpan.FromMilliseconds(100)) .ExpectNext(4); probe.Cancel(); // assertion may take longer then the throttle and therefore the next assertion fails result.ShouldAllBeEquivalentTo(new[] { new OnNext(1), new OnNext(2) }); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_burst_according_to_its_maximum_if_enough_time_passed() { this.AssertAllStagesStopped(() => { var upstream = this.CreatePublisherProbe<int>(); var downstream = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstream) .Throttle(2, TimeSpan.FromMilliseconds(400), 5, x => 1, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); // Exhaust bucket first downstream.Request(5); Enumerable.Range(1, 5).ForEach(i => upstream.SendNext(i)); // Check later, takes too long var exhaustElemens = downstream.ReceiveWhile(filter: o => o, max: TimeSpan.FromMilliseconds(300), msgs: 5); downstream.Request(1); upstream.SendNext(6); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); downstream.ExpectNext(6); downstream.Request(5); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1200)); var expected = new List<OnNext>(); for (var i = 7; i < 12; i++) { upstream.SendNext(i); expected.Add(new OnNext(i)); } downstream.ReceiveWhile(TimeSpan.FromMilliseconds(300), filter: x => x, msgs: 5) .ShouldAllBeEquivalentTo(expected); downstream.Cancel(); exhaustElemens .Cast<TestSubscriber.OnNext<int>>() .Select(n => n.Element) .ShouldAllBeEquivalentTo(Enumerable.Range(1, 5)); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_burst_some_elements_if_have_enough_time() { this.AssertAllStagesStopped(() => { var upstream = this.CreatePublisherProbe<int>(); var downstream = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstream) .Throttle(2, TimeSpan.FromMilliseconds(400), 5, e => e < 9 ? 1 : 20, ThrottleMode.Shaping) .RunWith(Sink.FromSubscriber(downstream), Materializer); // Exhaust bucket first downstream.Request(5); Enumerable.Range(1, 5).ForEach(i => upstream.SendNext(i)); // Check later, takes too long var exhaustElements = downstream.ReceiveWhile(filter: o => o, max: TimeSpan.FromMilliseconds(300), msgs: 5); downstream.Request(1); upstream.SendNext(6); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); downstream.ExpectNext(6); downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); //wait to receive 2 in burst afterwards downstream.Request(5); var expected = new List<OnNext>(); for (var i = 7; i < 10; i++) { upstream.SendNext(i); if (i < 9) expected.Add(new OnNext(i)); } downstream.ReceiveWhile(TimeSpan.FromMilliseconds(200), filter: x => x, msgs: 2) .ShouldAllBeEquivalentTo(expected); downstream.Cancel(); exhaustElements .Cast<TestSubscriber.OnNext<int>>() .Select(n => n.Element) .ShouldAllBeEquivalentTo(Enumerable.Range(1, 5)); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_throw_exception_when_exceeding_throughtput_in_enforced_mode() { this.AssertAllStagesStopped(() => { var t1 = Source.From(Enumerable.Range(1, 4)) .Throttle(2, TimeSpan.FromMilliseconds(200), 10, x => x, ThrottleMode.Enforcing) .RunWith(Sink.Seq<int>(), Materializer); t1.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t1.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 4)); // Burst is 10 so this will not fail var t2 = Source.From(Enumerable.Range(1, 6)) .Throttle(2, TimeSpan.FromMilliseconds(200), 5, x => x, ThrottleMode.Enforcing) .RunWith(Sink.Ignore<int>(), Materializer); t2.Invoking(task => task.Wait(TimeSpan.FromSeconds(2))).ShouldThrow<OverflowException>(); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_properly_combine_shape_and_enforce_modes() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 5)) .Throttle(2, TimeSpan.FromMilliseconds(200), 0, x => x, ThrottleMode.Shaping) .Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Enforcing) .RunWith(this.SinkProbe<int>(), Materializer) .Request(5) .ExpectNext(1, 2, 3, 4, 5) .ExpectComplete(); }, Materializer); } [Fact] public void Throttle_for_various_cost_elements_must_handle_rate_calculation_function_exception() { this.AssertAllStagesStopped(() => { var ex = new Exception(); Source.From(Enumerable.Range(1, 5)) .Throttle(2, TimeSpan.FromMilliseconds(200), 0, _ => { throw ex; }, ThrottleMode.Shaping) .Throttle(1, TimeSpan.FromMilliseconds(100), 5, ThrottleMode.Enforcing) .RunWith(this.SinkProbe<int>(), Materializer) .Request(5) .ExpectError().Should().Be(ex); }, Materializer); } } }
// 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.Globalization; /// <summary> /// Convert.ToString(System.DateTime,System.IFormatProvider) /// </summary> public class ConvertToString8 { public static int Main() { ConvertToString8 testObj = new ConvertToString8(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.DateTime,System.IFormatProvider)"); if (testObj.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; //ur-PK doesn't exist in telesto // retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify the DateTime is now and IFormatProvider is en-US CultureInfo... "; string c_TEST_ID = "P001"; DateTime dt = DateTime.Now; IFormatProvider provider = new CultureInfo("en-US"); String actualValue = dt.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(dt,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc = "\n IFormatProvider is en-US CultureInfo."; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify the DateTime is now and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P002"; DateTime dt = DateTime.Now; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = dt.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(dt,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc = "\n IFormatProvider is fr-FR CultureInfo."; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify DateTime instance is created by ctor(int year,int month,int day) and IFormatProvider is ur-PK... "; string c_TEST_ID = "P003"; Random rand = new Random(-55); int year = rand.Next(1900, 2050); int month = rand.Next(1, 12); int day = rand.Next(1, 28); DateTime dt = new DateTime(year, month, day); IFormatProvider provider = new CultureInfo("ur-PK"); String actualValue = dt.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(dt,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc = "\n IFormatProvider is ur-PK CultureInfo."; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string c_TEST_DESC = "PosTest4: Verify DateTime instance is created by ctor(int year,int month,int day,int hour,int minute,int second) and IFormatProvider is ru-RU CultureInfo...... "; string c_TEST_ID = "P004"; Random rand = new Random(-55); int year = rand.Next(1900, 2050); int month = rand.Next(1, 12); int day = rand.Next(1, 28); int hour = rand.Next(0, 23); int minute = rand.Next(0, 59); int second = rand.Next(0, 59); DateTime dt = new DateTime(year, month, day); IFormatProvider provider = new CultureInfo("ru-RU"); String actualValue = dt.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(dt,provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc = "\n IFormatProvider is ur-PK CultureInfo."; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string c_TEST_DESC = "PosTest5: Verify DateTime instance is created by ctor(int year,int month,int day,int hour,int minute,int second) and IFormatProvider is a null reference... "; string c_TEST_ID = "P005"; Random rand = new Random(-55); int year = rand.Next(1900, 2050); int month = rand.Next(1, 12); int day = rand.Next(1, 28); int hour = rand.Next(0, 23); int minute = rand.Next(0, 59); int second = rand.Next(0, 59); DateTime dt = new DateTime(year, month, day); IFormatProvider provider = null; String actualValue = dt.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(dt, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc = "\n IFormatProvider is a null reference."; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion }
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf; using Grpc.Core; using System.Threading.Tasks; namespace Google.Cloud.Spanner.V1 { /// <summary> /// Interface for common properties of <see cref="ReadRequest"/> and <see cref="ExecuteSqlRequest"/>. /// </summary> internal interface IReadOrQueryRequest { /// <summary> /// Returns a ByteString representation of this request. /// </summary> ByteString ToByteString(); /// <summary> /// See <see cref="ReadRequest.Clone"/> and <see cref="ExecuteSqlRequest.Clone"/> /// </summary> IReadOrQueryRequest CloneRequest(); /// <summary> /// See <see cref="ReadRequest.Session"/> and <see cref="ExecuteSqlRequest.Session"/> /// </summary> string Session { get; } /// <summary> /// See <see cref="ReadRequest.Session"/> and <see cref="ExecuteSqlRequest.Session"/> /// </summary> SessionName SessionAsSessionName { set; } /// <summary> /// See <see cref="ReadRequest.Transaction"/> and <see cref="ExecuteSqlRequest.Transaction"/> /// </summary> TransactionSelector Transaction { set; } /// <summary> /// See <see cref="ReadRequest.ResumeToken"/> and <see cref="ExecuteSqlRequest.ResumeToken"/> /// </summary> ByteString ResumeToken { set; } /// <summary> /// See <see cref="ReadRequest.PartitionToken"/> and <see cref="ExecuteSqlRequest.PartitionToken"/> /// </summary> ByteString PartitionToken { get; set; } /// <summary> /// Executes the streaming query/read RPC. /// </summary> /// <param name="client">The client to use for the execution</param> /// <param name="callSettings">The call settings to use for the invocation</param> /// <returns>The result stream for the query/read</returns> AsyncServerStreamingCall<PartialResultSet> ExecuteStreaming(SpannerClient client, CallSettings callSettings); } /// <summary> /// Interface for common properties of <see cref="PartitionReadRequest"/> and <see cref="PartitionQueryRequest"/>. /// </summary> internal interface IPartitionReadOrQueryRequest { /// <summary> /// See <see cref="PartitionReadRequest.Session"/> and <see cref="PartitionQueryRequest.Session"/> /// </summary> SessionName SessionAsSessionName { set; } /// <summary> /// See <see cref="PartitionReadRequest.Transaction"/> and <see cref="PartitionQueryRequest.Transaction"/> /// </summary> TransactionSelector Transaction { set; } /// <summary> /// See <see cref="PartitionReadRequest.PartitionOptions"/> and <see cref="PartitionQueryRequest.PartitionOptions"/> /// </summary> PartitionOptions PartitionOptions { get; set; } /// <summary> /// Executes the partition request using the given client and call settings. /// </summary> /// <param name="client">The client to use to execute the request</param> /// <param name="callSettings">The call settings to use for the invocation</param> /// <returns>The partition response</returns> Task<PartitionResponse> PartitionAsync(SpannerClient client, CallSettings callSettings); } /// <summary> /// Class for common properties of <see cref="ReadRequest"/> and <see cref="ExecuteSqlRequest"/>. /// </summary> public sealed class ReadOrQueryRequest { private IReadOrQueryRequest Request { get; } /// <summary> /// Creates a new ReadOrQueryRequest from an ExecuteSqlRequest. /// </summary> /// <param name="request">The request to wrap in a generic ReadOrQueryRequest</param> /// <returns>A new ReadOrQueryRequest that wraps the given request</returns> public static ReadOrQueryRequest FromQueryRequest(ExecuteSqlRequest request) => FromRequest(request); /// <summary> /// Creates a new ReadOrQueryRequest from an ReadRequest. /// </summary> /// <param name="request">The request to wrap in a generic ReadOrQueryRequest</param> /// <returns>A new ReadOrQueryRequest that wraps the given request</returns> public static ReadOrQueryRequest FromReadRequest(ReadRequest request) => FromRequest(request); internal static ReadOrQueryRequest FromRequest(IReadOrQueryRequest request) => new ReadOrQueryRequest(request); private ReadOrQueryRequest(IReadOrQueryRequest request) => Request = GaxPreconditions.CheckNotNull(request, nameof(request)); /// <summary> /// True if this is query, and false otherwise. /// </summary> public bool IsQuery => Request is ExecuteSqlRequest; /// <summary> /// True if this is a read, and false otherwise. /// </summary> public bool IsRead => Request is ReadRequest; /// <summary> /// The underlying ExecuteSqlRequest if this is a query, and null otherwise. /// </summary> public ExecuteSqlRequest ExecuteSqlRequest => Request as ExecuteSqlRequest; /// <summary> /// The underlying ReadRequest if this is a read, and null otherwise. /// </summary> public ReadRequest ReadRequest => Request as ReadRequest; /// <summary> /// Creates a PartitionReadOrQueryRequest from a ReadOrQueryRequest. /// </summary> /// <returns>A new PartitionReadOrQueryRequest with the properties of the given request</returns> public PartitionReadOrQueryRequest ToPartitionReadOrQueryRequest(long? partitionSizeBytes, long? maxPartitions) { var request = IsQuery ? PartitionReadOrQueryRequest.FromRequest(ToPartitionQueryRequest()) : PartitionReadOrQueryRequest.FromRequest(ToPartitionReadRequest()); request.PartitionOptions = partitionSizeBytes.HasValue || maxPartitions.HasValue ? new PartitionOptions() : null; if (partitionSizeBytes.HasValue) { request.PartitionOptions.PartitionSizeBytes = partitionSizeBytes.Value; } if (maxPartitions.HasValue) { request.PartitionOptions.MaxPartitions = maxPartitions.Value; } return request; } private PartitionQueryRequest ToPartitionQueryRequest() { var request = Request as ExecuteSqlRequest; return new PartitionQueryRequest { Sql = request.Sql, Params = request.Params, ParamTypes = { request.ParamTypes } }; } private PartitionReadRequest ToPartitionReadRequest() { var request = Request as ReadRequest; return new PartitionReadRequest { Table = request.Table, Columns = { request.Columns }, Index = request.Index, KeySet = request.KeySet }; } /// <summary> /// Extracts the corresponding CallSettings for the read or query request from the SpannerSettings. /// </summary> /// <param name="spannerSettings">The SpannerSettings to extract the CallSettings from</param> /// <returns>The CallSettings to use for the request</returns> public CallSettings GetCallSettings(SpannerSettings spannerSettings) => IsQuery ? spannerSettings.ExecuteStreamingSqlSettings : spannerSettings.StreamingReadSettings; /// <summary> /// Returns a ByteString representation of this request. /// </summary> public ByteString ToByteString() => Request.ToByteString(); /// <summary> /// See <see cref="V1.ReadRequest.Clone"/> and <see cref="V1.ExecuteSqlRequest.Clone"/> /// </summary> public ReadOrQueryRequest CloneRequest() => new ReadOrQueryRequest(Request.CloneRequest()); /// <summary> /// See <see cref="V1.Session"/> and <see cref="V1.Session"/> /// </summary> public string Session => Request.Session; /// <summary> /// See <see cref="V1.Session"/> and <see cref="V1.Session"/> /// </summary> public SessionName SessionAsSessionName { set => Request.SessionAsSessionName = value; } /// <summary> /// See <see cref="V1.ReadRequest.Transaction"/> and <see cref="V1.ExecuteSqlRequest.Transaction"/> /// </summary> public TransactionSelector Transaction { set => Request.Transaction = value; } /// <summary> /// See <see cref="V1.ReadRequest.ResumeToken"/> and <see cref="V1.ExecuteSqlRequest.ResumeToken"/> /// </summary> public ByteString ResumeToken { set => Request.ResumeToken = value; } /// <summary> /// See <see cref="V1.ReadRequest.PartitionToken"/> and <see cref="V1.ExecuteSqlRequest.PartitionToken"/> /// </summary> public ByteString PartitionToken { get => Request.PartitionToken; set => Request.PartitionToken = value; } /// <summary> /// Executes the streaming query/read RPC. /// </summary> /// <param name="client">The client to use for the execution</param> /// <param name="callSettings">The call settings to use for the invocation</param> /// <returns>The result stream for the query/read</returns> internal AsyncServerStreamingCall<PartialResultSet> ExecuteStreaming(SpannerClient client, CallSettings callSettings) => Request.ExecuteStreaming(client, callSettings); /// <summary> /// Creates a <see cref="ReliableStreamReader"/> for this request /// </summary> /// <param name="session">The session to use for the request.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A <see cref="ReliableStreamReader"/> for this request.</returns> public ReliableStreamReader ExecuteReadOrQueryStreamReader(PooledSession session, CallSettings callSettings) => session.ExecuteReadOrQueryStreamReader(this, callSettings); /// <inheritdoc/> public override bool Equals(object o) => o is ReadOrQueryRequest request && request.Request.Equals(Request); /// <inheritdoc/> public override int GetHashCode() => Request.GetHashCode(); } /// <summary> /// Class for common properties of <see cref="PartitionReadRequest"/> and <see cref="PartitionQueryRequest"/>. /// </summary> public sealed class PartitionReadOrQueryRequest { private IPartitionReadOrQueryRequest Request { get; } internal static PartitionReadOrQueryRequest FromRequest(IPartitionReadOrQueryRequest request) => new PartitionReadOrQueryRequest(request); private PartitionReadOrQueryRequest(IPartitionReadOrQueryRequest request) => Request = GaxPreconditions.CheckNotNull(request, nameof(request)); /// <summary> /// Extracts the corresponding CallSettings for the partition read or query request from the SpannerSettings. /// </summary> /// <param name="spannerSettings">The SpannerSettings to extract the CallSettings from</param> /// <returns>The CallSettings to use for the request</returns> public CallSettings GetCallSettings(SpannerSettings spannerSettings) => Request is PartitionQueryRequest ? spannerSettings.PartitionQuerySettings : spannerSettings.PartitionReadSettings; /// <summary> /// See <see cref="PartitionReadRequest.Session"/> and <see cref="PartitionQueryRequest.Session"/> /// </summary> public SessionName SessionAsSessionName { set => Request.SessionAsSessionName = value; } /// <summary> /// See <see cref="PartitionReadRequest.Transaction"/> and <see cref="PartitionQueryRequest.Transaction"/> /// </summary> public TransactionSelector Transaction { set => Request.Transaction = value; } /// <summary> /// See <see cref="PartitionReadRequest.PartitionOptions"/> and <see cref="PartitionQueryRequest.PartitionOptions"/> /// </summary> public PartitionOptions PartitionOptions { get => Request.PartitionOptions; set => Request.PartitionOptions = value; } /// <summary> /// Executes the partition request using the given client and call settings. /// </summary> /// <param name="client">The client to use to execute the request</param> /// <param name="callSettings">The call settings to use for the invocation</param> /// <returns>The partition response</returns> internal Task<PartitionResponse> PartitionAsync(SpannerClient client, CallSettings callSettings) => Request.PartitionAsync(client, callSettings); /// <summary> /// Executes a PartitionRead or PartitionQuery RPC asynchronously. /// </summary> /// <param name="session">The session to use for the request.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the asynchronous operation. When the task completes, the result is the response from the RPC.</returns> public Task<PartitionResponse> PartitionReadOrQueryAsync(PooledSession session, CallSettings callSettings) => session.PartitionReadOrQueryAsync(this, callSettings); /// <inheritdoc/> public override bool Equals(object o) => o is PartitionReadOrQueryRequest request && request.Request.Equals(Request); /// <inheritdoc/> public override int GetHashCode() => Request.GetHashCode(); } public sealed partial class ReadRequest : IReadOrQueryRequest { ByteString IReadOrQueryRequest.ToByteString() => this.ToByteString(); IReadOrQueryRequest IReadOrQueryRequest.CloneRequest() => Clone(); AsyncServerStreamingCall<PartialResultSet> IReadOrQueryRequest.ExecuteStreaming( SpannerClient client, CallSettings callSettings) => client.StreamingRead(this, callSettings).GrpcCall; } public sealed partial class ExecuteSqlRequest : IReadOrQueryRequest { ByteString IReadOrQueryRequest.ToByteString() => this.ToByteString(); IReadOrQueryRequest IReadOrQueryRequest.CloneRequest() => Clone(); AsyncServerStreamingCall<PartialResultSet> IReadOrQueryRequest.ExecuteStreaming( SpannerClient client, CallSettings callSettings) => client.ExecuteStreamingSql(this, callSettings).GrpcCall; } public sealed partial class PartitionReadRequest : IPartitionReadOrQueryRequest { Task<PartitionResponse> IPartitionReadOrQueryRequest.PartitionAsync(SpannerClient client, CallSettings callSettings) => client.PartitionReadAsync(this, callSettings); } public sealed partial class PartitionQueryRequest : IPartitionReadOrQueryRequest { Task<PartitionResponse> IPartitionReadOrQueryRequest.PartitionAsync(SpannerClient client, CallSettings callSettings) => client.PartitionQueryAsync(this, callSettings); } }