context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Epi.Fields; using System.Collections; namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs { /// <summary> /// Field definition dialog for option fields /// </summary> public partial class OptionFieldDefinition : GenericFieldDefinition { #region Fields private OptionField field; private List<string> optionList = new List<string>(); private int groupBottom_formBottom; private FontStyle promptStyle = FontStyle.Regular; private FontStyle optionStyle = FontStyle.Regular; #endregion //Fields #region Constructors /// <summary> /// Default Constsructor, for exclusive use by the designer. /// </summary> public OptionFieldDefinition() { InitializeComponent(); ScrapeControlLayout(); } /// <summary> /// Constructor for the class /// </summary> /// <param name="frm">The parent form</param> /// <param name="page">The current page</param> public OptionFieldDefinition(MainForm frm, Page page) : base(frm) { InitializeComponent(); ScrapeControlLayout(); this.mode = FormMode.Create; this.page = page; } private void ScrapeControlLayout() { groupBottom_formBottom = Size.Height - this.optionGroupBox.Bottom; } /// <summary> /// Constructor for the class /// </summary> /// <param name="frm">The parent form</param> /// <param name="field">The fied to be edited</param> public OptionFieldDefinition(MainForm frm, OptionField field) : base(frm) { InitializeComponent(); ScrapeControlLayout(); this.mode = FormMode.Edit; this.field = field; this.page = field.Page; LoadFormData(); } #endregion Constructors #region Private Methods private void LoadFormData() { if (((OptionField)this.field).ShowTextOnRight) { this.textOnRight.Checked = true; } else { this.textOnLeft.Checked = true; } if (((OptionField)this.field).Pattern.Contains(Enums.OptionLayout.Horizontal.ToString())) { this.radioButtonHorizontal.Checked = true; } else { this.radioButtonVertical.Checked = true; } if (((OptionField)this.field).Pattern.Contains(Enums.OptionLayout.Right.ToString())) { this.radioButtonStartOnRight.Checked = true; } else { this.radioButtonStartOnLeft.Checked = true; } optionList.AddRange(((OptionField)this.field).Options); this.optionGroupBox.Controls.Clear(); Configuration config = Configuration.GetNewInstance(); txtPrompt.Text = field.PromptText; txtFieldName.Text = field.Name; // prompt font if (config.Settings.EditorFontBold) { promptStyle |= FontStyle.Bold; } if (config.Settings.EditorFontItalics) { promptStyle |= FontStyle.Italic; } if ((field.PromptFont == null) || ((field.PromptFont.Name == "Microsoft Sans Serif") && (field.PromptFont.Size == 8.5))) { field.PromptFont = new Font(config.Settings.EditorFontName, (float)config.Settings.EditorFontSize, promptStyle); } promptFont = field.PromptFont; // control font if (config.Settings.ControlFontBold) { optionStyle |= FontStyle.Bold; } if (config.Settings.ControlFontItalics) { optionStyle |= FontStyle.Italic; } if ((field.ControlFont == null) || ((field.ControlFont.Name == "Microsoft Sans Serif") && (field.ControlFont.Size == 8.5))) { field.ControlFont = new Font(config.Settings.ControlFontName, (float)config.Settings.ControlFontSize, optionStyle); } controlFont = field.ControlFont; if (field.Options.Count == 0) { this.btnOk.Enabled = false; } if (field.Options.Count < numUpDown.Minimum) { numUpDown.Value = numUpDown.Minimum; } else { numUpDown.Value = field.Options.Count; } LoadRadioButtons((int)numUpDown.Value); } private void LoadRadioButtons(int pTotal ) { foreach (Control control in optionGroupBox.Controls) { if (control is TextBox) { this.optionList.Add(control.Text); } } this.optionGroupBox.Controls.Clear(); this.ResizeRedraw = true; int leftControlX = radioButtonForPositioning.Location.X; int leftControlY; int rightControlX; int rightControlY; if (textOnRight.Checked) { // (O) Words leftControlY = radioButtonForPositioning.Location.Y; rightControlX = textBoxForPositioning.Location.X; rightControlY = textBoxForPositioning.Location.Y; } else { // Words (O) leftControlY = textBoxForPositioning.Location.Y; rightControlX = leftControlX + textBoxForPositioning.Width + 8; rightControlY = radioButtonForPositioning.Location.Y; } if (pTotal > 1) { for (int i = 0; i < pTotal; i++) { RadioButton radioButton = new RadioButton(); TextBox textBox = new TextBox(); radioButton.Size = radioButtonForPositioning.Size; textBox.Size = textBoxForPositioning.Size; if (textOnRight.Checked) { // (O) Words radioButton.Location = new Point(leftControlX, leftControlY); textBox.Location = new Point(rightControlX, rightControlY); } else { // Words (O) radioButton.Location = new Point(rightControlX, rightControlY); textBox.Location = new Point(leftControlX, leftControlY); } if (optionList.Count > 0 && optionList.Count > i) { textBox.Text = optionList[i]; } textBox.TextChanged += new EventHandler(textBox_TextChanged); this.optionGroupBox.Controls.Add(radioButton); this.optionGroupBox.Controls.Add(textBox); leftControlY += textBoxForPositioning.Height + 8; rightControlY += textBoxForPositioning.Height + 8; this.optionGroupBox.Height = textBox.Bottom + 12; } } Size = new Size( Size.Width, optionGroupBox.Bottom + groupBottom_formBottom); btnOk.Location = new Point (btnOk.Location.X, Size.Height - groupBottom_formBottom - btnOk.Height); btnCancel.Location = new Point (btnCancel.Location.X, Size.Height - groupBottom_formBottom - btnCancel.Height); optionList.Clear(); } #endregion //Private Methods #region Public Methods /// <summary> /// Sets the field's properties based on GUI values /// </summary> protected override void SetFieldProperties() { field.PromptText = txtPrompt.Text; field.Name = txtFieldName.Text; field.PromptFont = promptFont; field.ControlFont = controlFont; } /// <summary> /// Gets the field defined by this field definition dialog /// </summary> public override RenderableField Field { get { return field; } } #endregion //Public Methods private void btnOk_Click(object sender, EventArgs e) { foreach (Control control in optionGroupBox.Controls) { if (control is TextBox) { this.optionList.Add(control.Text); } } ((OptionField)field).Options = optionList; ((OptionField)field).ShowTextOnRight = textOnRight.Checked; ((OptionField)field).PromptFont = promptFont; ((OptionField)field).ControlFont = controlFont; string vertHorz = Enums.OptionLayout.Vertical.ToString(); if (radioButtonHorizontal.Checked) { vertHorz = Enums.OptionLayout.Horizontal.ToString(); } string leftRight = Enums.OptionLayout.Left.ToString(); if (radioButtonStartOnRight.Checked) { leftRight = Enums.OptionLayout.Right.ToString(); } ((OptionField)field).Pattern = string.Format("{0},{1}",vertHorz, leftRight); } private void btnCancel_Click(object sender, EventArgs e) { if (this.optionGroupBox.Controls.Count > 0) { this.optionGroupBox.Controls.Clear(); } if (this.optionList.Count > 0) { this.optionList.Clear(); } } private void numUpDown_ValueChanged(object sender, EventArgs e) { LoadRadioButtons((int)numUpDown.Value); EnableDisableButtons(); } private void textOnRight_CheckedChanged(object sender, EventArgs e) { LoadRadioButtons((int)numUpDown.Value); } private void textOnLeft_CheckedChanged(object sender, EventArgs e) { LoadRadioButtons((int)numUpDown.Value); } void textBox_TextChanged(object sender, EventArgs e) { int selIndex = ((TextBox)sender).SelectionStart; ((TextBox)sender).Text = ((TextBox)sender).Text.Replace(",", ""); ((TextBox)sender).SelectionStart = selIndex; EnableDisableButtons(); } private void EnableDisableButtons() { bool enableOK = true; this.txtPrompt.TextChanged -= new System.EventHandler(this.txtPrompt_TextChanged); txtPrompt.Text = txtPrompt.Text.TrimStart(); this.txtPrompt.TextChanged += new System.EventHandler(this.txtPrompt_TextChanged); this.txtFieldName.TextChanged -= new System.EventHandler(this.txtFieldName_TextChanged); txtFieldName.Text = txtFieldName.Text.TrimStart(); this.txtFieldName.TextChanged += new System.EventHandler(this.txtFieldName_TextChanged); foreach (Control control in this.optionGroupBox.Controls) { if (control is TextBox) { control.TextChanged -= new EventHandler(textBox_TextChanged); control.Text = control.Text.TrimStart(); control.TextChanged += new EventHandler(textBox_TextChanged); if (control.Text == string.Empty) enableOK = false; } } if (txtPrompt.Text == string.Empty) enableOK = false; if (txtFieldName.Text == string.Empty) enableOK = false; btnOk.Enabled = enableOK; } private void txtPrompt_TextChanged(object sender, EventArgs e) { EnableDisableButtons(); } private void txtFieldName_TextChanged(object sender, EventArgs e) { EnableDisableButtons(); } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copysecond (c) 2017 Atif Aziz. All seconds reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; static partial class MoreEnumerable { /// <summary> /// Performs a right outer join on two homogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.RightJoin(second, keySelector, secondSelector, bothSelector, null); } /// <summary> /// Performs a right outer join on two homogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector, IEqualityComparer<TKey>? comparer) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.RightJoin(second, keySelector, keySelector, secondSelector, bothSelector, comparer); } /// <summary> /// Performs a right outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector) => first.RightJoin(second, firstKeySelector, secondKeySelector, secondSelector, bothSelector, null); /// <summary> /// Performs a right outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector, IEqualityComparer<TKey>? comparer) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (firstKeySelector == null) throw new ArgumentNullException(nameof(firstKeySelector)); if (secondKeySelector == null) throw new ArgumentNullException(nameof(secondKeySelector)); if (secondSelector == null) throw new ArgumentNullException(nameof(secondSelector)); if (bothSelector == null) throw new ArgumentNullException(nameof(bothSelector)); return second.LeftJoin(first, secondKeySelector, firstKeySelector, secondSelector, (x, y) => bothSelector(y, x), comparer); } } }
using System; using System.Threading; using System.Threading.Tasks; #if __UNIFIED__ using Foundation; using CoreFoundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.CoreFoundation; using MonoTouch.UIKit; #endif namespace ZXing.Mobile { public class MobileBarcodeScanner : MobileBarcodeScannerBase { //ZxingCameraViewController viewController; IScannerViewController viewController; UIViewController appController; ManualResetEvent scanResultResetEvent = new ManualResetEvent(false); public MobileBarcodeScanner (UIViewController delegateController) { appController = delegateController; } public MobileBarcodeScanner () { foreach (var window in UIApplication.SharedApplication.Windows) { if (window.RootViewController != null) { appController = window.RootViewController; break; } } } public Task<Result> Scan (bool useAVCaptureEngine) { return Scan (new MobileBarcodeScanningOptions (), useAVCaptureEngine); } public override Task<Result> Scan (MobileBarcodeScanningOptions options) { return Scan (options, false); } public override void ScanContinuously (MobileBarcodeScanningOptions options, Action<Result> scanHandler) { ScanContinuously (options, false, scanHandler); } public void ScanContinuously (MobileBarcodeScanningOptions options, bool useAVCaptureEngine, Action<Result> scanHandler) { try { Version sv = new Version (0, 0, 0); Version.TryParse (UIDevice.CurrentDevice.SystemVersion, out sv); var is7orgreater = sv.Major >= 7; var allRequestedFormatsSupported = true; if (useAVCaptureEngine) allRequestedFormatsSupported = AVCaptureScannerView.SupportsAllRequestedBarcodeFormats(options.PossibleFormats); this.appController.InvokeOnMainThread(() => { if (useAVCaptureEngine && is7orgreater && allRequestedFormatsSupported) { viewController = new AVCaptureScannerViewController(options, this); viewController.ContinuousScanning = true; } else { if (useAVCaptureEngine && !is7orgreater) Console.WriteLine("Not iOS 7 or greater, cannot use AVCapture for barcode decoding, using ZXing instead"); else if (useAVCaptureEngine && !allRequestedFormatsSupported) Console.WriteLine("Not all requested barcode formats were supported by AVCapture, using ZXing instead"); viewController = new ZXing.Mobile.ZXingScannerViewController(options, this); viewController.ContinuousScanning = true; } viewController.OnScannedResult += barcodeResult => { // If null, stop scanning was called if (barcodeResult == null) { ((UIViewController)viewController).InvokeOnMainThread(() => { ((UIViewController)viewController).DismissViewController(true, null); }); } scanHandler (barcodeResult); }; appController.PresentViewController((UIViewController)viewController, true, null); }); } catch (Exception ex) { Console.WriteLine(ex); } } public Task<Result> Scan (MobileBarcodeScanningOptions options, bool useAVCaptureEngine) { return Task.Factory.StartNew(() => { try { scanResultResetEvent.Reset(); Result result = null; Version sv = new Version (0, 0, 0); Version.TryParse (UIDevice.CurrentDevice.SystemVersion, out sv); var is7orgreater = sv.Major >= 7; var allRequestedFormatsSupported = true; if (useAVCaptureEngine) allRequestedFormatsSupported = AVCaptureScannerView.SupportsAllRequestedBarcodeFormats(options.PossibleFormats); this.appController.InvokeOnMainThread(() => { if (useAVCaptureEngine && is7orgreater && allRequestedFormatsSupported) { viewController = new AVCaptureScannerViewController(options, this); } else { if (useAVCaptureEngine && !is7orgreater) Console.WriteLine("Not iOS 7 or greater, cannot use AVCapture for barcode decoding, using ZXing instead"); else if (useAVCaptureEngine && !allRequestedFormatsSupported) Console.WriteLine("Not all requested barcode formats were supported by AVCapture, using ZXing instead"); viewController = new ZXing.Mobile.ZXingScannerViewController(options, this); } viewController.OnScannedResult += barcodeResult => { ((UIViewController)viewController).InvokeOnMainThread(() => { viewController.Cancel(); // Handle error situation that occurs when user manually closes scanner in the same moment that a QR code is detected try { ((UIViewController) viewController).DismissViewController(true, () => { result = barcodeResult; scanResultResetEvent.Set(); }); } catch (ObjectDisposedException) { // In all likelihood, iOS has decided to close the scanner at this point. But just in case it executes the // post-scan code instead, set the result so we will not get a NullReferenceException. result = barcodeResult; scanResultResetEvent.Set(); } }); }; appController.PresentViewController((UIViewController)viewController, true, null); }); scanResultResetEvent.WaitOne(); ((UIViewController)viewController).Dispose(); return result; } catch (Exception ex) { Console.WriteLine(ex); return null; } }); } public override void Cancel () { if (viewController != null) { ((UIViewController)viewController).InvokeOnMainThread(() => { viewController.Cancel(); // Calling with animated:true here will result in a blank screen when the scanner is closed on iOS 7. ((UIViewController)viewController).DismissViewController(false, null); }); } scanResultResetEvent.Set(); } public override void Torch (bool on) { if (viewController != null) viewController.Torch (on); } public override void ToggleTorch () { viewController.ToggleTorch(); } public override void AutoFocus () { //Does nothing on iOS } public override bool IsTorchOn { get { return viewController.IsTorchOn; } } public UIView CustomOverlay { get;set; } } }
// 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; using System.Reflection; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaskLoadInt32() { var test = new SimpleBinaryOpTest__MaskLoadInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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__MaskLoadInt32 { private struct TestStruct { public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MaskLoadInt32 testClass) { var result = Avx2.MaskLoad((Int32*)testClass._dataTable.inArray1Ptr, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.inArray1Ptr, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static SimpleBinaryOpTest__MaskLoadInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleBinaryOpTest__MaskLoadInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.MaskLoad( (Int32*)_dataTable.inArray1Ptr, Unsafe.Read<Vector128<Int32>>(_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 = Avx2.MaskLoad( (Int32*)_dataTable.inArray1Ptr, Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.MaskLoad( (Int32*)_dataTable.inArray1Ptr, Sse2.LoadAlignedVector128((Int32*)(_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(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(Int32*), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Int32*)), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(Int32*), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Int32*)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(Int32*), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Int32*)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.MaskLoad( (Int32*)_dataTable.inArray1Ptr, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = (Int32*)_dataTable.inArray1Ptr; var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = (Int32*)_dataTable.inArray1Ptr; var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = (Int32*)_dataTable.inArray1Ptr; var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MaskLoadInt32(); var result = Avx2.MaskLoad((Int32*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.MaskLoad((Int32*)_dataTable.inArray1Ptr, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.MaskLoad((Int32*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(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(void* left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((right[0] < 0) ? left[0] : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((right[i] < 0) ? left[i] : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskLoad)}<Int32>(Int32*, Vector128<Int32>): {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) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Tournament.Models; using osuTK; using osuTK.Graphics; using osuTK.Input; using SixLabors.Primitives; namespace osu.Game.Tournament.Screens.Ladder.Components { public class DrawableTournamentMatch : CompositeDrawable { public readonly TournamentMatch Match; private readonly bool editor; protected readonly FillFlowContainer<DrawableMatchTeam> Flow; private readonly Drawable selectionBox; protected readonly Drawable CurrentMatchSelectionBox; private Bindable<TournamentMatch> globalSelection; [Resolved(CanBeNull = true)] private LadderEditorInfo editorInfo { get; set; } [Resolved(CanBeNull = true)] private LadderInfo ladderInfo { get; set; } public DrawableTournamentMatch(TournamentMatch match, bool editor = false) { Match = match; this.editor = editor; AutoSizeAxes = Axes.Both; Margin = new MarginPadding(5); InternalChildren = new[] { selectionBox = new Container { Scale = new Vector2(1.1f), RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Alpha = 0, Colour = Color4.YellowGreen, Child = new Box { RelativeSizeAxes = Axes.Both } }, CurrentMatchSelectionBox = new Container { Scale = new Vector2(1.05f, 1.1f), RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Alpha = 0, Colour = Color4.White, Child = new Box { RelativeSizeAxes = Axes.Both } }, Flow = new FillFlowContainer<DrawableMatchTeam> { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Spacing = new Vector2(2) } }; boundReference(match.Team1).BindValueChanged(_ => updateTeams()); boundReference(match.Team2).BindValueChanged(_ => updateTeams()); boundReference(match.Team1Score).BindValueChanged(_ => updateWinConditions()); boundReference(match.Team2Score).BindValueChanged(_ => updateWinConditions()); boundReference(match.Round).BindValueChanged(_ => { updateWinConditions(); Changed?.Invoke(); }); boundReference(match.Completed).BindValueChanged(_ => updateProgression()); boundReference(match.Progression).BindValueChanged(_ => updateProgression()); boundReference(match.LosersProgression).BindValueChanged(_ => updateProgression()); boundReference(match.Losers).BindValueChanged(_ => { updateTeams(); Changed?.Invoke(); }); boundReference(match.Current).BindValueChanged(_ => updateCurrentMatch(), true); boundReference(match.Position).BindValueChanged(pos => { if (!IsDragged) Position = new Vector2(pos.NewValue.X, pos.NewValue.Y); Changed?.Invoke(); }, true); updateTeams(); } /// <summary> /// Fired when somethign changed that requires a ladder redraw. /// </summary> public Action Changed; private readonly List<IUnbindable> refBindables = new List<IUnbindable>(); private T boundReference<T>(T obj) where T : IBindable { obj = (T)obj.GetBoundCopy(); refBindables.Add(obj); return obj; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); foreach (var b in refBindables) b.UnbindAll(); } private void updateCurrentMatch() { if (Match.Current.Value) CurrentMatchSelectionBox.Show(); else CurrentMatchSelectionBox.Hide(); } private bool selected; public bool Selected { get => selected; set { if (value == selected) return; selected = value; if (selected) { selectionBox.Show(); if (editor) editorInfo.Selected.Value = Match; else ladderInfo.CurrentMatch.Value = Match; } else selectionBox.Hide(); } } private void updateProgression() { if (!Match.Completed.Value) { // ensure we clear any of our teams from our progression. // this is not pretty logic but should suffice for now. if (Match.Progression.Value != null && Match.Progression.Value.Team1.Value == Match.Team1.Value) Match.Progression.Value.Team1.Value = null; if (Match.Progression.Value != null && Match.Progression.Value.Team2.Value == Match.Team2.Value) Match.Progression.Value.Team2.Value = null; if (Match.LosersProgression.Value != null && Match.LosersProgression.Value.Team1.Value == Match.Team1.Value) Match.LosersProgression.Value.Team1.Value = null; if (Match.LosersProgression.Value != null && Match.LosersProgression.Value.Team2.Value == Match.Team2.Value) Match.LosersProgression.Value.Team2.Value = null; } else { transferProgression(Match.Progression?.Value, Match.Winner); transferProgression(Match.LosersProgression?.Value, Match.Loser); } Changed?.Invoke(); } private void transferProgression(TournamentMatch destination, TournamentTeam team) { if (destination == null) return; bool progressionAbove = destination.ID < Match.ID; Bindable<TournamentTeam> destinationTeam; // check for the case where we have already transferred out value if (destination.Team1.Value == team) destinationTeam = destination.Team1; else if (destination.Team2.Value == team) destinationTeam = destination.Team2; else { destinationTeam = progressionAbove ? destination.Team2 : destination.Team1; if (destinationTeam.Value != null) destinationTeam = progressionAbove ? destination.Team1 : destination.Team2; } destinationTeam.Value = team; } private void updateWinConditions() { if (Match.Round.Value == null) return; var instaWinAmount = Match.Round.Value.BestOf.Value / 2; Match.Completed.Value = Match.Round.Value.BestOf.Value > 0 && (Match.Team1Score.Value + Match.Team2Score.Value >= Match.Round.Value.BestOf.Value || Match.Team1Score.Value > instaWinAmount || Match.Team2Score.Value > instaWinAmount); } protected override void LoadComplete() { base.LoadComplete(); updateTeams(); if (editorInfo != null) { globalSelection = editorInfo.Selected.GetBoundCopy(); globalSelection.BindValueChanged(s => { if (s.NewValue != Match) Selected = false; }); } } private void updateTeams() { if (LoadState != LoadState.Loaded) return; // todo: teams may need to be bindable for transitions at a later point. if (Match.Team1.Value == null || Match.Team2.Value == null) Match.CancelMatchStart(); if (Match.ConditionalMatches.Count > 0) { foreach (var conditional in Match.ConditionalMatches) { var team1Match = conditional.Acronyms.Contains(Match.Team1Acronym); var team2Match = conditional.Acronyms.Contains(Match.Team2Acronym); if (team1Match && team2Match) Match.Date.Value = conditional.Date.Value; } } Flow.Children = new[] { new DrawableMatchTeam(Match.Team1.Value, Match, Match.Losers.Value), new DrawableMatchTeam(Match.Team2.Value, Match, Match.Losers.Value) }; SchedulerAfterChildren.Add(() => Scheduler.Add(updateProgression)); updateWinConditions(); } protected override bool OnMouseDown(MouseDownEvent e) => e.Button == MouseButton.Left && editorInfo != null; protected override bool OnDragStart(DragStartEvent e) => editorInfo != null; protected override bool OnKeyDown(KeyDownEvent e) { if (Selected && editorInfo != null && e.Key == Key.Delete) { Remove(); return true; } return base.OnKeyDown(e); } protected override bool OnClick(ClickEvent e) { if (editorInfo == null || Match is ConditionalTournamentMatch) return false; Selected = true; return true; } protected override void OnDrag(DragEvent e) { base.OnDrag(e); Selected = true; this.MoveToOffset(e.Delta); var pos = Position; Match.Position.Value = new Point((int)pos.X, (int)pos.Y); } public void Remove() { Selected = false; Match.Progression.Value = null; Match.LosersProgression.Value = null; ladderInfo.Matches.Remove(Match); } } }
/* * Copyright (c) 2007-2008, Second Life Reverse Engineering Team * 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. * - Neither the name of the Second Life Reverse Engineering Team 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. */ /* * * This implementation is based upon the description at * * http://wiki.secondlife.com/wiki/LLSD * * and (partially) tested against the (supposed) reference implementation at * * http://svn.secondlife.com/svn/linden/release/indra/lib/python/indra/base/llsd.py * */ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Text; namespace libsecondlife.StructuredData { /// <summary> /// /// </summary> public static partial class LLSDParser { private const int initialBufferSize = 128; private const int int32Length = 4; private const int doubleLength = 8; private static byte[] binaryHead = Encoding.ASCII.GetBytes( "<?llsd/binary?>\n" ); private const byte undefBinaryValue = (byte)'!'; private const byte trueBinaryValue = (byte) '1'; private const byte falseBinaryValue = (byte) '0'; private const byte integerBinaryMarker = (byte) 'i'; private const byte realBinaryMarker = (byte) 'r'; private const byte uuidBinaryMarker = (byte) 'u'; private const byte binaryBinaryMarker = (byte) 'b'; private const byte stringBinaryMarker = (byte) 's'; private const byte uriBinaryMarker = (byte) 'l'; private const byte dateBinaryMarker = (byte) 'd'; private const byte arrayBeginBinaryMarker = (byte) '['; private const byte arrayEndBinaryMarker = (byte) ']'; private const byte mapBeginBinaryMarker = (byte) '{'; private const byte mapEndBinaryMarker = (byte) '}'; private const byte keyBinaryMarker = (byte) 'k'; /// <summary> /// /// </summary> /// <param name="binaryData"></param> /// <returns></returns> public static LLSD DeserializeBinary(byte[] binaryData) { MemoryStream stream = new MemoryStream( binaryData ); LLSD llsd = DeserializeBinary( stream ); stream.Close(); return llsd; } /// <summary> /// /// </summary> /// <param name="stream"></param> /// <returns></returns> public static LLSD DeserializeBinary( MemoryStream stream ) { SkipWhiteSpace( stream ); bool result = FindByteArray( stream, binaryHead ); if ( !result ) throw new LLSDException( "No binary encoded LLSD." ); return ParseBinaryElement( stream ); } /// <summary> /// /// </summary> /// <param name="llsd"></param> /// <returns></returns> public static byte[] SerializeBinary(LLSD llsd) { MemoryStream stream = SerializeBinaryStream( llsd ); byte[] binaryData = stream.ToArray(); stream.Close(); return binaryData; } /// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public static MemoryStream SerializeBinaryStream(LLSD data) { MemoryStream stream = new MemoryStream( initialBufferSize ); stream.Write( binaryHead, 0, binaryHead.Length ); SerializeBinaryElement( stream, data ); return stream; } private static void SerializeBinaryElement( MemoryStream stream, LLSD llsd ) { switch( llsd.Type ) { case LLSDType.Unknown: stream.WriteByte( undefBinaryValue ); break; case LLSDType.Boolean: stream.Write( llsd.AsBinary(), 0, 1 ); break; case LLSDType.Integer: stream.WriteByte( integerBinaryMarker ); stream.Write( llsd.AsBinary(), 0, int32Length ); break; case LLSDType.Real: stream.WriteByte( realBinaryMarker ); stream.Write( llsd.AsBinary(), 0, doubleLength ); break; case LLSDType.UUID: stream.WriteByte( uuidBinaryMarker ); stream.Write( llsd.AsBinary(), 0, 16 ); break; case LLSDType.String: stream.WriteByte( stringBinaryMarker ); byte[] rawString = llsd.AsBinary(); byte[] stringLengthNetEnd = HostToNetworkIntBytes( rawString.Length ); stream.Write( stringLengthNetEnd, 0, int32Length ); stream.Write( rawString, 0, rawString.Length ); break; case LLSDType.Binary: stream.WriteByte( binaryBinaryMarker ); byte[] rawBinary = llsd.AsBinary(); byte[] binaryLengthNetEnd = HostToNetworkIntBytes( rawBinary.Length ); stream.Write( binaryLengthNetEnd, 0, int32Length ); stream.Write( rawBinary, 0, rawBinary.Length ); break; case LLSDType.Date: stream.WriteByte( dateBinaryMarker ); stream.Write( llsd.AsBinary(), 0, doubleLength ); break; case LLSDType.URI: stream.WriteByte( uriBinaryMarker ); byte[] rawURI = llsd.AsBinary(); byte[] uriLengthNetEnd = HostToNetworkIntBytes( rawURI.Length ); stream.Write( uriLengthNetEnd, 0, int32Length ); stream.Write( rawURI, 0, rawURI.Length ); break; case LLSDType.Array: SerializeBinaryArray( stream, (LLSDArray)llsd ); break; case LLSDType.Map: SerializeBinaryMap( stream, (LLSDMap)llsd ); break; default: throw new LLSDException( "Binary serialization: Not existing element discovered." ); } } private static void SerializeBinaryArray( MemoryStream stream, LLSDArray llsdArray ) { stream.WriteByte( arrayBeginBinaryMarker ); byte[] binaryNumElementsHostEnd = HostToNetworkIntBytes( llsdArray.Count ); stream.Write( binaryNumElementsHostEnd, 0, int32Length ); foreach( LLSD llsd in llsdArray ) { SerializeBinaryElement( stream, llsd ); } stream.WriteByte( arrayEndBinaryMarker ); } private static void SerializeBinaryMap( MemoryStream stream, LLSDMap llsdMap ) { stream.WriteByte( mapBeginBinaryMarker ); byte[] binaryNumElementsNetEnd = HostToNetworkIntBytes( llsdMap.Count ); stream.Write( binaryNumElementsNetEnd, 0, int32Length ); foreach( KeyValuePair<string, LLSD> kvp in llsdMap ) { stream.WriteByte( keyBinaryMarker ); byte[] binaryKey = Encoding.UTF8.GetBytes( kvp.Key ); byte[] binaryKeyLength = HostToNetworkIntBytes( binaryKey.Length ); stream.Write( binaryKeyLength, 0, int32Length ); stream.Write( binaryKey, 0, binaryKey.Length ); SerializeBinaryElement( stream, kvp.Value ); } stream.WriteByte( mapEndBinaryMarker ); } private static LLSD ParseBinaryElement(MemoryStream stream) { SkipWhiteSpace( stream ); LLSD llsd; int marker = stream.ReadByte(); if ( marker < 0 ) throw new LLSDException( "Binary LLSD parsing:Unexpected end of stream." ); switch( (byte)marker ) { case undefBinaryValue: llsd = new LLSD(); break; case trueBinaryValue: llsd = LLSD.FromBoolean( true ); break; case falseBinaryValue: llsd = LLSD.FromBoolean( false ); break; case integerBinaryMarker: int integer = NetworkToHostInt( ConsumeBytes( stream, int32Length )); llsd = LLSD.FromInteger( integer ); break; case realBinaryMarker: double dbl = NetworkToHostDouble( ConsumeBytes( stream, doubleLength )); llsd = LLSD.FromReal( dbl ); break; case uuidBinaryMarker: llsd = LLSD.FromUUID( new LLUUID( ConsumeBytes( stream, 16 ), 0)); break; case binaryBinaryMarker: int binaryLength = NetworkToHostInt( ConsumeBytes( stream, int32Length )); llsd = LLSD.FromBinary( ConsumeBytes( stream, binaryLength )); break; case stringBinaryMarker: int stringLength = NetworkToHostInt( ConsumeBytes( stream, int32Length )); string ss = Encoding.UTF8.GetString( ConsumeBytes( stream, stringLength )); llsd = LLSD.FromString( ss ); break; case uriBinaryMarker: int uriLength = NetworkToHostInt( ConsumeBytes( stream, int32Length )); string sUri = Encoding.UTF8.GetString( ConsumeBytes( stream, uriLength )); Uri uri; try { uri = new Uri( sUri, UriKind.RelativeOrAbsolute ); } catch { throw new LLSDException( "Binary LLSD parsing: Invalid Uri format detected." ); } llsd = LLSD.FromUri( uri ); break; case dateBinaryMarker: double timestamp = NetworkToHostDouble( ConsumeBytes( stream, doubleLength )); DateTime dateTime = DateTime.SpecifyKind( Helpers.Epoch, DateTimeKind.Utc ); dateTime = dateTime.AddSeconds(timestamp); llsd = LLSD.FromDate( dateTime.ToLocalTime() ); break; case arrayBeginBinaryMarker: llsd = ParseBinaryArray( stream ); break; case mapBeginBinaryMarker: llsd = ParseBinaryMap( stream ); break; default: throw new LLSDException( "Binary LLSD parsing: Unknown type marker." ); } return llsd; } private static LLSD ParseBinaryArray(MemoryStream stream) { int numElements = NetworkToHostInt( ConsumeBytes( stream, int32Length )); int crrElement = 0; LLSDArray llsdArray = new LLSDArray(); while ( crrElement < numElements ) { llsdArray.Add( ParseBinaryElement( stream )); crrElement++; } if ( !FindByte( stream, arrayEndBinaryMarker )) throw new LLSDException( "Binary LLSD parsing: Missing end marker in array." ); return (LLSD)llsdArray; } private static LLSD ParseBinaryMap(MemoryStream stream) { int numElements = NetworkToHostInt( ConsumeBytes( stream, int32Length )); int crrElement = 0; LLSDMap llsdMap = new LLSDMap(); while( crrElement < numElements ) { if (!FindByte( stream, keyBinaryMarker )) throw new LLSDException( "Binary LLSD parsing: Missing key marker in map." ); int keyLength = NetworkToHostInt( ConsumeBytes( stream, int32Length )); string key = Encoding.UTF8.GetString( ConsumeBytes( stream, keyLength )); llsdMap[key] = ParseBinaryElement( stream ); crrElement++; } if ( !FindByte( stream, mapEndBinaryMarker )) throw new LLSDException( "Binary LLSD parsing: Missing end marker in map." ); return (LLSD)llsdMap; } /// <summary> /// /// </summary> /// <param name="stream"></param> public static void SkipWhiteSpace(MemoryStream stream) { int bt; while ( ((bt = stream.ReadByte()) > 0) && ( (byte)bt == ' ' || (byte)bt == '\t' || (byte)bt == '\n' || (byte)bt == '\r' ) ) { } stream.Seek( -1, SeekOrigin.Current ); } /// <summary> /// /// </summary> /// <param name="stream"></param> /// <param name="toFind"></param> /// <returns></returns> public static bool FindByte( MemoryStream stream, byte toFind ) { int bt = stream.ReadByte(); if ( bt < 0 ) return false; if ( (byte)bt == toFind ) return true; else { stream.Seek( -1L, SeekOrigin.Current ); return false; } } /// <summary> /// /// </summary> /// <param name="stream"></param> /// <param name="toFind"></param> /// <returns></returns> public static bool FindByteArray( MemoryStream stream, byte[] toFind ) { int lastIndexToFind = toFind.Length - 1; int crrIndex = 0; bool found = true; int bt; long lastPosition = stream.Position; while( found && ((bt = stream.ReadByte()) > 0) && (crrIndex <= lastIndexToFind) ) { if ( toFind[crrIndex] == (byte)bt ) { found = true; crrIndex++; } else found = false; } if ( found && crrIndex > lastIndexToFind ) { stream.Seek( -1L, SeekOrigin.Current ); return true; } else { stream.Position = lastPosition; return false; } } /// <summary> /// /// </summary> /// <param name="stream"></param> /// <param name="consumeBytes"></param> /// <returns></returns> public static byte[] ConsumeBytes( MemoryStream stream, int consumeBytes ) { byte[] bytes = new byte[consumeBytes]; if (stream.Read( bytes, 0, consumeBytes ) < consumeBytes ) throw new LLSDException( "Binary LLSD parsing: Unexpected end of stream." ); return bytes; } /// <summary> /// /// </summary> /// <param name="binaryNetEnd"></param> /// <returns></returns> public static int NetworkToHostInt( byte[] binaryNetEnd ) { if ( binaryNetEnd == null ) return -1; int intNetEnd = BitConverter.ToInt32( binaryNetEnd, 0 ); int intHostEnd = System.Net.IPAddress.NetworkToHostOrder( intNetEnd ); return intHostEnd; } /// <summary> /// /// </summary> /// <param name="binaryNetEnd"></param> /// <returns></returns> public static double NetworkToHostDouble( byte[] binaryNetEnd ) { if ( binaryNetEnd == null ) return -1d; long longNetEnd = BitConverter.ToInt64( binaryNetEnd, 0 ); long longHostEnd = System.Net.IPAddress.NetworkToHostOrder( longNetEnd ); byte[] binaryHostEnd = BitConverter.GetBytes( longHostEnd ); double doubleHostEnd = BitConverter.ToDouble( binaryHostEnd, 0 ); return doubleHostEnd; } /// <summary> /// /// </summary> /// <param name="intHostEnd"></param> /// <returns></returns> public static byte[] HostToNetworkIntBytes( int intHostEnd ) { int intNetEnd = System.Net.IPAddress.HostToNetworkOrder( intHostEnd ); byte[] bytesNetEnd = BitConverter.GetBytes( intNetEnd ); return bytesNetEnd; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Xunit; namespace Microsoft.Build.UnitTests.OM.Definition { /// <summary> /// Tests around editing elements that are referenced by others or the ones that references others. /// </summary> public class EditingElementsReferencedByOrReferences_Tests { /// <summary> /// Changes the item type on an item used with the at operator. /// </summary> [Fact] public void ChangeItemTypeInReferencedItem() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <I Include=""X"" /> <I Include=""@(I);Y"" /> </ItemGroup> </Project>"); ProjectItem item = project.GetItems("I").Where(i => i.UnevaluatedInclude == "X").First(); item.ItemType = "J"; string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <J Include=""X"" /> <I Include=""@(I);Y"" /> </ItemGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); project.ReevaluateIfNecessary(); IEnumerable<ProjectItem> items = project.GetItems("I"); Assert.Single(items); // "Wrong number of items after changing type" Assert.Equal("Y", items.First().EvaluatedInclude); // "Wrong evaluated include after changing type" } /// <summary> /// Removes an item in a ; separated list. It blows up the list. /// </summary> [Fact] public void RemoveItemInList() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <I Include=""X"" /> <I Include=""@(I);Y;Z"" /> </ItemGroup> </Project>"); ProjectItem item = project.GetItems("I").Where(i => i.EvaluatedInclude == "Y").First(); project.RemoveItem(item); string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <I Include=""X"" /> <I Include=""X"" /> <I Include=""Z"" /> </ItemGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); } /// <summary> /// Renames an item in a ; separated list. It blows up the list. /// </summary> [Fact] public void RenameItemInList() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <I Include=""X"" /> <I Include=""@(I);Y"" /> </ItemGroup> </Project>"); ProjectItem item = project.GetItems("I").Where(i => i.EvaluatedInclude == "Y").First(); item.Rename("Z"); string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <I Include=""X"" /> <I Include=""X"" /> <I Include=""Z"" /> </ItemGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); } /// <summary> /// Removes metadata duplicated in item. /// </summary> [Fact] public void RemoveMetadata1() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemDefinitionGroup> <I> <M>A</M> </I> </ItemDefinitionGroup> <ItemGroup> <I Include=""X""> <M>%(M);B</M> <M>%(M);C</M> </I> <I Include=""Y""> <M>%(M);D</M> </I> </ItemGroup> </Project>"); ProjectItem item1 = project.GetItems("I").Where(i => i.EvaluatedInclude == "X").First(); Assert.Equal("A;B;C", item1.GetMetadataValue("M")); // "Invalid metadata at start" ProjectItem item2 = project.GetItems("I").Where(i => i.EvaluatedInclude == "Y").First(); Assert.Equal("A;D", item2.GetMetadataValue("M")); // "Invalid metadata at start" item1.RemoveMetadata("M"); string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemDefinitionGroup> <I> <M>A</M> </I> </ItemDefinitionGroup> <ItemGroup> <I Include=""X""> <M>%(M);B</M> </I> <I Include=""Y""> <M>%(M);D</M> </I> </ItemGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); } /// <summary> /// Removes duplicated metadata and checks evaluation. /// </summary> [Fact] public void RemoveMetadata2() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemDefinitionGroup> <I> <M>A</M> </I> </ItemDefinitionGroup> <ItemGroup> <I Include=""X""> <M>%(M);B</M> <M>%(M);C</M> </I> <I Include=""Y""> <M>%(M);D</M> </I> </ItemGroup> </Project>"); ProjectItem item1 = project.GetItems("I").Where(i => i.EvaluatedInclude == "X").First(); item1.RemoveMetadata("M"); string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemDefinitionGroup> <I> <M>A</M> </I> </ItemDefinitionGroup> <ItemGroup> <I Include=""X""> <M>%(M);B</M> </I> <I Include=""Y""> <M>%(M);D</M> </I> </ItemGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); project.ReevaluateIfNecessary(); item1 = project.GetItems("I").Where(i => i.EvaluatedInclude == "X").First(); Assert.Equal("A;B", item1.GetMetadataValue("M")); // "Invalid metadata after first removal" ProjectItem item2 = project.GetItems("I").Where(i => i.EvaluatedInclude == "Y").First(); Assert.Equal("A;D", item2.GetMetadataValue("M")); // "Invalid metadata after first removal" } /// <summary> /// Removes metadata but still keep inherited one from item definition. /// </summary> [Fact] public void RemoveMetadata3() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemDefinitionGroup> <I> <M>A</M> </I> </ItemDefinitionGroup> <ItemGroup> <I Include=""X""> <M>%(M);B</M> <M>%(M);C</M> </I> <I Include=""Y""> <M>%(M);D</M> </I> </ItemGroup> </Project>"); ProjectItem item1 = project.GetItems("I").Where(i => i.EvaluatedInclude == "X").First(); item1.RemoveMetadata("M"); project.ReevaluateIfNecessary(); ProjectItem item2 = project.GetItems("I").Where(i => i.EvaluatedInclude == "Y").First(); item2.RemoveMetadata("M"); string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemDefinitionGroup> <I> <M>A</M> </I> </ItemDefinitionGroup> <ItemGroup> <I Include=""X""> <M>%(M);B</M> </I> <I Include=""Y"" /> </ItemGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); project.ReevaluateIfNecessary(); item1 = project.GetItems("I").Where(i => i.EvaluatedInclude == "X").First(); Assert.Equal("A;B", item1.GetMetadataValue("M")); // "Invalid metadata after second removal" item2 = project.GetItems("I").Where(i => i.EvaluatedInclude == "Y").First(); Assert.Equal("A", item2.GetMetadataValue("M")); // "Invalid metadata after second removal" } /// <summary> /// Removes metadata referenced with % qualification. /// </summary> [Fact] public void RemoveReferencedMetadata() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <I Include=""i""> <M>m</M> <N>%(I.M)</N> </I> </ItemGroup> </Project>"); ProjectItem item = project.GetItems("I").First(); Assert.Equal("m", item.GetMetadataValue("N")); // "Wrong metadata value at startup" item.RemoveMetadata("M"); string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <I Include=""i""> <N>%(I.M)</N> </I> </ItemGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); project.ReevaluateIfNecessary(); item = project.GetItems("I").First(); ProjectMetadata metadata = item.GetMetadata("N"); Assert.Equal("%(I.M)", metadata.UnevaluatedValue); // "Unevaluated value is wrong" Assert.Equal(String.Empty, metadata.EvaluatedValue); // "Evaluated value is wrong" } /// <summary> /// Removes duplicated property. /// </summary> [Fact] public void RemoveProperty() { Project project = GetProject( @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <P>A</P> <P>$(P)B</P> </PropertyGroup> </Project>"); ProjectProperty property = project.GetProperty("P"); project.RemoveProperty(property); string expected = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <P>A</P> </PropertyGroup> </Project>"; Helpers.VerifyAssertProjectContent(expected, project.Xml, false); } /// <summary> /// Creates a new project the given contents. /// </summary> /// <param name="contents">The contents for the project.</param> /// <returns>The project contents.</returns> private Project GetProject(string contents) { return new Project(XmlReader.Create(new StringReader(contents))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; public class StringCtor5 { #region const define private const int c_MIN_STRING_LEN = 1; private const int c_MAX_STRING_LEN = 256; #endregion public static int Main(string[] args) { StringCtor5 sc = new StringCtor5(); TestLibrary.TestFramework.BeginTestCase("StringCtor_charArray_Int32_Int32"); if (sc.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation(""); TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; return retVal; } /// <summary> /// /// </summary> /// <returns></returns> public bool PosTest1() { bool retVal = true; string str = TestLibrary.Generator.GetString(-55, true, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario("Generate a string with valid index and length!"); char[] charArray = new char[str.Length]; str.CopyTo(0, charArray, 0, charArray.Length); try { //char[] charsArray = null; string strGen = new string(charArray, 0, charArray.Length); if (strGen != str) { TestLibrary.TestFramework.LogError("001", "The new generated string is not uqual to the original one!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected Error :" + e); retVal = false; } return retVal; } /// <summary> /// Generate a string with max range index and zero length /// </summary> /// <returns></returns> public bool PosTest2() { bool retVal = true; string str = TestLibrary.Generator.GetString(-55, true, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario("Generate a string with max index and zero length..."); char[] charArray = new char[str.Length]; str.CopyTo(0, charArray, 0, charArray.Length); try { string strGen = new string(charArray, charArray.Length, 0); if (strGen != str.Substring(charArray.Length, 0)) { TestLibrary.TestFramework.LogError("003", "sdfsadfsa"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected Exception occurs : " + e); retVal = false; } return retVal; } /// <summary> /// Generate string with max-1 index and valid length... /// </summary> /// <returns></returns> public bool PosTest3() { bool retVal = true; string str = TestLibrary.Generator.GetString(-55, true, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario("Generate string with max-1 index and valid length..."); char[] charArray = new char[str.Length]; str.CopyTo(0, charArray, 0, charArray.Length); try { string strGen = new string(charArray, charArray.Length - 1, 1); if (strGen != str.Substring(charArray.Length - 1, 1)) { TestLibrary.TestFramework.LogError("005", "The new generated sring is not the expected one!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected Expection occurs :" + e); retVal = false; } return retVal; } /// <summary> /// Negtest1: Generate a string with a null charArray /// </summary> /// <returns></returns> public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Negtest1: Generate a string with a null charArray"); try { char[] charArray = null; string str = new string(charArray, 0, 0); TestLibrary.TestFramework.LogError("007", "The new string can be generated by using a charArray with null value!!"); retVal = false; } catch (ArgumentNullException) { TestLibrary.TestFramework.LogInformation("ArgumentNullException is thrown when pass charArray with null value!"); } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected Error :" + e); retVal = false; } return retVal; } /// <summary> /// NegTest2: Generate string with max+1 index... /// </summary> /// <returns></returns> public bool NegTest2() { bool retVal = true; string str = TestLibrary.Generator.GetString(-55, true, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario("NegTest2: Generate string with max+1 index..."); char[] charArray = new char[str.Length]; str.CopyTo(0, charArray, 0, charArray.Length); try { string strGen = new string(charArray, charArray.Length + 1, 0); TestLibrary.TestFramework.LogError("009", "The string is generated with no exception occures!"); retVal = false; } catch (ArgumentOutOfRangeException) { TestLibrary.TestFramework.LogInformation("ArgumentOutOfRangeException is thrown when the index param is max+1!"); } catch (Exception e) { TestLibrary.TestFramework.LogError("00X", "Unexpected Exception occurs :" + e); retVal = false; } return retVal; } /// <summary> /// NegTest3: Generate string with max+1 length... /// </summary> /// <returns></returns> public bool NegTest3() { bool retVal = true; string str = TestLibrary.Generator.GetString(-55, true, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario("NegTest3: Generate string with max+1 length..."); char[] charArray = new char[str.Length]; str.CopyTo(0, charArray, 0, charArray.Length); try { string strGen = new string(charArray, 0, charArray.Length + 1); TestLibrary.TestFramework.LogError("010", "The string is generated with no exception occurs!"); retVal = false; } catch (ArgumentOutOfRangeException) { TestLibrary.TestFramework.LogInformation("ArgumentOutOfRangeException is thrown when the length param is max+1"); } catch (Exception e) { TestLibrary.TestFramework.LogError("011", "Unexpected Exception occurs :" + e); retVal = false; } return retVal; } /// <summary> /// NegTest4: Generate string when index with minus value... /// </summary> /// <returns></returns> public bool NegTest4() { bool retVal = true; string str = TestLibrary.Generator.GetString(-55, true, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario("NegTest4: Generate string when index with minus value..."); char[] charArray = new char[str.Length]; str.CopyTo(0, charArray, 0, charArray.Length); try { string strGen = new string(charArray, -1, charArray.Length); TestLibrary.TestFramework.LogError("012", "The string is generated with no exception occurs!"); retVal = false; } catch (ArgumentOutOfRangeException) { TestLibrary.TestFramework.LogInformation("ArgumentOutOfRangeException is thrown when the index param is minus"); } catch (Exception e) { TestLibrary.TestFramework.LogError("013", "Unexpected Exception occurs :" + e); retVal = false; } return retVal; } /// <summary> /// NegTest4: Generate string when index with minus value... /// </summary> /// <returns></returns> public bool NegTest5() { bool retVal = true; string str = TestLibrary.Generator.GetString(-55, true, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario("NegTest4: Generate string when index with minus value..."); char[] charArray = new char[str.Length]; str.CopyTo(0, charArray, 0, charArray.Length); try { string strGen = new string(charArray, 0, -1); TestLibrary.TestFramework.LogError("013", "The string is generated with no exception occurs!"); retVal = false; } catch (ArgumentOutOfRangeException) { TestLibrary.TestFramework.LogInformation("ArgumentOutOfRangeException is thrown when index is minus!"); } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected Exception occurs :" + e); retVal = false; } return retVal; } }
using System; using System.Collections; namespace TidyNet { /// <summary> /// Tidy options. /// /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.cs for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// /// </summary> /// <author>Dave Raggett &lt;[email protected]&gt;</author> /// <author>Andy Quick &lt;[email protected]&gt; (translation to Java)</author> /// <author>Seth Yates &lt;[email protected]&gt; (translation to C#)</author> /// <version>1.0, 1999/05/22</version> /// <version>1.0.1, 1999/05/29</version> /// <version>1.1, 1999/06/18 Java Bean</version> /// <version>1.2, 1999/07/10 Tidy Release 7 Jul 1999</version> /// <version>1.3, 1999/07/30 Tidy Release 26 Jul 1999</version> /// <version>1.4, 1999/09/04 DOM support</version> /// <version>1.5, 1999/10/23 Tidy Release 27 Sep 1999</version> /// <version>1.6, 1999/11/01 Tidy Release 22 Oct 1999</version> /// <version>1.7, 1999/12/06 Tidy Release 30 Nov 1999</version> /// <version>1.8, 2000/01/22 Tidy Release 13 Jan 2000</version> /// <version>1.9, 2000/06/03 Tidy Release 30 Apr 2000</version> /// <version>1.10, 2000/07/22 Tidy Release 8 Jul 2000</version> /// <version>1.11, 2000/08/16 Tidy Release 4 Aug 2000</version> public class TidyOptions { /// <summary> /// Default constructor. /// </summary> /// <param name="configuration"></param> public TidyOptions() { } /// <summary>Default indentation</summary> public virtual int Spaces { get { return _spaces; } set { _spaces = value; } } /// <summary>Default wrap margin</summary> public virtual int WrapLen { get { return _wrapLen; } set { _wrapLen = value; } } /// <summary>Character Encoding</summary> public virtual CharEncoding CharEncoding { get { return _charEncoding; } set { _charEncoding = value; } } /// <summary>Tab size</summary> public virtual int TabSize { get { return _tabSize; } set { _tabSize = value; } } /// <summary>Indent content of appropriate tags</summary> public virtual bool IndentContent { get { return _indentContent; } set { _indentContent = value; } } /// <summary>Does text/block level content affect indentation</summary> public virtual bool SmartIndent { get { return _smartIndent; } set { _smartIndent = value; } } /// <summary>Suppress optional end tags</summary> public virtual bool HideEndTags { get { return _hideEndTags; } set { _hideEndTags = value; } } /// <summary>Treat input as XML</summary> public virtual bool XmlTags { get { return _xmlTags; } set { _xmlTags = value; } } /// <summary>Create output as XML</summary> public virtual bool XmlOut { get { return _xmlOut; } set { _xmlOut = value; } } /// <summary>Output XHTML</summary> public virtual bool Xhtml { get { return _xhtml; } set { _xhtml = value; } } /// <summary>Avoid mapping values > 127 to entities</summary> public virtual bool RawOut { get { return _rawOut; } set { _rawOut = value; } } /// <summary>Output tags in upper not lower case</summary> public virtual bool UpperCaseTags { get { return _upperCaseTags; } set { _upperCaseTags = value; } } /// <summary>Output attributes in upper not lower case</summary> public virtual bool UpperCaseAttrs { get { return _upperCaseAttrs; } set { _upperCaseAttrs = value; } } /// <summary>Remove presentational clutter</summary> public virtual bool MakeClean { get { return _makeClean; } set { _makeClean = value; } } /// <summary>O/p newline before &lt;br&gt; or not?</summary> public virtual bool BreakBeforeBR { get { return _breakBeforeBR; } set { _breakBeforeBR = value; } } /// <summary>Create slides on each h2 element</summary> public virtual bool BurstSlides { get { return _burstSlides; } set { _burstSlides = value; } } /// <summary>Use numeric entities</summary> public virtual bool NumEntities { get { return _numEntities; } set { _numEntities = value; } } /// <summary>Output " marks as &amp;quot;</summary> public virtual bool QuoteMarks { get { return _quoteMarks; } set { _quoteMarks = value; } } /// <summary>Output non-breaking space as entity</summary> public virtual bool QuoteNbsp { get { return _quoteNbsp; } set { _quoteNbsp = value; } } /// <summary>Output naked ampersand as &amp;</summary> public virtual bool QuoteAmpersand { get { return _quoteAmpersand; } set { _quoteAmpersand = value; } } /// <summary>Wrap within attribute values</summary> public virtual bool WrapAttVals { get { return _wrapAttVals; } set { _wrapAttVals = value; } } /// <summary>Wrap within JavaScript string literals</summary> public virtual bool WrapScriptlets { get { return _wrapScriptlets; } set { _wrapScriptlets = value; } } /// <summary>Wrap within &lt;![ ... ]&gt; section tags</summary> public virtual bool WrapSection { get { return _wrapSection; } set { _wrapSection = value; } } /// <summary>Default text for alt attribute</summary> public virtual string AltText { get { return _altText; } set { _altText = value; } } /// <summary>Style sheet for slides</summary> public virtual string Slidestyle { get { return _slideStyle; } set { _slideStyle = value; } } /// <summary>Add &lt;?xml?&gt; for XML docs</summary> public virtual bool XmlPi { get { return _xmlPi; } set { _xmlPi = value; } } /// <summary>Discard presentation tags</summary> public virtual bool DropFontTags { get { return _dropFontTags; } set { _dropFontTags = value; } } /// <summary>Discard empty p elements</summary> public virtual bool DropEmptyParas { get { return _dropEmptyParas; } set { _dropEmptyParas = value; } } /// <summary>Fix comments with adjacent hyphens</summary> public virtual bool FixComments { get { return _fixComments; } set { _fixComments = value; } } /// <summary>Wrap within ASP pseudo elements</summary> public virtual bool WrapAsp { get { return _wrapAsp; } set { _wrapAsp = value; } } /// <summary>Wrap within JSTE pseudo elements</summary> public virtual bool WrapJste { get { return _wrapJste; } set { _wrapJste = value; } } /// <summary>Wrap within PHP pseudo elements</summary> public virtual bool WrapPhp { get { return _wrapPhp; } set { _wrapPhp = value; } } /// <summary>Fix URLs by replacing \ with /</summary> public virtual bool FixBackslash { get { return _fixBackslash; } set { _fixBackslash = value; } } /// <summary>Newline+indent before each attribute</summary> public virtual bool IndentAttributes { get { return _indentAttributes; } set { _indentAttributes = value; } } /// <summary>Replace i by em and b by strong</summary> public virtual bool LogicalEmphasis { get { return _logicalEmphasis; } set { _logicalEmphasis = value; } } /// <summary>If set to true PIs must end with ?></summary> public virtual bool XmlPIs { get { return _xmlPIs; } set { _xmlPIs = value; } } /// <summary>If true text at body is wrapped in &lt;p&gt;'s</summary> public virtual bool EncloseText { get { return _encloseBodyText; } set { _encloseBodyText = value; } } /// <summary>If true text in blocks is wrapped in &lt;p&gt;'s</summary> public virtual bool EncloseBlockText { get { return _encloseBlockText; } set { _encloseBlockText = value; } } /// <summary>Draconian cleaning for Word2000</summary> public virtual bool Word2000 { get { return _word2000; } set { _word2000 = value; } } /// <summary>Add meta element indicating tidied doc</summary> public virtual bool TidyMark { get { return _tidyMark; } set { _tidyMark = value; } } /// <summary>If set to yes adds xml:space attr as needed</summary> public virtual bool XmlSpace { get { return _xmlSpace; } set { _xmlSpace = value; } } /// <summary>If true attributes may use newlines</summary> public virtual bool LiteralAttribs { get { return _literalAttribs; } set { _literalAttribs = value; } } /// <summary> /// The DOCTYPE /// </summary> public virtual DocType DocType { get { return _docType; } set { _docType = value; } } /* doctype: omit | auto | strict | loose | <fpi> where the fpi is a string similar to "-//ACME//DTD HTML 3.14159//EN" */ /* protected internal */ internal string ParseDocType(string s, string option) { s = s.Trim(); /* "-//ACME//DTD HTML 3.14159//EN" or similar */ if (s.StartsWith("\"")) { DocType = TidyNet.DocType.User; return s; } /* read first word */ string word = ""; Tokenizer t = new Tokenizer(s, " \t\n\r,"); if (t.HasMoreTokens()) { word = t.NextToken(); } if (String.Compare(word, "omit") == 0) { DocType = TidyNet.DocType.Omit; } else if (String.Compare(word, "strict") == 0) { DocType = TidyNet.DocType.Strict; } else if (String.Compare(word, "loose") == 0 || String.Compare(word, "transitional") == 0) { DocType = TidyNet.DocType.Loose; } else if (String.Compare(word, "auto") == 0) { DocType = TidyNet.DocType.Auto; } else { DocType = TidyNet.DocType.Auto; Report.BadArgument(option); } return null; } /// <summary> DocType - user specified doctype /// omit | auto | strict | loose | <i>fpi</i> /// where the <i>fpi</i> is a string similar to /// &quot;-//ACME//DTD HTML 3.14159//EN&quot; /// Note: for <i>fpi</i> include the double-quotes in the string. /// </summary> public virtual string DocTypeStr { get { string result = null; switch (_docType) { case TidyNet.DocType.Omit: result = "omit"; break; case TidyNet.DocType.Auto: result = "auto"; break; case TidyNet.DocType.Strict: result = "strict"; break; case TidyNet.DocType.Loose: result = "loose"; break; case TidyNet.DocType.User: result = _docTypeStr; break; } return result; } set { if (value != null) { _docTypeStr = ParseDocType(value, "doctype"); } } } internal class Tokenizer { public Tokenizer(string source, string delimiters) { _elements = new ArrayList(); _delimiters = delimiters; _elements.AddRange(source.Split(_delimiters.ToCharArray())); for (int index = 0; index < _elements.Count; index++) { if ((string)_elements[index] == "") { _elements.RemoveAt(index); index--; } } _source = source; } public bool HasMoreTokens() { return (_elements.Count > 0); } public string NextToken() { string result; if (_source.Length == 0) { throw new Exception(); } else { _elements = new ArrayList(); _elements.AddRange(_source.Split(_delimiters.ToCharArray())); for (int index = 0; index < _elements.Count; index++) { if ((string)_elements[index] == "") { _elements.RemoveAt(index); index--; } } result = (string) _elements[0]; _elements.RemoveAt(0); _source = _source.Remove(_source.IndexOf(result), result.Length); _source = _source.TrimStart(_delimiters.ToCharArray()); return result; } } private ArrayList _elements; private string _source; private string _delimiters = " \t\n\r"; } internal virtual TagTable tt { get { return _tt; } set { _tt = value; } } /* ensure that config is self consistent */ internal virtual void Adjust() { if (EncloseBlockText) { EncloseText = true; } /* avoid the need to set IndentContent when SmartIndent is set */ if (SmartIndent) { IndentContent = true; } /* disable wrapping */ if (WrapLen == 0) { WrapLen = 0x7FFFFFFF; } /* Word 2000 needs o:p to be declared as inline */ if (Word2000) { tt.DefineInlineTag("o:p"); } /* XHTML is written in lower case */ if (Xhtml) { XmlOut = true; UpperCaseTags = false; UpperCaseAttrs = false; } /* if XML in, then XML out */ if (XmlTags) { XmlOut = true; XmlPIs = true; } /* XML requires end tags */ if (XmlOut) { QuoteAmpersand = true; HideEndTags = false; } } private void ParseInlineTagNames(string s, string option) { Tokenizer t = new Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.DefineInlineTag(t.NextToken()); } } private void ParseBlockTagNames(string s, string option) { Tokenizer t = new Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.DefineBlockTag(t.NextToken()); } } private void ParseEmptyTagNames(string s, string option) { Tokenizer t = new Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.defineEmptyTag(t.NextToken()); } } private void ParsePreTagNames(string s, string option) { Tokenizer t = new Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.DefinePreTag(t.NextToken()); } } private int _spaces = 2; /* default indentation */ private int _wrapLen = 68; /* default wrap margin */ private CharEncoding _charEncoding = TidyNet.CharEncoding.ASCII; private int _tabSize = 4; private TidyNet.DocType _docType = TidyNet.DocType.Auto; private string _altText = null; /* default text for alt attribute */ private string _slideStyle = null; /* style sheet for slides */ private string _docTypeStr = null; /* user specified doctype */ private bool _indentContent = false; /* indent content of appropriate tags */ private bool _smartIndent = false; /* does text/block level content effect indentation */ private bool _hideEndTags = false; /* suppress optional end tags */ private bool _xmlTags = false; /* treat input as XML */ private bool _xmlOut = false; /* create output as XML */ private bool _xhtml = false; /* output extensible HTML */ private bool _xmlPi = false; /* add <?xml?> for XML docs */ private bool _rawOut = false; /* avoid mapping values > 127 to entities */ private bool _upperCaseTags = false; /* output tags in upper not lower case */ private bool _upperCaseAttrs = false; /* output attributes in upper not lower case */ private bool _makeClean = false; /* remove presentational clutter */ private bool _logicalEmphasis = false; /* replace i by em and b by strong */ private bool _dropFontTags = false; /* discard presentation tags */ private bool _dropEmptyParas = true; /* discard empty p elements */ private bool _fixComments = true; /* fix comments with adjacent hyphens */ private bool _breakBeforeBR = false; /* o/p newline before <br> or not? */ private bool _burstSlides = false; /* create slides on each h2 element */ private bool _numEntities = false; /* use numeric entities */ private bool _quoteMarks = false; /* output " marks as &quot; */ private bool _quoteNbsp = true; /* output non-breaking space as entity */ private bool _quoteAmpersand = true; /* output naked ampersand as &amp; */ private bool _wrapAttVals = false; /* wrap within attribute values */ private bool _wrapScriptlets = false; /* wrap within JavaScript string literals */ private bool _wrapSection = true; /* wrap within <![ ... ]> section tags */ private bool _wrapAsp = true; /* wrap within ASP pseudo elements */ private bool _wrapJste = true; /* wrap within JSTE pseudo elements */ private bool _wrapPhp = true; /* wrap within PHP pseudo elements */ private bool _fixBackslash = true; /* fix URLs by replacing \ with / */ private bool _indentAttributes = false; /* newline+indent before each attribute */ private bool _xmlPIs = false; /* if set to yes PIs must end with ?> */ private bool _xmlSpace = false; /* if set to yes adds xml:space attr as needed */ private bool _encloseBodyText = false; /* if yes text at body is wrapped in <p>'s */ private bool _encloseBlockText = false; /* if yes text in blocks is wrapped in <p>'s */ private bool _word2000 = false; /* draconian cleaning for Word2000 */ private bool _tidyMark = true; /* add meta element indicating tidied doc */ private bool _literalAttribs = false; /* if true attributes may use newlines */ private TagTable _tt = new TagTable(); } }
/////////////////////////////////////////////////////////////////////////////// //File: Wrapper_MyHuds.cs // //Description: Contains MetaViewWrapper classes implementing Virindi View Service // views. These classes are only compiled if the VVS_REFERENCED symbol is defined. // //References required: // System.Drawing // VirindiViewService (if VVS_REFERENCED is defined) // //This file is Copyright (c) 2010 VirindiPlugins // //Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #if VVS_REFERENCED using System; using System.Collections.Generic; using System.Text; using VirindiViewService; #if METAVIEW_PUBLIC_NS namespace MetaViewWrappers.VirindiViewServiceHudControls #else namespace MyClasses.MetaViewWrappers.VirindiViewServiceHudControls #endif { #if VVS_WRAPPERS_PUBLIC public #else internal #endif class View : IView { HudView myView; public HudView Underlying { get { return myView; } } #region IView Members public void Initialize(Decal.Adapter.Wrappers.PluginHost p, string pXML) { VirindiViewService.XMLParsers.Decal3XMLParser ps = new VirindiViewService.XMLParsers.Decal3XMLParser(); ViewProperties iprop; ControlGroup igroup; ps.ParseFromResource(pXML, out iprop, out igroup); myView = new VirindiViewService.HudView(iprop, igroup); } public void InitializeRawXML(Decal.Adapter.Wrappers.PluginHost p, string pXML) { VirindiViewService.XMLParsers.Decal3XMLParser ps = new VirindiViewService.XMLParsers.Decal3XMLParser(); ViewProperties iprop; ControlGroup igroup; ps.Parse(pXML, out iprop, out igroup); myView = new VirindiViewService.HudView(iprop, igroup); } public void Initialize(Decal.Adapter.Wrappers.PluginHost p, string pXML, string pWindowKey) { VirindiViewService.XMLParsers.Decal3XMLParser ps = new VirindiViewService.XMLParsers.Decal3XMLParser(); ViewProperties iprop; ControlGroup igroup; ps.ParseFromResource(pXML, out iprop, out igroup); myView = new VirindiViewService.HudView(iprop, igroup, pWindowKey); } public void InitializeRawXML(Decal.Adapter.Wrappers.PluginHost p, string pXML, string pWindowKey) { VirindiViewService.XMLParsers.Decal3XMLParser ps = new VirindiViewService.XMLParsers.Decal3XMLParser(); ViewProperties iprop; ControlGroup igroup; ps.Parse(pXML, out iprop, out igroup); myView = new VirindiViewService.HudView(iprop, igroup, pWindowKey); } public void SetIcon(int icon, int iconlibrary) { myView.Icon = ACImage.FromIconLibrary(icon, iconlibrary); } public void SetIcon(int portalicon) { myView.Icon = portalicon; } public string Title { get { return myView.Title; } set { myView.Title = value; } } public bool Visible { get { return myView.Visible; } set { myView.Visible = value; } } public bool Activated { get { return Visible; } set { Visible = value; } } public void Activate() { Visible = true; } public void Deactivate() { Visible = false; } public System.Drawing.Point Location { get { return myView.Location; } set { myView.Location = value; } } public System.Drawing.Size Size { get { return new System.Drawing.Size(myView.Width, myView.Height); } } public System.Drawing.Rectangle Position { get { return new System.Drawing.Rectangle(Location, Size); } set { Location = value.Location; myView.ClientArea = value.Size; } } #if VVS_WRAPPERS_PUBLIC internal #else public #endif ViewSystemSelector.eViewSystem ViewType { get { return ViewSystemSelector.eViewSystem.VirindiViewService; } } Dictionary<string, Control> CreatedControlsByName = new Dictionary<string, Control>(); public IControl this[string id] { get { if (CreatedControlsByName.ContainsKey(id)) return CreatedControlsByName[id]; Control ret = null; VirindiViewService.Controls.HudControl iret = myView[id]; if (iret.GetType() == typeof(VirindiViewService.Controls.HudButton)) ret = new Button(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudCheckBox)) ret = new CheckBox(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudTextBox)) ret = new TextBox(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudCombo)) ret = new Combo(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudHSlider)) ret = new Slider(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudList)) ret = new List(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudStaticText)) ret = new StaticText(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudTabView)) ret = new Notebook(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudProgressBar)) ret = new ProgressBar(); if (iret.GetType() == typeof(VirindiViewService.Controls.HudImageButton)) ret = new ImageButton(); if (ret == null) return null; ret.myControl = iret; ret.myName = id; ret.Initialize(); allocatedcontrols.Add(ret); CreatedControlsByName[id] = ret; return ret; } } #endregion #region IDisposable Members bool disposed = false; public void Dispose() { if (disposed) return; disposed = true; GC.SuppressFinalize(this); foreach (Control c in allocatedcontrols) c.Dispose(); myView.Dispose(); } #endregion List<Control> allocatedcontrols = new List<Control>(); } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class Control : IControl { internal VirindiViewService.Controls.HudControl myControl; internal string myName; public VirindiViewService.Controls.HudControl Underlying { get { return myControl; } } public virtual void Initialize() { } #region IControl Members public string Name { get { return myName; } } public bool Visible { get { return myControl.Visible; } set { myControl.Visible = value; } } VirindiViewService.TooltipSystem.cTooltipInfo itooltipinfo = null; public string TooltipText { get { if (itooltipinfo != null) return itooltipinfo.Text; else return ""; } set { if (itooltipinfo != null) { VirindiViewService.TooltipSystem.RemoveTooltip(itooltipinfo); itooltipinfo = null; } if (!String.IsNullOrEmpty(value)) { itooltipinfo = VirindiViewService.TooltipSystem.AssociateTooltip(myControl, value); } } } public int Id { get { return myControl.XMLID; } } public System.Drawing.Rectangle LayoutPosition { get { //Relative to what?!??! if (Underlying.Group.HeadControl == null) return new System.Drawing.Rectangle(); if (Underlying.Group.HeadControl.Name == Underlying.Name) return new System.Drawing.Rectangle(); VirindiViewService.Controls.HudControl myparent = Underlying.Group.ParentOf(Underlying.Name); if (myparent == null) return new System.Drawing.Rectangle(); //Position only valid inside fixedlayouts VirindiViewService.Controls.HudFixedLayout layoutparent = myparent as VirindiViewService.Controls.HudFixedLayout; if (layoutparent == null) return new System.Drawing.Rectangle(); return layoutparent.GetControlRect(Underlying); } set { if (Underlying.Group.HeadControl == null) return; if (Underlying.Group.HeadControl.Name == Underlying.Name) return; VirindiViewService.Controls.HudControl myparent = Underlying.Group.ParentOf(Underlying.Name); if (myparent == null) return; //Position only valid inside fixedlayouts VirindiViewService.Controls.HudFixedLayout layoutparent = myparent as VirindiViewService.Controls.HudFixedLayout; if (layoutparent == null) return; layoutparent.SetControlRect(Underlying, value); } } #endregion #region IDisposable Members bool disposed = false; public virtual void Dispose() { if (disposed) return; disposed = true; myControl.Dispose(); } #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class Button : Control, IButton { public override void Initialize() { base.Initialize(); ((VirindiViewService.Controls.HudButton)myControl).MouseEvent += new EventHandler<VirindiViewService.Controls.ControlMouseEventArgs>(Button_MouseEvent); } public override void Dispose() { base.Dispose(); ((VirindiViewService.Controls.HudButton)myControl).MouseEvent -= new EventHandler<VirindiViewService.Controls.ControlMouseEventArgs>(Button_MouseEvent); } void Button_MouseEvent(object sender, VirindiViewService.Controls.ControlMouseEventArgs e) { switch (e.EventType) { case VirindiViewService.Controls.ControlMouseEventArgs.MouseEventType.MouseHit: if (Click != null) Click(this, new MVControlEventArgs(this.Id)); return; case VirindiViewService.Controls.ControlMouseEventArgs.MouseEventType.MouseDown: if (Hit != null) Hit(this, null); return; } } #region IButton Members public string Text { get { return ((VirindiViewService.Controls.HudButton)myControl).Text; } set { ((VirindiViewService.Controls.HudButton)myControl).Text = value; } } public System.Drawing.Color TextColor { get { return System.Drawing.Color.Black; } set { } } public event EventHandler Hit; public event EventHandler<MVControlEventArgs> Click; #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class CheckBox : Control, ICheckBox { public override void Initialize() { base.Initialize(); ((VirindiViewService.Controls.HudCheckBox)myControl).Change += new EventHandler(CheckBox_Change); } public override void Dispose() { base.Dispose(); ((VirindiViewService.Controls.HudCheckBox)myControl).Change -= new EventHandler(CheckBox_Change); } void CheckBox_Change(object sender, EventArgs e) { if (Change != null) Change(this, new MVCheckBoxChangeEventArgs(this.Id, Checked)); if (Change_Old != null) Change_Old(this, null); } #region ICheckBox Members public string Text { get { return ((VirindiViewService.Controls.HudCheckBox)myControl).Text; } set { ((VirindiViewService.Controls.HudCheckBox)myControl).Text = value; } } public bool Checked { get { return ((VirindiViewService.Controls.HudCheckBox)myControl).Checked; } set { ((VirindiViewService.Controls.HudCheckBox)myControl).Checked = value; } } public event EventHandler<MVCheckBoxChangeEventArgs> Change; public event EventHandler Change_Old; #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class TextBox : Control, ITextBox { public override void Initialize() { base.Initialize(); ((VirindiViewService.Controls.HudTextBox)myControl).Change += new EventHandler(TextBox_Change); myControl.LostFocus += new EventHandler(myControl_LostFocus); } public override void Dispose() { base.Dispose(); ((VirindiViewService.Controls.HudTextBox)myControl).Change -= new EventHandler(TextBox_Change); myControl.LostFocus -= new EventHandler(myControl_LostFocus); } void TextBox_Change(object sender, EventArgs e) { if (Change != null) Change(this, new MVTextBoxChangeEventArgs(this.Id, Text)); if (Change_Old != null) Change_Old(this, null); } void myControl_LostFocus(object sender, EventArgs e) { if (!myControl.HasFocus) return; if (End != null) End(this, new MVTextBoxEndEventArgs(this.Id, true)); } #region ITextBox Members public string Text { get { return ((VirindiViewService.Controls.HudTextBox)myControl).Text; } set { ((VirindiViewService.Controls.HudTextBox)myControl).Text = value; } } public int Caret { get { return 0; } set { } } public event EventHandler<MVTextBoxChangeEventArgs> Change; public event EventHandler Change_Old; public event EventHandler<MVTextBoxEndEventArgs> End; #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class Combo : Control, ICombo { List<object> iData = new List<object>(); public Combo() { //TODO: add data values from the xml } public class ComboIndexer : IComboIndexer { Combo underlying; internal ComboIndexer(Combo c) { underlying = c; } #region IComboIndexer Members public string this[int index] { get { return ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudCombo)underlying.myControl)[index])).Text; } set { ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudCombo)underlying.myControl)[index])).Text = value; } } #endregion } public class ComboDataIndexer : IComboDataIndexer { Combo underlying; internal ComboDataIndexer(Combo c) { underlying = c; } #region IComboIndexer Members public object this[int index] { get { return underlying.iData[index]; } set { underlying.iData[index] = value; } } #endregion } public override void Initialize() { base.Initialize(); ((VirindiViewService.Controls.HudCombo)myControl).Change += new EventHandler(Combo_Change); } public override void Dispose() { base.Dispose(); ((VirindiViewService.Controls.HudCombo)myControl).Change -= new EventHandler(Combo_Change); } void Combo_Change(object sender, EventArgs e) { if (Change != null) Change(this, new MVIndexChangeEventArgs(this.Id, Selected)); if (Change_Old != null) Change_Old(this, null); } #region ICombo Members public IComboIndexer Text { get { return new ComboIndexer(this); } } public IComboDataIndexer Data { get { return new ComboDataIndexer(this); } } public int Count { get { return ((VirindiViewService.Controls.HudCombo)myControl).Count; } } public int Selected { get { return ((VirindiViewService.Controls.HudCombo)myControl).Current; } set { ((VirindiViewService.Controls.HudCombo)myControl).Current = value; } } public event EventHandler<MVIndexChangeEventArgs> Change; public event EventHandler Change_Old; public void Add(string text) { ((VirindiViewService.Controls.HudCombo)myControl).AddItem(text, null); iData.Add(null); } public void Add(string text, object obj) { ((VirindiViewService.Controls.HudCombo)myControl).AddItem(text, null); iData.Add(obj); } public void Insert(int index, string text) { ((VirindiViewService.Controls.HudCombo)myControl).InsertItem(index, text, null); iData.Insert(index, null); } public void RemoveAt(int index) { ((VirindiViewService.Controls.HudCombo)myControl).DeleteItem(index); iData.RemoveAt(index); } public void Remove(int index) { RemoveAt(index); } public void Clear() { ((VirindiViewService.Controls.HudCombo)myControl).Clear(); iData.Clear(); } #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class Slider : Control, ISlider { public override void Initialize() { base.Initialize(); ((VirindiViewService.Controls.HudHSlider)myControl).Changed += new VirindiViewService.Controls.LinearPositionControl.delScrollChanged(Slider_Changed); } public override void Dispose() { base.Dispose(); ((VirindiViewService.Controls.HudHSlider)myControl).Changed -= new VirindiViewService.Controls.LinearPositionControl.delScrollChanged(Slider_Changed); } void Slider_Changed(int min, int max, int pos) { if (Change != null) Change(this, new MVIndexChangeEventArgs(this.Id, pos)); if (Change_Old != null) Change_Old(this, null); } #region ISlider Members public int Position { get { return ((VirindiViewService.Controls.HudHSlider)myControl).Position; } set { ((VirindiViewService.Controls.HudHSlider)myControl).Position = value; } } public event EventHandler<MVIndexChangeEventArgs> Change; public event EventHandler Change_Old; public int Maximum { get { return ((VirindiViewService.Controls.HudHSlider)myControl).Max; } set { ((VirindiViewService.Controls.HudHSlider)myControl).Max = value; } } public int Minimum { get { return ((VirindiViewService.Controls.HudHSlider)myControl).Min; } set { ((VirindiViewService.Controls.HudHSlider)myControl).Min = value; } } #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class List : Control, IList { public override void Initialize() { base.Initialize(); ((VirindiViewService.Controls.HudList)myControl).Click += new VirindiViewService.Controls.HudList.delClickedControl(List_Click); } public override void Dispose() { base.Dispose(); ((VirindiViewService.Controls.HudList)myControl).Click -= new VirindiViewService.Controls.HudList.delClickedControl(List_Click); } void List_Click(object sender, int row, int col) { if (Click != null) Click(this, row, col); if (Selected != null) Selected(this, new MVListSelectEventArgs(this.Id, row, col)); } public class ListRow : IListRow { List myList; int myRow; internal ListRow(int row, List l) { myList = l; myRow = row; } #region IListRow Members public IListCell this[int col] { get { return new ListCell(myRow, col, myList); } } #endregion } public class ListCell : IListCell { List myList; int myRow; int myCol; internal ListCell(int row, int col, List l) { myRow = row; myCol = col; myList = l; } #region IListCell Members public void ResetColor() { ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).ResetTextColor(); } public System.Drawing.Color Color { get { return ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).TextColor; } set { ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).TextColor = value; } } public int Width { get { return ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).ClipRegion.Width; } set { throw new Exception("The method or operation is not implemented."); } } public object this[int subval] { get { VirindiViewService.Controls.HudControl c = ((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol]; if (subval == 0) { if (c.GetType() == typeof(VirindiViewService.Controls.HudStaticText)) return ((VirindiViewService.Controls.HudStaticText)c).Text; if (c.GetType() == typeof(VirindiViewService.Controls.HudCheckBox)) return ((VirindiViewService.Controls.HudCheckBox)c).Checked; } else if (subval == 1) { if (c.GetType() == typeof(VirindiViewService.Controls.HudPictureBox)) return ((VirindiViewService.Controls.HudPictureBox)c).Image.PortalImageID; } return null; } set { VirindiViewService.Controls.HudControl c = ((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol]; if (subval == 0) { if (c.GetType() == typeof(VirindiViewService.Controls.HudStaticText)) ((VirindiViewService.Controls.HudStaticText)c).Text = (string)value; if (c.GetType() == typeof(VirindiViewService.Controls.HudCheckBox)) ((VirindiViewService.Controls.HudCheckBox)c).Checked = (bool)value; } else if (subval == 1) { if (c.GetType() == typeof(VirindiViewService.Controls.HudPictureBox)) ((VirindiViewService.Controls.HudPictureBox)c).Image = (int)value; } } } #endregion } #region IList Members public event dClickedList Click; public event EventHandler<MVListSelectEventArgs> Selected; public void Clear() { ((VirindiViewService.Controls.HudList)myControl).ClearRows(); } public IListRow this[int row] { get { return new ListRow(row, this); } } public IListRow AddRow() { ((VirindiViewService.Controls.HudList)myControl).AddRow(); return new ListRow(((VirindiViewService.Controls.HudList)myControl).RowCount - 1, this); } public IListRow Add() { return AddRow(); } public IListRow InsertRow(int pos) { ((VirindiViewService.Controls.HudList)myControl).InsertRow(pos); return new ListRow(pos, this); } public IListRow Insert(int pos) { return InsertRow(pos); } public int RowCount { get { return ((VirindiViewService.Controls.HudList)myControl).RowCount; } } public void RemoveRow(int index) { ((VirindiViewService.Controls.HudList)myControl).RemoveRow(index); } public void Delete(int index) { RemoveRow(index); } public int ColCount { get { return ((VirindiViewService.Controls.HudList)myControl).ColumnCount; } } public int ScrollPosition { get { return ((VirindiViewService.Controls.HudList)myControl).ScrollPosition; } set { ((VirindiViewService.Controls.HudList)myControl).ScrollPosition = value; } } #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class StaticText : Control, IStaticText { public override void Initialize() { base.Initialize(); //((VirindiViewService.Controls.HudStaticText)myControl) } public override void Dispose() { base.Dispose(); } #region IStaticText Members public string Text { get { return ((VirindiViewService.Controls.HudStaticText)myControl).Text; } set { ((VirindiViewService.Controls.HudStaticText)myControl).Text = value; } } #pragma warning disable 0067 public event EventHandler<MVControlEventArgs> Click; #pragma warning restore 0067 #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class Notebook : Control, INotebook { public override void Initialize() { base.Initialize(); ((VirindiViewService.Controls.HudTabView)myControl).OpenTabChange += new EventHandler(Notebook_OpenTabChange); } public override void Dispose() { ((VirindiViewService.Controls.HudTabView)myControl).OpenTabChange -= new EventHandler(Notebook_OpenTabChange); base.Dispose(); } void Notebook_OpenTabChange(object sender, EventArgs e) { if (Change != null) Change(this, new MVIndexChangeEventArgs(this.Id, ActiveTab)); } #region INotebook Members public event EventHandler<MVIndexChangeEventArgs> Change; public int ActiveTab { get { return ((VirindiViewService.Controls.HudTabView)myControl).CurrentTab; } set { ((VirindiViewService.Controls.HudTabView)myControl).CurrentTab = value; ((VirindiViewService.Controls.HudTabView)myControl).Invalidate(); } } #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class ProgressBar : Control, IProgressBar { #region IProgressBar Members public int Position { get { return ((VirindiViewService.Controls.HudProgressBar)myControl).Position; } set { ((VirindiViewService.Controls.HudProgressBar)myControl).Position = value; } } public int Value { get { return Position; } set { Position = value; } } public string PreText { get { return ((VirindiViewService.Controls.HudProgressBar)myControl).PreText; } set { ((VirindiViewService.Controls.HudProgressBar)myControl).PreText = value; } } public int MaxValue { get { return ((VirindiViewService.Controls.HudProgressBar)myControl).Max; } set { ((VirindiViewService.Controls.HudProgressBar)myControl).Max = value; } } #endregion } #if VVS_WRAPPERS_PUBLIC public #else internal #endif class ImageButton : Control, IImageButton { public override void Initialize() { base.Initialize(); myControl.MouseEvent += new EventHandler<VirindiViewService.Controls.ControlMouseEventArgs>(Button_MouseEvent); } public override void Dispose() { base.Dispose(); myControl.MouseEvent -= new EventHandler<VirindiViewService.Controls.ControlMouseEventArgs>(Button_MouseEvent); } void Button_MouseEvent(object sender, VirindiViewService.Controls.ControlMouseEventArgs e) { switch (e.EventType) { case VirindiViewService.Controls.ControlMouseEventArgs.MouseEventType.MouseHit: if (Click != null) Click(this, new MVControlEventArgs(this.Id)); return; } } #region IImageButton Members public event EventHandler<MVControlEventArgs> Click; public void SetImages(int unpressed, int pressed) { ACImage upimg; if (!VirindiViewService.Service.PortalBitmapExists(unpressed | 0x06000000)) upimg = new ACImage(); else upimg = new ACImage(unpressed, ACImage.eACImageDrawOptions.DrawStretch); ACImage pimg; if (!VirindiViewService.Service.PortalBitmapExists(pressed | 0x06000000)) pimg = new ACImage(); else pimg = new ACImage(pressed, ACImage.eACImageDrawOptions.DrawStretch); ((VirindiViewService.Controls.HudImageButton)myControl).Image_Up = upimg; ((VirindiViewService.Controls.HudImageButton)myControl).Image_Up_Pressing = pimg; } public void SetImages(int hmodule, int unpressed, int pressed) { ((VirindiViewService.Controls.HudImageButton)myControl).Image_Up = ACImage.FromIconLibrary(unpressed, hmodule); ((VirindiViewService.Controls.HudImageButton)myControl).Image_Up_Pressing = ACImage.FromIconLibrary(pressed, hmodule); } public int Background { set { ((VirindiViewService.Controls.HudImageButton)myControl).Image_Background2 = new ACImage(value, ACImage.eACImageDrawOptions.DrawStretch); } } public System.Drawing.Color Matte { set { ((VirindiViewService.Controls.HudImageButton)myControl).Image_Background = new ACImage(value); } } #endregion } } #else #warning VVS_REFERENCED not defined, MetaViewWrappers for VVS will not be available. #endif
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sns-2010-03-31.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SimpleNotificationService.Model; namespace Amazon.SimpleNotificationService { /// <summary> /// Interface for accessing SimpleNotificationService /// /// Amazon Simple Notification Service /// <para> /// Amazon Simple Notification Service (Amazon SNS) is a web service that enables you /// to build distributed web-enabled applications. Applications can use Amazon SNS /// to easily push real-time notification messages to interested subscribers over /// multiple delivery protocols. For more information about this product see <a href="http://aws.amazon.com/sns/">http://aws.amazon.com/sns</a>. /// For detailed information about Amazon SNS features and their associated API calls, see /// the <a href="http://docs.aws.amazon.com/sns/latest/dg/">Amazon SNS Developer Guide</a>. /// </para> /// /// <para> /// We also provide SDKs that enable you to access Amazon SNS from your preferred programming /// language. The SDKs contain functionality that automatically takes care of tasks /// such as: cryptographically signing your service requests, retrying requests, /// and handling error responses. For a list of available SDKs, go to <a href="http://aws.amazon.com/tools/">Tools /// for Amazon Web Services</a>. /// </para> /// </summary> public partial interface IAmazonSimpleNotificationService : IDisposable { #region AddPermission /// <summary> /// Initiates the asynchronous execution of the AddPermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddPermission operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<AddPermissionResponse> AddPermissionAsync(AddPermissionRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ConfirmSubscription /// <summary> /// Initiates the asynchronous execution of the ConfirmSubscription operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ConfirmSubscription operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ConfirmSubscriptionResponse> ConfirmSubscriptionAsync(ConfirmSubscriptionRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreatePlatformApplication /// <summary> /// Initiates the asynchronous execution of the CreatePlatformApplication operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreatePlatformApplication operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreatePlatformApplicationResponse> CreatePlatformApplicationAsync(CreatePlatformApplicationRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreatePlatformEndpoint /// <summary> /// Initiates the asynchronous execution of the CreatePlatformEndpoint operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreatePlatformEndpoint operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreatePlatformEndpointResponse> CreatePlatformEndpointAsync(CreatePlatformEndpointRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateTopic /// <summary> /// Initiates the asynchronous execution of the CreateTopic operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateTopic operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateTopicResponse> CreateTopicAsync(CreateTopicRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteEndpoint /// <summary> /// Initiates the asynchronous execution of the DeleteEndpoint operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteEndpoint operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteEndpointResponse> DeleteEndpointAsync(DeleteEndpointRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeletePlatformApplication /// <summary> /// Initiates the asynchronous execution of the DeletePlatformApplication operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeletePlatformApplication operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeletePlatformApplicationResponse> DeletePlatformApplicationAsync(DeletePlatformApplicationRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteTopic /// <summary> /// Initiates the asynchronous execution of the DeleteTopic operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteTopic operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteTopicResponse> DeleteTopicAsync(DeleteTopicRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetEndpointAttributes /// <summary> /// Initiates the asynchronous execution of the GetEndpointAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetEndpointAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetEndpointAttributesResponse> GetEndpointAttributesAsync(GetEndpointAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetPlatformApplicationAttributes /// <summary> /// Initiates the asynchronous execution of the GetPlatformApplicationAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetPlatformApplicationAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetPlatformApplicationAttributesResponse> GetPlatformApplicationAttributesAsync(GetPlatformApplicationAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetSubscriptionAttributes /// <summary> /// Initiates the asynchronous execution of the GetSubscriptionAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSubscriptionAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetSubscriptionAttributesResponse> GetSubscriptionAttributesAsync(GetSubscriptionAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetTopicAttributes /// <summary> /// Initiates the asynchronous execution of the GetTopicAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetTopicAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetTopicAttributesResponse> GetTopicAttributesAsync(GetTopicAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListEndpointsByPlatformApplication /// <summary> /// Initiates the asynchronous execution of the ListEndpointsByPlatformApplication operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListEndpointsByPlatformApplication operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListEndpointsByPlatformApplicationResponse> ListEndpointsByPlatformApplicationAsync(ListEndpointsByPlatformApplicationRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListPlatformApplications /// <summary> /// Initiates the asynchronous execution of the ListPlatformApplications operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPlatformApplications operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListPlatformApplicationsResponse> ListPlatformApplicationsAsync(ListPlatformApplicationsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListSubscriptions /// <summary> /// Initiates the asynchronous execution of the ListSubscriptions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListSubscriptions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListSubscriptionsResponse> ListSubscriptionsAsync(ListSubscriptionsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListSubscriptionsByTopic /// <summary> /// Initiates the asynchronous execution of the ListSubscriptionsByTopic operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListSubscriptionsByTopic operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListSubscriptionsByTopicResponse> ListSubscriptionsByTopicAsync(ListSubscriptionsByTopicRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListTopics /// <summary> /// Initiates the asynchronous execution of the ListTopics operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTopics operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListTopicsResponse> ListTopicsAsync(ListTopicsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Publish /// <summary> /// Initiates the asynchronous execution of the Publish operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Publish operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PublishResponse> PublishAsync(PublishRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RemovePermission /// <summary> /// Initiates the asynchronous execution of the RemovePermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RemovePermission operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RemovePermissionResponse> RemovePermissionAsync(RemovePermissionRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetEndpointAttributes /// <summary> /// Initiates the asynchronous execution of the SetEndpointAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetEndpointAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetEndpointAttributesResponse> SetEndpointAttributesAsync(SetEndpointAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetPlatformApplicationAttributes /// <summary> /// Initiates the asynchronous execution of the SetPlatformApplicationAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetPlatformApplicationAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetPlatformApplicationAttributesResponse> SetPlatformApplicationAttributesAsync(SetPlatformApplicationAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetSubscriptionAttributes /// <summary> /// Initiates the asynchronous execution of the SetSubscriptionAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetSubscriptionAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetSubscriptionAttributesResponse> SetSubscriptionAttributesAsync(SetSubscriptionAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetTopicAttributes /// <summary> /// Initiates the asynchronous execution of the SetTopicAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetTopicAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetTopicAttributesResponse> SetTopicAttributesAsync(SetTopicAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Subscribe /// <summary> /// Initiates the asynchronous execution of the Subscribe operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Subscribe operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SubscribeResponse> SubscribeAsync(SubscribeRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Unsubscribe /// <summary> /// Initiates the asynchronous execution of the Unsubscribe operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Unsubscribe operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<UnsubscribeResponse> UnsubscribeAsync(UnsubscribeRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
/******************************************************** * ADO.NET 2.0 Data Provider for SQLite Version 3.X * Written by Robert Simpson ([email protected]) * * Released to the public domain, use at your own risk! ********************************************************/ namespace Mono.Data.Sqlite { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Globalization; /// <summary> /// This abstract class is designed to handle user-defined functions easily. An instance of the derived class is made for each /// connection to the database. /// </summary> /// <remarks> /// Although there is one instance of a class derived from SqliteFunction per database connection, the derived class has no access /// to the underlying connection. This is necessary to deter implementers from thinking it would be a good idea to make database /// calls during processing. /// /// It is important to distinguish between a per-connection instance, and a per-SQL statement context. One instance of this class /// services all SQL statements being stepped through on that connection, and there can be many. One should never store per-statement /// information in member variables of user-defined function classes. /// /// For aggregate functions, always create and store your per-statement data in the contextData object on the 1st step. This data will /// be automatically freed for you (and Dispose() called if the item supports IDisposable) when the statement completes. /// </remarks> public abstract class SqliteFunction : IDisposable { private class AggregateData { internal int _count = 1; internal object _data = null; } /// <summary> /// The base connection this function is attached to /// </summary> internal SQLiteBase _base; /// <summary> /// Internal array used to keep track of aggregate function context data /// </summary> private Dictionary<long, AggregateData> _contextDataList; /// <summary> /// Holds a reference to the callback function for user functions /// </summary> private SQLiteCallback _InvokeFunc; /// <summary> /// Holds a reference to the callbakc function for stepping in an aggregate function /// </summary> private SQLiteCallback _StepFunc; /// <summary> /// Holds a reference to the callback function for finalizing an aggregate function /// </summary> private SQLiteFinalCallback _FinalFunc; /// <summary> /// Holds a reference to the callback function for collation sequences /// </summary> private SQLiteCollation _CompareFunc; private SQLiteCollation _CompareFunc16; /// <summary> /// Current context of the current callback. Only valid during a callback /// </summary> internal IntPtr _context; /// <summary> /// This static list contains all the user-defined functions declared using the proper attributes. /// </summary> private static List<SqliteFunctionAttribute> _registeredFunctions = new List<SqliteFunctionAttribute>(); /// <summary> /// Internal constructor, initializes the function's internal variables. /// </summary> protected SqliteFunction() { _contextDataList = new Dictionary<long, AggregateData>(); } /// <summary> /// Returns a reference to the underlying connection's SqliteConvert class, which can be used to convert /// strings and DateTime's into the current connection's encoding schema. /// </summary> public SqliteConvert SqliteConvert { get { return _base; } } /// <summary> /// Scalar functions override this method to do their magic. /// </summary> /// <remarks> /// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available /// to force them into a certain type. Therefore the only types you will ever see as parameters are /// DBNull.Value, Int64, Double, String or byte[] array. /// </remarks> /// <param name="args">The arguments for the command to process</param> /// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or /// you may return an Exception-derived class if you wish to return an error to SQLite. Do not actually throw the error, /// just return it!</returns> public virtual object Invoke(object[] args) { return null; } /// <summary> /// Aggregate functions override this method to do their magic. /// </summary> /// <remarks> /// Typically you'll be updating whatever you've placed in the contextData field and returning as quickly as possible. /// </remarks> /// <param name="args">The arguments for the command to process</param> /// <param name="stepNumber">The 1-based step number. This is incrememted each time the step method is called.</param> /// <param name="contextData">A placeholder for implementers to store contextual data pertaining to the current context.</param> public virtual void Step(object[] args, int stepNumber, ref object contextData) { } /// <summary> /// Aggregate functions override this method to finish their aggregate processing. /// </summary> /// <remarks> /// If you implemented your aggregate function properly, /// you've been recording and keeping track of your data in the contextData object provided, and now at this stage you should have /// all the information you need in there to figure out what to return. /// NOTE: It is possible to arrive here without receiving a previous call to Step(), in which case the contextData will /// be null. This can happen when no rows were returned. You can either return null, or 0 or some other custom return value /// if that is the case. /// </remarks> /// <param name="contextData">Your own assigned contextData, provided for you so you can return your final results.</param> /// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or /// you may return an Exception-derived class if you wish to return an error to SQLite. Do not actually throw the error, /// just return it! /// </returns> public virtual object Final(object contextData) { return null; } /// <summary> /// User-defined collation sequences override this method to provide a custom string sorting algorithm. /// </summary> /// <param name="param1">The first string to compare</param> /// <param name="param2">The second strnig to compare</param> /// <returns>1 if param1 is greater than param2, 0 if they are equal, or -1 if param1 is less than param2</returns> public virtual int Compare(string param1, string param2) { return 0; } /// <summary> /// Converts an IntPtr array of context arguments to an object array containing the resolved parameters the pointers point to. /// </summary> /// <remarks> /// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available /// to force them into a certain type. Therefore the only types you will ever see as parameters are /// DBNull.Value, Int64, Double, String or byte[] array. /// </remarks> /// <param name="nArgs">The number of arguments</param> /// <param name="argsptr">A pointer to the array of arguments</param> /// <returns>An object array of the arguments once they've been converted to .NET values</returns> internal object[] ConvertParams(int nArgs, IntPtr argsptr) { object[] parms = new object[nArgs]; #if !PLATFORM_COMPACTFRAMEWORK IntPtr[] argint = new IntPtr[nArgs]; #else int[] argint = new int[nArgs]; #endif Marshal.Copy(argsptr, argint, 0, nArgs); for (int n = 0; n < nArgs; n++) { switch (_base.GetParamValueType((IntPtr)argint[n])) { case TypeAffinity.Null: parms[n] = DBNull.Value; break; case TypeAffinity.Int64: parms[n] = _base.GetParamValueInt64((IntPtr)argint[n]); break; case TypeAffinity.Double: parms[n] = _base.GetParamValueDouble((IntPtr)argint[n]); break; case TypeAffinity.Text: parms[n] = _base.GetParamValueText((IntPtr)argint[n]); break; case TypeAffinity.Blob: { int x; byte[] blob; x = (int)_base.GetParamValueBytes((IntPtr)argint[n], 0, null, 0, 0); blob = new byte[x]; _base.GetParamValueBytes((IntPtr)argint[n], 0, blob, 0, x); parms[n] = blob; } break; case TypeAffinity.DateTime: // Never happens here but what the heck, maybe it will one day. parms[n] = _base.ToDateTime(_base.GetParamValueText((IntPtr)argint[n])); break; } } return parms; } /// <summary> /// Takes the return value from Invoke() and Final() and figures out how to return it to SQLite's context. /// </summary> /// <param name="context">The context the return value applies to</param> /// <param name="returnValue">The parameter to return to SQLite</param> void SetReturnValue(IntPtr context, object returnValue) { if (returnValue == null || returnValue == DBNull.Value) { _base.ReturnNull(context); return; } Type t = returnValue.GetType(); if (t == typeof(DateTime)) { _base.ReturnText(context, _base.ToString((DateTime)returnValue)); return; } else { Exception r = returnValue as Exception; if (r != null) { _base.ReturnError(context, r.Message); return; } } switch (SqliteConvert.TypeToAffinity(t)) { case TypeAffinity.Null: _base.ReturnNull(context); return; case TypeAffinity.Int64: _base.ReturnInt64(context, Convert.ToInt64(returnValue, CultureInfo.CurrentCulture)); return; case TypeAffinity.Double: _base.ReturnDouble(context, Convert.ToDouble(returnValue, CultureInfo.CurrentCulture)); return; case TypeAffinity.Text: _base.ReturnText(context, returnValue.ToString()); return; case TypeAffinity.Blob: _base.ReturnBlob(context, (byte[])returnValue); return; } } /// <summary> /// Internal scalar callback function, which wraps the raw context pointer and calls the virtual Invoke() method. /// </summary> /// <param name="context">A raw context pointer</param> /// <param name="nArgs">Number of arguments passed in</param> /// <param name="argsptr">A pointer to the array of arguments</param> internal void ScalarCallback(IntPtr context, int nArgs, IntPtr argsptr) { _context = context; SetReturnValue(context, Invoke(ConvertParams(nArgs, argsptr))); } /// <summary> /// Internal collation sequence function, which wraps up the raw string pointers and executes the Compare() virtual function. /// </summary> /// <param name="ptr">Not used</param> /// <param name="len1">Length of the string pv1</param> /// <param name="ptr1">Pointer to the first string to compare</param> /// <param name="len2">Length of the string pv2</param> /// <param name="ptr2">Pointer to the second string to compare</param> /// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater /// than the second.</returns> internal int CompareCallback(IntPtr ptr, int len1, IntPtr ptr1, int len2, IntPtr ptr2) { return Compare(SqliteConvert.UTF8ToString(ptr1, len1), SqliteConvert.UTF8ToString(ptr2, len2)); } internal int CompareCallback16(IntPtr ptr, int len1, IntPtr ptr1, int len2, IntPtr ptr2) { return Compare(SQLite3_UTF16.UTF16ToString(ptr1, len1), SQLite3_UTF16.UTF16ToString(ptr2, len2)); } /// <summary> /// The internal aggregate Step function callback, which wraps the raw context pointer and calls the virtual Step() method. /// </summary> /// <remarks> /// This function takes care of doing the lookups and getting the important information put together to call the Step() function. /// That includes pulling out the user's contextData and updating it after the call is made. We use a sorted list for this so /// binary searches can be done to find the data. /// </remarks> /// <param name="context">A raw context pointer</param> /// <param name="nArgs">Number of arguments passed in</param> /// <param name="argsptr">A pointer to the array of arguments</param> internal void StepCallback(IntPtr context, int nArgs, IntPtr argsptr) { long nAux; AggregateData data; nAux = (long)_base.AggregateContext(context); if (_contextDataList.TryGetValue(nAux, out data) == false) { data = new AggregateData(); _contextDataList[nAux] = data; } try { _context = context; Step(ConvertParams(nArgs, argsptr), data._count, ref data._data); } finally { data._count++; } } /// <summary> /// An internal aggregate Final function callback, which wraps the context pointer and calls the virtual Final() method. /// </summary> /// <param name="context">A raw context pointer</param> internal void FinalCallback(IntPtr context) { long n = (long)_base.AggregateContext(context); object obj = null; if (_contextDataList.ContainsKey(n)) { obj = _contextDataList[n]._data; _contextDataList.Remove(n); } _context = context; SetReturnValue(context, Final(obj)); IDisposable disp = obj as IDisposable; if (disp != null) disp.Dispose(); } /// <summary> /// Placeholder for a user-defined disposal routine /// </summary> /// <param name="disposing">True if the object is being disposed explicitly</param> protected virtual void Dispose(bool disposing) { if (disposing) { IDisposable disp; foreach (KeyValuePair<long, AggregateData> kv in _contextDataList) { disp = kv.Value._data as IDisposable; if (disp != null) disp.Dispose(); } _contextDataList.Clear(); _InvokeFunc = null; _StepFunc = null; _FinalFunc = null; _CompareFunc = null; _base = null; _contextDataList = null; } } /// <summary> /// Disposes of any active contextData variables that were not automatically cleaned up. Sometimes this can happen if /// someone closes the connection while a DataReader is open. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// Using reflection, enumerate all assemblies in the current appdomain looking for classes that /// have a SqliteFunctionAttribute attribute, and registering them accordingly. /// </summary> #if !PLATFORM_COMPACTFRAMEWORK [global::System.Security.Permissions.FileIOPermission(global::System.Security.Permissions.SecurityAction.Assert, AllFiles = global::System.Security.Permissions.FileIOPermissionAccess.PathDiscovery)] #endif static SqliteFunction() { try { #if !PLATFORM_COMPACTFRAMEWORK SqliteFunctionAttribute at; System.Reflection.Assembly[] arAssemblies = System.AppDomain.CurrentDomain.GetAssemblies(); int w = arAssemblies.Length; System.Reflection.AssemblyName sqlite = System.Reflection.Assembly.GetCallingAssembly().GetName(); for (int n = 0; n < w; n++) { Type[] arTypes; bool found = false; System.Reflection.AssemblyName[] references; try { // Inspect only assemblies that reference SQLite references = arAssemblies[n].GetReferencedAssemblies(); int t = references.Length; for (int z = 0; z < t; z++) { if (references[z].Name == sqlite.Name) { found = true; break; } } if (found == false) continue; arTypes = arAssemblies[n].GetTypes(); } catch (global::System.Reflection.ReflectionTypeLoadException e) { arTypes = e.Types; } int v = arTypes.Length; for (int x = 0; x < v; x++) { if (arTypes[x] == null) continue; object[] arAtt = arTypes[x].GetCustomAttributes(typeof(SqliteFunctionAttribute), false); int u = arAtt.Length; for (int y = 0; y < u; y++) { at = arAtt[y] as SqliteFunctionAttribute; if (at != null) { at._instanceType = arTypes[x]; _registeredFunctions.Add(at); } } } } #endif } catch // SQLite provider can continue without being able to find built-in functions { } } /// <summary> /// Manual method of registering a function. The type must still have the SqliteFunctionAttributes in order to work /// properly, but this is a workaround for the Compact Framework where enumerating assemblies is not currently supported. /// </summary> /// <param name="typ">The type of the function to register</param> public static void RegisterFunction(Type typ) { object[] arAtt = typ.GetCustomAttributes(typeof(SqliteFunctionAttribute), false); int u = arAtt.Length; SqliteFunctionAttribute at; for (int y = 0; y < u; y++) { at = arAtt[y] as SqliteFunctionAttribute; if (at != null) { at._instanceType = typ; _registeredFunctions.Add(at); } } } /// <summary> /// Called by SQLiteBase derived classes, this function binds all user-defined functions to a connection. /// It is done this way so that all user-defined functions will access the database using the same encoding scheme /// as the connection (UTF-8 or UTF-16). /// </summary> /// <remarks> /// The wrapper functions that interop with SQLite will create a unique cookie value, which internally is a pointer to /// all the wrapped callback functions. The interop function uses it to map CDecl callbacks to StdCall callbacks. /// </remarks> /// <param name="sqlbase">The base object on which the functions are to bind</param> /// <returns>Returns an array of functions which the connection object should retain until the connection is closed.</returns> internal static SqliteFunction[] BindFunctions(SQLiteBase sqlbase) { SqliteFunction f; List<SqliteFunction> lFunctions = new List<SqliteFunction>(); foreach (SqliteFunctionAttribute pr in _registeredFunctions) { f = (SqliteFunction)Activator.CreateInstance(pr._instanceType); f._base = sqlbase; f._InvokeFunc = (pr.FuncType == FunctionType.Scalar) ? new SQLiteCallback(f.ScalarCallback) : null; f._StepFunc = (pr.FuncType == FunctionType.Aggregate) ? new SQLiteCallback(f.StepCallback) : null; f._FinalFunc = (pr.FuncType == FunctionType.Aggregate) ? new SQLiteFinalCallback(f.FinalCallback) : null; f._CompareFunc = (pr.FuncType == FunctionType.Collation) ? new SQLiteCollation(f.CompareCallback) : null; f._CompareFunc16 = (pr.FuncType == FunctionType.Collation) ? new SQLiteCollation(f.CompareCallback16) : null; if (pr.FuncType != FunctionType.Collation) sqlbase.CreateFunction(pr.Name, pr.Arguments, (f is SqliteFunctionEx), f._InvokeFunc, f._StepFunc, f._FinalFunc); else sqlbase.CreateCollation(pr.Name, f._CompareFunc, f._CompareFunc16); lFunctions.Add(f); } SqliteFunction[] arFunctions = new SqliteFunction[lFunctions.Count]; lFunctions.CopyTo(arFunctions, 0); return arFunctions; } } /// <summary> /// Extends SqliteFunction and allows an inherited class to obtain the collating sequence associated with a function call. /// </summary> /// <remarks> /// User-defined functions can call the GetCollationSequence() method in this class and use it to compare strings and char arrays. /// </remarks> public class SqliteFunctionEx : SqliteFunction { /// <summary> /// Obtains the collating sequence in effect for the given function. /// </summary> /// <returns></returns> protected CollationSequence GetCollationSequence() { return _base.GetCollationSequence(this, _context); } } /// <summary> /// The type of user-defined function to declare /// </summary> public enum FunctionType { /// <summary> /// Scalar functions are designed to be called and return a result immediately. Examples include ABS(), Upper(), Lower(), etc. /// </summary> Scalar = 0, /// <summary> /// Aggregate functions are designed to accumulate data until the end of a call and then return a result gleaned from the accumulated data. /// Examples include SUM(), COUNT(), AVG(), etc. /// </summary> Aggregate = 1, /// <summary> /// Collation sequences are used to sort textual data in a custom manner, and appear in an ORDER BY clause. Typically text in an ORDER BY is /// sorted using a straight case-insensitive comparison function. Custom collating sequences can be used to alter the behavior of text sorting /// in a user-defined manner. /// </summary> Collation = 2, } /// <summary> /// An internal callback delegate declaration. /// </summary> /// <param name="context">Raw context pointer for the user function</param> /// <param name="nArgs">Count of arguments to the function</param> /// <param name="argsptr">A pointer to the array of argument pointers</param> #if !PLATFORM_COMPACTFRAMEWORK [UnmanagedFunctionPointer(CallingConvention.Cdecl)] #endif internal delegate void SQLiteCallback(IntPtr context, int nArgs, IntPtr argsptr); /// <summary> /// An internal final callback delegate declaration. /// </summary> /// <param name="context">Raw context pointer for the user function</param> #if !PLATFORM_COMPACTFRAMEWORK [UnmanagedFunctionPointer(CallingConvention.Cdecl)] #endif internal delegate void SQLiteFinalCallback(IntPtr context); /// <summary> /// Internal callback delegate for implementing collation sequences /// </summary> /// <param name="puser">Not used</param> /// <param name="len1">Length of the string pv1</param> /// <param name="pv1">Pointer to the first string to compare</param> /// <param name="len2">Length of the string pv2</param> /// <param name="pv2">Pointer to the second string to compare</param> /// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater /// than the second.</returns> #if !PLATFORM_COMPACTFRAMEWORK [UnmanagedFunctionPointer(CallingConvention.Cdecl)] #endif internal delegate int SQLiteCollation(IntPtr puser, int len1, IntPtr pv1, int len2, IntPtr pv2); /// <summary> /// The type of collating sequence /// </summary> public enum CollationTypeEnum { /// <summary> /// The built-in BINARY collating sequence /// </summary> Binary = 1, /// <summary> /// The built-in NOCASE collating sequence /// </summary> NoCase = 2, /// <summary> /// The built-in REVERSE collating sequence /// </summary> Reverse = 3, /// <summary> /// A custom user-defined collating sequence /// </summary> Custom = 0, } /// <summary> /// The encoding type the collation sequence uses /// </summary> public enum CollationEncodingEnum { /// <summary> /// The collation sequence is UTF8 /// </summary> UTF8 = 1, /// <summary> /// The collation sequence is UTF16 little-endian /// </summary> UTF16LE = 2, /// <summary> /// The collation sequence is UTF16 big-endian /// </summary> UTF16BE = 3, } /// <summary> /// A struct describing the collating sequence a function is executing in /// </summary> public struct CollationSequence { /// <summary> /// The name of the collating sequence /// </summary> public string Name; /// <summary> /// The type of collating sequence /// </summary> public CollationTypeEnum Type; /// <summary> /// The text encoding of the collation sequence /// </summary> public CollationEncodingEnum Encoding; /// <summary> /// Context of the function that requested the collating sequence /// </summary> internal SqliteFunction _func; /// <summary> /// Calls the base collating sequence to compare two strings /// </summary> /// <param name="s1">The first string to compare</param> /// <param name="s2">The second string to compare</param> /// <returns>-1 if s1 is less than s2, 0 if s1 is equal to s2, and 1 if s1 is greater than s2</returns> public int Compare(string s1, string s2) { return _func._base.ContextCollateCompare(Encoding, _func._context, s1, s2); } /// <summary> /// Calls the base collating sequence to compare two character arrays /// </summary> /// <param name="c1">The first array to compare</param> /// <param name="c2">The second array to compare</param> /// <returns>-1 if c1 is less than c2, 0 if c1 is equal to c2, and 1 if c1 is greater than c2</returns> public int Compare(char[] c1, char[] c2) { return _func._base.ContextCollateCompare(Encoding, _func._context, c1, c2); } } }
// *********************************************************************** // Copyright (c) 2007-2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; #if PORTABLE using System.Linq; #endif namespace NUnit.Framework.Internal { /// <summary> /// Helper methods for inspecting a type by reflection. /// /// Many of these methods take ICustomAttributeProvider as an /// argument to avoid duplication, even though certain attributes can /// only appear on specific types of members, like MethodInfo or Type. /// /// In the case where a type is being examined for the presence of /// an attribute, interface or named member, the Reflect methods /// operate with the full name of the member being sought. This /// removes the necessity of the caller having a reference to the /// assembly that defines the item being sought and allows the /// NUnit core to inspect assemblies that reference an older /// version of the NUnit framework. /// </summary> public static class Reflect { private static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; // A zero-length Type array - not provided by System.Type for all CLR versions we support. private static readonly Type[] EmptyTypes = new Type[0]; #region Get Methods of a type /// <summary> /// Examine a fixture type and return an array of methods having a /// particular attribute. The array is order with base methods first. /// </summary> /// <param name="fixtureType">The type to examine</param> /// <param name="attributeType">The attribute Type to look for</param> /// <param name="inherit">Specifies whether to search the fixture type inheritance chain</param> /// <returns>The array of methods found</returns> public static MethodInfo[] GetMethodsWithAttribute(Type fixtureType, Type attributeType, bool inherit) { List<MethodInfo> list = new List<MethodInfo>(); #if NETCF if (fixtureType.IsGenericTypeDefinition) { var genArgs = fixtureType.GetGenericArguments(); Type[] args = new Type[genArgs.Length]; for (int ix = 0; ix < genArgs.Length; ++ix) { args[ix] = typeof(object); } fixtureType = fixtureType.MakeGenericType(args); } #endif var flags = AllMembers | (inherit ? BindingFlags.FlattenHierarchy : BindingFlags.DeclaredOnly); foreach (MethodInfo method in fixtureType.GetMethods(flags)) { if (method.IsDefined(attributeType, inherit)) list.Add(method); } list.Sort(new BaseTypesFirstComparer()); return list.ToArray(); } private class BaseTypesFirstComparer : IComparer<MethodInfo> { public int Compare(MethodInfo m1, MethodInfo m2) { if (m1 == null || m2 == null) return 0; Type m1Type = m1.DeclaringType; Type m2Type = m2.DeclaringType; if ( m1Type == m2Type ) return 0; if ( m1Type.IsAssignableFrom(m2Type) ) return -1; return 1; } } /// <summary> /// Examine a fixture type and return true if it has a method with /// a particular attribute. /// </summary> /// <param name="fixtureType">The type to examine</param> /// <param name="attributeType">The attribute Type to look for</param> /// <returns>True if found, otherwise false</returns> public static bool HasMethodWithAttribute(Type fixtureType, Type attributeType) { #if PORTABLE return fixtureType.GetMethods(AllMembers | BindingFlags.FlattenHierarchy) .Any(m => m.GetCustomAttributes(false).Any(a => attributeType.IsAssignableFrom(a.GetType()))); #else #if NETCF if (fixtureType.ContainsGenericParameters) return false; #endif foreach (MethodInfo method in fixtureType.GetMethods(AllMembers | BindingFlags.FlattenHierarchy)) { if (method.IsDefined(attributeType, false)) return true; } return false; #endif } #endregion #region Invoke Constructors /// <summary> /// Invoke the default constructor on a Type /// </summary> /// <param name="type">The Type to be constructed</param> /// <returns>An instance of the Type</returns> public static object Construct(Type type) { ConstructorInfo ctor = type.GetConstructor(EmptyTypes); if (ctor == null) throw new InvalidTestFixtureException(type.FullName + " does not have a default constructor"); return ctor.Invoke(null); } /// <summary> /// Invoke a constructor on a Type with arguments /// </summary> /// <param name="type">The Type to be constructed</param> /// <param name="arguments">Arguments to the constructor</param> /// <returns>An instance of the Type</returns> public static object Construct(Type type, object[] arguments) { if (arguments == null) return Construct(type); Type[] argTypes = GetTypeArray(arguments); ITypeInfo typeInfo = new TypeWrapper(type); ConstructorInfo ctor = typeInfo.GetConstructor(argTypes); if (ctor == null) throw new InvalidTestFixtureException(type.FullName + " does not have a suitable constructor"); return ctor.Invoke(arguments); } /// <summary> /// Returns an array of types from an array of objects. /// Used because the compact framework doesn't support /// Type.GetTypeArray() /// </summary> /// <param name="objects">An array of objects</param> /// <returns>An array of Types</returns> internal static Type[] GetTypeArray(object[] objects) { Type[] types = new Type[objects.Length]; int index = 0; foreach (object o in objects) { // NUnitNullType is a marker to indicate null since we can't do typeof(null) or null.GetType() types[index++] = o == null ? typeof(NUnitNullType) : o.GetType(); } return types; } #endregion #region Invoke Methods /// <summary> /// Invoke a parameterless method returning void on an object. /// </summary> /// <param name="method">A MethodInfo for the method to be invoked</param> /// <param name="fixture">The object on which to invoke the method</param> public static object InvokeMethod( MethodInfo method, object fixture ) { return InvokeMethod(method, fixture, null); } /// <summary> /// Invoke a method, converting any TargetInvocationException to an NUnitException. /// </summary> /// <param name="method">A MethodInfo for the method to be invoked</param> /// <param name="fixture">The object on which to invoke the method</param> /// <param name="args">The argument list for the method</param> /// <returns>The return value from the invoked method</returns> public static object InvokeMethod( MethodInfo method, object fixture, params object[] args ) { if(method != null) { try { return method.Invoke(fixture, args); } #if !PORTABLE catch (System.Threading.ThreadAbortException) { // No need to wrap or rethrow ThreadAbortException return null; } #endif catch (TargetInvocationException e) { throw new NUnitException("Rethrown", e.InnerException); } catch (Exception e) { throw new NUnitException("Rethrown", e); } } return null; } #endregion } }
using System; using System.Collections; using Assembly = System.Reflection.Assembly; using ArrayList = System.Collections.ArrayList; using Debug = System.Diagnostics.Debug; using AST = antlr.collections.AST; using ASTArray = antlr.collections.impl.ASTArray; using ANTLRException = antlr.ANTLRException; namespace antlr { /*ANTLR Translator Generator * Project led by Terence Parr at http://www.jGuru.com * Software rights: http://www.antlr.org/license.html * * $Id:$ */ // // ANTLR C# Code Generator by Micheal Jordan // Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com // Anthony Oguntimehin // // With many thanks to Eric V. Smith from the ANTLR list. // // HISTORY: // // 19-Aug-2002 kunle Augmented the basic flexibility of the default ASTFactory with a map // of TokenID-to-NodeTypeName. It's now a proper GoF-style Factory ;-) // /// <summary> /// AST Support code shared by TreeParser and Parser. /// </summary> /// <remarks> /// <para> /// We use delegation to share code (and have only one /// bit of code to maintain) rather than subclassing /// or superclassing (forces AST support code to be /// loaded even when you don't want to do AST stuff). /// </para> /// <para> /// Typically, <see cref="setASTNodeType"/> is used to specify the /// homogeneous type of node to create, but you can override /// <see cref="create"/> to make heterogeneous nodes etc... /// </para> /// </remarks> public class ASTFactory { //--------------------------------------------------------------------- // CONSTRUCTORS //--------------------------------------------------------------------- /// <summary> /// Constructs an <c>ASTFactory</c> with the default AST node type of /// <see cref="antlr.CommonAST"/>. /// </summary> public ASTFactory() : this("antlr.CommonAST") { } /// <summary> /// Constructs an <c>ASTFactory</c> and use the specified AST node type /// as the default. /// </summary> /// <param name="nodeTypeName"> /// Name of default AST node type for this factory. /// </param> public ASTFactory(string nodeTypeName) { heteroList_ = new FactoryEntry[Token.MIN_USER_TYPE+1]; defaultASTNodeTypeObject_ = loadNodeTypeObject(nodeTypeName); defaultCreator_ = null; typename2creator_ = new Hashtable(32, (float) 0.3); typename2creator_["antlr.CommonAST"] = CommonAST.Creator; typename2creator_["antlr.CommonASTWithHiddenTokens"] = CommonASTWithHiddenTokens.Creator; } //--------------------------------------------------------------------- // DATA MEMBERS //--------------------------------------------------------------------- /// <summary> /// Stores the Type of the default AST node class to be used during tree construction. /// </summary> protected Type defaultASTNodeTypeObject_; protected ASTNodeCreator defaultCreator_; /// <summary> /// Stores the mapping between custom AST NodeTypes and their NodeTypeName/NodeTypeClass /// and ASTNodeCreator. /// </summary> protected FactoryEntry[] heteroList_; /// <summary> /// Stores the mapping between AST node typenames and their token ID. /// </summary> protected Hashtable typename2creator_; //--------------------------------------------------------------------- // FUNCTION MEMBERS //--------------------------------------------------------------------- /// <summary> /// Specify an "override" for the <see cref="AST"/> type created for /// the specified Token type. /// </summary> /// <remarks> /// This method is useful for situations that ANTLR cannot oridinarily deal /// with (i.e., when you create a token based upon a nonliteral token symbol /// like #[LT(1)]. This is a runtime value and ANTLR cannot determine the token /// type (and hence the AST) statically. /// </remarks> /// <param name="tokenType">Token type to override.</param> /// <param name="NodeTypeName"> /// Fully qualified AST typename (or null to specify /// the factory's default AST type). /// </param> public void setTokenTypeASTNodeType(int tokenType, string NodeTypeName) { // check validity of arguments... if( tokenType < Token.MIN_USER_TYPE ) throw new ANTLRException("Internal parser error: Cannot change AST Node Type for Token ID '" + tokenType + "'"); // resize up to and including 'type' and initialize any gaps to default // factory. if (tokenType > (heteroList_.Length+1)) setMaxNodeType(tokenType); // And add new thing.. if (heteroList_[tokenType] == null) heteroList_[tokenType] = new FactoryEntry(loadNodeTypeObject(NodeTypeName)); else heteroList_[tokenType].NodeTypeObject = loadNodeTypeObject(NodeTypeName); } /// <summary> /// Register an AST Node Type for a given Token type ID. /// </summary> /// <param name="NodeType">The Token type ID.</param> /// <param name="NodeTypeName">The AST Node Type to register.</param> [Obsolete("Replaced by setTokenTypeASTNodeType(int, string) since version 2.7.2.6", true)] public void registerFactory(int NodeType, string NodeTypeName) { setTokenTypeASTNodeType(NodeType, NodeTypeName); } /// <summary> /// Register an ASTNodeCreator for a given Token type ID. /// </summary> /// <param name="NodeType">The Token type ID.</param> /// <param name="creator">The creater to register.</param> public void setTokenTypeASTNodeCreator(int NodeType, ASTNodeCreator creator) { // check validity of arguments... if( NodeType < Token.MIN_USER_TYPE ) throw new ANTLRException("Internal parser error: Cannot change AST Node Type for Token ID '" + NodeType + "'"); // resize up to and including 'type' and initialize any gaps to default // factory. if (NodeType > (heteroList_.Length+1)) setMaxNodeType(NodeType); // And add new thing.. if (heteroList_[NodeType] == null) heteroList_[NodeType] = new FactoryEntry(creator); else heteroList_[NodeType].Creator = creator; //typename2creator_[NodeType.ToString()] = creator; typename2creator_[creator.ASTNodeTypeName] = creator; } /// <summary> /// Register an ASTNodeCreator to be used for creating node by default. /// </summary> /// <param name="creator">The ASTNodeCreator.</param> public void setASTNodeCreator(ASTNodeCreator creator) { defaultCreator_ = creator; } /// <summary> /// Pre-expands the internal list of TokenTypeID-to-ASTNodeType mappings /// to the specified size. /// This is primarily a convenience method that can be used to prevent /// unnecessary and costly re-org of the mappings list. /// </summary> /// <param name="NodeType">Maximum Token Type ID.</param> public void setMaxNodeType( int NodeType ) { //Debug.WriteLine(this, "NodeType = " + NodeType + " and NodeList.Length = " + nodeTypeList_.Length); if (heteroList_ == null) { heteroList_ = new FactoryEntry[NodeType+1]; } else { int length = heteroList_.Length; if ( NodeType > (length + 1) ) { FactoryEntry[] newList = new FactoryEntry[NodeType+1]; Array.Copy(heteroList_, 0, newList, 0, heteroList_.Length); heteroList_ = newList; } else if ( NodeType < (length + 1) ) { FactoryEntry[] newList = new FactoryEntry[NodeType+1]; Array.Copy(heteroList_, 0, newList, 0, (NodeType+1)); heteroList_ = newList; } } //Debug.WriteLine(this, "NodeType = " + NodeType + " and NodeList.Length = " + nodeTypeList_.Length); } /// <summary> /// Add a child to the current AST /// </summary> /// <param name="currentAST">The AST to add a child to</param> /// <param name="child">The child AST to be added</param> public virtual void addASTChild(ASTPair currentAST, AST child) { if (child != null) { if (currentAST.root == null) { // Make new child the current root currentAST.root = child; } else { if (currentAST.child == null) { // Add new child to current root currentAST.root.setFirstChild(child); } else { currentAST.child.setNextSibling(child); } } // Make new child the current child currentAST.child = child; currentAST.advanceChildToEnd(); } } /// <summary> /// Creates a new uninitialized AST node. Since a specific AST Node Type /// wasn't indicated, the new AST node is created using the current default /// AST Node type - <see cref="defaultASTNodeTypeObject_"/> /// </summary> /// <returns>An uninitialized AST node object.</returns> public virtual AST create() { AST newNode; if (defaultCreator_ == null) newNode = createFromNodeTypeObject(defaultASTNodeTypeObject_); else newNode = defaultCreator_.Create(); return newNode; } /// <summary> /// Creates and initializes a new AST node using the specified Token Type ID. /// The <see cref="System.Type"/> used for creating this new AST node is /// determined by the following: /// <list type="bullet"> /// <item>the current TokenTypeID-to-ASTNodeType mapping (if any) or,</item> /// <item>the <see cref="defaultASTNodeTypeObject_"/> otherwise</item> /// </list> /// </summary> /// <param name="type">Token type ID to be used to create new AST Node.</param> /// <returns>An initialized AST node object.</returns> public virtual AST create(int type) { AST newNode = createFromNodeType(type); newNode.initialize(type, ""); return newNode; } /// <summary> /// Creates and initializes a new AST node using the specified Token Type ID. /// The <see cref="System.Type"/> used for creating this new AST node is /// determined by the following: /// <list type="bullet"> /// <item>the current TokenTypeID-to-ASTNodeType mapping (if any) or,</item> /// <item>the <see cref="defaultASTNodeTypeObject_"/> otherwise</item> /// </list> /// </summary> /// <param name="type">Token type ID to be used to create new AST Node.</param> /// <param name="txt">Text for initializing the new AST Node.</param> /// <returns>An initialized AST node object.</returns> public virtual AST create(int type, string txt) { AST newNode = createFromNodeType(type); newNode.initialize(type, txt); return newNode; } /// <summary> /// Creates a new AST node using the specified AST Node Type name. Once created, /// the new AST node is initialized with the specified Token type ID and string. /// The <see cref="System.Type"/> used for creating this new AST node is /// determined solely by <c>ASTNodeTypeName</c>. /// The AST Node type must have a default/parameterless constructor. /// </summary> /// <param name="type">Token type ID to be used to create new AST Node.</param> /// <param name="txt">Text for initializing the new AST Node.</param> /// <param name="ASTNodeTypeName">Fully qualified name of the Type to be used for creating the new AST Node.</param> /// <returns>An initialized AST node object.</returns> public virtual AST create(int type, string txt, string ASTNodeTypeName) { AST newNode = createFromNodeName(ASTNodeTypeName); newNode.initialize(type, txt); return newNode; } /// <summary> /// Creates a new AST node using the specified AST Node Type name. /// </summary> /// <param name="tok">Token instance to be used to initialize the new AST Node.</param> /// <param name="ASTNodeTypeName"> /// Fully qualified name of the Type to be used for creating the new AST Node. /// </param> /// <returns>A newly created and initialized AST node object.</returns> /// <remarks> /// Once created, the new AST node is initialized with the specified Token /// instance. The <see cref="System.Type"/> used for creating this new AST /// node is determined solely by <c>ASTNodeTypeName</c>. /// <para>The AST Node type must have a default/parameterless constructor.</para> /// </remarks> public virtual AST create(IToken tok, string ASTNodeTypeName) { AST newNode = createFromNodeName(ASTNodeTypeName); newNode.initialize(tok); return newNode; } /// <summary> /// Creates and initializes a new AST node using the specified AST Node instance. /// the new AST node is initialized with the specified Token type ID and string. /// The <see cref="System.Type"/> used for creating this new AST node is /// determined solely by <c>aNode</c>. /// The AST Node type must have a default/parameterless constructor. /// </summary> /// <param name="aNode">AST Node instance to be used for creating the new AST Node.</param> /// <returns>An initialized AST node object.</returns> public virtual AST create(AST aNode) { AST newNode; if (aNode == null) newNode = null; else { newNode = createFromAST(aNode); newNode.initialize(aNode); } return newNode; } /// <summary> /// Creates and initializes a new AST node using the specified Token instance. /// The <see cref="System.Type"/> used for creating this new AST node is /// determined by the following: /// <list type="bullet"> /// <item>the current TokenTypeID-to-ASTNodeType mapping (if any) or,</item> /// <item>the <see cref="defaultASTNodeTypeObject_"/> otherwise</item> /// </list> /// </summary> /// <param name="tok">Token instance to be used to create new AST Node.</param> /// <returns>An initialized AST node object.</returns> public virtual AST create(IToken tok) { AST newNode; if (tok == null) newNode = null; else { newNode = createFromNodeType(tok.Type); newNode.initialize(tok); } return newNode; } /// <summary> /// Returns a copy of the specified AST Node instance. The copy is obtained by /// using the <see cref="ICloneable"/> method Clone(). /// </summary> /// <param name="t">AST Node to copy.</param> /// <returns>An AST Node (or null if <c>t</c> is null).</returns> public virtual AST dup(AST t) { // The Java version is implemented using code like this: if (t == null) return null; AST dup_edNode = createFromAST(t); dup_edNode.initialize(t); return dup_edNode; } /// <summary> /// Duplicate AST Node tree rooted at specified AST node and all of it's siblings. /// </summary> /// <param name="t">Root of AST Node tree.</param> /// <returns>Root node of new AST Node tree (or null if <c>t</c> is null).</returns> public virtual AST dupList(AST t) { AST result = dupTree(t); // if t == null, then result==null AST nt = result; while (t != null) { // for each sibling of the root t = t.getNextSibling(); nt.setNextSibling(dupTree(t)); // dup each subtree, building new tree nt = nt.getNextSibling(); } return result; } /// <summary> /// Duplicate AST Node tree rooted at specified AST node. Ignore it's siblings. /// </summary> /// <param name="t">Root of AST Node tree.</param> /// <returns>Root node of new AST Node tree (or null if <c>t</c> is null).</returns> public virtual AST dupTree(AST t) { AST result = dup(t); // make copy of root // copy all children of root. if (t != null) { result.setFirstChild(dupList(t.getFirstChild())); } return result; } /// <summary> /// Make a tree from a list of nodes. The first element in the /// array is the root. If the root is null, then the tree is /// a simple list not a tree. Handles null children nodes correctly. /// For example, build(a, b, null, c) yields tree (a b c). build(null,a,b) /// yields tree (nil a b). /// </summary> /// <param name="nodes">List of Nodes.</param> /// <returns>AST Node tree.</returns> public virtual AST make(params AST[] nodes) { if (nodes == null || nodes.Length == 0) return null; AST root = nodes[0]; AST tail = null; if (root != null) { root.setFirstChild(null); // don't leave any old pointers set } // link in children; for (int i = 1; i < nodes.Length; i++) { if (nodes[i] == null) continue; // ignore null nodes if (root == null) { // Set the root and set it up for a flat list root = (tail = nodes[i]); } else if (tail == null) { root.setFirstChild(nodes[i]); tail = root.getFirstChild(); } else { tail.setNextSibling(nodes[i]); tail = tail.getNextSibling(); } // Chase tail to last sibling while (tail.getNextSibling() != null) { tail = tail.getNextSibling(); } } return root; } /// <summary> /// Make a tree from a list of nodes, where the nodes are contained /// in an ASTArray object. /// </summary> /// <param name="nodes">List of Nodes.</param> /// <returns>AST Node tree.</returns> public virtual AST make(ASTArray nodes) { return make(nodes.array); } /// <summary> /// Make an AST the root of current AST. /// </summary> /// <param name="currentAST"></param> /// <param name="root"></param> public virtual void makeASTRoot(ASTPair currentAST, AST root) { if (root != null) { // Add the current root as a child of new root root.addChild(currentAST.root); // The new current child is the last sibling of the old root currentAST.child = currentAST.root; currentAST.advanceChildToEnd(); // Set the new root currentAST.root = root; } } /// <summary> /// Sets the global default AST Node Type for this ASTFactory instance. /// This method also attempts to load the <see cref="System.Type"/> instance /// for the specified typename. /// </summary> /// <param name="t">Fully qualified AST Node Type name.</param> public virtual void setASTNodeType(string t) { if (defaultCreator_ != null) { if (t != defaultCreator_.ASTNodeTypeName) { defaultCreator_ = null; } } defaultASTNodeTypeObject_ = loadNodeTypeObject(t); } /// <summary> /// To change where error messages go, can subclass/override this method /// and then setASTFactory in Parser and TreeParser. This method removes /// a prior dependency on class antlr.Tool. /// </summary> /// <param name="e"></param> public virtual void error(string e) { Console.Error.WriteLine(e); } //--------------------------------------------------------------------- // PRIVATE FUNCTION MEMBERS //--------------------------------------------------------------------- private Type loadNodeTypeObject(string nodeTypeName) { Type nodeTypeObject = null; bool typeCreated = false; if (nodeTypeName != null) { foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies()) { try { nodeTypeObject = assem.GetType(nodeTypeName); if (nodeTypeObject != null) { typeCreated = true; break; } } catch { typeCreated = false; } } } if (!typeCreated) { throw new TypeLoadException("Unable to load AST Node Type: '" + nodeTypeName + "'"); } return nodeTypeObject; } private AST createFromAST(AST node) { AST newNode = null; Type nodeAsTypeObj = node.GetType(); ASTNodeCreator creator = (ASTNodeCreator) typename2creator_[nodeAsTypeObj.FullName]; if (creator != null) { newNode = creator.Create(); if (newNode == null) { throw new ArgumentException("Unable to create AST Node Type: '" + nodeAsTypeObj.FullName + "'"); } } else { newNode = createFromNodeTypeObject(nodeAsTypeObj); } return newNode; } private AST createFromNodeName(string nodeTypeName) { AST newNode = null; ASTNodeCreator creator = (ASTNodeCreator) typename2creator_[nodeTypeName]; if (creator != null) { newNode = creator.Create(); if (newNode == null) { throw new ArgumentException("Unable to create AST Node Type: '" + nodeTypeName + "'"); } } else { newNode = createFromNodeTypeObject( loadNodeTypeObject(nodeTypeName) ); } return newNode; } private AST createFromNodeType(int nodeTypeIndex) { Debug.Assert((nodeTypeIndex >= 0) && (nodeTypeIndex <= heteroList_.Length), "Invalid AST node type!"); AST newNode = null; FactoryEntry entry = heteroList_[nodeTypeIndex]; if ((entry != null) && (entry.Creator != null)) { newNode = entry.Creator.Create(); } else { if ((entry == null) || (entry.NodeTypeObject == null)) { if (defaultCreator_ == null) { newNode = createFromNodeTypeObject(defaultASTNodeTypeObject_); } else newNode = defaultCreator_.Create(); } else newNode = createFromNodeTypeObject( entry.NodeTypeObject ); } return newNode; } private AST createFromNodeTypeObject(Type nodeTypeObject) { AST newNode = null; try { newNode = (AST) Activator.CreateInstance(nodeTypeObject); if (newNode == null) { throw new ArgumentException("Unable to create AST Node Type: '" + nodeTypeObject.FullName + "'"); } } catch(Exception ex) { throw new ArgumentException("Unable to create AST Node Type: '" + nodeTypeObject.FullName + "'", ex); } return newNode; } protected class FactoryEntry { public FactoryEntry(Type typeObj, ASTNodeCreator creator) { NodeTypeObject = typeObj; Creator = creator; } public FactoryEntry(Type typeObj) { NodeTypeObject = typeObj; } public FactoryEntry(ASTNodeCreator creator) { Creator = creator; } public Type NodeTypeObject; public ASTNodeCreator Creator; } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // 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. // #region using NLog.Config; using NLog.Layouts; using NLog.Targets; using System.IO; using Xunit; #endregion namespace NLog.UnitTests.LayoutRenderers { public class VariableLayoutRendererTests : NLogTestBase { [Fact] public void Var_from_xml() { CreateConfigFromXml(); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=realgoodpassword", lastMessage); } [Fact] public void Var_from_xml_and_edit() { CreateConfigFromXml(); LogManager.Configuration.Variables["password"] = "123"; ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=123", lastMessage); } [Fact] public void Var_with_layout_renderers() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name='user' value='logger=${logger}' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.Configuration.Variables["password"] = "123"; ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and logger=A=123", lastMessage); } [Fact] public void Var_in_file_target() { string folderPath = Path.GetTempPath(); string logFilePath = Path.Combine(folderPath, "test.log"); LogManager.Configuration = CreateConfigurationFromString($@" <nlog> <variable name='dir' value='{folderPath}' /> <targets> <target name='f' type='file' fileName='${{var:dir}}/test.log' layout='${{message}}' lineEnding='LF' /> </targets> <rules> <logger name='*' writeTo='f' /> </rules> </nlog>"); try { LogManager.GetLogger("A").Debug("msg"); Assert.True(File.Exists(logFilePath), "Log file was not created at expected file path."); Assert.Equal("msg\n", File.ReadAllText(logFilePath)); } finally { File.Delete(logFilePath); } } [Fact] public void Var_with_other_var() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name='user' value='${var:password}=' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.Configuration.Variables["password"] = "123"; ILogger logger = LogManager.GetLogger("A"); // LogManager.ReconfigExistingLoggers(); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and 123==123", lastMessage); } [Fact] public void Var_from_api() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.Configuration.Variables["user"] = "admin"; LogManager.Configuration.Variables["password"] = "123"; ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=123", lastMessage); } [Fact] public void Var_default() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=unknown", lastMessage); } [Fact] public void Var_default_after_clear() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); LogManager.Configuration.Variables.Remove("password"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=unknown", lastMessage); } [Fact] public void Var_default_after_set_null() { CreateConfigFromXml(); ILogger logger = LogManager.GetLogger("A"); LogManager.Configuration.Variables["password"] = null; logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=", lastMessage); } [Fact] public void Var_default_after_set_emptyString() { CreateConfigFromXml(); ILogger logger = LogManager.GetLogger("A"); LogManager.Configuration.Variables["password"] = ""; logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=", lastMessage); } [Fact] public void Var_default_after_xml_emptyString() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); var lastMessage = GetDebugLastMessage("debug"); Assert.Equal("msg and admin=", lastMessage); } [Fact] public void null_should_be_ok() { Layout l = "${var:var1}"; var config = new LoggingConfiguration(); config.Variables["var1"] = null; l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("", result); } [Fact] public void null_should_not_use_default() { Layout l = "${var:var1:default=x}"; var config = new LoggingConfiguration(); config.Variables["var1"] = null; l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("", result); } [Fact] public void notset_should_use_default() { Layout l = "${var:var1:default=x}"; var config = new LoggingConfiguration(); l.Initialize(config); var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("x", result); } [Fact] public void test_with_mockLogManager() { ILogger logger = MyLogManager.Instance.GetLogger("A"); logger.Debug("msg"); var t1 = _mockConfig.FindTargetByName<DebugTarget>("t1"); Assert.NotNull(t1); Assert.NotNull(t1.LastMessage); Assert.Equal("msg|my-mocking-manager", t1.LastMessage); } private static readonly LoggingConfiguration _mockConfig = new LoggingConfiguration(); static VariableLayoutRendererTests() { var t1 = new DebugTarget { Name = "t1", Layout = "${message}|${var:var1:default=x}" }; _mockConfig.AddTarget(t1); _mockConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, t1)); _mockConfig.Variables["var1"] = "my-mocking-manager"; } class MyLogManager { private static readonly LogFactory _instance = new LogFactory(_mockConfig); public static LogFactory Instance => _instance; } private void CreateConfigFromXml() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name='user' value='admin' /> <variable name='password' value='realgoodpassword' /> <targets> <target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Compiler; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; namespace Microsoft.Zing { public class ZingDecompiler : StandardVisitor { public ZingDecompiler(CodeGeneratorOptions options) { this.options = options; this.braceOnNewLine = (options.BracingStyle != "Block"); indentStrings = new string[maxLevel]; indentStrings[0] = string.Empty; indentStrings[1] = options.IndentString; for (int i = 2; i < maxLevel; i++) indentStrings[i] = indentStrings[i - 1] + indentStrings[1]; } #region Code-generation helpers private void In() { indentLevel++; if (indentLevel >= maxLevel) throw new InvalidOperationException("Maximum indentation level exceeded"); } private void Out() { indentLevel--; Debug.Assert(indentLevel >= 0); } private void WriteLine(string format, params object[] args) { if (!string.IsNullOrEmpty(currentLine)) WriteFinish(string.Empty); lines.Add(indentStrings[indentLevel] + string.Format(CultureInfo.InvariantCulture, format, args)); } private void WriteLine(string str) { if (!string.IsNullOrEmpty(currentLine)) WriteFinish(string.Empty); lines.Add(indentStrings[indentLevel] + str); } private void Write(string format, params object[] args) { currentLine += string.Format(CultureInfo.InvariantCulture, format, args); } private void Write(string str) { currentLine += str; } private void WriteStart(string format, params object[] args) { if (!string.IsNullOrEmpty(currentLine)) WriteFinish(string.Empty); currentLine = indentStrings[indentLevel] + string.Format(CultureInfo.InvariantCulture, format, args); } private void WriteStart(string str) { if (!string.IsNullOrEmpty(currentLine)) WriteFinish(string.Empty); currentLine = indentStrings[indentLevel] + str; } #if UNUSED private void WriteFinish(string format, params object[] args) { lines.Add(currentLine + string.Format(format, args)); currentLine = string.Empty; } #endif private void WriteFinish(string str) { lines.Add(currentLine + str); currentLine = string.Empty; } private string currentLine = string.Empty; private List<string> lines; #endregion Code-generation helpers private int SourceLength { get { return currentLine.Length; } } private int indentLevel; // current indentation level (during decompilation) private string[] indentStrings; private const int maxLevel = 30; private bool braceOnNewLine; private CodeGeneratorOptions options; public void Decompile(Node node, TextWriter tw) { lines = new List<string>(1000); indentLevel = 0; this.Visit(node); foreach (string s in lines) tw.WriteLine(s); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public override Node Visit(Node node) { if (node == null) return null; // // Short-circuit unsupported node types here and throw an exception // switch (node.NodeType) { case NodeType.Yield: case NodeType.AddressDereference: case NodeType.AliasDefinition: case NodeType.Assembly: case NodeType.AssemblyReference: case NodeType.Attribute: case NodeType.Base: case NodeType.BlockExpression: case NodeType.Branch: case NodeType.Catch: case NodeType.Composition: case NodeType.ConstrainedType: case NodeType.ConstructArray: case NodeType.ConstructDelegate: case NodeType.ConstructFlexArray: case NodeType.ConstructIterator: case NodeType.ConstructTuple: case NodeType.Continue: case NodeType.DelegateNode: case NodeType.DoWhile: case NodeType.EndFilter: case NodeType.EndFinally: case NodeType.Event: case NodeType.Exit: case NodeType.ExpressionSnippet: case NodeType.FaultHandler: case NodeType.FieldInitializerBlock: case NodeType.Filter: case NodeType.Finally: case NodeType.For: case NodeType.Interface: case NodeType.InterfaceExpression: case NodeType.InstanceInitializer: case NodeType.Local: case NodeType.LRExpression: case NodeType.Module: case NodeType.NameBinding: case NodeType.NamedArgument: case NodeType.PrefixExpression: case NodeType.PostfixExpression: case NodeType.Property: case NodeType.Repeat: case NodeType.SetterValue: case NodeType.StatementSnippet: case NodeType.StaticInitializer: case NodeType.Switch: case NodeType.SwitchCase: case NodeType.SwitchInstruction: case NodeType.Typeswitch: case NodeType.TypeswitchCase: case NodeType.Try: case NodeType.TypeAlias: case NodeType.TypeMemberSnippet: case NodeType.TypeParameter: throw new InvalidOperationException( string.Format(CultureInfo.CurrentUICulture, "Invalid node type for Zing ({0})", node.NodeType)); default: break; } switch (((ZingNodeType)node.NodeType)) { case ZingNodeType.Array: return this.VisitArray((ZArray)node); case ZingNodeType.Accept: return this.VisitAccept((AcceptStatement)node); case ZingNodeType.Assert: return this.VisitAssert((AssertStatement)node); case ZingNodeType.Assume: return this.VisitAssume((AssumeStatement)node); case ZingNodeType.Async: return this.VisitAsync((AsyncMethodCall)node); case ZingNodeType.Atomic: return this.VisitAtomic((AtomicBlock)node); case ZingNodeType.AttributedStatement: return this.VisitAttributedStatement((AttributedStatement)node); case ZingNodeType.Chan: return this.VisitChan((Chan)node); case ZingNodeType.Choose: return this.VisitChoose((UnaryExpression)node); case ZingNodeType.EventPattern: return this.VisitEventPattern((EventPattern)node); case ZingNodeType.Event: return this.VisitEventStatement((EventStatement)node); case ZingNodeType.In: return this.VisitIn((BinaryExpression)node); case ZingNodeType.JoinStatement: return this.VisitJoinStatement((JoinStatement)node); case ZingNodeType.InvokePlugin: return this.VisitInvokePlugin((InvokePluginStatement)node); case ZingNodeType.Range: return this.VisitRange((Range)node); case ZingNodeType.ReceivePattern: return this.VisitReceivePattern((ReceivePattern)node); case ZingNodeType.Select: return this.VisitSelect((Select)node); case ZingNodeType.Send: return this.VisitSend((SendStatement)node); case ZingNodeType.Set: return this.VisitSet((Set)node); case ZingNodeType.Trace: return this.VisitTrace((TraceStatement)node); case ZingNodeType.TimeoutPattern: return this.VisitTimeoutPattern((TimeoutPattern)node); case ZingNodeType.Try: return this.VisitZTry((ZTry)node); case ZingNodeType.WaitPattern: return this.VisitWaitPattern((WaitPattern)node); case ZingNodeType.With: return this.VisitWith((With)node); default: if (node.NodeType == NodeType.TypeExpression) return this.VisitTypeExpression((TypeExpression)node); return base.Visit(node); } } /// <summary> /// This method is called in contexts where surrounding parentheses /// are required, but we wish to avoid extraneous ones. If the /// expression is a BinaryExpression or UnaryExpression, then we /// need not supply our own parens here. /// </summary> /// <param name="expr"></param> /// <returns></returns> private Expression VisitParenthesizedExpression(Expression expr) { if (expr is BinaryExpression) this.VisitExpression(expr); else { Write("("); this.VisitExpression(expr); Write(")"); } return expr; } private TypeExpression VisitTypeExpression(TypeExpression tExpr) { this.Visit(tExpr.Expression); return tExpr; } #region Zing nodes private ZArray VisitArray(ZArray array) { if (array.IsDynamic) WriteStart("array {0}[] ", array.Name.Name); else WriteStart("array {0}[{1}] ", array.Name.Name, array.Sizes[0]); this.VisitTypeReference(array.ElementType); WriteFinish(";"); return array; } private AssertStatement VisitAssert(AssertStatement assert) { if (assert.Comment != null) { WriteStart("assert("); this.VisitExpression(assert.booleanExpr); Write(", @\"{0}\"", assert.Comment.Replace("\"", "\"\"")); WriteFinish(");"); } else { WriteStart("assert"); this.VisitParenthesizedExpression(assert.booleanExpr); WriteFinish(";"); } return assert; } private AcceptStatement VisitAccept(AcceptStatement accept) { WriteStart("accept"); this.VisitParenthesizedExpression(accept.booleanExpr); WriteFinish(";"); return accept; } private AssumeStatement VisitAssume(AssumeStatement assume) { WriteStart("assume"); this.VisitParenthesizedExpression(assume.booleanExpr); WriteFinish(";"); return assume; } private EventStatement VisitEventStatement(EventStatement Event) { WriteStart("event("); this.VisitExpression(Event.ChannelNumber); Write(", "); this.VisitExpression(Event.MessageType); Write(", "); this.VisitExpression(Event.Direction); WriteFinish(");"); return Event; } private TraceStatement VisitTrace(TraceStatement trace) { WriteStart("trace("); this.VisitExpressionList(trace.Operands); WriteFinish(");"); return trace; } private InvokePluginStatement VisitInvokePlugin(InvokePluginStatement InvokePlugin) { WriteStart("invokeplugin("); this.VisitExpressionList(InvokePlugin.Operands); WriteFinish(");"); return InvokePlugin; } private InvokeSchedulerStatement VisitInvokeSched(InvokeSchedulerStatement InvokeSched) { WriteStart("invokescheduler("); this.VisitExpressionList(InvokeSched.Operands); WriteFinish(");"); return InvokeSched; } private AsyncMethodCall VisitAsync(AsyncMethodCall async) { WriteLine("async"); this.VisitExpressionStatement((ExpressionStatement)async); return async; } private AtomicBlock VisitAtomic(AtomicBlock atomic) { WriteStart("atomic"); return (AtomicBlock)this.VisitBlock((Block)atomic); } private AttributedStatement VisitAttributedStatement(AttributedStatement attributedStmt) { this.VisitAttributeList(attributedStmt.Attributes); this.Visit(attributedStmt.Statement); return attributedStmt; } private Chan VisitChan(Chan chan) { WriteStart("chan {0} ", chan.Name.Name); this.VisitTypeReference(chan.ChannelType); WriteFinish(";"); return chan; } private UnaryExpression VisitChoose(UnaryExpression expr) { Write("choose"); this.VisitParenthesizedExpression(expr.Operand); return expr; } private BinaryExpression VisitIn(BinaryExpression expr) { Write("("); this.Visit(expr.Operand1); Write(" in "); this.Visit(expr.Operand2); Write(")"); return expr; } private Range VisitRange(Range range) { WriteStart("range {0} ", range.Name.Name); this.VisitExpression(range.Min); Write(" .. "); this.VisitExpression(range.Max); WriteFinish(";"); return range; } private SendStatement VisitSend(SendStatement send) { WriteStart("send("); this.VisitExpression(send.channel); Write(", "); this.VisitExpression(send.data); WriteFinish(");"); return send; } private Set VisitSet(Set @set) { WriteStart("set {0} ", @set.Name.Name); this.VisitTypeReference(@set.SetType); WriteFinish(";"); return @set; } private Select VisitSelect(Select select) { WriteStart("select "); if (select.deterministicSelection) Write("first "); if (select.Visible) Write("visible "); if (select.validEndState) Write("end "); if (this.braceOnNewLine) { WriteFinish(string.Empty); WriteLine("{"); } else WriteFinish("{"); In(); for (int i = 0, n = select.joinStatementList.Length; i < n; i++) this.VisitJoinStatement(select.joinStatementList[i]); Out(); WriteLine("}"); return select; } private JoinStatement VisitJoinStatement(JoinStatement joinstmt) { this.VisitAttributeList(joinstmt.Attributes); WriteStart(string.Empty); for (int i = 0, n = joinstmt.joinPatternList.Length; i < n; i++) { this.Visit(joinstmt.joinPatternList[i]); if ((i + 1) < n) Write(" && "); } Write(" -> "); bool indentStmt = !(joinstmt.statement is Block); if (indentStmt) In(); this.Visit(joinstmt.statement); if (indentStmt) Out(); return joinstmt; } private WaitPattern VisitWaitPattern(WaitPattern wp) { Write("wait "); this.VisitParenthesizedExpression(wp.expression); return wp; } private ReceivePattern VisitReceivePattern(ReceivePattern rp) { Write("receive("); this.Visit(rp.channel); Write(", "); this.Visit(rp.data); Write(")"); return rp; } private EventPattern VisitEventPattern(EventPattern ep) { Write("event("); this.Visit(ep.ChannelNumber); Write(", "); this.Visit(ep.MessageType); Write(", "); this.Visit(ep.Direction); Write(")"); return ep; } private TimeoutPattern VisitTimeoutPattern(TimeoutPattern tp) { Write("timeout"); return tp; } private ZTry VisitZTry(ZTry Try) { WriteStart("try"); this.VisitBlock(Try.Body); WriteLine("with"); WriteLine("{"); In(); for (int i = 0, n = Try.Catchers.Length; i < n; i++) this.VisitWith(Try.Catchers[i]); Out(); WriteLine("}"); return Try; } private With VisitWith(With with) { if (with.Name != null) WriteStart("{0} -> ", with.Name.Name); else WriteStart("* -> "); this.VisitBlock(with.Block); return with; } public override Statement VisitThrow(Throw Throw) { WriteLine("raise {0};", ((Identifier)Throw.Expression).Name); return Throw; } #endregion Zing nodes #region CCI nodes public override Expression VisitAssignmentExpression(AssignmentExpression assignment) { return base.VisitAssignmentExpression(assignment); } public override Statement VisitAssignmentStatement(AssignmentStatement assignment) { this.VisitExpression(assignment.Target); Write(" {0} ", GetAssignmentOperator(assignment.Operator)); this.VisitExpression(assignment.Source); return assignment; } public override Expression VisitAttributeConstructor(AttributeNode attribute) { throw new NotImplementedException("Node type not yet supported"); } public override AttributeNode VisitAttributeNode(AttributeNode attribute) { // Ignore the ParamArray attribute if (attribute.Constructor is MemberBinding) { MemberBinding mb = (MemberBinding)attribute.Constructor; if (mb.BoundMember.DeclaringType.Name.Name == "ParamArrayAttribute") return attribute; } WriteStart("["); this.VisitExpression(attribute.Constructor); Write("("); this.VisitExpressionList(attribute.Expressions); WriteFinish(")]"); return attribute; } public override AttributeList VisitAttributeList(AttributeList attributes) { return base.VisitAttributeList(attributes); } public override Expression VisitBinaryExpression(BinaryExpression binaryExpression) { Write("("); if ((binaryExpression.NodeType == NodeType.Castclass) || (binaryExpression.NodeType == NodeType.ExplicitCoercion)) { Write("("); this.VisitExpression(binaryExpression.Operand2); Write(") "); this.VisitExpression(binaryExpression.Operand1); } else { this.VisitExpression(binaryExpression.Operand1); Write(" {0} ", GetBinaryOperator(binaryExpression.NodeType)); this.VisitExpression(binaryExpression.Operand2); } Write(")"); return binaryExpression; } public override Block VisitBlock(Block block) { // We special-case this because it's how a null statement is // represented. if (block.Statements == null) { WriteLine(";"); return block; } if (this.braceOnNewLine) { WriteFinish(string.Empty); WriteLine("{"); } else WriteFinish(" {"); In(); Block result = base.VisitBlock(block); Out(); WriteLine("}"); return result; } public override Class VisitClass(Class Class) { WriteStart("class {0}", Class.Name.Name); if (this.braceOnNewLine) { WriteFinish(string.Empty); WriteLine("{"); } else WriteFinish(" {"); In(); Class.Members = this.VisitMemberList(Class.Members); Out(); WriteLine("};"); return Class; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public override MemberList VisitMemberList(MemberList members) { if (members == null) return null; for (int i = 0, n = members.Count; i < n; i++) { Member mem = members[i]; if (mem == null) continue; this.Visit(mem); if (this.options.BlankLinesBetweenMembers && (i + 1) < n) WriteLine(string.Empty); } return members; } public override Expression VisitConstruct(Construct cons) { Write("new "); this.VisitExpression(cons.Constructor); // This only happens for variable-length arrays, and only one // parameter is permitted. if (cons.Operands.Count > 0) { Write("["); this.VisitExpression(cons.Operands[0]); Write("]"); } return cons; } public override EnumNode VisitEnumNode(EnumNode enumNode) { WriteStart("enum {0}", enumNode.Name.Name); if (this.braceOnNewLine) { WriteFinish(string.Empty); WriteLine("{"); } else WriteFinish(" {"); In(); for (int i = 0, n = enumNode.Members.Count; i < n; i++) { Field field = (Field)enumNode.Members[i]; if (!field.IsSpecialName) { WriteStart(field.Name.Name); WriteFinish(","); } } Out(); WriteLine("};"); return enumNode; } public override Expression VisitExpression(Expression expression) { Expression result = base.VisitExpression(expression); return result; } public override ExpressionList VisitExpressionList(ExpressionList list) { if (list == null) return null; for (int i = 0, n = list.Count; i < n; i++) { this.VisitExpression(list[i]); if (i < (n - 1)) Write(", "); } return list; } public override Statement VisitExpressionStatement(ExpressionStatement statement) { WriteStart(string.Empty); int len = this.SourceLength; base.VisitExpressionStatement(statement); if (len != this.SourceLength) Write(";"); WriteFinish(string.Empty); return statement; } public override Field VisitField(Field field) { if (field == null) return null; WriteStart(GetFieldQualifiers(field)); this.VisitTypeReference(field.Type); Write(" {0}", field.Name.Name); if (field.Initializer != null) { Write(" = "); field.Initializer = this.VisitExpression(field.Initializer); } WriteFinish(";"); return field; } public override Statement VisitForEach(ForEach forEach) { WriteStart("foreach ("); this.VisitTypeReference(forEach.TargetVariableType); Write(" "); this.VisitExpression(forEach.TargetVariable); Write(" in "); this.VisitExpression(forEach.SourceEnumerable); Write(")"); this.VisitBlock(forEach.Body); return forEach; } public override Statement VisitGoto(Goto Goto) { WriteLine("goto {0};", Goto.TargetLabel.Name); return Goto; } public override Expression VisitIdentifier(Identifier identifier) { Write(identifier.Name); return identifier; } public override Statement VisitIf(If If) { WriteStart("if "); this.VisitParenthesizedExpression(If.Condition); Write(""); this.VisitBlock(If.TrueBlock); if (If.FalseBlock != null) { WriteStart("else"); this.VisitBlock(If.FalseBlock); } return If; } public override Expression VisitIndexer(Indexer indexer) { this.VisitExpression(indexer.Object); Write("["); this.VisitExpressionList(indexer.Operands); Write("]"); return indexer; } public override Statement VisitLabeledStatement(LabeledStatement lStatement) { if (lStatement.Statement is Block && !this.braceOnNewLine) WriteStart("{0}:", lStatement.Label.Name); else WriteLine("{0}:", lStatement.Label.Name); return base.VisitLabeledStatement(lStatement); } public override Expression VisitLiteral(Literal literal) { // TODO: probably need special cases here for the various integer & real types. // Also need to investigate quoting behavior in string literals. if (literal.Value == null) Write("null"); else if (literal.Value is string) Write("@\"{0}\"", literal.Value.ToString().Replace("\"", "\"\"")); else if (literal.Value is bool) Write(((bool)literal.Value) ? "true" : "false"); else if (literal.Value is char) Write("'\\x{0:X4}'", ((ushort)(char)literal.Value)); else if (literal.Value is TypeNode) this.VisitTypeReference((TypeNode)literal.Value); else if (literal.Type == SystemTypes.UInt64) Write("{0}ul", literal.Value); else Write("{0}", literal.Value); return literal; } public override Expression VisitMethodCall(MethodCall call) { if (call == null) return null; QualifiedIdentifier id = call.Callee as QualifiedIdentifier; if (id != null) { if (id.Identifier.Name == ".ctor") return call; } this.VisitExpression(call.Callee); Write("("); this.VisitExpressionList(call.Operands); Write(")"); return call; } public override Expression VisitMemberBinding(MemberBinding memberBinding) { // TODO: Just guessing here for now - need to understand this better. if (memberBinding == null) return null; if (memberBinding.TargetObject != null) this.VisitExpression(memberBinding.TargetObject); else if (memberBinding.BoundMember is TypeExpression) this.VisitExpression(((TypeExpression)memberBinding.BoundMember).Expression); else if (memberBinding.BoundMember is TypeNode) this.VisitTypeReference((TypeNode)memberBinding.BoundMember); else if (memberBinding.BoundMember is InstanceInitializer) this.VisitTypeReference(((InstanceInitializer)memberBinding.BoundMember).DeclaringType); else throw new NotImplementedException("Unexpected scenario in VisitMemberBinding"); return memberBinding; } public override Method VisitMethod(Method method) { if (method == null) return null; WriteStart(GetMethodQualifiers(method)); method.ReturnType = this.VisitTypeReference(method.ReturnType); Write(" {0}(", method.Name.Name); this.VisitParameterList(method.Parameters); Write(")"); this.VisitBlock(method.Body); return method; } public override Namespace VisitNamespace(Namespace nspace) { this.VisitTypeNodeList(nspace.Types); return nspace; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public override TypeNodeList VisitTypeNodeList(TypeNodeList types) { if (types == null) return null; for (int i = 0; i < types.Count; i++) { types[i] = (TypeNode)this.Visit(types[i]); if (this.options.BlankLinesBetweenMembers && (i + 1 < types.Count)) WriteLine(string.Empty); } return types; } public override Expression VisitParameter(Parameter parameter) { if (parameter == null) return null; Write("{0}", GetParameterDirection(parameter.Flags)); this.VisitTypeReference(parameter.Type); Write(" "); if (parameter.DefaultValue != null) throw new ArgumentException("Unexpected parameter default value"); Write("{0}", parameter.Name.Name); return parameter; } public override ParameterList VisitParameterList(ParameterList parameterList) { if (parameterList == null) return null; for (int i = 0, n = parameterList.Count; i < n; i++) { this.VisitParameter(parameterList[i]); if (i < (n - 1)) Write(", "); } return parameterList; } public override Expression VisitQualifiedIdentifier(QualifiedIdentifier qualifiedIdentifier) { this.VisitExpression(qualifiedIdentifier.Qualifier); Write("."); this.VisitIdentifier(qualifiedIdentifier.Identifier); return qualifiedIdentifier; } public override Statement VisitReturn(Return Return) { if (Return == null) return null; WriteStart("return"); if (Return.Expression != null) { Write(" "); this.VisitExpression(Return.Expression); } WriteFinish(";"); return Return; } public override StatementList VisitStatementList(StatementList statements) { if (statements == null) { WriteLine(";"); return null; } for (int i = 0, n = statements.Count; i < n; i++) this.Visit(statements[i]); return statements; } public override Struct VisitStruct(Struct Struct) { WriteStart("struct {0}", Struct.Name.Name); if (this.braceOnNewLine) { WriteFinish(string.Empty); WriteLine("{"); } else WriteFinish(" {"); In(); this.VisitMemberList(Struct.Members); Out(); WriteLine("};"); return Struct; } public override Expression VisitThis(This This) { Write("this"); return This; } private static string TranslateTypeName(string typeName) { switch (typeName) { case "Object": return "object"; case "Void": return "void"; case "Byte": return "byte"; case "SByte": return "sbyte"; case "Int16": return "short"; case "UInt16": return "ushort"; case "Int32": return "int"; case "UInt32": return "uint"; case "Int64": return "long"; case "UInt64": return "ulong"; case "Single": return "float"; case "Double": return "double"; case "Decimal": return "decimal"; case "String": return "string"; case "Char": return "char"; case "Boolean": return "bool"; default: return null; } } public override TypeNode VisitTypeReference(TypeNode type) { string nativeType = null; ArrayTypeExpression ate = type as ArrayTypeExpression; ReferenceTypeExpression rte = type as ReferenceTypeExpression; InterfaceExpression ie = type as InterfaceExpression; TypeExpression te = type as TypeExpression; if (type.Name != null) nativeType = TranslateTypeName(type.Name.Name); if (nativeType != null) Write(nativeType); else if (te != null) this.VisitExpression(te.Expression); else if (ie != null) this.VisitExpression(ie.Expression); else if (ate != null) { this.VisitTypeReference(ate.ElementType); if (ate.Rank > 1) throw new NotImplementedException("Multidimensional arrays not yet implemented"); Write("[]"); } else if (rte != null) { // This occurs with "out" parameters where we've already noted the unique // nature of the parameter via the parameter direction. Here, we can just // recurse on the ElementType and ignore the indirection. For other scenarios, // (e.g. unsafe code?) this would be incorrect. this.VisitTypeReference(rte.ElementType); } else if (type.FullName != null && type.FullName.Length > 0) { // ISSUE: Is this ever a good idea? int sepPos = type.FullName.IndexOf('+'); if (sepPos > 0) Write(type.FullName.Substring(sepPos + 1)); else Write(type.FullName); } else if (type.Name != null) Write(type.Name.Name); else throw new NotImplementedException("Unsupported type reference style"); return type; } public override Expression VisitUnaryExpression(UnaryExpression unaryExpression) { bool isFunctionStyle; string opString; opString = GetUnaryOperator(unaryExpression.NodeType, out isFunctionStyle); if (isFunctionStyle) { Write("{0}(", opString); this.VisitExpression(unaryExpression.Operand); Write(")"); } else { Write(opString); this.VisitExpression(unaryExpression.Operand); } return unaryExpression; } public override Statement VisitVariableDeclaration(VariableDeclaration variableDeclaration) { WriteStart(""); this.VisitTypeReference(variableDeclaration.Type); Write(" {0}", variableDeclaration.Name.Name); if (variableDeclaration.Initializer != null) { Write(" = "); this.Visit(variableDeclaration.Initializer); } WriteFinish(";"); return variableDeclaration; } public override Statement VisitWhile(While While) { WriteStart("while "); this.VisitParenthesizedExpression(While.Condition); this.VisitBlock(While.Body); return While; } private static string GetMethodQualifiers(Method method) { string qualifiers = string.Empty; ZMethod zm = method as ZMethod; if (method.IsStatic) qualifiers += "static "; if (zm != null && zm.Atomic) qualifiers += "atomic "; if (zm != null && zm.Activated) qualifiers += "activate "; return qualifiers; } private static string GetParameterDirection(ParameterFlags flags) { switch (flags) { case ParameterFlags.None: return string.Empty; case ParameterFlags.In: return string.Empty; case ParameterFlags.Out: return "out "; case ParameterFlags.In | ParameterFlags.Out: return "ref "; default: throw new ArgumentException("Unexpected ParameterFlags value"); } } private static string GetAssignmentOperator(NodeType op) { Debug.Assert(op == NodeType.Nop, "Invalid assignment operator type"); return "="; } private static string GetFieldQualifiers(Field field) { string qualifiers = string.Empty; if (field.IsStatic) qualifiers += "static "; return qualifiers; } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static string GetBinaryOperator(NodeType nodeType) { switch (nodeType) { case NodeType.Add: case NodeType.Add_Ovf_Un: case NodeType.Add_Ovf: return "+"; case NodeType.And: return "&"; case NodeType.Div: return "/"; case NodeType.Eq: return "=="; case NodeType.Ge: return ">="; case NodeType.Gt: return ">"; case NodeType.Le: return "<="; case NodeType.LogicalAnd: return "&&"; case NodeType.LogicalOr: return "||"; case NodeType.Lt: return "<"; case NodeType.Mul: return "*"; case NodeType.Ne: return "!="; case NodeType.Or: return "|"; case NodeType.Shl: return "<<"; case NodeType.Shr: return ">>"; case NodeType.Xor: return "^"; case NodeType.Rem: return "%"; case NodeType.Sub: case NodeType.Sub_Ovf_Un: case NodeType.Sub_Ovf: return "-"; default: throw new NotImplementedException("Binary operator not supported"); } } private static string GetUnaryOperator(NodeType nodeType, out bool isFunctionStyle) { isFunctionStyle = false; switch (nodeType) { case NodeType.LogicalNot: return "!"; case NodeType.Not: return "~"; case NodeType.Neg: return "-"; case NodeType.UnaryPlus: return "+"; case NodeType.Sizeof: isFunctionStyle = true; return "sizeof"; case NodeType.OutAddress: return "out "; case NodeType.RefAddress: return "ref "; case NodeType.Parentheses: isFunctionStyle = true; return string.Empty; default: throw new NotImplementedException("Unary operator not supported"); } } } #endregion CCI nodes }
using System; using System.Collections.Generic; using System.Text; using gView.Framework.Carto; using gView.Framework.Geometry; using gView.Framework.Symbology; using gView.Framework.UI; using gView.Framework.IO; using gView.Framework.GPS; namespace gView.Plugins.GPS { internal class GPSPoint : IGraphicElement { private double _lon, _lat; private bool _hook; public GPSPoint(double lon, double lat, bool hook) { _lon = lon; _lat = lat; _hook = hook; } #region IGraphicElement Members internal IPoint Project(IDisplay display) { if (display.SpatialReference != null) { return GeometricTransformer.Transform2D(new Point(_lon, _lat), SpatialReference.FromID("EPSG:4326"), display.SpatialReference) as IPoint; } else { return new Point(_lon, _lat); } } public void Draw(IDisplay display) { if (_hook && Device.GPS != null) { _lon = Device.GPS.Longitude; _lat = Device.GPS.Latitude; } if (display == null || display.GraphicsContext == null) return; IPoint mapPoint = Project(display); if (mapPoint != null) { double x = mapPoint.X, y = mapPoint.Y; display.World2Image(ref x, ref y); using (System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Red,2)) { display.GraphicsContext.DrawEllipse(pen, (float)x - 8, (float)y - 8, 16, 16); display.GraphicsContext.DrawLine(pen, (float)x - 8, (float)y, (float)x + 8, (float)y); display.GraphicsContext.DrawLine(pen, (float)x, (float)y - 8, (float)x, (float)y + 8); } } } #endregion } [gView.Framework.system.RegisterPlugIn("37D3FFDB-F847-4053-A08A-99895266D7EF")] public class GPSTrack : IGraphicElement, IPersistable { private Polyline _polyline; private ISymbol _symbol,_pointSymbol; private bool _connected; IMapDocument _doc; private IMap _map; public GPSTrack() { _polyline = new Polyline(); _polyline.AddPath(new Path()); _symbol = new SimpleLineSymbol(); ((SimpleLineSymbol)_symbol).Color = System.Drawing.Color.Red; _pointSymbol = new SimplePointSymbol(); ((SimplePointSymbol)_pointSymbol).Color = System.Drawing.Color.Red; ((SimplePointSymbol)_pointSymbol).Size = 5; } public GPSTrack(IMapDocument doc) : this() { _doc = doc; _map = doc.FocusMap; Connect(); } public void Connect() { if (_connected) return; Device.GPS.PositionReceived += new GPSDevice.PositionReceivedEventHandler(GPS_PositionReceived); _connected = true; } public void Disconnect() { Device.GPS.PositionReceived -= new GPSDevice.PositionReceivedEventHandler(GPS_PositionReceived); _connected = false; } public bool IsConnected { get { return _connected; } } private IPolyline Project(IDisplay display) { if (display.SpatialReference != null) { return GeometricTransformer.Transform2D(_polyline, SpatialReference.FromID("EPSG:4326"), display.SpatialReference) as IPolyline; } else { return _polyline; } } void GPS_PositionReceived(GPSDevice sender, string latitude, string longitude, double deciLat, double deciLon) { if (_polyline[0].PointCount > 0) { IPoint p = _polyline[0][_polyline[0].PointCount - 1]; if (Math.Abs(p.X - deciLon) < 1e-10 && Math.Abs(p.Y - deciLat) < 1e-10) return; } _polyline[_polyline.PathCount-1].AddPoint( new TrackPoint(sender, deciLat, deciLon)); //if (_doc != null && _doc.FocusMap != null && _doc.FocusMap == _map && // _doc.Application is IMapApplication) //{ // ((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.Graphics); //} } #region IGraphicElement Member public void Draw(IDisplay display) { IPolyline pLine = Project(display); if (pLine != null) { if (_pointSymbol != null) { for (int i = 0; i < pLine[0].PointCount; i++) { display.Draw(_pointSymbol, pLine[0][i]); } } if (_symbol != null) { display.Draw(_symbol, pLine); } } } #endregion #region HelperClasses private class TrackPoint : IPoint, IPersistable { private double _lon, _lat, _h, _speed; private double _pdop, _hdop, _vdop; internal TrackPoint() {} public TrackPoint(GPSDevice sender, double deciLat, double deciLon) { _lat = deciLat; _lon = deciLon; _h = sender.EllipsoidHeight; _speed = sender.Speed; _pdop = sender.PDOP; _hdop = sender.HDOP; _vdop = sender.VDOP; } public double Longitude { get { return _lon; } } public double Latitude { get { return _lat; } } public double PDOP { get { return _pdop; } } public double VDOP { get { return _vdop; } } public double HDOP { get { return _hdop; } } #region IPoint Member public double X { get { return _lon; } set { } } public double Y { get { return _lat; } set { } } public double Z { get { return _h; } set { } } public double M { get { return 0.0; } set { } } #endregion #region IGeometry Member public geometryType GeometryType { get { return geometryType.Point; } } public IEnvelope Envelope { get { return new Envelope(this.X, this.Y, this.X, this.Y); } } public void Serialize(System.IO.BinaryWriter w, IGeometryDef geomDef) { } public void Deserialize(System.IO.BinaryReader r, IGeometryDef geomDef) { } public int? Srs { get; set; } #endregion #region ICloneable Member public object Clone() { return new Point(this.X, this.Y); } #endregion #region IPersistable Member public void Load(IPersistStream stream) { _lon = (double)stream.Load("Lon", 0.0); _lat = (double)stream.Load("Lat", 0.0); _h = (double)stream.Load("h", 0.0); _speed = (double)stream.Load("Speed", 0.0); _pdop = (double)stream.Load("PDOP", 0.0); _vdop = (double)stream.Load("VDOP", 0.0); _hdop = (double)stream.Load("HDOP", 0.0); } public void Save(IPersistStream stream) { stream.Save("Lon", _lon); stream.Save("Lat", _lat); stream.Save("h", _h); stream.Save("Speed", _speed); stream.Save("PDOP", _pdop); stream.Save("VDOP", _vdop); stream.Save("HDOP", _hdop); } #endregion public override bool Equals(object obj) { return Equals(obj, 0.0); } public bool Equals(object obj, double epsi) { if (obj is IPoint) { IPoint point = (IPoint)obj; return Math.Abs(point.X - this.X) <= epsi && Math.Abs(point.Y - this.Y) <= epsi && Math.Abs(point.Z - this.Z) <= epsi; } return false; } #region IPoint Member public double Distance(IPoint p) { throw new NotImplementedException(); } #endregion #region IPoint Member public double Distance2(IPoint p) { throw new NotImplementedException(); } #endregion } #endregion #region IPersistable Member public void Load(IPersistStream stream) { TrackPoint point; while ((point = (TrackPoint)stream.Load("Point", null, new TrackPoint())) != null) { _polyline[0].AddPoint(point); } } public void Save(IPersistStream stream) { if (_polyline == null || _polyline.PathCount != 1) return; for (int i = 0; i < _polyline[0].PointCount; i++) { stream.Save("Point", _polyline[0][i]); } } #endregion } }
using System; using System.Drawing; using FoxTrader.UI.ControlInternal; using FoxTrader.UI.DragDrop; using static FoxTrader.Constants; namespace FoxTrader.UI.Control { /// <summary>Base for dockable containers</summary> internal class Panel : GameControl { private Panel m_bottom; // Only CHILD dockpanels have a tabcontrol. private DockedTabControl m_dockedTabControl; private bool m_drawHover; private bool m_dropFar; private Rectangle m_hoverRect; private Panel m_left; private Panel m_right; private Resizer m_sizer; private Panel m_top; /// <summary>Initializes a new instance of the <see cref="Panel" /> class</summary> /// <param name="c_parentControl">Parent control</param> public Panel(GameControl c_parentControl) : base(c_parentControl) { Padding = Padding.kOne; SetSize(200, 200); } // TODO: dock events? /// <summary>Control docked on the left side</summary> public Panel LeftPanel => GetChildPanel(Pos.Left); /// <summary>Control docked on the right side</summary> public Panel RightPanel => GetChildPanel(Pos.Right); /// <summary>Control docked on the top side</summary> public Panel TopPanel => GetChildPanel(Pos.Top); /// <summary>Control docked on the bottom side</summary> public Panel BottomPanel => GetChildPanel(Pos.Bottom); public TabControl TabControl => m_dockedTabControl; /// <summary>Indicates whether the control contains any docked children</summary> public virtual bool IsEmpty { get { if (m_dockedTabControl != null && m_dockedTabControl.TabCount > 0) { return false; } if (m_left != null && !m_left.IsEmpty) { return false; } if (m_right != null && !m_right.IsEmpty) { return false; } if (m_top != null && !m_top.IsEmpty) { return false; } if (m_bottom != null && !m_bottom.IsEmpty) { return false; } return true; } } /// <summary>Initializes an inner docked control for the specified position</summary> /// <param name="c_pos">Dock position</param> protected virtual void SetupChildPanel(Pos c_pos) { if (m_dockedTabControl == null) { m_dockedTabControl = new DockedTabControl(this); m_dockedTabControl.TabRemoved += OnTabRemoved; m_dockedTabControl.TabStripPosition = Pos.Bottom; m_dockedTabControl.TitleBarVisible = true; } Dock = c_pos; Pos a_sizeDir; if (c_pos == Pos.Right) { a_sizeDir = Pos.Left; } else if (c_pos == Pos.Left) { a_sizeDir = Pos.Right; } else if (c_pos == Pos.Top) { a_sizeDir = Pos.Bottom; } else if (c_pos == Pos.Bottom) { a_sizeDir = Pos.Top; } else { throw new ArgumentException("Invalid dock", "c_pos"); } if (m_sizer != null) { m_sizer.Dispose(); } m_sizer = new Resizer(this); m_sizer.Dock = a_sizeDir; m_sizer.ResizeDir = a_sizeDir; m_sizer.SetSize(2, 2); } /// <summary>Renders the control using specified skin</summary> /// <param name="c_skin">Skin to use</param> protected override void Render(Skin c_skin) { } /// <summary>Gets an inner docked control for the specified position</summary> /// <param name="c_pos"></param> /// <returns></returns> protected virtual Panel GetChildPanel(Pos c_pos) { // TODO: verify Panel a_dock = null; switch (c_pos) { case Pos.Left: if (m_left == null) { m_left = new Panel(this); m_left.SetupChildPanel(c_pos); } a_dock = m_left; break; case Pos.Right: if (m_right == null) { m_right = new Panel(this); m_right.SetupChildPanel(c_pos); } a_dock = m_right; break; case Pos.Top: if (m_top == null) { m_top = new Panel(this); m_top.SetupChildPanel(c_pos); } a_dock = m_top; break; case Pos.Bottom: if (m_bottom == null) { m_bottom = new Panel(this); m_bottom.SetupChildPanel(c_pos); } a_dock = m_bottom; break; } if (a_dock != null) { a_dock.IsHidden = false; } return a_dock; } /// <summary>Calculates dock direction from dragdrop coordinates</summary> /// <param name="c_x">X coordinate</param> /// <param name="c_y">Y coordinate</param> /// <returns>Dock direction</returns> protected virtual Pos GetDroppedTabDirection(int c_x, int c_y) { var a_w = Width; var a_h = Height; var a_top = c_y / (float)a_h; var a_left = c_x / (float)a_w; var a_right = (a_w - c_x) / (float)a_w; var a_bottom = (a_h - c_y) / (float)a_h; var a_minimum = Math.Min(Math.Min(Math.Min(a_top, a_left), a_right), a_bottom); m_dropFar = (a_minimum < 0.2f); if (a_minimum > 0.3f) { return Pos.Fill; } if (a_top == a_minimum && (null == m_top || m_top.IsHidden)) { return Pos.Top; } if (a_left == a_minimum && (null == m_left || m_left.IsHidden)) { return Pos.Left; } if (a_right == a_minimum && (null == m_right || m_right.IsHidden)) { return Pos.Right; } if (a_bottom == a_minimum && (null == m_bottom || m_bottom.IsHidden)) { return Pos.Bottom; } return Pos.Fill; } public override bool DragAndDrop_CanAcceptPackage(Package c_p) { // A TAB button dropped if (c_p.m_name == "TabButtonMove") { return true; } // a TAB window dropped if (c_p.m_name == "TabWindowMove") { return true; } return false; } public override bool DragAndDrop_HandleDrop(Package c_p, int c_x, int c_y) { var a_pos = CanvasPosToLocal(new Point(c_x, c_y)); var a_dir = GetDroppedTabDirection(a_pos.X, a_pos.Y); var a_addTo = m_dockedTabControl; if (a_dir == Pos.Fill && a_addTo == null) { return false; } if (a_dir != Pos.Fill) { var a_dock = GetChildPanel(a_dir); a_addTo = a_dock.m_dockedTabControl; if (!m_dropFar) { a_dock.BringToFront(); } else { a_dock.SendToBack(); } } if (c_p.m_name == "TabButtonMove") { var a_tabButton = DragAndDrop.m_sourceControl as TabButton; if (null == a_tabButton) { return false; } a_addTo.AddPage(a_tabButton); } if (c_p.m_name == "TabWindowMove") { var a_tabControl = DragAndDrop.m_sourceControl as DockedTabControl; if (null == a_tabControl) { return false; } if (a_tabControl == a_addTo) { return false; } a_tabControl.MoveTabsTo(a_addTo); } Invalidate(); return true; } protected virtual void OnTabRemoved(GameControl c_control) { DoRedundancyCheck(); DoConsolidateCheck(); } protected virtual void DoRedundancyCheck() { if (!IsEmpty) { return; } var a_pDockParent = Parent as Panel; if (null == a_pDockParent) { return; } a_pDockParent.OnRedundantChildPanel(this); } protected virtual void DoConsolidateCheck() { if (IsEmpty) { return; } if (null == m_dockedTabControl) { return; } if (m_dockedTabControl.TabCount > 0) { return; } if (m_bottom != null && !m_bottom.IsEmpty) { m_bottom.m_dockedTabControl.MoveTabsTo(m_dockedTabControl); return; } if (m_top != null && !m_top.IsEmpty) { m_top.m_dockedTabControl.MoveTabsTo(m_dockedTabControl); return; } if (m_left != null && !m_left.IsEmpty) { m_left.m_dockedTabControl.MoveTabsTo(m_dockedTabControl); return; } if (m_right != null && !m_right.IsEmpty) { m_right.m_dockedTabControl.MoveTabsTo(m_dockedTabControl); } } protected virtual void OnRedundantChildPanel(Panel c_panel) { c_panel.IsHidden = true; DoRedundancyCheck(); DoConsolidateCheck(); } public override void DragAndDrop_HoverEnter(Package c_p, int c_x, int c_y) { m_drawHover = true; } public override void DragAndDrop_HoverLeave(Package c_p) { m_drawHover = false; } public override void DragAndDrop_Hover(Package c_p, int c_x, int c_y) { var a_pos = CanvasPosToLocal(new Point(c_x, c_y)); var a_dir = GetDroppedTabDirection(a_pos.X, a_pos.Y); if (a_dir == Pos.Fill) { if (null == m_dockedTabControl) { m_hoverRect = Rectangle.Empty; return; } m_hoverRect = InnerBounds; return; } m_hoverRect = RenderBounds; var a_helpBarWidth = 0; if (a_dir == Pos.Left) { a_helpBarWidth = (int)(m_hoverRect.Width * 0.25f); m_hoverRect.Width = a_helpBarWidth; } if (a_dir == Pos.Right) { a_helpBarWidth = (int)(m_hoverRect.Width * 0.25f); m_hoverRect.X = m_hoverRect.Width - a_helpBarWidth; m_hoverRect.Width = a_helpBarWidth; } if (a_dir == Pos.Top) { a_helpBarWidth = (int)(m_hoverRect.Height * 0.25f); m_hoverRect.Height = a_helpBarWidth; } if (a_dir == Pos.Bottom) { a_helpBarWidth = (int)(m_hoverRect.Height * 0.25f); m_hoverRect.Y = m_hoverRect.Height - a_helpBarWidth; m_hoverRect.Height = a_helpBarWidth; } if ((a_dir == Pos.Top || a_dir == Pos.Bottom) && !m_dropFar) { if (m_left != null && m_left.IsVisible) { m_hoverRect.X += m_left.Width; m_hoverRect.Width -= m_left.Width; } if (m_right != null && m_right.IsVisible) { m_hoverRect.Width -= m_right.Width; } } if ((a_dir == Pos.Left || a_dir == Pos.Right) && !m_dropFar) { if (m_top != null && m_top.IsVisible) { m_hoverRect.Y += m_top.Height; m_hoverRect.Height -= m_top.Height; } if (m_bottom != null && m_bottom.IsVisible) { m_hoverRect.Height -= m_bottom.Height; } } } /// <summary>Renders over the actual control (overlays)</summary> /// <param name="c_skin">Skin to use</param> protected override void RenderOver(Skin c_skin) { if (!m_drawHover) { return; } var a_render = c_skin.Renderer; a_render.DrawColor = Color.FromArgb(20, 255, 200, 255); a_render.DrawFilledRect(RenderBounds); if (m_hoverRect.Width == 0) { return; } a_render.DrawColor = Color.FromArgb(100, 255, 200, 255); a_render.DrawFilledRect(m_hoverRect); a_render.DrawColor = Color.FromArgb(200, 255, 200, 255); a_render.DrawLinedRect(m_hoverRect); } } }
using System; using System.Collections.Generic; using ClipperLib; using MatterHackers.Agg.Transform; using MatterHackers.Agg.UI; using MatterHackers.Agg.UI.Examples; using MatterHackers.Agg.VertexSource; using MatterHackers.DataConverters2D; using MatterHackers.VectorMath; namespace MatterHackers.Agg { public class PolygonClippingDemo : GuiWidget, IDemoApp { private VertexStorage CombinePaths(IVertexSource a, IVertexSource b, ClipType clipType) { List<List<IntPoint>> aPolys = VertexSourceToClipperPolygons.CreatePolygons(a); List<List<IntPoint>> bPolys = VertexSourceToClipperPolygons.CreatePolygons(b); Clipper clipper = new Clipper(); clipper.AddPaths(aPolys, PolyType.ptSubject, true); clipper.AddPaths(bPolys, PolyType.ptClip, true); List<List<IntPoint>> intersectedPolys = new List<List<IntPoint>>(); clipper.Execute(clipType, intersectedPolys); VertexStorage output = VertexSourceToClipperPolygons.CreateVertexStorage(intersectedPolys); output.Add(0, 0, ShapePath.FlagsAndCommand.Stop); return output; } private double m_x; private double m_y; private RadioButtonGroup m_operation; private RadioButtonGroup m_polygons; public PolygonClippingDemo() { BackgroundColor = Color.White; m_operation = new RadioButtonGroup(new Vector2(555, 5), new Vector2(80, 130)) { HAnchor = HAnchor.Right | HAnchor.Fit, VAnchor = VAnchor.Bottom | VAnchor.Fit, Margin = new BorderDouble(5), }; m_polygons = new RadioButtonGroup(new Vector2(5, 5), new Vector2(205, 110)) { HAnchor = HAnchor.Left | HAnchor.Fit, VAnchor = VAnchor.Bottom | VAnchor.Fit, Margin = new BorderDouble(5), }; m_operation.AddRadioButton("None"); m_operation.AddRadioButton("OR"); m_operation.AddRadioButton("AND"); m_operation.AddRadioButton("XOR"); m_operation.AddRadioButton("A-B"); m_operation.AddRadioButton("B-A"); m_operation.SelectedIndex = 2; AddChild(m_operation); m_polygons.AddRadioButton("Two Simple Paths"); m_polygons.AddRadioButton("Closed Stroke"); m_polygons.AddRadioButton("Great Britain and Arrows"); m_polygons.AddRadioButton("Great Britain and Spiral"); m_polygons.AddRadioButton("Spiral and Glyph"); m_polygons.SelectedIndex = 3; AddChild(m_polygons); AnchorAll(); } public string Title { get; } = "PolygonClipping"; public string DemoCategory { get; } = "Clipping"; public string DemoDescription { get; } = "Demonstration of general polygon clipping using the clipper library."; private void render_gpc(Graphics2D graphics2D) { switch (m_polygons.SelectedIndex) { case 0: { //------------------------------------ // Two simple paths // VertexStorage ps1 = new VertexStorage(); VertexStorage ps2 = new VertexStorage(); double x = m_x - Width / 2 + 100; double y = m_y - Height / 2 + 100; ps1.MoveTo(x + 140, y + 145); ps1.LineTo(x + 225, y + 44); ps1.LineTo(x + 296, y + 219); ps1.ClosePolygon(); ps1.LineTo(x + 226, y + 289); ps1.LineTo(x + 82, y + 292); ps1.MoveTo(x + 220, y + 222); ps1.LineTo(x + 363, y + 249); ps1.LineTo(x + 265, y + 331); ps1.MoveTo(x + 242, y + 243); ps1.LineTo(x + 268, y + 309); ps1.LineTo(x + 325, y + 261); ps1.MoveTo(x + 259, y + 259); ps1.LineTo(x + 273, y + 288); ps1.LineTo(x + 298, y + 266); ps2.MoveTo(100 + 32, 100 + 77); ps2.LineTo(100 + 473, 100 + 263); ps2.LineTo(100 + 351, 100 + 290); ps2.LineTo(100 + 354, 100 + 374); graphics2D.Render(ps1, new ColorF(0, 0, 0, 0.1).ToColor()); graphics2D.Render(ps2, new ColorF(0, 0.6, 0, 0.1).ToColor()); CreateAndRenderCombined(graphics2D, ps1, ps2); } break; case 1: { //------------------------------------ // Closed stroke // VertexStorage ps1 = new VertexStorage(); VertexStorage ps2 = new VertexStorage(); Stroke stroke = new Stroke(ps2); stroke.Width = 10.0; double x = m_x - Width / 2 + 100; double y = m_y - Height / 2 + 100; ps1.MoveTo(x + 140, y + 145); ps1.LineTo(x + 225, y + 44); ps1.LineTo(x + 296, y + 219); ps1.ClosePolygon(); ps1.LineTo(x + 226, y + 289); ps1.LineTo(x + 82, y + 292); ps1.MoveTo(x + 220 - 50, y + 222); ps1.LineTo(x + 265 - 50, y + 331); ps1.LineTo(x + 363 - 50, y + 249); ps1.close_polygon(ShapePath.FlagsAndCommand.FlagCCW); ps2.MoveTo(100 + 32, 100 + 77); ps2.LineTo(100 + 473, 100 + 263); ps2.LineTo(100 + 351, 100 + 290); ps2.LineTo(100 + 354, 100 + 374); ps2.ClosePolygon(); graphics2D.Render(ps1, new ColorF(0, 0, 0, 0.1).ToColor()); graphics2D.Render(stroke, new ColorF(0, 0.6, 0, 0.1).ToColor()); CreateAndRenderCombined(graphics2D, ps1, stroke); } break; case 2: { //------------------------------------ // Great Britain and Arrows // VertexStorage gb_poly = new VertexStorage(); VertexStorage arrows = new VertexStorage(); GreatBritanPathStorage.Make(gb_poly); make_arrows(arrows); Affine mtx1 = Affine.NewIdentity(); Affine mtx2 = Affine.NewIdentity(); mtx1 *= Affine.NewTranslation(-1150, -1150); mtx1 *= Affine.NewScaling(2.0); mtx2 = mtx1; mtx2 *= Affine.NewTranslation(m_x - Width / 2, m_y - Height / 2); VertexSourceApplyTransform trans_gb_poly = new VertexSourceApplyTransform(gb_poly, mtx1); VertexSourceApplyTransform trans_arrows = new VertexSourceApplyTransform(arrows, mtx2); graphics2D.Render(trans_gb_poly, new ColorF(0.5, 0.5, 0, 0.1).ToColor()); Stroke stroke_gb_poly = new Stroke(trans_gb_poly); stroke_gb_poly.Width = 0.1; graphics2D.Render(stroke_gb_poly, new ColorF(0, 0, 0).ToColor()); graphics2D.Render(trans_arrows, new ColorF(0.0, 0.5, 0.5, 0.1).ToColor()); CreateAndRenderCombined(graphics2D, trans_gb_poly, trans_arrows); } break; case 3: { //------------------------------------ // Great Britain and a Spiral // spiral sp = new spiral(m_x, m_y, 10, 150, 30, 0.0); Stroke stroke = new Stroke(sp); stroke.Width = 15.0; VertexStorage gb_poly = new VertexStorage(); GreatBritanPathStorage.Make(gb_poly); Affine mtx = Affine.NewIdentity(); ; mtx *= Affine.NewTranslation(-1150, -1150); mtx *= Affine.NewScaling(2.0); VertexSourceApplyTransform trans_gb_poly = new VertexSourceApplyTransform(gb_poly, mtx); graphics2D.Render(trans_gb_poly, new ColorF(0.5, 0.5, 0, 0.1).ToColor()); Stroke stroke_gb_poly = new Stroke(trans_gb_poly); stroke_gb_poly.Width = 0.1; graphics2D.Render(stroke_gb_poly, new ColorF(0, 0, 0).ToColor()); graphics2D.Render(stroke, new ColorF(0.0, 0.5, 0.5, 0.1).ToColor()); CreateAndRenderCombined(graphics2D, trans_gb_poly, stroke); } break; case 4: { //------------------------------------ // Spiral and glyph // spiral sp = new spiral(m_x, m_y, 10, 150, 30, 0.0); Stroke stroke = new Stroke(sp); stroke.Width = 15.0; VertexStorage glyph = new VertexStorage(); glyph.MoveTo(28.47, 6.45); glyph.curve3(21.58, 1.12, 19.82, 0.29); glyph.curve3(17.19, -0.93, 14.21, -0.93); glyph.curve3(9.57, -0.93, 6.57, 2.25); glyph.curve3(3.56, 5.42, 3.56, 10.60); glyph.curve3(3.56, 13.87, 5.03, 16.26); glyph.curve3(7.03, 19.58, 11.99, 22.51); glyph.curve3(16.94, 25.44, 28.47, 29.64); glyph.LineTo(28.47, 31.40); glyph.curve3(28.47, 38.09, 26.34, 40.58); glyph.curve3(24.22, 43.07, 20.17, 43.07); glyph.curve3(17.09, 43.07, 15.28, 41.41); glyph.curve3(13.43, 39.75, 13.43, 37.60); glyph.LineTo(13.53, 34.77); glyph.curve3(13.53, 32.52, 12.38, 31.30); glyph.curve3(11.23, 30.08, 9.38, 30.08); glyph.curve3(7.57, 30.08, 6.42, 31.35); glyph.curve3(5.27, 32.62, 5.27, 34.81); glyph.curve3(5.27, 39.01, 9.57, 42.53); glyph.curve3(13.87, 46.04, 21.63, 46.04); glyph.curve3(27.59, 46.04, 31.40, 44.04); glyph.curve3(34.28, 42.53, 35.64, 39.31); glyph.curve3(36.52, 37.21, 36.52, 30.71); glyph.LineTo(36.52, 15.53); glyph.curve3(36.52, 9.13, 36.77, 7.69); glyph.curve3(37.01, 6.25, 37.57, 5.76); glyph.curve3(38.13, 5.27, 38.87, 5.27); glyph.curve3(39.65, 5.27, 40.23, 5.62); glyph.curve3(41.26, 6.25, 44.19, 9.18); glyph.LineTo(44.19, 6.45); glyph.curve3(38.72, -0.88, 33.74, -0.88); glyph.curve3(31.35, -0.88, 29.93, 0.78); glyph.curve3(28.52, 2.44, 28.47, 6.45); glyph.ClosePolygon(); glyph.MoveTo(28.47, 9.62); glyph.LineTo(28.47, 26.66); glyph.curve3(21.09, 23.73, 18.95, 22.51); glyph.curve3(15.09, 20.36, 13.43, 18.02); glyph.curve3(11.77, 15.67, 11.77, 12.89); glyph.curve3(11.77, 9.38, 13.87, 7.06); glyph.curve3(15.97, 4.74, 18.70, 4.74); glyph.curve3(22.41, 4.74, 28.47, 9.62); glyph.ClosePolygon(); Affine mtx = Affine.NewIdentity(); mtx *= Affine.NewScaling(4.0); mtx *= Affine.NewTranslation(220, 200); VertexSourceApplyTransform trans = new VertexSourceApplyTransform(glyph, mtx); FlattenCurves curve = new FlattenCurves(trans); CreateAndRenderCombined(graphics2D, stroke, curve); graphics2D.Render(stroke, new ColorF(0, 0, 0, 0.1).ToColor()); graphics2D.Render(curve, new ColorF(0, 0.6, 0, 0.1).ToColor()); } break; } } private void CreateAndRenderCombined(Graphics2D graphics2D, IVertexSource ps1, IVertexSource ps2) { VertexStorage combined = null; switch (m_operation.SelectedIndex) { case 1: combined = CombinePaths(ps1, ps2, ClipType.ctUnion); break; case 2: combined = CombinePaths(ps1, ps2, ClipType.ctIntersection); break; case 3: combined = CombinePaths(ps1, ps2, ClipType.ctXor); break; case 4: combined = CombinePaths(ps1, ps2, ClipType.ctDifference); break; case 5: combined = CombinePaths(ps2, ps1, ClipType.ctDifference); break; } if (combined != null) { graphics2D.Render(combined, new ColorF(0.5, 0.0, 0, 0.5).ToColor()); } } public override void OnBoundsChanged(EventArgs e) { m_x = Width / 2.0; m_y = Height / 2.0; base.OnBoundsChanged(e); } public override void OnDraw(Graphics2D graphics2D) { render_gpc(graphics2D); base.OnDraw(graphics2D); } public override void OnMouseDown(MouseEventArgs mouseEvent) { base.OnMouseDown(mouseEvent); if (mouseEvent.Button == MouseButtons.Left && FirstWidgetUnderMouse) { m_x = mouseEvent.X; m_y = mouseEvent.Y; Invalidate(); } } public override void OnMouseMove(MouseEventArgs mouseEvent) { if (MouseCaptured) { m_x = mouseEvent.X; m_y = mouseEvent.Y; Invalidate(); } base.OnMouseMove(mouseEvent); } [STAThread] public static void Main(string[] args) { var demoWidget = new PolygonClippingDemo(); var systemWindow = new SystemWindow(640, 520); systemWindow.Title = demoWidget.Title; systemWindow.AddChild(demoWidget); systemWindow.ShowAsSystemWindow(); } private void make_arrows(VertexStorage ps) { ps.remove_all(); ps.MoveTo(1330.599999999999909, 1282.399999999999864); ps.LineTo(1377.400000000000091, 1282.399999999999864); ps.LineTo(1361.799999999999955, 1298.000000000000000); ps.LineTo(1393.000000000000000, 1313.599999999999909); ps.LineTo(1361.799999999999955, 1344.799999999999955); ps.LineTo(1346.200000000000045, 1313.599999999999909); ps.LineTo(1330.599999999999909, 1329.200000000000045); ps.ClosePolygon(); ps.MoveTo(1330.599999999999909, 1266.799999999999955); ps.LineTo(1377.400000000000091, 1266.799999999999955); ps.LineTo(1361.799999999999955, 1251.200000000000045); ps.LineTo(1393.000000000000000, 1235.599999999999909); ps.LineTo(1361.799999999999955, 1204.399999999999864); ps.LineTo(1346.200000000000045, 1235.599999999999909); ps.LineTo(1330.599999999999909, 1220.000000000000000); ps.ClosePolygon(); ps.MoveTo(1315.000000000000000, 1282.399999999999864); ps.LineTo(1315.000000000000000, 1329.200000000000045); ps.LineTo(1299.400000000000091, 1313.599999999999909); ps.LineTo(1283.799999999999955, 1344.799999999999955); ps.LineTo(1252.599999999999909, 1313.599999999999909); ps.LineTo(1283.799999999999955, 1298.000000000000000); ps.LineTo(1268.200000000000045, 1282.399999999999864); ps.ClosePolygon(); ps.MoveTo(1268.200000000000045, 1266.799999999999955); ps.LineTo(1315.000000000000000, 1266.799999999999955); ps.LineTo(1315.000000000000000, 1220.000000000000000); ps.LineTo(1299.400000000000091, 1235.599999999999909); ps.LineTo(1283.799999999999955, 1204.399999999999864); ps.LineTo(1252.599999999999909, 1235.599999999999909); ps.LineTo(1283.799999999999955, 1251.200000000000045); ps.ClosePolygon(); } } public class spiral : IVertexSource { private double m_x; private double m_y; private double m_r1; private double m_r2; private double m_step; private double m_start_angle; private double m_angle; private double m_curr_r; private double m_da; private double m_dr; private bool m_start; public spiral(double x, double y, double r1, double r2, double step, double start_angle = 0) { m_x = x; m_y = y; m_r1 = r1; m_r2 = r2; m_step = step; m_start_angle = start_angle; m_angle = start_angle; m_da = agg_basics.deg2rad(4.0); m_dr = m_step / 90.0; } public IEnumerable<VertexData> Vertices() { throw new NotImplementedException(); } public void rewind(int index) { m_angle = m_start_angle; m_curr_r = m_r1; m_start = true; } public ShapePath.FlagsAndCommand vertex(out double x, out double y) { x = 0; y = 0; if (m_curr_r > m_r2) { return ShapePath.FlagsAndCommand.Stop; } x = m_x + Math.Cos(m_angle) * m_curr_r; y = m_y + Math.Sin(m_angle) * m_curr_r; m_curr_r += m_dr; m_angle += m_da; if (m_start) { m_start = false; return ShapePath.FlagsAndCommand.MoveTo; } return ShapePath.FlagsAndCommand.LineTo; } } internal class conv_poly_counter { private int m_contours; private int m_points; private conv_poly_counter(IVertexSource src) { m_contours = 0; m_points = 0; foreach (VertexData vertexData in src.Vertices()) { if (ShapePath.is_vertex(vertexData.command)) { ++m_points; } if (ShapePath.is_move_to(vertexData.command)) { ++m_contours; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DevTestLabs { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// FormulasOperations operations. /// </summary> internal partial class FormulasOperations : IServiceOperations<DevTestLabsClient>, IFormulasOperations { /// <summary> /// Initializes a new instance of the FormulasOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal FormulasOperations(DevTestLabsClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the DevTestLabsClient /// </summary> public DevTestLabsClient Client { get; private set; } /// <summary> /// List formulas in a given lab. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Formula>>> ListWithHttpMessagesAsync(string labName, ODataQuery<Formula> odataQuery = default(ODataQuery<Formula>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("labName", labName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Formula>>(); _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<Formula>>(_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 formula. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the formula. /// </param> /// <param name='expand'> /// Specify the $expand query. Example: 'properties($select=description)' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Formula>> GetWithHttpMessagesAsync(string labName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("expand", expand); 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.DevTestLab/labs/{labName}/formulas/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand))); } 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<Formula>(); _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<Formula>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or replace an existing Formula. This operation can take a while to /// complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the formula. /// </param> /// <param name='formula'> /// A formula for creating a VM, specifying an image base and other parameters /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Formula>> CreateOrUpdateWithHttpMessagesAsync(string labName, string name, Formula formula, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Formula> _response = await BeginCreateOrUpdateWithHttpMessagesAsync( labName, name, formula, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Create or replace an existing Formula. This operation can take a while to /// complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the formula. /// </param> /// <param name='formula'> /// A formula for creating a VM, specifying an image base and other parameters /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Formula>> BeginCreateOrUpdateWithHttpMessagesAsync(string labName, string name, Formula formula, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (formula == null) { throw new ValidationException(ValidationRules.CannotBeNull, "formula"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("formula", formula); 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.DevTestLab/labs/{labName}/formulas/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(formula != null) { _requestContent = SafeJsonConvert.SerializeObject(formula, 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<Formula>(); _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<Formula>(_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<Formula>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete formula. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the formula. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List formulas in a given lab. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Formula>>> 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<Formula>>(); _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<Formula>>(_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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeProcessHandle : System.Runtime.InteropServices.SafeHandle { public SafeProcessHandle(System.IntPtr existingHandle, bool ownsHandle) : base(default(System.IntPtr), default(bool)) { } protected override bool ReleaseHandle() { return default(bool); } } } namespace System.Diagnostics { public partial class DataReceivedEventArgs : System.EventArgs { internal DataReceivedEventArgs() { } public string Data { get { return default(string); } } } public delegate void DataReceivedEventHandler(object sender, System.Diagnostics.DataReceivedEventArgs e); public partial class Process { public Process() { } public int BasePriority { get { return default(int); } } [System.ComponentModel.DefaultValueAttribute(false)] public bool EnableRaisingEvents { get { return default(bool); } set { } } public int ExitCode { get { return default(int); } } public System.DateTime ExitTime { get { return default(System.DateTime); } } public bool HasExited { get { return default(bool); } } public int Id { get { return default(int); } } public string MachineName { get { return default(string); } } public System.Diagnostics.ProcessModule MainModule { get { return default(System.Diagnostics.ProcessModule); } } public System.IntPtr MaxWorkingSet { get { return default(System.IntPtr); } set { } } public System.IntPtr MinWorkingSet { get { return default(System.IntPtr); } set { } } public System.Diagnostics.ProcessModuleCollection Modules { get { return default(System.Diagnostics.ProcessModuleCollection); } } public long NonpagedSystemMemorySize64 { get { return default(long); } } public long PagedMemorySize64 { get { return default(long); } } public long PagedSystemMemorySize64 { get { return default(long); } } public long PeakPagedMemorySize64 { get { return default(long); } } public long PeakVirtualMemorySize64 { get { return default(long); } } public long PeakWorkingSet64 { get { return default(long); } } public bool PriorityBoostEnabled { get { return default(bool); } set { } } public System.Diagnostics.ProcessPriorityClass PriorityClass { get { return default(System.Diagnostics.ProcessPriorityClass); } set { } } public long PrivateMemorySize64 { get { return default(long); } } public System.TimeSpan PrivilegedProcessorTime { get { return default(System.TimeSpan); } } public string ProcessName { get { return default(string); } } public System.IntPtr ProcessorAffinity { get { return default(System.IntPtr); } set { } } public Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle { get { return default(Microsoft.Win32.SafeHandles.SafeProcessHandle); } } public int SessionId { get { return default(int); } } public System.IO.StreamReader StandardError { get { return default(System.IO.StreamReader); } } public System.IO.StreamWriter StandardInput { get { return default(System.IO.StreamWriter); } } public System.IO.StreamReader StandardOutput { get { return default(System.IO.StreamReader); } } public System.Diagnostics.ProcessStartInfo StartInfo { get { return default(System.Diagnostics.ProcessStartInfo); } set { } } public System.DateTime StartTime { get { return default(System.DateTime); } } public System.Diagnostics.ProcessThreadCollection Threads { get { return default(System.Diagnostics.ProcessThreadCollection); } } public System.TimeSpan TotalProcessorTime { get { return default(System.TimeSpan); } } public System.TimeSpan UserProcessorTime { get { return default(System.TimeSpan); } } public long VirtualMemorySize64 { get { return default(long); } } public long WorkingSet64 { get { return default(long); } } public event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived { add { } remove { } } public event System.EventHandler Exited { add { } remove { } } public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived { add { } remove { } } public void BeginErrorReadLine() { } public void BeginOutputReadLine() { } public void CancelErrorRead() { } public void CancelOutputRead() { } public static void EnterDebugMode() { } public static System.Diagnostics.Process GetCurrentProcess() { return default(System.Diagnostics.Process); } public static System.Diagnostics.Process GetProcessById(int processId) { return default(System.Diagnostics.Process); } public static System.Diagnostics.Process GetProcessById(int processId, string machineName) { return default(System.Diagnostics.Process); } public static System.Diagnostics.Process[] GetProcesses() { return default(System.Diagnostics.Process[]); } public static System.Diagnostics.Process[] GetProcesses(string machineName) { return default(System.Diagnostics.Process[]); } public static System.Diagnostics.Process[] GetProcessesByName(string processName) { return default(System.Diagnostics.Process[]); } public static System.Diagnostics.Process[] GetProcessesByName(string processName, string machineName) { return default(System.Diagnostics.Process[]); } public void Kill() { } public static void LeaveDebugMode() { } protected void OnExited() { } public void Refresh() { } public bool Start() { return default(bool); } public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo startInfo) { return default(System.Diagnostics.Process); } public static System.Diagnostics.Process Start(string fileName) { return default(System.Diagnostics.Process); } public static System.Diagnostics.Process Start(string fileName, string arguments) { return default(System.Diagnostics.Process); } public void WaitForExit() { } public bool WaitForExit(int milliseconds) { return default(bool); } } public partial class ProcessModule { internal ProcessModule() { } public System.IntPtr BaseAddress { get { return default(System.IntPtr); } } public System.IntPtr EntryPointAddress { get { return default(System.IntPtr); } } public string FileName { get { return default(string); } } public int ModuleMemorySize { get { return default(int); } } public string ModuleName { get { return default(string); } } public override string ToString() { return default(string); } } public partial class ProcessModuleCollection { protected ProcessModuleCollection() { } public ProcessModuleCollection(System.Diagnostics.ProcessModule[] processModules) { } public System.Diagnostics.ProcessModule this[int index] { get { return default(System.Diagnostics.ProcessModule); } } public bool Contains(System.Diagnostics.ProcessModule module) { return default(bool); } public void CopyTo(System.Diagnostics.ProcessModule[] array, int index) { } public int IndexOf(System.Diagnostics.ProcessModule module) { return default(int); } } public enum ProcessPriorityClass { AboveNormal = 32768, BelowNormal = 16384, High = 128, Idle = 64, Normal = 32, RealTime = 256, } public sealed partial class ProcessStartInfo { public ProcessStartInfo() { } public ProcessStartInfo(string fileName) { } public ProcessStartInfo(string fileName, string arguments) { } public string Arguments { get { return default(string); } set { } } public bool CreateNoWindow { get { return default(bool); } set { } } [System.ComponentModel.DefaultValueAttribute(null)] public System.Collections.Generic.IDictionary<string, string> Environment { get { return default(System.Collections.Generic.IDictionary<string, string>); } } public string FileName { get { return default(string); } set { } } public bool RedirectStandardError { get { return default(bool); } set { } } public bool RedirectStandardInput { get { return default(bool); } set { } } public bool RedirectStandardOutput { get { return default(bool); } set { } } public System.Text.Encoding StandardErrorEncoding { get { return default(System.Text.Encoding); } set { } } public System.Text.Encoding StandardOutputEncoding { get { return default(System.Text.Encoding); } set { } } public bool UseShellExecute { get { return default(bool); } set { } } public string WorkingDirectory { get { return default(string); } set { } } } public partial class ProcessThread { internal ProcessThread() { } public int BasePriority { get { return default(int); } } public int CurrentPriority { get { return default(int); } } public int Id { get { return default(int); } } public int IdealProcessor { set { } } public bool PriorityBoostEnabled { get { return default(bool); } set { } } public System.Diagnostics.ThreadPriorityLevel PriorityLevel { get { return default(System.Diagnostics.ThreadPriorityLevel); } set { } } public System.TimeSpan PrivilegedProcessorTime { get { return default(System.TimeSpan); } } public System.IntPtr ProcessorAffinity { set { } } public System.IntPtr StartAddress { get { return default(System.IntPtr); } } public System.DateTime StartTime { get { return default(System.DateTime); } } public System.Diagnostics.ThreadState ThreadState { get { return default(System.Diagnostics.ThreadState); } } public System.TimeSpan TotalProcessorTime { get { return default(System.TimeSpan); } } public System.TimeSpan UserProcessorTime { get { return default(System.TimeSpan); } } public System.Diagnostics.ThreadWaitReason WaitReason { get { return default(System.Diagnostics.ThreadWaitReason); } } public void ResetIdealProcessor() { } } public partial class ProcessThreadCollection { protected ProcessThreadCollection() { } public ProcessThreadCollection(System.Diagnostics.ProcessThread[] processThreads) { } public System.Diagnostics.ProcessThread this[int index] { get { return default(System.Diagnostics.ProcessThread); } } public int Add(System.Diagnostics.ProcessThread thread) { return default(int); } public bool Contains(System.Diagnostics.ProcessThread thread) { return default(bool); } public void CopyTo(System.Diagnostics.ProcessThread[] array, int index) { } public int IndexOf(System.Diagnostics.ProcessThread thread) { return default(int); } public void Insert(int index, System.Diagnostics.ProcessThread thread) { } public void Remove(System.Diagnostics.ProcessThread thread) { } } public enum ThreadPriorityLevel { AboveNormal = 1, BelowNormal = -1, Highest = 2, Idle = -15, Lowest = -2, Normal = 0, TimeCritical = 15, } public enum ThreadState { Initialized = 0, Ready = 1, Running = 2, Standby = 3, Terminated = 4, Transition = 6, Unknown = 7, Wait = 5, } public enum ThreadWaitReason { EventPairHigh = 7, EventPairLow = 8, ExecutionDelay = 4, Executive = 0, FreePage = 1, LpcReceive = 9, LpcReply = 10, PageIn = 2, PageOut = 12, Suspended = 5, SystemAllocation = 3, Unknown = 13, UserRequest = 6, VirtualMemory = 11, } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using log4net; using SFML.Graphics; namespace NetGore.Graphics.GUI { /// <summary> /// Defines and draws the border of a control /// </summary> public class ControlBorder { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The maximum draw calls that are to be made before a Debug.Error() is produced. This is an indicated that /// the <see cref="ControlBorder"/> is simply drawing way too much and that you either are using /// <see cref="ControlBorderDrawStyle.Tile"/> when you meant to use <see cref="ControlBorderDrawStyle.Stretch"/>, /// your <see cref="ControlBorder"/> is larger than anticipated, or that the <see cref="ISprite"/> used to draw /// the border is too small. This is not an error, but rather more of a warning, and only shows in debug. /// </summary> const int _maxDrawCallsBeforeDebugWarning = 30; static readonly object _drawSync = new object(); static readonly ControlBorder _empty; static readonly List<Func<Control, Color, Color>> _globalColorTransformations = new List<Func<Control, Color, Color>>(); static readonly object _globalColorTransformationsSync = new object(); static readonly int _numSprites; readonly ControlBorderDrawStyle[] _drawStyles; readonly ISprite[] _sprites; /// <summary> /// Contains a cached value of whether or not the border can be drawn so we only have to do a quick boolean /// check each time we draw instead of a more extensive and expensive check. /// </summary> bool _canDraw = false; /// <summary> /// Initializes the <see cref="ControlBorder"/> class. /// </summary> static ControlBorder() { _numSprites = EnumHelper<ControlBorderSpriteType>.MaxValue + 1; _empty = new ControlBorder(null, null, null, null, null, null, null, null, null); } /// <summary> /// Initializes a new instance of the <see cref="ControlBorder"/> class. /// </summary> /// <param name="source">ControlBorder to copy from</param> public ControlBorder(ControlBorder source) { _sprites = new ISprite[_numSprites]; _drawStyles = new ControlBorderDrawStyle[_numSprites]; Array.Copy(source._sprites, 0, _sprites, 0, _sprites.Length); Array.Copy(source._drawStyles, 0, _drawStyles, 0, _drawStyles.Length); } /// <summary> /// Initializes a new instance of the <see cref="ControlBorder"/> class. /// </summary> /// <param name="topLeft">Source of the top-left corner</param> /// <param name="top">Source of the top side</param> /// <param name="topRight">Source of the top-right corner</param> /// <param name="right">Source of the right side</param> /// <param name="bottomRight">Source of the bottom-right corner</param> /// <param name="bottom">Source of the bottom side</param> /// <param name="bottomLeft">Source of the bottom-left corner</param> /// <param name="left">Source of the left side</param> /// <param name="background">Source of the background</param> public ControlBorder(ISprite topLeft, ISprite top, ISprite topRight, ISprite right, ISprite bottomRight, ISprite bottom, ISprite bottomLeft, ISprite left, ISprite background) { _sprites = new ISprite[_numSprites]; _drawStyles = new ControlBorderDrawStyle[_numSprites]; SetSprite(ControlBorderSpriteType.Background, background); SetSprite(ControlBorderSpriteType.Bottom, bottom); SetSprite(ControlBorderSpriteType.BottomLeft, bottomLeft); SetSprite(ControlBorderSpriteType.BottomRight, bottomRight); SetSprite(ControlBorderSpriteType.Left, left); SetSprite(ControlBorderSpriteType.Right, right); SetSprite(ControlBorderSpriteType.Top, top); SetSprite(ControlBorderSpriteType.TopLeft, topLeft); SetSprite(ControlBorderSpriteType.TopRight, topRight); UpdateCanDraw(); } /// <summary> /// Gets the height of the bottom side of the border /// </summary> public int BottomHeight { get { var s = GetSprite(ControlBorderSpriteType.Bottom); // If the ISprite is null, return a 0 if (s == null) return 0; return s.Source.Height; } } /// <summary> /// Gets the default empty <see cref="ControlBorder"/>. /// </summary> public static ControlBorder Empty { get { return _empty; } } /// <summary> /// Gets the height of both the top and bottom border sides /// </summary> public int Height { get { return TopHeight + BottomHeight; } } /// <summary> /// Gets the width of the left side of the border /// </summary> public int LeftWidth { get { var s = GetSprite(ControlBorderSpriteType.Left); // If the ISprite is null, return a 0 if (s == null) return 0; return s.Source.Width; } } /// <summary> /// Gets the width of the right side of the border /// </summary> public int RightWidth { get { var s = GetSprite(ControlBorderSpriteType.Right); // If the ISprite is null, return a 0 if (s == null) return 0; return s.Source.Width; } } /// <summary> /// Gets a Vector2 that represents the Width and Height of all sides of the border. /// </summary> public Vector2 Size { get { return new Vector2(Width, Height); } } /// <summary> /// Gets the height of the top side of the border /// </summary> public int TopHeight { get { var s = GetSprite(ControlBorderSpriteType.Top); // If the ISprite is null, return a 0 if (s == null) return 0; return s.Source.Height; } } /// <summary> /// Gets the width of both the left and right border sides /// </summary> public int Width { get { return LeftWidth + RightWidth; } } /// <summary> /// Adds a <see cref="Func{T,U}"/> that can be used to apply a transformation on the <see cref="Color"/> of a /// <see cref="ControlBorder"/> for a <see cref="Control"/> for every <see cref="ControlBorder"/> being drawn. /// </summary> /// <param name="transformer">The transformation.</param> public static void AddGlobalColorTransformation(Func<Control, Color, Color> transformer) { lock (_globalColorTransformationsSync) { if (!_globalColorTransformations.Contains(transformer)) _globalColorTransformations.Add(transformer); } } /// <summary> /// Checks that the amount being drawn for a tiled draw call is a sane amount. /// </summary> /// <param name="min">The starting draw coordinate.</param> /// <param name="max">The ending draw coordinate.</param> /// <param name="spriteSize">The size of the sprite being drawn.</param> /// <param name="side">The <see cref="ControlBorderSpriteType"/>.</param> [Conditional("DEBUG")] void AssertSaneDrawTilingAmount(int min, int max, float spriteSize, ControlBorderSpriteType side) { const string errmsg = "Too many draw calls being made to draw the ControlBorder `{0}` on side `{1}` - performance will suffer." + " Either use a larger sprite, or use ControlBorderDrawStyle.Stretch instead of ControlBorderDrawStyle.Tile." + " This may also be an indication that you are using ControlBorderDrawStyle.Tile unintentionally."; var drawCalls = (int)((max - min) / spriteSize); if (drawCalls <= _maxDrawCallsBeforeDebugWarning) return; if (log.IsWarnEnabled) log.WarnFormat(errmsg, this, side); Debug.Fail(string.Format(errmsg, this, side)); } /// <summary> /// Draws the <see cref="ControlBorder"/> to the specified region. /// </summary> /// <param name="sb"><see cref="ISpriteBatch"/> to draw with.</param> /// <param name="region">Region to draw the <see cref="ControlBorder"/> to. These values represent /// the absolute screen position.</param> public void Draw(ISpriteBatch sb, Rectangle region) { Draw(sb, region, Color.White); } /// <summary> /// Draws the <see cref="ControlBorder"/> to the specified region. /// </summary> /// <param name="sb"><see cref="ISpriteBatch"/> to draw with.</param> /// <param name="region">Region to draw the <see cref="ControlBorder"/> to. These values represent /// the absolute screen position.</param> /// <param name="color">The <see cref="Color"/> to use to draw the <see cref="ControlBorder"/>.</param> public void Draw(ISpriteBatch sb, Rectangle region, Color color) { if (!_canDraw) return; var _bg = GetSprite(ControlBorderSpriteType.Background); var _t = GetSprite(ControlBorderSpriteType.Top); var _tl = GetSprite(ControlBorderSpriteType.TopLeft); var _tr = GetSprite(ControlBorderSpriteType.TopRight); var _l = GetSprite(ControlBorderSpriteType.Left); var _r = GetSprite(ControlBorderSpriteType.Right); var _b = GetSprite(ControlBorderSpriteType.Bottom); var _bl = GetSprite(ControlBorderSpriteType.BottomLeft); var _br = GetSprite(ControlBorderSpriteType.BottomRight); var bSrc = _b.Source; var tSrc = _t.Source; var tlSrc = _tl.Source; var trSrc = _tr.Source; var lSrc = _l.Source; var rSrc = _r.Source; var blSrc = _bl.Source; var brSrc = _br.Source; // Set some values we will be using extensively var cX = region.X; var cY = region.Y; var cW = region.Width; var cH = region.Height; lock (_drawSync) { // Background (draw first to ensure it stays behind the border in case something goes wrong) Rectangle r; if (_bg != null) { r = new Rectangle(cX + lSrc.Width, cY + tSrc.Height, cW - lSrc.Width - rSrc.Width, cH - tSrc.Height - bSrc.Height); switch (GetDrawStyle(ControlBorderSpriteType.Background)) { case ControlBorderDrawStyle.Stretch: _bg.Draw(sb, r, Color.White); break; case ControlBorderDrawStyle.Tile: AssertSaneDrawTilingAmount(r.X, r.Right, _bg.Size.X, ControlBorderSpriteType.Background); AssertSaneDrawTilingAmount(r.Y, r.Bottom, _bg.Size.Y, ControlBorderSpriteType.Background); sb.DrawTiledXY(r.X, r.Right, r.Y, r.Bottom, _bg, Color.White); break; } } // Top side r = new Rectangle(cX + tlSrc.Width, cY, cW - tlSrc.Width - trSrc.Width, tSrc.Height); switch (GetDrawStyle(ControlBorderSpriteType.Top)) { case ControlBorderDrawStyle.Stretch: _t.Draw(sb, r, Color.White); break; case ControlBorderDrawStyle.Tile: AssertSaneDrawTilingAmount(r.X, r.Right, _t.Size.X, ControlBorderSpriteType.Top); sb.DrawTiledX(r.X, r.Right, r.Y, _t, Color.White); break; } // Left side r = new Rectangle(cX, cY + tlSrc.Height, lSrc.Width, cH - tlSrc.Height - blSrc.Height); switch (GetDrawStyle(ControlBorderSpriteType.Left)) { case ControlBorderDrawStyle.Stretch: _l.Draw(sb, r, Color.White); break; case ControlBorderDrawStyle.Tile: AssertSaneDrawTilingAmount(r.Y, r.Bottom, _l.Size.Y, ControlBorderSpriteType.Left); sb.DrawTiledY(r.Y, r.Bottom, r.X, _l, Color.White); break; } // Right side r = new Rectangle(cX + cW - rSrc.Width, cY + trSrc.Height, rSrc.Width, cH - trSrc.Height - brSrc.Height); switch (GetDrawStyle(ControlBorderSpriteType.Right)) { case ControlBorderDrawStyle.Stretch: _r.Draw(sb, r, Color.White); break; case ControlBorderDrawStyle.Tile: AssertSaneDrawTilingAmount(r.Y, r.Bottom, _r.Size.Y, ControlBorderSpriteType.Right); sb.DrawTiledY(r.Y, r.Bottom, r.X, _r, Color.White); break; } // Bottom side r = new Rectangle(cX + _bl.Source.Width, cY + cH - bSrc.Height, cW - blSrc.Width - brSrc.Width, bSrc.Height); switch (GetDrawStyle(ControlBorderSpriteType.Bottom)) { case ControlBorderDrawStyle.Stretch: _b.Draw(sb, r, Color.White); break; case ControlBorderDrawStyle.Tile: AssertSaneDrawTilingAmount(r.X, r.Right, _b.Size.X, ControlBorderSpriteType.Bottom); sb.DrawTiledX(r.X, r.Right, r.Y, _b, Color.White); break; } // Top-left corner r = new Rectangle(cX, cY, tlSrc.Width, tlSrc.Height); _tl.Draw(sb, r, Color.White); // Top-right corner r = new Rectangle(cX + cW - trSrc.Width, cY, trSrc.Width, trSrc.Height); _tr.Draw(sb, r, Color.White); // Bottom-left corner r = new Rectangle(cX, cY + cH - blSrc.Height, blSrc.Width, blSrc.Height); _bl.Draw(sb, r, Color.White); // Bottom-right corner r = new Rectangle(cX + cW - brSrc.Width, cY + cH - brSrc.Height, brSrc.Width, brSrc.Height); _br.Draw(sb, r, Color.White); } } /// <summary> /// Draws the <see cref="ControlBorder"/> to a given <see cref="Control"/>. /// </summary> /// <param name="sb"><see cref="ISpriteBatch"/> to draw with.</param> /// <param name="c">Control to draw to.</param> public void Draw(ISpriteBatch sb, Control c) { if (!_canDraw) return; var color = c.BorderColor; // Apply the color transformations (if they exist) if (_globalColorTransformations.Count > 0) { lock (_globalColorTransformationsSync) { foreach (var t in _globalColorTransformations) { color = t(c, color); } } } Vector2 sp = c.ScreenPosition; Rectangle region = new Rectangle(sp.X, sp.Y, c.Size.X, c.Size.Y); Draw(sb, region, color); } /// <summary> /// Gets the <see cref="ControlBorderDrawStyle"/> for the given <see cref="ControlBorderSpriteType"/>. /// </summary> /// <param name="spriteType">The type of <see cref="ControlBorderSpriteType"/>.</param> /// <returns>The <see cref="ControlBorderDrawStyle"/> for the <paramref name="spriteType"/>.</returns> public ControlBorderDrawStyle GetDrawStyle(ControlBorderSpriteType spriteType) { return _drawStyles[(int)spriteType]; } /// <summary> /// Gets the <see cref="ISprite"/> for the given <see cref="ControlBorderSpriteType"/>. /// </summary> /// <param name="spriteType">The type of <see cref="ControlBorderSpriteType"/>.</param> /// <returns>The <see cref="ISprite"/> for the <paramref name="spriteType"/>.</returns> public ISprite GetSprite(ControlBorderSpriteType spriteType) { return _sprites[(int)spriteType]; } /// <summary> /// Loads the <see cref="ControlBorderDrawStyle"/>s from file. /// </summary> /// <param name="filePath">The path to the file to load the <see cref="ControlBorderDrawStyle"/>s from.</param> /// <returns>The loaded <see cref="ControlBorderDrawStyle"/>s, where each element in the array contains the /// <see cref="ControlBorderDrawStyle"/> and can be indexed with the <see cref="ControlBorderSpriteType"/>.</returns> public static ControlBorderDrawStyle[] LoadDrawStyles(string filePath) { var ret = new ControlBorderDrawStyle[_numSprites]; var lines = File.ReadAllLines(filePath); foreach (var line in lines) { if (string.IsNullOrEmpty(line)) continue; var l = line.Trim(); if (l.Length == 0) continue; var split = l.Split(':'); if (split.Length == 2) { var key = split[0]; ControlBorderDrawStyle value; if (EnumHelper<ControlBorderDrawStyle>.TryParse(split[1], out value)) { // Wild-card if (StringComparer.OrdinalIgnoreCase.Equals(key, "*")) { for (var i = 0; i < ret.Length; i++) { ret[i] = value; } continue; } // Parse enum ControlBorderSpriteType keyEnum; if (EnumHelper<ControlBorderSpriteType>.TryParse(key, out keyEnum)) { ret[(int)keyEnum] = value; continue; } } } // Unable to parse const string errmsg = "Unable to parse line in file `{0}`: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, filePath, line); Debug.Fail(string.Format(errmsg, filePath, line)); } return ret; } /// <summary> /// Removes a <see cref="Func{T,U}"/> that can be used to apply a transformation on the <see cref="Color"/> of a /// <see cref="ControlBorder"/> for a <see cref="Control"/> for every <see cref="ControlBorder"/> being drawn. /// </summary> /// <param name="transformer">The transformation.</param> public static void RemoveGlobalColorTransformation(Func<Control, Color, Color> transformer) { lock (_globalColorTransformationsSync) { _globalColorTransformations.Remove(transformer); } } /// <summary> /// Gets the <see cref="ISprite"/> for the given <see cref="ControlBorderSpriteType"/>. /// </summary> /// <param name="spriteType">The type of <see cref="ControlBorderSpriteType"/>.</param> /// <param name="value">The <see cref="ControlBorderDrawStyle"/> to assign to the <paramref name="spriteType"/>.</param> public void SetDrawStyle(ControlBorderSpriteType spriteType, ControlBorderDrawStyle value) { _drawStyles[(int)spriteType] = value; UpdateCanDraw(); } /// <summary> /// Gets the <see cref="ISprite"/> for the given <see cref="ControlBorderSpriteType"/>. /// </summary> /// <param name="spriteType">The type of <see cref="ControlBorderSpriteType"/>.</param> /// <param name="value">The <see cref="ISprite"/> to assign to the <paramref name="spriteType"/>.</param> public void SetSprite(ControlBorderSpriteType spriteType, ISprite value) { _sprites[(int)spriteType] = value; UpdateCanDraw(); } /// <summary> /// Loads the <see cref="ControlBorderDrawStyle"/>s from file. /// </summary> /// <param name="filePath">The path to the file to load the <see cref="ControlBorderDrawStyle"/>s from.</param> /// <returns>True if successfully loaded the data from the <paramref name="filePath"/>; otherwise false.</returns> public bool TrySetDrawStyles(string filePath) { if (!File.Exists(filePath)) return false; try { var styles = LoadDrawStyles(filePath); for (var i = 0; i < _drawStyles.Length; i++) { _drawStyles[i] = styles[i]; } return true; } catch (Exception ex) { const string errmsg = "Failed to load ControlBorderDrawStyles from `{0}`. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, filePath, ex); Debug.Fail(string.Format(errmsg, filePath, ex)); return false; } } /// <summary> /// Updates the <see cref="_canDraw"/> value. /// </summary> void UpdateCanDraw() { Debug.Assert((int)ControlBorderSpriteType.Background == 0); _canDraw = true; for (var i = 1; i < _sprites.Length; i++) { if (_sprites[i] == null) { _canDraw = false; break; } } } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2010 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Diagnostics; #if !MINIMAL using System.Drawing; #endif namespace OpenTK { /// <summary> /// Defines a display device on the underlying system, and provides /// methods to query and change its display parameters. /// </summary> public class DisplayDevice { // TODO: Add properties that describe the 'usable' size of the Display, i.e. the maximized size without the taskbar etc. // TODO: Does not detect changes to primary device. #region Fields bool primary; Rectangle bounds; DisplayResolution current_resolution = new DisplayResolution(), original_resolution; List<DisplayResolution> available_resolutions = new List<DisplayResolution>(); IList<DisplayResolution> available_resolutions_readonly; internal object Id; // A platform-specific id for this monitor static readonly object display_lock = new object(); static DisplayDevice primary_display; static Platform.IDisplayDeviceDriver implementation; #endregion #region Constructors static DisplayDevice() { implementation = Platform.Factory.Default.CreateDisplayDeviceDriver(); } internal DisplayDevice() { available_resolutions_readonly = available_resolutions.AsReadOnly(); } internal DisplayDevice(DisplayResolution currentResolution, bool primary, IEnumerable<DisplayResolution> availableResolutions, Rectangle bounds, object id) : this() { #warning "Consolidate current resolution with bounds? Can they fall out of sync right now?" this.current_resolution = currentResolution; IsPrimary = primary; this.available_resolutions.AddRange(availableResolutions); this.bounds = bounds == Rectangle.Empty ? currentResolution.Bounds : bounds; this.Id = id; } #endregion #region --- Public Methods --- #region public Rectangle Bounds /// <summary> /// Gets the bounds of this instance in pixel coordinates.. /// </summary> public Rectangle Bounds { get { return bounds; } internal set { bounds = value; current_resolution.Height = bounds.Height; current_resolution.Width = bounds.Width; } } #endregion #region public int Width /// <summary>Gets a System.Int32 that contains the width of this display in pixels.</summary> public int Width { get { return current_resolution.Width; } } #endregion #region public int Height /// <summary>Gets a System.Int32 that contains the height of this display in pixels.</summary> public int Height { get { return current_resolution.Height; } } #endregion #region public int BitsPerPixel /// <summary>Gets a System.Int32 that contains number of bits per pixel of this display. Typical values include 8, 16, 24 and 32.</summary> public int BitsPerPixel { get { return current_resolution.BitsPerPixel; } internal set { current_resolution.BitsPerPixel = value; } } #endregion #region public float RefreshRate /// <summary> /// Gets a System.Single representing the vertical refresh rate of this display. /// </summary> public float RefreshRate { get { return current_resolution.RefreshRate; } internal set { current_resolution.RefreshRate = value; } } #endregion #region public bool IsPrimary /// <summary>Gets a System.Boolean that indicates whether this Display is the primary Display in systems with multiple Displays.</summary> public bool IsPrimary { get { return primary; } internal set { if (value && primary_display != null && primary_display != this) primary_display.IsPrimary = false; lock (display_lock) { primary = value; if (value) primary_display = this; } } } #endregion #region public DisplayResolution SelectResolution(int width, int height, int bitsPerPixel, float refreshRate) /// <summary> /// Selects an available resolution that matches the specified parameters. /// </summary> /// <param name="width">The width of the requested resolution in pixels.</param> /// <param name="height">The height of the requested resolution in pixels.</param> /// <param name="bitsPerPixel">The bits per pixel of the requested resolution.</param> /// <param name="refreshRate">The refresh rate of the requested resolution in hertz.</param> /// <returns>The requested DisplayResolution or null if the parameters cannot be met.</returns> /// <remarks> /// <para>If a matching resolution is not found, this function will retry ignoring the specified refresh rate, /// bits per pixel and resolution, in this order. If a matching resolution still doesn't exist, this function will /// return the current resolution.</para> /// <para>A parameter set to 0 or negative numbers will not be used in the search (e.g. if refreshRate is 0, /// any refresh rate will be considered valid).</para> /// <para>This function allocates memory.</para> /// </remarks> public DisplayResolution SelectResolution(int width, int height, int bitsPerPixel, float refreshRate) { DisplayResolution resolution = FindResolution(width, height, bitsPerPixel, refreshRate); if (resolution == null) resolution = FindResolution(width, height, bitsPerPixel, 0); if (resolution == null) resolution = FindResolution(width, height, 0, 0); if (resolution == null) return current_resolution; return resolution; } #endregion #region public IList<DisplayResolution> AvailableResolutions /// <summary> /// Gets the list of <see cref="DisplayResolution"/> objects available on this device. /// </summary> public IList<DisplayResolution> AvailableResolutions { get { return available_resolutions_readonly; } internal set { available_resolutions = (List<DisplayResolution>)value; available_resolutions_readonly = available_resolutions.AsReadOnly(); } } #endregion #region public void ChangeResolution(DisplayResolution resolution) /// <summary>Changes the resolution of the DisplayDevice.</summary> /// <param name="resolution">The resolution to set. <see cref="DisplayDevice.SelectResolution"/></param> /// <exception cref="Graphics.GraphicsModeException">Thrown if the requested resolution could not be set.</exception> /// <remarks>If the specified resolution is null, this function will restore the original DisplayResolution.</remarks> public void ChangeResolution(DisplayResolution resolution) { if (resolution == null) this.RestoreResolution(); if (resolution == current_resolution) return; //effect.FadeOut(); if (implementation.TryChangeResolution(this, resolution)) { if (original_resolution == null) original_resolution = current_resolution; current_resolution = resolution; } else throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to change resolution to {1}.", this, resolution)); //effect.FadeIn(); } #endregion #region public void ChangeResolution(int width, int height, int bitsPerPixel, float refreshRate) /// <summary>Changes the resolution of the DisplayDevice.</summary> /// <param name="width">The new width of the DisplayDevice.</param> /// <param name="height">The new height of the DisplayDevice.</param> /// <param name="bitsPerPixel">The new bits per pixel of the DisplayDevice.</param> /// <param name="refreshRate">The new refresh rate of the DisplayDevice.</param> /// <exception cref="Graphics.GraphicsModeException">Thrown if the requested resolution could not be set.</exception> public void ChangeResolution(int width, int height, int bitsPerPixel, float refreshRate) { this.ChangeResolution(this.SelectResolution(width, height, bitsPerPixel, refreshRate)); } #endregion #region public void RestoreResolution() /// <summary>Restores the original resolution of the DisplayDevice.</summary> /// <exception cref="Graphics.GraphicsModeException">Thrown if the original resolution could not be restored.</exception> public void RestoreResolution() { if (original_resolution != null) { //effect.FadeOut(); if (implementation.TryRestoreResolution(this)) { current_resolution = original_resolution; original_resolution = null; } else throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to restore resolution.", this)); //effect.FadeIn(); } } #endregion #region public static IList<DisplayDevice> AvailableDisplays /// <summary> /// Gets the list of available <see cref="DisplayDevice"/> objects. /// This function allocates memory. /// </summary> [Obsolete("Use GetDisplay(DisplayIndex) instead.")] public static IList<DisplayDevice> AvailableDisplays { get { List<DisplayDevice> displays = new List<DisplayDevice>(); for (int i = 0; i < 6; i++) { DisplayDevice dev = GetDisplay(DisplayIndex.First + i); if (dev != null) displays.Add(dev); } return displays.AsReadOnly(); } } #endregion #region public static DisplayDevice Default /// <summary>Gets the default (primary) display of this system.</summary> public static DisplayDevice Default { get { return implementation.GetDisplay(DisplayIndex.Primary); } } #endregion #region GetDisplay /// <summary> /// Gets the <see cref="DisplayDevice"/> for the specified <see cref="DeviceIndex"/>. /// </summary> /// <param name="index">The <see cref="DeviceIndex"/> that defines the desired display.</param> /// <returns>A <see cref="DisplayDevice"/> or null, if no device corresponds to the specified index.</returns> public static DisplayDevice GetDisplay(DisplayIndex index) { return implementation.GetDisplay(index); } #endregion #endregion #region --- Private Methods --- #region DisplayResolution FindResolution(int width, int height, int bitsPerPixel, float refreshRate) DisplayResolution FindResolution(int width, int height, int bitsPerPixel, float refreshRate) { return available_resolutions.Find(delegate(DisplayResolution test) { return ((width > 0 && width == test.Width) || width == 0) && ((height > 0 && height == test.Height) || height == 0) && ((bitsPerPixel > 0 && bitsPerPixel == test.BitsPerPixel) || bitsPerPixel == 0) && ((refreshRate > 0 && System.Math.Abs(refreshRate - test.RefreshRate) < 1.0) || refreshRate == 0); }); } #endregion #endregion #region --- Overrides --- #region public override string ToString() /// <summary> /// Returns a System.String representing this DisplayDevice. /// </summary> /// <returns>A System.String representing this DisplayDevice.</returns> public override string ToString() { return String.Format("{0}: {1} ({2} modes available)", IsPrimary ? "Primary" : "Secondary", Bounds.ToString(), available_resolutions.Count); } #endregion #region public override bool Equals(object obj) ///// <summary>Determines whether the specified DisplayDevices are equal.</summary> ///// <param name="obj">The System.Object to check against.</param> ///// <returns>True if the System.Object is an equal DisplayDevice; false otherwise.</returns> //public override bool Equals(object obj) //{ // if (obj is DisplayDevice) // { // DisplayDevice dev = (DisplayDevice)obj; // return // IsPrimary == dev.IsPrimary && // current_resolution == dev.current_resolution && // available_resolutions.Count == dev.available_resolutions.Count; // } // return false; //} #endregion #region public override int GetHashCode() ///// <summary>Returns a unique hash representing this DisplayDevice.</summary> ///// <returns>A System.Int32 that may serve as a hash code for this DisplayDevice.</returns> ////public override int GetHashCode() //{ // return current_resolution.GetHashCode() ^ IsPrimary.GetHashCode() ^ available_resolutions.Count; //} #endregion #endregion } #region --- FadeEffect --- #if false class FadeEffect : IDisposable { List<Form> forms = new List<Form>(); double opacity_step = 0.04; int sleep_step; internal FadeEffect() { foreach (Screen s in Screen.AllScreens) { Form form = new Form(); form.ShowInTaskbar = false; form.StartPosition = FormStartPosition.Manual; form.WindowState = FormWindowState.Maximized; form.FormBorderStyle = FormBorderStyle.None; form.TopMost = true; form.BackColor = System.Drawing.Color.Black; forms.Add(form); } sleep_step = 10 / forms.Count; MoveToStartPositions(); } void MoveToStartPositions() { int count = 0; foreach (Screen s in Screen.AllScreens) { // forms[count++].Location = new System.Drawing.Point(s.Bounds.X, s.Bounds.Y); //forms[count].Size = new System.Drawing.Size(4096, 4096); count++; } } bool FadedOut { get { bool ready = true; foreach (Form form in forms) ready = ready && form.Opacity >= 1.0; return ready; } } bool FadedIn { get { bool ready = true; foreach (Form form in forms) ready = ready && form.Opacity <= 0.0; return ready; } } internal void FadeOut() { MoveToStartPositions(); foreach (Form form in forms) { form.Opacity = 0.0; form.Visible = true; } while (!FadedOut) { foreach (Form form in forms) { form.Opacity += opacity_step; form.Refresh(); } Thread.Sleep(sleep_step); } } internal void FadeIn() { MoveToStartPositions(); foreach (Form form in forms) form.Opacity = 1.0; while (!FadedIn) { foreach (Form form in forms) { form.Opacity -= opacity_step; form.Refresh(); } Thread.Sleep(sleep_step); } foreach (Form form in forms) form.Visible = false; } #region IDisposable Members public void Dispose() { foreach (Form form in forms) form.Dispose(); } #endregion } #endif #endregion }
using Antlr4.Runtime; using Plang.Compiler.TypeChecker.AST; using Plang.Compiler.TypeChecker.AST.Declarations; using Plang.Compiler.TypeChecker.AST.Expressions; using Plang.Compiler.TypeChecker.AST.Statements; using Plang.Compiler.TypeChecker.Types; using System; using System.Collections.Generic; using System.Linq; namespace Plang.Compiler.TypeChecker { public class StatementVisitor : PParserBaseVisitor<IPStmt> { private readonly ExprVisitor exprVisitor; private readonly ITranslationErrorHandler handler; private readonly Machine machine; private readonly Function method; private readonly Scope table; public StatementVisitor(ITranslationErrorHandler handler, Machine machine, Function method) { this.handler = handler; this.machine = machine; this.method = method; table = method.Scope; exprVisitor = new ExprVisitor(method, handler); } public override IPStmt VisitFunctionBody(PParser.FunctionBodyContext context) { List<IPStmt> statements = context.statement().Select(Visit).ToList(); return new CompoundStmt(context, statements); } public override IPStmt VisitCompoundStmt(PParser.CompoundStmtContext context) { List<IPStmt> statements = context.statement().Select(Visit).ToList(); return new CompoundStmt(context, statements); } public override IPStmt VisitAssertStmt(PParser.AssertStmtContext context) { IPExpr assertion = exprVisitor.Visit(context.assertion); if (!PrimitiveType.Bool.IsSameTypeAs(assertion.Type)) { throw handler.TypeMismatch(context.assertion, assertion.Type, PrimitiveType.Bool); } IPExpr message; if (context.message == null) message = new StringExpr(context, "", new List<IPExpr>()); else { message = exprVisitor.Visit(context.message); if (!message.Type.IsSameTypeAs(PrimitiveType.String)) { throw handler.TypeMismatch(context.message, message.Type, PrimitiveType.String); } } return new AssertStmt(context, assertion, message); } public override IPStmt VisitPrintStmt(PParser.PrintStmtContext context) { IPExpr message = exprVisitor.Visit(context.message); if (!message.Type.IsSameTypeAs(PrimitiveType.String)) { throw handler.TypeMismatch(context.message, message.Type, PrimitiveType.String); } return new PrintStmt(context, message); } public override IPStmt VisitReturnStmt(PParser.ReturnStmtContext context) { IPExpr returnValue = context.expr() == null ? null : exprVisitor.Visit(context.expr()); PLanguageType returnType = returnValue?.Type ?? PrimitiveType.Null; if (!method.Signature.ReturnType.IsAssignableFrom(returnType)) { throw handler.TypeMismatch(context, returnType, method.Signature.ReturnType); } return new ReturnStmt(context, returnValue); } public override IPStmt VisitBreakStmt(PParser.BreakStmtContext context) { return new BreakStmt(context); } public override IPStmt VisitContinueStmt(PParser.ContinueStmtContext context) { return new ContinueStmt(context); } public override IPStmt VisitAssignStmt(PParser.AssignStmtContext context) { IPExpr variable = exprVisitor.Visit(context.lvalue()); IPExpr value = exprVisitor.Visit(context.rvalue()); // If this is a value assignment, we just need subtyping if (!variable.Type.IsAssignableFrom(value.Type)) { throw handler.TypeMismatch(context.rvalue(), value.Type, variable.Type); } return new AssignStmt(context, variable, value); } public override IPStmt VisitAddStmt(PParser.AddStmtContext context) { var variable = exprVisitor.Visit(context.lvalue()); var value = exprVisitor.Visit(context.rvalue()); // Check subtyping var valueType = value.Type; PLanguageType expectedValueType; switch (variable.Type.Canonicalize()) { case SetType setType: expectedValueType = setType.ElementType; break; default: throw handler.TypeMismatch(variable, TypeKind.Set); } if (!expectedValueType.IsAssignableFrom(valueType)) throw handler.TypeMismatch(context.rvalue(), valueType, expectedValueType); return new AddStmt(context, variable, value); } public override IPStmt VisitInsertStmt(PParser.InsertStmtContext context) { IPExpr variable = exprVisitor.Visit(context.lvalue()); IPExpr index = exprVisitor.Visit(context.expr()); IPExpr value = exprVisitor.Visit(context.rvalue()); // Check subtyping PLanguageType keyType = index.Type; PLanguageType valueType = value.Type; PLanguageType expectedKeyType; PLanguageType expectedValueType; switch (variable.Type.Canonicalize()) { case SequenceType sequenceType: expectedKeyType = PrimitiveType.Int; expectedValueType = sequenceType.ElementType; break; case MapType mapType: expectedKeyType = mapType.KeyType; expectedValueType = mapType.ValueType; break; default: throw handler.TypeMismatch(variable, TypeKind.Sequence, TypeKind.Map); } if (!expectedKeyType.IsAssignableFrom(keyType)) { throw handler.TypeMismatch(context.rvalue(), keyType, expectedKeyType); } if (!expectedValueType.IsAssignableFrom(valueType)) { throw handler.TypeMismatch(context.rvalue(), valueType, expectedValueType); } return new InsertStmt(context, variable, index, value); } public override IPStmt VisitRemoveStmt(PParser.RemoveStmtContext context) { IPExpr variable = exprVisitor.Visit(context.lvalue()); IPExpr value = exprVisitor.Visit(context.expr()); if (PLanguageType.TypeIsOfKind(variable.Type, TypeKind.Sequence)) { if (!PrimitiveType.Int.IsAssignableFrom(value.Type)) { throw handler.TypeMismatch(context.expr(), value.Type, PrimitiveType.Int); } } else if (PLanguageType.TypeIsOfKind(variable.Type, TypeKind.Map)) { MapType map = (MapType)variable.Type.Canonicalize(); if (!map.KeyType.IsAssignableFrom(value.Type)) { throw handler.TypeMismatch(context.expr(), value.Type, map.KeyType); } } else if (PLanguageType.TypeIsOfKind(variable.Type, TypeKind.Set)) { var set = (SetType)variable.Type.Canonicalize(); if (!set.ElementType.IsAssignableFrom(value.Type)) throw handler.TypeMismatch(context.expr(), value.Type, set.ElementType); } else { throw handler.TypeMismatch(variable, TypeKind.Sequence, TypeKind.Map); } return new RemoveStmt(context, variable, value); } public override IPStmt VisitWhileStmt(PParser.WhileStmtContext context) { IPExpr condition = exprVisitor.Visit(context.expr()); if (!Equals(condition.Type, PrimitiveType.Bool)) { throw handler.TypeMismatch(context.expr(), condition.Type, PrimitiveType.Bool); } IPStmt body = Visit(context.statement()); return new WhileStmt(context, condition, body); } public override IPStmt VisitForeachStmt(PParser.ForeachStmtContext context) { string varName = context.item.GetText(); if (!table.Lookup(varName, out Variable var)) { throw handler.MissingDeclaration(context.item, "foreach iterator variable", varName); } IPExpr collection = exprVisitor.Visit(context.collection); // make sure that foreach is applied to either sequence or set type // Check subtyping var itemType = var.Type; PLanguageType expectedItemType; switch (collection.Type.Canonicalize()) { case SetType setType: expectedItemType = setType.ElementType; break; case SequenceType seqType: expectedItemType = seqType.ElementType; break; default: throw handler.TypeMismatch(collection, TypeKind.Set, TypeKind.Sequence); } if (!expectedItemType.IsSameTypeAs(itemType) || !expectedItemType.IsAssignableFrom(itemType)) throw handler.TypeMismatch(context.item, itemType, expectedItemType); IPStmt body = Visit(context.statement()); return new ForeachStmt(context, var, collection, body); } public override IPStmt VisitIfStmt(PParser.IfStmtContext context) { IPExpr condition = exprVisitor.Visit(context.expr()); if (!Equals(condition.Type, PrimitiveType.Bool)) { throw handler.TypeMismatch(context.expr(), condition.Type, PrimitiveType.Bool); } IPStmt thenBody = Visit(context.thenBranch); IPStmt elseBody = context.elseBranch == null ? new NoStmt(context) : Visit(context.elseBranch); return new IfStmt(context, condition, thenBody, elseBody); } public override IPStmt VisitCtorStmt(PParser.CtorStmtContext context) { string interfaceName = context.iden().GetText(); if (!table.Lookup(interfaceName, out Interface targetInterface)) { throw handler.MissingDeclaration(context.iden(), "interface", interfaceName); } List<IPExpr> args = TypeCheckingUtils.VisitRvalueList(context.rvalueList(), exprVisitor).ToList(); TypeCheckingUtils.ValidatePayloadTypes(handler, context, targetInterface.PayloadType, args); return new CtorStmt(context, targetInterface, args); } public override IPStmt VisitFunCallStmt(PParser.FunCallStmtContext context) { string funName = context.fun.GetText(); List<IPExpr> argsList = TypeCheckingUtils.VisitRvalueList(context.rvalueList(), exprVisitor).ToList(); if (!table.Lookup(funName, out Function fun)) { throw handler.MissingDeclaration(context.fun, "function or function prototype", funName); } if (fun.Signature.Parameters.Count != argsList.Count) { throw handler.IncorrectArgumentCount((ParserRuleContext)context.rvalueList() ?? context, argsList.Count, fun.Signature.Parameters.Count); } foreach (Tuple<Variable, IPExpr> pair in fun.Signature.Parameters.Zip(argsList, Tuple.Create)) { TypeCheckingUtils.CheckArgument(handler, context, pair.Item1.Type, pair.Item2); } method.AddCallee(fun); return new FunCallStmt(context, fun, argsList); } public override IPStmt VisitRaiseStmt(PParser.RaiseStmtContext context) { if (!method.Signature.ReturnType.IsSameTypeAs(PrimitiveType.Null)) { throw handler.RaiseEventInNonVoidFunction(context); } IPExpr evtExpr = exprVisitor.Visit(context.expr()); if (IsDefinitelyNullEvent(evtExpr)) { throw handler.EmittedNullEvent(evtExpr); } if (!PrimitiveType.Event.IsAssignableFrom(evtExpr.Type)) { throw handler.TypeMismatch(context.expr(), evtExpr.Type, PrimitiveType.Event); } method.CanRaiseEvent = true; IPExpr[] args = TypeCheckingUtils.VisitRvalueList(context.rvalueList(), exprVisitor).ToArray(); if (evtExpr is EventRefExpr eventRef) { TypeCheckingUtils.ValidatePayloadTypes(handler, context, eventRef.Value.PayloadType, args); } return new RaiseStmt(context, evtExpr, args); } public override IPStmt VisitSendStmt(PParser.SendStmtContext context) { if (machine?.IsSpec == true) { throw handler.IllegalMonitorOperation(context, context.SEND().Symbol, machine); } IPExpr machineExpr = exprVisitor.Visit(context.machine); if (!PrimitiveType.Machine.IsAssignableFrom(machineExpr.Type)) { throw handler.TypeMismatch(context.machine, machineExpr.Type, PrimitiveType.Machine); } IPExpr evtExpr = exprVisitor.Visit(context.@event); if (IsDefinitelyNullEvent(evtExpr)) { throw handler.EmittedNullEvent(evtExpr); } if (!PrimitiveType.Event.IsAssignableFrom(evtExpr.Type)) { throw handler.TypeMismatch(context.@event, evtExpr.Type, PrimitiveType.Event); } IPExpr[] args = TypeCheckingUtils.VisitRvalueList(context.rvalueList(), exprVisitor).ToArray(); if (evtExpr is EventRefExpr eventRef) { TypeCheckingUtils.ValidatePayloadTypes(handler, context, eventRef.Value.PayloadType, args); } return new SendStmt(context, machineExpr, evtExpr, args); } private static bool IsDefinitelyNullEvent(IPExpr evtExpr) { return evtExpr is NullLiteralExpr || evtExpr is EventRefExpr evtRef && evtRef.Value.Name.Equals("null"); } public override IPStmt VisitAnnounceStmt(PParser.AnnounceStmtContext context) { if (machine?.IsSpec == true) { throw handler.IllegalMonitorOperation(context, context.ANNOUNCE().Symbol, machine); } IPExpr evtExpr = exprVisitor.Visit(context.expr()); if (IsDefinitelyNullEvent(evtExpr)) { throw handler.EmittedNullEvent(evtExpr); } if (!PrimitiveType.Event.IsAssignableFrom(evtExpr.Type)) { throw handler.TypeMismatch(context.expr(), evtExpr.Type, PrimitiveType.Event); } List<IPExpr> args = TypeCheckingUtils.VisitRvalueList(context.rvalueList(), exprVisitor).ToList(); return new AnnounceStmt(context, evtExpr, args.Count == 0 ? null : args[0]); } public override IPStmt VisitGotoStmt(PParser.GotoStmtContext context) { if (!method.Signature.ReturnType.IsSameTypeAs(PrimitiveType.Null)) { throw handler.ChangeStateInNonVoidFunction(context); } PParser.StateNameContext stateNameContext = context.stateName(); string stateName = stateNameContext.state.GetText(); IStateContainer current = machine; AST.States.State state = current?.GetState(stateName); if (state == null) { throw handler.MissingDeclaration(stateNameContext.state, "state", stateName); } PLanguageType expectedType = state.Entry?.Signature.ParameterTypes.ElementAtOrDefault(0) ?? PrimitiveType.Null; IPExpr[] rvaluesList = TypeCheckingUtils.VisitRvalueList(context.rvalueList(), exprVisitor).ToArray(); IPExpr payload; if (rvaluesList.Length == 0) { payload = null; } else if (rvaluesList.Length == 1) { payload = rvaluesList[0]; } else { payload = new UnnamedTupleExpr(context, rvaluesList); } PLanguageType payloadType = payload?.Type ?? PrimitiveType.Null; if (!expectedType.IsAssignableFrom(payloadType)) { throw handler.TypeMismatch(context, payloadType, expectedType); } method.CanChangeState = true; return new GotoStmt(context, state, payload); } public override IPStmt VisitReceiveStmt(PParser.ReceiveStmtContext context) { if (machine?.IsSpec == true) { throw handler.IllegalMonitorOperation(context, context.RECEIVE().Symbol, machine); } Dictionary<PEvent, Function> cases = new Dictionary<PEvent, Function>(); foreach (PParser.RecvCaseContext caseContext in context.recvCase()) { foreach (PParser.EventIdContext eventIdContext in caseContext.eventList().eventId()) { Function recvHandler = new Function(caseContext.anonEventHandler()) { Scope = table.MakeChildScope(), Owner = method.Owner, ParentFunction = method, Role = FunctionRole.ReceiveHandler }; var param = caseContext.anonEventHandler().funParam(); if (param != null) { Variable paramVar = recvHandler.Scope.Put(param.name.GetText(), param, VariableRole.Param); paramVar.Type = TypeResolver.ResolveType(param.type(), recvHandler.Scope, handler); recvHandler.Signature.Parameters.Add(paramVar); } FunctionBodyVisitor.PopulateMethod(handler, recvHandler); if (!table.Lookup(eventIdContext.GetText(), out PEvent pEvent)) { throw handler.MissingDeclaration(eventIdContext, "event", eventIdContext.GetText()); } if (cases.ContainsKey(pEvent)) { throw handler.DuplicateReceiveCase(eventIdContext, pEvent); } PLanguageType expectedType = recvHandler.Signature.ParameterTypes.ElementAtOrDefault(0) ?? PrimitiveType.Null; if (!expectedType.IsAssignableFrom(pEvent.PayloadType)) { throw handler.TypeMismatch(caseContext.anonEventHandler(), expectedType, pEvent.PayloadType); } if (recvHandler.CanChangeState == true) { if (!method.Signature.ReturnType.IsSameTypeAs(PrimitiveType.Null)) { throw handler.ChangeStateInNonVoidFunction(context); } method.CanChangeState = true; } if (recvHandler.CanRaiseEvent == true) { if (!method.Signature.ReturnType.IsSameTypeAs(PrimitiveType.Null)) { throw handler.RaiseEventInNonVoidFunction(context); } method.CanRaiseEvent = true; } foreach (var callee in recvHandler.Callees) { method.AddCallee(callee); } cases.Add(pEvent, recvHandler); } } method.CanReceive = true; return new ReceiveStmt(context, cases); } public override IPStmt VisitNoStmt(PParser.NoStmtContext context) { return new NoStmt(context); } } }
using UnityEngine; using System.Collections.Generic; using System.Linq; public class MouseManager : MonoBehaviour { public GameObject selectionIndicatorPrefab; public LayerMask groundLayer; public LayerMask worldObjectsLayer; Player player; bool dragging; Vector2 dragStart; Vector2 dragEnd; HashSet<WorldObject> selectedObjectsThisFrame; enum SelectionType { None, Units, Buildings }; // can only drag select units of the same type, // the first one will be recorded here SelectionType selectionType; void Start () { player = GetComponent<Player> (); selectedObjectsThisFrame = new HashSet<WorldObject> (); } void Update () { HandleLeftClick (); HandleRightClick (); } void HandleLeftClick() { if (Input.GetMouseButtonDown (0)) { if (player.hud && player.hud.IsMouseInHUDBounds ()) { return; } WorldObjectHitInfo hitInfo = FindHitObject (); if (hitInfo.worldObject) { WorldObject wob = hitInfo.worldObject; if (!wob.Selected) { SelectObject (wob); } selectionType = SelectionType.None; } else if (hitInfo.hitGround) { ClearSelection (); dragging = true; dragStart = Input.mousePosition; selectionType = SelectionType.None; } } if (dragging) { dragEnd = Input.mousePosition; DragSelectBoxCast(dragStart, dragEnd); } if (Input.GetMouseButtonUp (0)) { dragging = false; if (_selectionMesh) { Destroy (_selectionMesh); _selectionMesh = null; } } } void HandleRightClick() { if (Input.GetMouseButtonDown (1)) { WorldObjectHitInfo hitInfo = FindHitObject (); Debug.Log ("Right click at " + hitInfo.worldPosition); Vector3 groundPosition = hitInfo.worldPosition; groundPosition.y = 0; foreach (var selected in player.SelectedObjects) { Debug.Log ("Sending right click to " + selected.name); selected.HandleRightClick (groundPosition, hitInfo.worldObject); } } } // ()()()()()()()() // ---------------- // [][][][][][][][] static GameObject _dragStartMarker; static GameObject _dragEndMarker; static GameObject _dragCenterMarker; GameObject DebugSphere(Vector3 center, Color color) { var sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere); sphere.transform.position = center; sphere.transform.rotation = Quaternion.LookRotation (Camera.main.transform.forward); sphere.GetComponent<MeshRenderer> ().material.color = color; sphere.transform.localScale = Vector3.one * 4f; return sphere; } bool enabledBoxCastVisual = true; static GameObject _boxCastVisual; void DragSelectBoxCast(Vector2 screenPos1, Vector2 screenPos2) { // normalize the positions so we always have a top-left -> bottom-right // selection Vector2 tmp = screenPos1; screenPos1 = new Vector2 ( Mathf.Min (screenPos1.x, screenPos2.x), Mathf.Max (screenPos1.y, screenPos2.y) ); screenPos2 = new Vector2 ( Mathf.Max (tmp.x, screenPos2.x), Mathf.Min (tmp.y, screenPos2.y) ); Vector3 wp1 = Camera.main.ScreenToWorldPoint (screenPos1); Vector3 wp2 = Camera.main.ScreenToWorldPoint (screenPos2); Vector3 wp3 = Camera.main.ScreenToWorldPoint (new Vector2(screenPos1.x, screenPos2.y)); Vector3 wp4 = Camera.main.ScreenToWorldPoint (new Vector2(screenPos2.x, screenPos1.y)); Vector3 wpcenter = Camera.main.ScreenToWorldPoint ( new Vector2(screenPos1.x + (screenPos2.x - screenPos1.x) / 2f, screenPos1.y + (screenPos2.y - screenPos1.y) / 2f) ); Vector3 halfExtents = new Vector3(wpcenter.x - wp1.x, wp1.y - wpcenter.y, 25); Vector3 direction = Camera.main.transform.forward; Quaternion rotation = Quaternion.LookRotation (direction); RaycastHit[] hits = Physics.BoxCastAll (wpcenter, halfExtents, direction, rotation, Mathf.Infinity); if (enabledBoxCastVisual) { if (_selectionMesh == null) { _selectionMesh = CreateSelectionMeshObject (); } else { UpdateSelectionMesh (_selectionMesh, wp1, wp2, wp3, wp4); } if (_boxCastVisual == null) { _boxCastVisual = GameObject.CreatePrimitive (PrimitiveType.Cube); _boxCastVisual.GetComponent<MeshRenderer> ().material.color = Color.yellow; } _boxCastVisual.transform.transform.position = wpcenter; _boxCastVisual.transform.localScale = new Vector3 (halfExtents.x * 2, halfExtents.y * 2, 4); // halfExtents * 2.5f; _boxCastVisual.transform.rotation = rotation; // move it foward so we can see it _boxCastVisual.transform.Translate (Vector3.forward * 100); } Debug.Log ("hits: " + hits.Length); // keep track of selected objects this so we can remove the ones that are no longer selected selectedObjectsThisFrame.Clear(); //var noLongerSelected = new HashSet<WorldObject> (player.SelectedObjects); foreach (var hit in hits) { var wob = hit.transform.root.GetComponentInChildren<WorldObject> (); if (wob == null) { continue; } if (selectionType == SelectionType.None) { // set selection type from first unit hit selectionType = WorldObjectSelectionType(wob); } if (WorldObjectSelectionType (wob) != selectionType) { Debug.Log ("Skipping selection of " + wob.GetType () + " because it doesn't match the current selection type of " + selectionType); continue; } selectedObjectsThisFrame.Add(wob); AddToSelection (wob); } var noLongerSelected = player.SelectedObjects.Where (x => !selectedObjectsThisFrame.Contains (x)); //anything leftover is no longer selected foreach (var wob in noLongerSelected) { UnselectObject (wob); } } SelectionType WorldObjectSelectionType(WorldObject wob) { if (wob.GetType () == typeof(Unit) || wob.GetType().IsSubclassOf (typeof(Unit))) { return SelectionType.Units; } else if (wob.GetType () == typeof(Building) || wob.GetType ().IsSubclassOf (typeof(Building))) { return SelectionType.Buildings; } Debug.LogError ("Undefined selection type for object: " + wob.GetType ()); return SelectionType.None; } // this method is not used, but left for reference. // it puts a mesh into the world where you select and would use // colliders to select objects. static GameObject _selectionMesh; void DragSelect(Vector2 screenPos1, Vector2 screenPos2) { // ray cast this to the ground so we can create a 3d collision cube in world space Ray ray1 = Camera.main.ScreenPointToRay (screenPos1); Ray ray2 = Camera.main.ScreenPointToRay (screenPos2); Ray ray3 = Camera.main.ScreenPointToRay (new Vector2 (screenPos1.x, screenPos2.y)); Ray ray4 = Camera.main.ScreenPointToRay (new Vector2 (screenPos2.x, screenPos1.y)); RaycastHit hit1, hit2, hit3, hit4; if (Physics.Raycast (ray1, out hit1, Mathf.Infinity, groundLayer) && Physics.Raycast (ray2, out hit2, Mathf.Infinity, groundLayer) && Physics.Raycast (ray3, out hit3, Mathf.Infinity, groundLayer) && Physics.Raycast (ray4, out hit4, Mathf.Infinity, groundLayer) ) { Vector3 worldPos1 = hit1.point; Vector3 worldPos2 = hit2.point; Vector3 worldPos3 = hit3.point; Vector3 worldPos4 = hit4.point; // if we dragged backwards, need to flip the points so the mesh gets created facing the right way if (worldPos1.x > worldPos2.x || worldPos1.z > worldPos2.z) { Vector3 tmp = worldPos1; worldPos1 = worldPos2; worldPos2 = tmp; tmp = worldPos3; worldPos3 = worldPos4; worldPos4 = tmp; } if (_selectionMesh == null) { _selectionMesh = CreateSelectionMeshObject (); } UpdateSelectionMesh (_selectionMesh, worldPos1, worldPos2, worldPos3, worldPos4); } else { Debug.LogWarning ("No raycast hit?"); } } GameObject CreateSelectionMeshObject() { var selectionObject = new GameObject (); selectionObject.name = "SelectionTrap"; var collider = selectionObject.AddComponent<BoxCollider> (); collider.tag = "SelectionBox"; collider.isTrigger = true; var meshFilter = selectionObject.AddComponent<MeshFilter> (); meshFilter.sharedMesh = new Mesh (); var meshRenderer = selectionObject.AddComponent<MeshRenderer> (); meshRenderer.material.color = Color.blue; return selectionObject; } void UpdateSelectionMesh(GameObject selectionObject, Vector3 worldPos1, Vector3 worldPos2, Vector3 worldPos3, Vector3 worldPos4) { var mf = selectionObject.GetComponent<MeshFilter> (); var mesh = mf.sharedMesh; // 1......4 // ........ // ........ // 3......2 var vertices = new Vector3[] { worldPos1, worldPos4, worldPos3, worldPos2 }; var triangles = new int[] { 0, 1, 2, 2, 1, 3 }; mesh.vertices = vertices; mesh.triangles = triangles; // FIXME: positioned in the wrong spot var collider = selectionObject.GetComponent<BoxCollider> (); collider.center = new Vector3 (worldPos2.x - worldPos1.x, 0, worldPos2.z - worldPos1.z); collider.size = new Vector3 (worldPos2.x - worldPos1.x, 10, worldPos2.z - worldPos1.z); Vector3 pos = Vector3.zero; pos.y = 0.2f; selectionObject.transform.position = pos; } void SelectObject(WorldObject wob) { if (player.SelectedObjects.Contains (wob)) { return; } ClearSelectionRings (); player.SelectObject (wob, true); AddSelectionRing (wob); } void UnselectObject(WorldObject wob) { player.UnselectObject(wob); RemoveSelectionRing (wob); } void AddToSelection(WorldObject wob) { if (player.SelectedObjects.Contains (wob)) { return; } player.SelectObject (wob, false); AddSelectionRing (wob); } void OnGUI() { if (dragging) { var rect = Utils.ScreenDrawing.GetScreenRect (dragStart, dragEnd); Utils.ScreenDrawing.DrawRect (rect, new Color (0.7f, 1.0f, 0.7f, 0.3f)); Utils.ScreenDrawing.DrawBox (rect, 3, new Color (0.8f, 1.0f, 0.8f, 0.5f)); } } void AddSelectionRing(WorldObject wob) { if (wob.GetComponentInChildren<SelectionRing> ()) { return; } MeshRenderer[] renderers = wob.GetComponentsInChildren<MeshRenderer> (); if (renderers.Length == 0) { Debug.LogWarning (wob.name + " has no mesh renderers"); return; } Bounds bounds = renderers [0].bounds; for (int i = 1; i < renderers.Length; i++) { MeshRenderer r = renderers [i]; bounds.Encapsulate (r.bounds); } float maxSize = Mathf.Max (bounds.size.x, bounds.size.z); Vector3 objPosition = bounds.center; objPosition.y = 0.01f; var ring = (GameObject)Instantiate (selectionIndicatorPrefab, objPosition, Quaternion.identity); ring.transform.localScale = new Vector3 (maxSize * 1.75f, 1, maxSize * 1.75f); ring.transform.SetParent (wob.transform); } void ClearSelection() { ClearSelectionRings (); player.ClearSelection (); } void RemoveSelectionRing(WorldObject wob) { var selectionRing = wob.GetComponentInChildren<SelectionRing> (); if (selectionRing) { Destroy (selectionRing.gameObject); } } void ClearSelectionRings() { foreach (WorldObject wob in player.SelectedObjects) { RemoveSelectionRing (wob); } } WorldObjectHitInfo FindHitObject() { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hitInfo; if (Physics.Raycast (ray, out hitInfo)) { Transform rootOfHitObject = hitInfo.collider.gameObject.transform.root; WorldObject obj = rootOfHitObject.GetComponentInChildren<WorldObject> (); if (obj) { return new WorldObjectHitInfo(obj, hitInfo.point); } else if (rootOfHitObject.gameObject.layer == LayerMask.NameToLayer("Ground")) { return new WorldObjectHitInfo (hitInfo.point); } } return WorldObjectHitInfo.Invalid(); } bool HitGround() { RaycastHit hitInfo; if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo)) { Transform rootOfHitObject = hitInfo.collider.gameObject.transform.root; return rootOfHitObject.gameObject.name == "Ground"; } return false; } } class WorldObjectHitInfo { public bool invalid; public bool hitGround; public WorldObject worldObject; public Vector3 worldPosition; public WorldObjectHitInfo (WorldObject worldObject, Vector3 worldPosition) { this.worldObject = worldObject; this.worldPosition = worldPosition; } public WorldObjectHitInfo(Vector3 groundPosition) { this.hitGround = true; this.worldPosition = groundPosition; } private WorldObjectHitInfo() { } public static WorldObjectHitInfo Invalid() { var instance = new WorldObjectHitInfo (); instance.invalid = true; return instance; } }
using System; using System.Data; using System.Web; using System.Collections; using System.Web.Security; using System.Web.Services; using System.Web.Services.Protocols; using System.ComponentModel; using System.Web.Script.Services; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Diagnostics; using System.Net; using System.Web.UI; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Web; using Umbraco.Web.Cache; using Umbraco.Web.WebServices; using umbraco.BusinessLogic; using umbraco.businesslogic.Exceptions; using umbraco.cms.businesslogic.web; using umbraco.cms.businesslogic.media; using umbraco.BasePages; namespace umbraco.presentation.webservices { /// <summary> /// Summary description for legacyAjaxCalls /// </summary> [WebService(Namespace = "http://umbraco.org/webservices")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] [ScriptService] public class legacyAjaxCalls : UmbracoAuthorizedWebService { [WebMethod] public bool ValidateUser(string username, string password) { if (ValidateCredentials(username, password)) { var u = new BusinessLogic.User(username); BasePage.doLogin(u); return true; } else { return false; } } /// <summary> /// method to accept a string value for the node id. Used for tree's such as python /// and xslt since the file names are the node IDs /// </summary> /// <param name="nodeId"></param> /// <param name="alias"></param> /// <param name="nodeType"></param> [WebMethod] [ScriptMethod] public void Delete(string nodeId, string alias, string nodeType) { AuthorizeRequest(true); //check which parameters to pass depending on the types passed in int intNodeID; if (nodeType == "memberGroup") { presentation.create.dialogHandler_temp.Delete(nodeType, 0, alias); } else if (int.TryParse(nodeId, out intNodeID) && nodeType != "member") // Fix for #26965 - numeric member login gets parsed as nodeId { presentation.create.dialogHandler_temp.Delete(nodeType, intNodeID, alias); } else { presentation.create.dialogHandler_temp.Delete(nodeType, 0, nodeId); } } /// <summary> /// Permanently deletes a document/media object. /// Used to remove an item from the recycle bin. /// </summary> /// <param name="nodeId"></param> [WebMethod] [ScriptMethod] public void DeleteContentPermanently(string nodeId, string nodeType) { int intNodeID; if (int.TryParse(nodeId, out intNodeID)) { switch (nodeType) { case "media": case "mediaRecycleBin": //ensure user has access to media AuthorizeRequest(DefaultApps.media.ToString(), true); new Media(intNodeID).delete(true); break; case "content": case "contentRecycleBin": default: //ensure user has access to content AuthorizeRequest(DefaultApps.content.ToString(), true); new Document(intNodeID).delete(true); break; } } else { throw new ArgumentException("The nodeId argument could not be parsed to an integer"); } } [WebMethod] [ScriptMethod] public void DisableUser(int userId) { AuthorizeRequest(DefaultApps.users.ToString(), true); BusinessLogic.User.GetUser(userId).disable(); } [WebMethod] [ScriptMethod] public string GetNodeName(int nodeId) { AuthorizeRequest(true); return new cms.businesslogic.CMSNode(nodeId).Text; } [WebMethod] [ScriptMethod] public string[] GetNodeBreadcrumbs(int nodeId) { AuthorizeRequest(true); var node = new cms.businesslogic.CMSNode(nodeId); var crumbs = new System.Collections.Generic.List<string>() { node.Text }; while (node != null && node.Level > 1) { node = node.Parent; crumbs.Add(node.Text); } crumbs.Reverse(); return crumbs.ToArray(); } [WebMethod] [ScriptMethod] public string NiceUrl(int nodeId) { AuthorizeRequest(true); return library.NiceUrl(nodeId); } [WebMethod] [ScriptMethod] public string ProgressStatus(string Key) { AuthorizeRequest(true); return Application[helper.Request("key")].ToString(); } [WebMethod] [ScriptMethod] public void RenewUmbracoSession() { AuthorizeRequest(true); BasePage.RenewLoginTimeout(); } [WebMethod] [ScriptMethod] public int GetSecondsBeforeUserLogout() { //TODO: Change this to not throw an exception otherwise we end up with JS errors all the time when recompiling!! AuthorizeRequest(true); long timeout = BasePage.GetTimeout(true); DateTime timeoutDate = new DateTime(timeout); DateTime currentDate = DateTime.Now; return (int) timeoutDate.Subtract(currentDate).TotalSeconds; } [WebMethod] [ScriptMethod] public string TemplateMasterPageContentContainer(int templateId, int masterTemplateId) { AuthorizeRequest(DefaultApps.settings.ToString(), true); return new cms.businesslogic.template.Template(templateId).GetMasterContentElement(masterTemplateId); } [WebMethod] [ScriptMethod] public string SaveFile(string fileName, string fileAlias, string fileContents, string fileType, int fileID, int masterID, bool ignoreDebug) { switch (fileType) { case "xslt": AuthorizeRequest(DefaultApps.developer.ToString(), true); return SaveXslt(fileName, fileContents, ignoreDebug); case "python": AuthorizeRequest(DefaultApps.developer.ToString(), true); return "true"; case "css": AuthorizeRequest(DefaultApps.settings.ToString(), true); return SaveCss(fileName, fileContents, fileID); case "script": AuthorizeRequest(DefaultApps.settings.ToString(), true); return SaveScript(fileName, fileContents); case "template": AuthorizeRequest(DefaultApps.settings.ToString(), true); return SaveTemplate(fileName, fileAlias, fileContents, fileID, masterID); default: throw new ArgumentException(String.Format("Invalid fileType passed: '{0}'", fileType)); } } public string Tidy(string textToTidy) { AuthorizeRequest(true); return library.Tidy(helper.Request("StringToTidy"), true); } private static string SaveCss(string fileName, string fileContents, int fileID) { string returnValue; var stylesheet = new StyleSheet(fileID) {Content = fileContents, Text = fileName}; try { stylesheet.saveCssToFile(); returnValue = "true"; } catch (Exception ee) { throw new Exception("Couldn't save file", ee); } //this.speechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editStylesheetSaved", base.getUser()), ""); return returnValue; } private string SaveXslt(string fileName, string fileContents, bool ignoreDebugging) { var tempFileName = IOHelper.MapPath(SystemDirectories.Xslt + "/" + System.DateTime.Now.Ticks + "_temp.xslt"); using (var sw = File.CreateText(tempFileName)) { sw.Write(fileContents); sw.Close(); } // Test the xslt string errorMessage = ""; if (!ignoreDebugging) { try { // Check if there's any documents yet if (content.Instance.XmlContent.SelectNodes("/root/node").Count > 0) { XmlDocument macroXML = new XmlDocument(); macroXML.LoadXml("<macro/>"); XslCompiledTransform macroXSLT = new XslCompiledTransform(); page umbPage = new page(content.Instance.XmlContent.SelectSingleNode("//node [@parentID = -1]")); XsltArgumentList xslArgs; xslArgs = macro.AddMacroXsltExtensions(); library lib = new library(umbPage); xslArgs.AddExtensionObject("urn:umbraco.library", lib); HttpContext.Current.Trace.Write("umbracoMacro", "After adding extensions"); // Add the current node xslArgs.AddParam("currentPage", "", library.GetXmlNodeById(umbPage.PageID.ToString())); HttpContext.Current.Trace.Write("umbracoMacro", "Before performing transformation"); // Create reader and load XSL file // We need to allow custom DTD's, useful for defining an ENTITY XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ProhibitDtd = false; using (XmlReader xmlReader = XmlReader.Create(tempFileName, readerSettings)) { XmlUrlResolver xslResolver = new XmlUrlResolver(); xslResolver.Credentials = CredentialCache.DefaultCredentials; macroXSLT.Load(xmlReader, XsltSettings.TrustedXslt, xslResolver); xmlReader.Close(); // Try to execute the transformation HtmlTextWriter macroResult = new HtmlTextWriter(new StringWriter()); macroXSLT.Transform(macroXML, xslArgs, macroResult); macroResult.Close(); } } else { errorMessage = "stub"; //base.speechBubble(speechBubbleIcon.info, ui.Text("errors", "xsltErrorHeader", base.getUser()), "Unable to validate xslt as no published content nodes exist."); } } catch (Exception errorXslt) { //base.speechBubble(speechBubbleIcon.error, ui.Text("errors", "xsltErrorHeader", base.getUser()), ui.Text("errors", "xsltErrorText", base.getUser())); //errorHolder.Visible = true; //closeErrorMessage.Visible = true; //errorHolder.Attributes.Add("style", "height: 250px; overflow: auto; border: 1px solid CCC; padding: 5px;"); errorMessage = (errorXslt.InnerException ?? errorXslt).ToString(); // Full error message errorMessage = errorMessage.Replace("\n", "<br/>\n"); //closeErrorMessage.Visible = true; string[] errorLine; // Find error MatchCollection m = Regex.Matches(errorMessage, @"\d*[^,],\d[^\)]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match mm in m) { errorLine = mm.Value.Split(','); if (errorLine.Length > 0) { int theErrorLine = int.Parse(errorLine[0]); int theErrorChar = int.Parse(errorLine[1]); errorMessage = "Error in XSLT at line " + errorLine[0] + ", char " + errorLine[1] + "<br/>"; errorMessage += "<span style=\"font-family: courier; font-size: 11px;\">"; string[] xsltText = fileContents.Split("\n".ToCharArray()); for (int i = 0; i < xsltText.Length; i++) { if (i >= theErrorLine - 3 && i <= theErrorLine + 1) if (i + 1 == theErrorLine) { errorMessage += "<b>" + (i + 1) + ": &gt;&gt;&gt;&nbsp;&nbsp;" + Server.HtmlEncode(xsltText[i].Substring(0, theErrorChar)); errorMessage += "<span style=\"text-decoration: underline; border-bottom: 1px solid red\">" + Server.HtmlEncode(xsltText[i].Substring(theErrorChar, xsltText[i].Length - theErrorChar)).Trim() + "</span>"; errorMessage += " &lt;&lt;&lt;</b><br/>"; } else errorMessage += (i + 1) + ": &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + Server.HtmlEncode(xsltText[i]) + "<br/>"; } errorMessage += "</span>"; } } } } if (errorMessage == "" && fileName.ToLower().EndsWith(".xslt")) { //Hardcoded security-check... only allow saving files in xslt directory... var savePath = IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName); if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Xslt))) { using (var sw = File.CreateText(savePath)) { sw.Write(fileContents); sw.Close(); } errorMessage = "true"; } else { errorMessage = "Illegal path"; } } File.Delete(tempFileName); return errorMessage; } private static string SaveScript(string filename, string contents) { var val = contents; string returnValue; try { var savePath = IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename); //Directory check.. only allow files in script dir and below to be edited if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Scripts + "/"))) { StreamWriter SW; SW = File.CreateText(IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename)); SW.Write(val); SW.Close(); returnValue = "true"; } else { throw new ArgumentException("Couldnt save to file - Illegal path"); } } catch (Exception ex) { throw new ArgumentException(String.Format("Couldnt save to file '{0}'", filename), ex); } return returnValue; } private static string SaveTemplate(string templateName, string templateAlias, string templateContents, int templateID, int masterTemplateID) { var tp = new cms.businesslogic.template.Template(templateID); var retVal = "false"; tp.Text = templateName; tp.Alias = templateAlias; tp.MasterTemplate = masterTemplateID; tp.Design = templateContents; tp.Save(); retVal = "true"; return retVal; } [Obsolete("You should use the AuthorizeRequest methods on the base class of UmbracoAuthorizedWebService and ensure you inherit from that class for umbraco asmx web services")] public static void Authorize() { // check for secure connection if (GlobalSettings.UseSSL && !HttpContext.Current.Request.IsSecureConnection) throw new UserAuthorizationException("This installation requires a secure connection (via SSL). Please update the URL to include https://"); if (!BasePages.BasePage.ValidateUserContextID(BasePages.BasePage.umbracoUserContextID)) throw new Exception("Client authorization failed. User is not logged in"); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Write action delegate. /// </summary> /// <param name="obj">Target object.</param> /// <param name="writer">Writer.</param> internal delegate void BinaryReflectiveWriteAction(object obj, IBinaryWriter writer); /// <summary> /// Read action delegate. /// </summary> /// <param name="obj">Target object.</param> /// <param name="reader">Reader.</param> internal delegate void BinaryReflectiveReadAction(object obj, IBinaryReader reader); /// <summary> /// Routines for reflective reads and writes. /// </summary> internal static class BinaryReflectiveActions { /** Method: read enum. */ private static readonly MethodInfo MthdReadEnum = typeof(IBinaryReader).GetMethod("ReadEnum", new[] { typeof(string) }); /** Method: read enum. */ private static readonly MethodInfo MthdReadEnumRaw = typeof (IBinaryRawReader).GetMethod("ReadEnum"); /** Method: read enum array. */ private static readonly MethodInfo MthdReadEnumArray = typeof(IBinaryReader).GetMethod("ReadEnumArray", new[] { typeof(string) }); /** Method: read enum array. */ private static readonly MethodInfo MthdReadEnumArrayRaw = typeof(IBinaryRawReader).GetMethod("ReadEnumArray"); /** Method: read array. */ private static readonly MethodInfo MthdReadObjArray = typeof(IBinaryReader).GetMethod("ReadArray", new[] { typeof(string) }); /** Method: read array. */ private static readonly MethodInfo MthdReadObjArrayRaw = typeof(IBinaryRawReader).GetMethod("ReadArray"); /** Method: read object. */ private static readonly MethodInfo MthdReadObj= typeof(IBinaryReader).GetMethod("ReadObject", new[] { typeof(string) }); /** Method: read object. */ private static readonly MethodInfo MthdReadObjRaw = typeof(IBinaryRawReader).GetMethod("ReadObject"); /** Method: write enum array. */ private static readonly MethodInfo MthdWriteEnumArray = typeof(IBinaryWriter).GetMethod("WriteEnumArray"); /** Method: write enum array. */ private static readonly MethodInfo MthdWriteEnumArrayRaw = typeof(IBinaryRawWriter).GetMethod("WriteEnumArray"); /** Method: write array. */ private static readonly MethodInfo MthdWriteObjArray = typeof(IBinaryWriter).GetMethod("WriteArray"); /** Method: write array. */ private static readonly MethodInfo MthdWriteObjArrayRaw = typeof(IBinaryRawWriter).GetMethod("WriteArray"); /** Method: write object. */ private static readonly MethodInfo MthdWriteObj = typeof(IBinaryWriter).GetMethod("WriteObject"); /** Method: write object. */ private static readonly MethodInfo MthdWriteObjRaw = typeof(IBinaryRawWriter).GetMethod("WriteObject"); /** Method: raw writer */ private static readonly MethodInfo MthdGetRawWriter = typeof(IBinaryWriter).GetMethod("GetRawWriter"); /** Method: raw writer */ private static readonly MethodInfo MthdGetRawReader = typeof(IBinaryReader).GetMethod("GetRawReader"); /// <summary> /// Lookup read/write actions for the given type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> public static void GetTypeActions(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { var type = field.FieldType; if (type.IsPrimitive) HandlePrimitive(field, out writeAction, out readAction, raw); else if (type.IsArray) HandleArray(field, out writeAction, out readAction, raw); else HandleOther(field, out writeAction, out readAction, raw); } /// <summary> /// Handle primitive type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> /// <exception cref="IgniteException">Unsupported primitive type: + type.Name</exception> private static void HandlePrimitive(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { var type = field.FieldType; if (type == typeof (bool)) { writeAction = raw ? GetRawWriter<bool>(field, (w, o) => w.WriteBoolean(o)) : GetWriter<bool>(field, (f, w, o) => w.WriteBoolean(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadBoolean()) : GetReader(field, (f, r) => r.ReadBoolean(f)); } else if (type == typeof (sbyte)) { writeAction = raw ? GetRawWriter<sbyte>(field, (w, o) => w.WriteByte(unchecked((byte) o))) : GetWriter<sbyte>(field, (f, w, o) => w.WriteByte(f, unchecked((byte) o))); readAction = raw ? GetRawReader(field, r => unchecked ((sbyte) r.ReadByte())) : GetReader(field, (f, r) => unchecked ((sbyte) r.ReadByte(f))); } else if (type == typeof (byte)) { writeAction = raw ? GetRawWriter<byte>(field, (w, o) => w.WriteByte(o)) : GetWriter<byte>(field, (f, w, o) => w.WriteByte(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadByte()) : GetReader(field, (f, r) => r.ReadByte(f)); } else if (type == typeof (short)) { writeAction = raw ? GetRawWriter<short>(field, (w, o) => w.WriteShort(o)) : GetWriter<short>(field, (f, w, o) => w.WriteShort(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadShort()) : GetReader(field, (f, r) => r.ReadShort(f)); } else if (type == typeof (ushort)) { writeAction = raw ? GetRawWriter<ushort>(field, (w, o) => w.WriteShort(unchecked((short) o))) : GetWriter<ushort>(field, (f, w, o) => w.WriteShort(f, unchecked((short) o))); readAction = raw ? GetRawReader(field, r => unchecked((ushort) r.ReadShort())) : GetReader(field, (f, r) => unchecked((ushort) r.ReadShort(f))); } else if (type == typeof (char)) { writeAction = raw ? GetRawWriter<char>(field, (w, o) => w.WriteChar(o)) : GetWriter<char>(field, (f, w, o) => w.WriteChar(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadChar()) : GetReader(field, (f, r) => r.ReadChar(f)); } else if (type == typeof (int)) { writeAction = raw ? GetRawWriter<int>(field, (w, o) => w.WriteInt(o)) : GetWriter<int>(field, (f, w, o) => w.WriteInt(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadInt()) : GetReader(field, (f, r) => r.ReadInt(f)); } else if (type == typeof (uint)) { writeAction = raw ? GetRawWriter<uint>(field, (w, o) => w.WriteInt(unchecked((int) o))) : GetWriter<uint>(field, (f, w, o) => w.WriteInt(f, unchecked((int) o))); readAction = raw ? GetRawReader(field, r => unchecked((uint) r.ReadInt())) : GetReader(field, (f, r) => unchecked((uint) r.ReadInt(f))); } else if (type == typeof (long)) { writeAction = raw ? GetRawWriter<long>(field, (w, o) => w.WriteLong(o)) : GetWriter<long>(field, (f, w, o) => w.WriteLong(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadLong()) : GetReader(field, (f, r) => r.ReadLong(f)); } else if (type == typeof (ulong)) { writeAction = raw ? GetRawWriter<ulong>(field, (w, o) => w.WriteLong(unchecked((long) o))) : GetWriter<ulong>(field, (f, w, o) => w.WriteLong(f, unchecked((long) o))); readAction = raw ? GetRawReader(field, r => unchecked((ulong) r.ReadLong())) : GetReader(field, (f, r) => unchecked((ulong) r.ReadLong(f))); } else if (type == typeof (float)) { writeAction = raw ? GetRawWriter<float>(field, (w, o) => w.WriteFloat(o)) : GetWriter<float>(field, (f, w, o) => w.WriteFloat(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadFloat()) : GetReader(field, (f, r) => r.ReadFloat(f)); } else if (type == typeof (double)) { writeAction = raw ? GetRawWriter<double>(field, (w, o) => w.WriteDouble(o)) : GetWriter<double>(field, (f, w, o) => w.WriteDouble(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDouble()) : GetReader(field, (f, r) => r.ReadDouble(f)); } else throw new IgniteException("Unsupported primitive type: " + type.Name); } /// <summary> /// Handle array type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> private static void HandleArray(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { Type elemType = field.FieldType.GetElementType(); if (elemType == typeof (bool)) { writeAction = raw ? GetRawWriter<bool[]>(field, (w, o) => w.WriteBooleanArray(o)) : GetWriter<bool[]>(field, (f, w, o) => w.WriteBooleanArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadBooleanArray()) : GetReader(field, (f, r) => r.ReadBooleanArray(f)); } else if (elemType == typeof (byte)) { writeAction = raw ? GetRawWriter<byte[]>(field, (w, o) => w.WriteByteArray(o)) : GetWriter<byte[]>(field, (f, w, o) => w.WriteByteArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadByteArray()) : GetReader(field, (f, r) => r.ReadByteArray(f)); } else if (elemType == typeof (sbyte)) { writeAction = raw ? GetRawWriter<sbyte[]>(field, (w, o) => w.WriteByteArray((byte[]) (Array) o)) : GetWriter<sbyte[]>(field, (f, w, o) => w.WriteByteArray(f, (byte[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (sbyte[]) (Array) r.ReadByteArray()) : GetReader(field, (f, r) => (sbyte[]) (Array) r.ReadByteArray(f)); } else if (elemType == typeof (short)) { writeAction = raw ? GetRawWriter<short[]>(field, (w, o) => w.WriteShortArray(o)) : GetWriter<short[]>(field, (f, w, o) => w.WriteShortArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadShortArray()) : GetReader(field, (f, r) => r.ReadShortArray(f)); } else if (elemType == typeof (ushort)) { writeAction = raw ? GetRawWriter<ushort[]>(field, (w, o) => w.WriteShortArray((short[]) (Array) o)) : GetWriter<ushort[]>(field, (f, w, o) => w.WriteShortArray(f, (short[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (ushort[]) (Array) r.ReadShortArray()) : GetReader(field, (f, r) => (ushort[]) (Array) r.ReadShortArray(f)); } else if (elemType == typeof (char)) { writeAction = raw ? GetRawWriter<char[]>(field, (w, o) => w.WriteCharArray(o)) : GetWriter<char[]>(field, (f, w, o) => w.WriteCharArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadCharArray()) : GetReader(field, (f, r) => r.ReadCharArray(f)); } else if (elemType == typeof (int)) { writeAction = raw ? GetRawWriter<int[]>(field, (w, o) => w.WriteIntArray(o)) : GetWriter<int[]>(field, (f, w, o) => w.WriteIntArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadIntArray()) : GetReader(field, (f, r) => r.ReadIntArray(f)); } else if (elemType == typeof (uint)) { writeAction = raw ? GetRawWriter<uint[]>(field, (w, o) => w.WriteIntArray((int[]) (Array) o)) : GetWriter<uint[]>(field, (f, w, o) => w.WriteIntArray(f, (int[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (uint[]) (Array) r.ReadIntArray()) : GetReader(field, (f, r) => (uint[]) (Array) r.ReadIntArray(f)); } else if (elemType == typeof (long)) { writeAction = raw ? GetRawWriter<long[]>(field, (w, o) => w.WriteLongArray(o)) : GetWriter<long[]>(field, (f, w, o) => w.WriteLongArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadLongArray()) : GetReader(field, (f, r) => r.ReadLongArray(f)); } else if (elemType == typeof (ulong)) { writeAction = raw ? GetRawWriter<ulong[]>(field, (w, o) => w.WriteLongArray((long[]) (Array) o)) : GetWriter<ulong[]>(field, (f, w, o) => w.WriteLongArray(f, (long[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (ulong[]) (Array) r.ReadLongArray()) : GetReader(field, (f, r) => (ulong[]) (Array) r.ReadLongArray(f)); } else if (elemType == typeof (float)) { writeAction = raw ? GetRawWriter<float[]>(field, (w, o) => w.WriteFloatArray(o)) : GetWriter<float[]>(field, (f, w, o) => w.WriteFloatArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadFloatArray()) : GetReader(field, (f, r) => r.ReadFloatArray(f)); } else if (elemType == typeof (double)) { writeAction = raw ? GetRawWriter<double[]>(field, (w, o) => w.WriteDoubleArray(o)) : GetWriter<double[]>(field, (f, w, o) => w.WriteDoubleArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDoubleArray()) : GetReader(field, (f, r) => r.ReadDoubleArray(f)); } else if (elemType == typeof (decimal?)) { writeAction = raw ? GetRawWriter<decimal?[]>(field, (w, o) => w.WriteDecimalArray(o)) : GetWriter<decimal?[]>(field, (f, w, o) => w.WriteDecimalArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDecimalArray()) : GetReader(field, (f, r) => r.ReadDecimalArray(f)); } else if (elemType == typeof (string)) { writeAction = raw ? GetRawWriter<string[]>(field, (w, o) => w.WriteStringArray(o)) : GetWriter<string[]>(field, (f, w, o) => w.WriteStringArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadStringArray()) : GetReader(field, (f, r) => r.ReadStringArray(f)); } else if (elemType == typeof (Guid?)) { writeAction = raw ? GetRawWriter<Guid?[]>(field, (w, o) => w.WriteGuidArray(o)) : GetWriter<Guid?[]>(field, (f, w, o) => w.WriteGuidArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadGuidArray()) : GetReader(field, (f, r) => r.ReadGuidArray(f)); } else if (elemType.IsEnum) { writeAction = raw ? GetRawWriter(field, MthdWriteEnumArrayRaw, elemType) : GetWriter(field, MthdWriteEnumArray, elemType); readAction = raw ? GetRawReader(field, MthdReadEnumArrayRaw, elemType) : GetReader(field, MthdReadEnumArray, elemType); } else { writeAction = raw ? GetRawWriter(field, MthdWriteObjArrayRaw, elemType) : GetWriter(field, MthdWriteObjArray, elemType); readAction = raw ? GetRawReader(field, MthdReadObjArrayRaw, elemType) : GetReader(field, MthdReadObjArray, elemType); } } /// <summary> /// Determines whether specified field is a query field (has QueryFieldAttribute). /// </summary> private static bool IsQueryField(FieldInfo fieldInfo) { Debug.Assert(fieldInfo != null && fieldInfo.DeclaringType != null); var fieldName = BinaryUtils.CleanFieldName(fieldInfo.Name); object[] attrs = null; if (fieldName != fieldInfo.Name) { // Backing field, check corresponding property var prop = fieldInfo.DeclaringType.GetProperty(fieldName, fieldInfo.FieldType); if (prop != null) attrs = prop.GetCustomAttributes(true); } attrs = attrs ?? fieldInfo.GetCustomAttributes(true); return attrs.OfType<QuerySqlFieldAttribute>().Any(); } /// <summary> /// Handle other type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> private static void HandleOther(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { var type = field.FieldType; var genericDef = type.IsGenericType ? type.GetGenericTypeDefinition() : null; bool nullable = genericDef == typeof (Nullable<>); var nullableType = nullable ? type.GetGenericArguments()[0] : null; if (type == typeof (decimal)) { writeAction = raw ? GetRawWriter<decimal>(field, (w, o) => w.WriteDecimal(o)) : GetWriter<decimal>(field, (f, w, o) => w.WriteDecimal(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDecimal()) : GetReader(field, (f, r) => r.ReadDecimal(f)); } else if (type == typeof (string)) { writeAction = raw ? GetRawWriter<string>(field, (w, o) => w.WriteString(o)) : GetWriter<string>(field, (f, w, o) => w.WriteString(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadString()) : GetReader(field, (f, r) => r.ReadString(f)); } else if (type == typeof (Guid)) { writeAction = raw ? GetRawWriter<Guid>(field, (w, o) => w.WriteGuid(o)) : GetWriter<Guid>(field, (f, w, o) => w.WriteGuid(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadObject<Guid>()) : GetReader(field, (f, r) => r.ReadObject<Guid>(f)); } else if (nullable && nullableType == typeof (Guid)) { writeAction = raw ? GetRawWriter<Guid?>(field, (w, o) => w.WriteGuid(o)) : GetWriter<Guid?>(field, (f, w, o) => w.WriteGuid(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadGuid()) : GetReader(field, (f, r) => r.ReadGuid(f)); } else if (type.IsEnum) { writeAction = raw ? GetRawWriter<object>(field, (w, o) => w.WriteEnum(o), true) : GetWriter<object>(field, (f, w, o) => w.WriteEnum(f, o), true); readAction = raw ? GetRawReader(field, MthdReadEnumRaw) : GetReader(field, MthdReadEnum); } else if (type == BinaryUtils.TypDictionary || type.GetInterface(BinaryUtils.TypDictionary.FullName) != null && !type.IsGenericType) { writeAction = raw ? GetRawWriter<IDictionary>(field, (w, o) => w.WriteDictionary(o)) : GetWriter<IDictionary>(field, (f, w, o) => w.WriteDictionary(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDictionary()) : GetReader(field, (f, r) => r.ReadDictionary(f)); } else if (type == BinaryUtils.TypCollection || type.GetInterface(BinaryUtils.TypCollection.FullName) != null && !type.IsGenericType) { writeAction = raw ? GetRawWriter<ICollection>(field, (w, o) => w.WriteCollection(o)) : GetWriter<ICollection>(field, (f, w, o) => w.WriteCollection(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadCollection()) : GetReader(field, (f, r) => r.ReadCollection(f)); } else if (type == typeof (DateTime) && IsQueryField(field)) { writeAction = GetWriter<DateTime>(field, (f, w, o) => w.WriteTimestamp(f, o)); readAction = GetReader(field, (f, r) => r.ReadObject<DateTime>(f)); } else if (nullableType == typeof (DateTime) && IsQueryField(field)) { writeAction = GetWriter<DateTime?>(field, (f, w, o) => w.WriteTimestamp(f, o)); readAction = GetReader(field, (f, r) => r.ReadTimestamp(f)); } else { writeAction = raw ? GetRawWriter(field, MthdWriteObjRaw) : GetWriter(field, MthdWriteObj); readAction = raw ? GetRawReader(field, MthdReadObjRaw) : GetReader(field, MthdReadObj); } } /// <summary> /// Gets the reader with a specified write action. /// </summary> private static BinaryReflectiveWriteAction GetWriter<T>(FieldInfo field, Expression<Action<string, IBinaryWriter, T>> write, bool convertFieldValToObject = false) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(write != null); // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); Expression fldExpr = Expression.Field(targetParamConverted, field); if (convertFieldValToObject) fldExpr = Expression.Convert(fldExpr, typeof (object)); // Call Writer method var writerParam = Expression.Parameter(typeof(IBinaryWriter)); var fldNameParam = Expression.Constant(BinaryUtils.CleanFieldName(field.Name)); var writeExpr = Expression.Invoke(write, fldNameParam, writerParam, fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the reader with a specified write action. /// </summary> private static BinaryReflectiveWriteAction GetRawWriter<T>(FieldInfo field, Expression<Action<IBinaryRawWriter, T>> write, bool convertFieldValToObject = false) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(write != null); // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); Expression fldExpr = Expression.Field(targetParamConverted, field); if (convertFieldValToObject) fldExpr = Expression.Convert(fldExpr, typeof (object)); // Call Writer method var writerParam = Expression.Parameter(typeof(IBinaryWriter)); var writeExpr = Expression.Invoke(write, Expression.Call(writerParam, MthdGetRawWriter), fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetWriter(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetWriter0(field, method, false, genericArgs); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetRawWriter(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetWriter0(field, method, true, genericArgs); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetWriter0(FieldInfo field, MethodInfo method, bool raw, params Type[] genericArgs) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(method != null); if (genericArgs.Length == 0) genericArgs = new[] {field.FieldType}; // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); var fldExpr = Expression.Field(targetParamConverted, field); // Call Writer method var writerParam = Expression.Parameter(typeof (IBinaryWriter)); var writeMethod = method.MakeGenericMethod(genericArgs); var writeExpr = raw ? Expression.Call(Expression.Call(writerParam, MthdGetRawWriter), writeMethod, fldExpr) : Expression.Call(writerParam, writeMethod, Expression.Constant(BinaryUtils.CleanFieldName(field.Name)), fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the reader with a specified read action. /// </summary> private static BinaryReflectiveReadAction GetReader<T>(FieldInfo field, Expression<Func<string, IBinaryReader, T>> read) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static // Call Reader method var readerParam = Expression.Parameter(typeof(IBinaryReader)); var fldNameParam = Expression.Constant(BinaryUtils.CleanFieldName(field.Name)); Expression readExpr = Expression.Invoke(read, fldNameParam, readerParam); if (typeof(T) != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParam, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } /// <summary> /// Gets the reader with a specified read action. /// </summary> private static BinaryReflectiveReadAction GetRawReader<T>(FieldInfo field, Expression<Func<IBinaryRawReader, T>> read) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static // Call Reader method var readerParam = Expression.Parameter(typeof(IBinaryReader)); Expression readExpr = Expression.Invoke(read, Expression.Call(readerParam, MthdGetRawReader)); if (typeof(T) != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParam, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetReader(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetReader0(field, method, false, genericArgs); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetRawReader(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetReader0(field, method, true, genericArgs); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetReader0(FieldInfo field, MethodInfo method, bool raw, params Type[] genericArgs) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static if (genericArgs.Length == 0) genericArgs = new[] {field.FieldType}; // Call Reader method var readerParam = Expression.Parameter(typeof (IBinaryReader)); var readMethod = method.MakeGenericMethod(genericArgs); Expression readExpr = raw ? Expression.Call(Expression.Call(readerParam, MthdGetRawReader), readMethod) : Expression.Call(readerParam, readMethod, Expression.Constant(BinaryUtils.CleanFieldName(field.Name))); if (readMethod.ReturnType != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParamConverted, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System; using System.Text.RegularExpressions; using System.Collections.Generic; namespace Soomla.Profile { /// <summary> /// This class provides functions for event handling. To handle various events, just add your /// game-specific behavior to the delegates below. /// </summary> public class ProfileEvents : MonoBehaviour { private const string TAG = "SOOMLA ProfileEvents"; private static ProfileEvents instance = null; #pragma warning disable 414 private static ProfileEventPusher pep = null; #pragma warning restore 414 /// <summary> /// Initializes the game state before the game starts. /// </summary> void Awake(){ if(instance == null){ // making sure we only initialize one instance. SoomlaUtils.LogDebug(TAG, "Initializing ProfileEvents (Awake)"); instance = this; GameObject.DontDestroyOnLoad(this.gameObject); Initialize(); // now we initialize the event pusher #if UNITY_ANDROID && !UNITY_EDITOR pep = new ProfileEventPusherAndroid(); #elif UNITY_IOS && !UNITY_EDITOR pep = new ProfileEventPusherIOS(); #endif } else { // Destroying unused instances. GameObject.Destroy(this.gameObject); } } public static void Initialize() { SoomlaUtils.LogDebug (TAG, "Initializing ProfileEvents ..."); #if UNITY_ANDROID && !UNITY_EDITOR AndroidJNI.PushLocalFrame(100); //init ProfileEventHandler using(AndroidJavaClass jniEventHandler = new AndroidJavaClass("com.soomla.profile.unity.ProfileEventHandler")) { jniEventHandler.CallStatic("initialize"); } AndroidJNI.PopLocalFrame(IntPtr.Zero); #elif UNITY_IOS && !UNITY_EDITOR // On iOS, this is initialized inside the bridge library when we call "soomlaProfile_Initialize" in SoomlaProfileIOS #endif } /// <summary> /// Handles an <c>onSoomlaProfileInitialized</c> event, which is fired when SoomlaProfile /// has been initialzed /// </summary> public void onSoomlaProfileInitialized() { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSoomlaProfileInitialized"); SoomlaProfile.TryFireProfileInitialized(); } /// <summary> /// Handles an <c>onUserRatingEvent</c> event /// </summary> public void onUserRatingEvent() { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onUserRatingEvent"); ProfileEvents.OnUserRatingEvent (); } /// <summary> /// Handles an <c>onUserProfileUpdated</c> event /// </summary> /// <param name="message">Will contain a JSON representation of a <c>UserProfile</c></param> public void onUserProfileUpdated(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onUserProfileUpdated"); JSONObject eventJson = new JSONObject(message); UserProfile userProfile = new UserProfile (eventJson ["userProfile"]); ProfileEvents.OnUserProfileUpdated (userProfile); } /// <summary> /// Handles an <c>onLoginStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// as well as payload </param> public void onLoginStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt((int)(eventJson["provider"].n)); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnLoginStarted (provider, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLoginFinished</c> event /// </summary> /// <param name="message">Will contain a JSON representation of a <c>UserProfile</c> and payload</param> public void onLoginFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginFinished"); JSONObject eventJson = new JSONObject(message); UserProfile userProfile = new UserProfile (eventJson ["userProfile"]); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); //give a reward Reward reward = Reward.GetReward(ProfilePayload.GetRewardId(payloadJSON)); if (reward !=null) reward.Give(); ProfileEvents.OnLoginFinished (userProfile, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLoginCancelled</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// as well as payload </param> public void onLoginCancelled(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginCancelled"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt((int)(eventJson["provider"].n)); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnLoginCancelled (provider, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLoginFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// ,error message and payload </param> public void onLoginFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt((int)(eventJson["provider"].n)); String errorMessage = eventJson["message"].str; JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnLoginFailed(provider, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onLogoutStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c></param> public void onLogoutStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); ProfileEvents.OnLogoutStarted (provider); } /// <summary> /// Handles an <c>onLogoutFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c></param> public void onLogoutFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); ProfileEvents.OnLogoutFinished(provider); } /// <summary> /// Handles an <c>onLogoutFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// and payload</param> public void onLogoutFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); String errorMessage = eventJson["message"].str; ProfileEvents.OnLogoutFailed (provider, errorMessage); } /// <summary> /// Handles an <c>onSocialActionStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c> and payload</param> public void onSocialActionStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)(eventJson["provider"].n)); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnSocialActionStarted (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onSocialActionFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c> and payload</param> public void onSocialActionFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); //give a reward Reward reward = Reward.GetReward(ProfilePayload.GetRewardId(payloadJSON)); if (reward != null) reward.Give(); ProfileEvents.OnSocialActionFinished (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onSocialActionCancelled</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c> and payload</param> public void onSocialActionCancelled(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionCancelled"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnSocialActionCancelled (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onSocialActionFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c> /// numeric representation of <c>SocialActionType</c>, /// error message and payload</param> public void onSocialActionFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n); String errorMessage = eventJson["message"].str; JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); ProfileEvents.OnSocialActionFailed (provider, socialAction, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onGetContactsStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// and payload</param> public void onGetContactsStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); bool fromStart = eventJson["fromStart"].b; ProfileEvents.OnGetContactsStarted (provider, fromStart, ProfilePayload.GetUserPayload (payloadJSON)); } /// <summary> /// Handles an <c>onGetContactsFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// JSON array of <c>UserProfile</c>s and payload</param> public void onGetContactsFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); bool hasMore = eventJson["hasMore"].b; JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); JSONObject userProfilesArray = eventJson ["contacts"]; List<UserProfile> userProfiles = new List<UserProfile>(); foreach (JSONObject userProfileJson in userProfilesArray.list) { userProfiles.Add(new UserProfile(userProfileJson)); } SocialPageData<UserProfile> data = new SocialPageData<UserProfile>(); data.PageData = userProfiles; data.PageNumber = 0; data.HasMore = hasMore; ProfileEvents.OnGetContactsFinished(provider, data, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onGetContactsFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// error message payload</param> public void onGetContactsFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); String errorMessage = eventJson["message"].str; JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str); bool fromStart = eventJson["fromStart"].b; ProfileEvents.OnGetContactsFailed (provider, errorMessage, fromStart, ProfilePayload.GetUserPayload(payloadJSON)); } /// <summary> /// Handles an <c>onGetFeedStarted</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// and payload</param> public void onGetFeedStarted(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedStarted"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); ProfileEvents.OnGetFeedStarted (provider); } /// <summary> /// Handles an <c>onGetFeedFinished</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// json array of feeds</param> public void onGetFeedFinished(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedFinished"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); JSONObject feedsJson = eventJson ["feeds"]; List<String> feeds = new List<String>(); foreach (String key in feedsJson.keys) { //iterate "feed" keys feeds.Add(feedsJson[key].str); } ProfileEvents.OnGetFeedFinished (provider, feeds); } /// <summary> /// Handles an <c>onGetFeedFailed</c> event /// </summary> /// <param name="message"> /// Will contain a numeric representation of <c>Provider</c>, /// and an error message</param> public void onGetFeedFailed(String message) { SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedFailed"); JSONObject eventJson = new JSONObject(message); Provider provider = Provider.fromInt ((int)eventJson["provider"].n); String errorMessage = eventJson["message"].str; ProfileEvents.OnGetFeedFailed (provider, errorMessage); } public delegate void Action(); public static Action OnSoomlaProfileInitialized = delegate {}; public static Action OnUserRatingEvent =delegate {}; public static Action<Provider, string> OnLoginCancelled = delegate {}; public static Action<UserProfile> OnUserProfileUpdated = delegate {}; public static Action<Provider, string, string> OnLoginFailed = delegate {}; public static Action<UserProfile, string> OnLoginFinished = delegate {}; public static Action<Provider, string> OnLoginStarted = delegate {}; public static Action<Provider, string> OnLogoutFailed = delegate {}; public static Action<Provider> OnLogoutFinished = delegate {}; public static Action<Provider> OnLogoutStarted = delegate {}; public static Action<Provider, SocialActionType, string, string> OnSocialActionFailed = delegate {}; public static Action<Provider, SocialActionType, string> OnSocialActionFinished = delegate {}; public static Action<Provider, SocialActionType, string> OnSocialActionStarted = delegate {}; public static Action<Provider, SocialActionType, string> OnSocialActionCancelled = delegate {}; public static Action<Provider, string, bool, string> OnGetContactsFailed = delegate {}; public static Action<Provider, SocialPageData<UserProfile>, string> OnGetContactsFinished = delegate {}; public static Action<Provider, bool, string> OnGetContactsStarted = delegate {}; public static Action<Provider, string> OnGetFeedFailed = delegate {}; public static Action<Provider, List<string>> OnGetFeedFinished = delegate {}; public static Action<Provider> OnGetFeedStarted = delegate {}; public static Action<Provider> OnAddAppRequestStarted = delegate {}; public static Action<Provider, string> OnAddAppRequestFinished = delegate {}; public static Action<Provider, string> OnAddAppRequestFailed = delegate {}; public static Action<Provider, string> OnInviteStarted = delegate {}; public static Action<Provider, string, List<string>, string> OnInviteFinished = delegate {}; public static Action<Provider, string, string> OnInviteFailed = delegate {}; public static Action<Provider, string> OnInviteCancelled = delegate {}; public class ProfileEventPusher { /// <summary> /// Registers all events. /// </summary> public ProfileEventPusher() { ProfileEvents.OnLoginCancelled += _pushEventLoginStarted; ProfileEvents.OnLoginFailed += _pushEventLoginFailed; ProfileEvents.OnLoginFinished += _pushEventLoginFinished; ProfileEvents.OnLoginStarted += _pushEventLoginStarted; ProfileEvents.OnLogoutFailed += _pushEventLogoutFailed; ProfileEvents.OnLogoutFinished += _pushEventLogoutFinished; ProfileEvents.OnLogoutStarted += _pushEventLogoutStarted; ProfileEvents.OnSocialActionCancelled += _pushEventSocialActionCancelled; ProfileEvents.OnSocialActionFailed += _pushEventSocialActionFailed; ProfileEvents.OnSocialActionFinished += _pushEventSocialActionFinished; ProfileEvents.OnSocialActionStarted += _pushEventSocialActionStarted; ProfileEvents.OnGetContactsStarted += _pushEventGetContactsStarted; ProfileEvents.OnGetContactsFinished += _pushEventGetContactsFinished; ProfileEvents.OnGetContactsFailed += _pushEventGetContactsFailed; ProfileEvents.OnInviteStarted += _pushEventInviteStarted; ProfileEvents.OnInviteFinished += _pushEventInviteFinished; ProfileEvents.OnInviteFailed += _pushEventInviteFailed; ProfileEvents.OnInviteCancelled += _pushEventInviteCancelled; } // Event pushing back to native (when using FB Unity SDK) protected virtual void _pushEventLoginStarted(Provider provider, string payload) {} protected virtual void _pushEventLoginFinished(UserProfile userProfileJson, string payload){} protected virtual void _pushEventLoginFailed(Provider provider, string message, string payload){} protected virtual void _pushEventLoginCancelled(Provider provider, string payload){} protected virtual void _pushEventLogoutStarted(Provider provider){} protected virtual void _pushEventLogoutFinished(Provider provider){} protected virtual void _pushEventLogoutFailed(Provider provider, string message){} protected virtual void _pushEventSocialActionStarted(Provider provider, SocialActionType actionType, string payload){} protected virtual void _pushEventSocialActionFinished(Provider provider, SocialActionType actionType, string payload){} protected virtual void _pushEventSocialActionCancelled(Provider provider, SocialActionType actionType, string payload){} protected virtual void _pushEventSocialActionFailed(Provider provider, SocialActionType actionType, string message, string payload){} protected virtual void _pushEventGetContactsStarted(Provider provider, bool fromStart, string payload){} protected virtual void _pushEventGetContactsFinished(Provider provider, SocialPageData<UserProfile> contactsPage, string payload){} protected virtual void _pushEventGetContactsFailed(Provider provider, string message, bool fromStart, string payload){} protected virtual void _pushEventInviteStarted(Provider provider, string payload){} protected virtual void _pushEventInviteFinished(Provider provider, string requestId, List<string> invitedIds, string payload){} protected virtual void _pushEventInviteFailed(Provider provider, string message, string payload){} protected virtual void _pushEventInviteCancelled(Provider provider, string payload){} } } }
using System; using Shouldly; using Spk.Common.Helpers.Guard; using Xunit; namespace Spk.Common.Tests.Helpers.Guard { public partial class ArgumentGuardTests { public class GuardIsLessThanOrEqualTo_double { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( double argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(-1230, -1231)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( double argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } public class GuardIsLessThanOrEqualTo_float { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( float argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(-1230, -1231)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( float argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } public class GuardIsLessThanOrEqualTo_decimal { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( decimal argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(-1230, -1231)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( decimal argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } public class GuardIsLessThanOrEqualTo_short { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( short argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(-1230, -1231)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( short argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } public class GuardIsLessThanOrEqualTo_int { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( int argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(-1230, -1231)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( int argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } public class GuardIsLessThanOrEqualTo_long { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( long argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(-1230, -1231)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( long argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } public class GuardIsLessThanOrEqualTo_ushort { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( ushort argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( ushort argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } public class GuardIsLessThanOrEqualTo_uint { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( uint argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( uint argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } public class GuardIsLessThanOrEqualTo_ulong { [Theory] [InlineData(1, 2)] [InlineData(2, 2)] public void GuardIsLessThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsLessThanOrEqualToTarget( ulong argument, double target) { var result = argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] public void GuardIsLessThanOrEqualTo_ShouldThrow_WhenArgumentIsNotLessThanTarget( ulong argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThanOrEqualTo(target, nameof(argument)); }); } } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // Path to the folder that contains the editors we will load. //--------------------------------------------------------------------------------------------- $Tools::resourcePath = "tools/"; // These must be loaded first, in this order, before anything else is loaded $Tools::loadFirst = "editorClasses base worldEditor"; //--------------------------------------------------------------------------------------------- // Object that holds the simObject id that the materialEditor uses to interpret its material list //--------------------------------------------------------------------------------------------- $Tools::materialEditorList = ""; //--------------------------------------------------------------------------------------------- // Tools Package. //--------------------------------------------------------------------------------------------- package Tools { function loadKeybindings() { Parent::loadKeybindings(); } // Start-up. function onStart() { //First, we want to ensure we don't inadvertently clean up our editor objects by leaving them in the MissionCleanup group, so lets change that real fast $instantGroup = ""; pushInstantGroup(); new Settings(EditorSettings) { file = "tools/settings.xml"; }; EditorSettings.read(); echo( " % - Initializing Tools" ); // Default file path when saving from the editor (such as prefabs) if ($Pref::WorldEditor::LastPath $= "") { $Pref::WorldEditor::LastPath = getMainDotCsDir(); } // Common GUI stuff. exec( "./gui/cursors.ed.cs" ); exec( "./gui/profiles.ed.cs" ); exec( "./gui/messageBoxes/messageBox.ed.cs" ); exec( "./editorClasses/gui/panels/navPanelProfiles.ed.cs" ); // Make sure we get editor profiles before any GUI's // BUG: these dialogs are needed earlier in the init sequence, and should be moved to // common, along with the guiProfiles they depend on. exec( "./gui/guiDialogs.ed.cs" ); //%toggle = $Scripts::ignoreDSOs; //$Scripts::ignoreDSOs = true; $ignoredDatablockSet = new SimSet(); // fill the list of editors $editors[count] = getWordCount( $Tools::loadFirst ); for ( %i = 0; %i < $editors[count]; %i++ ) { $editors[%i] = getWord( $Tools::loadFirst, %i ); } %pattern = $Tools::resourcePath @ "/*/main.cs"; %folder = findFirstFile( %pattern ); if ( %folder $= "") { // if we have absolutely no matches for main.cs, we look for main.cs.dso %pattern = $Tools::resourcePath @ "/*/main.cs.dso"; %folder = findFirstFile( %pattern ); } while ( %folder !$= "" ) { if( filePath( %folder ) !$= "tools" ) // Skip the actual 'tools' folder...we want the children { %folder = filePath( %folder ); %editor = fileName( %folder ); if ( IsDirectory( %folder ) ) { // Yes, this sucks and should be done better if ( strstr( $Tools::loadFirst, %editor ) == -1 ) { $editors[$editors[count]] = %editor; $editors[count]++; } } } %folder = findNextFile( %pattern ); } // initialize every editor new SimSet( EditorPluginSet ); %count = $editors[count]; for ( %i = 0; %i < %count; %i++ ) { exec( "./" @ $editors[%i] @ "/main.cs" ); %initializeFunction = "initialize" @ $editors[%i]; if( isFunction( %initializeFunction ) ) call( %initializeFunction ); } // Popuplate the default SimObject icons that // are used by the various editors. EditorIconRegistry::loadFromPath( "tools/classIcons/" ); // Load up the tools resources. All the editors are initialized at this point, so // resources can override, redefine, or add functionality. Tools::LoadResources( $Tools::resourcePath ); //Now that we're done loading, we can set the instant group back popInstantGroup(); $instantGroup = MissionCleanup; pushInstantGroup(); } function startToolTime(%tool) { if($toolDataToolCount $= "") $toolDataToolCount = 0; if($toolDataToolEntry[%tool] !$= "true") { $toolDataToolEntry[%tool] = "true"; $toolDataToolList[$toolDataToolCount] = %tool; $toolDataToolCount++; $toolDataClickCount[%tool] = 0; } $toolDataStartTime[%tool] = getSimTime(); $toolDataClickCount[%tool]++; } function endToolTime(%tool) { %startTime = 0; if($toolDataStartTime[%tool] !$= "") %startTime = $toolDataStartTime[%tool]; if($toolDataTotalTime[%tool] $= "") $toolDataTotalTime[%tool] = 0; $toolDataTotalTime[%tool] += getSimTime() - %startTime; } function dumpToolData() { %count = $toolDataToolCount; for(%i=0; %i<%count; %i++) { %tool = $toolDataToolList[%i]; %totalTime = $toolDataTotalTime[%tool]; if(%totalTime $= "") %totalTime = 0; %clickCount = $toolDataClickCount[%tool]; echo("---"); echo("Tool: " @ %tool); echo("Time (seconds): " @ %totalTime / 1000); echo("Activated: " @ %clickCount); echo("---"); } } // Shutdown. function onExit() { if( EditorGui.isInitialized ) EditorGui.shutdown(); // Free all the icon images in the registry. EditorIconRegistry::clear(); // Save any Layouts we might be using //GuiFormManager::SaveLayout(LevelBuilder, Default, User); %count = $editors[count]; for (%i = 0; %i < %count; %i++) { %destroyFunction = "destroy" @ $editors[%i]; if( isFunction( %destroyFunction ) ) call( %destroyFunction ); } // Call Parent. Parent::onExit(); // write out our settings xml file EditorSettings.write(); } }; function fastLoadWorldEdit(%val) { if(%val) { if(!$Tools::loaded) { onStart(); } if(!$Game::running) { //startGame(); activatePackage( "BootEditor" ); ChooseLevelDlg.launchInEditor = false; StartGame("tools/levels/BlankRoom.mis", "SinglePlayer"); if(!isObject(Observer)) { datablock CameraData(Observer) {}; } %cam = new Camera() { datablock = Observer; }; %cam.scopeToClient(LocalClientConnection); LocalClientConnection.setCameraObject(%cam); LocalClientConnection.setControlObject(%cam); LocalClientConnection.camera = %cam; %cam.setPosition("0 0 0"); } else { toggleEditor(true); } } } function fastLoadGUIEdit(%val) { if(%val) { if(!$Tools::loaded) { onStart(); } toggleGuiEditor(true); } } function Tools::LoadResources( %path ) { %resourcesPath = %path @ "resources/"; %resourcesList = getDirectoryList( %resourcesPath ); %wordCount = getFieldCount( %resourcesList ); for( %i = 0; %i < %wordCount; %i++ ) { %resource = GetField( %resourcesList, %i ); if( isFile( %resourcesPath @ %resource @ "/resourceDatabase.cs") ) ResourceObject::load( %path, %resource ); } } //----------------------------------------------------------------------------- // Activate Package. //----------------------------------------------------------------------------- activatePackage(Tools); //This lets us fast-load the editor from the menu GlobalActionMap.bind(keyboard, "F11", fastLoadWorldEdit); GlobalActionMap.bind(keyboard, "F10", fastLoadGUIEdit); function EditorIsActive() { return ( isObject(EditorGui) && Canvas.getContent() == EditorGui.getId() ); } function GuiEditorIsActive() { return ( isObject(GuiEditorGui) && Canvas.getContent() == GuiEditorGui.getId() ); }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace ISSE.SafetyChecking { using System; using ExecutedModel; using Utilities; public enum LtmcModelChecker { BuiltInLtmc, BuiltInDtmc, ExternalMrmc } public enum LtmdpModelChecker { BuiltInLtmdp, BuiltInNmdp, BuildInMdpWithNewStates, BuildInMdpWithNewStatesConstantDistance, BuildInMdpWithFlattening } /// <summary> /// Configures S#'s model checker, determining the amount of CPU cores and memory to use. /// </summary> public struct AnalysisConfiguration { private const long DefaultStackCapacity = 1 << 20; private const long DefaultSuccessorStateCapacity = 1 << 14; private const long MinCapacity = 1024; private static readonly ModelCapacity _defaultModelCapacity = ModelCapacityByModelDensity.Normal; private int _cpuCount; private long _stackCapacity; private long _successorStateCapacity; /// <summary> /// </summary> public bool AllowFaultsOnInitialTransitions { get; set; } /// <summary> /// Simulation only: Use the probabilities of the options when selecting the result of a probabilistic choice. /// Thus, more probable options get selected more probable. Otherwise, each option has the same chance to get selected. /// </summary> public bool UseOptionProbabilitiesInSimulation { get; set; } /// <summary> /// </summary> public bool EnableEarlyTermination { get; set; } /// <summary> /// If set to true, the model checker uses a compact state storage, in which the found states are indexed by a continuous variable. /// If set to false, the traditional sparse state storage is used, which requires a little less memory and is unnoticeable faster. /// </summary> public bool UseCompactStateStorage { get; set; } /// <summary> /// Gets or sets a value indicating whether a counter example should be generated when a formula violation is detected or an /// unhandled exception occurred during model checking. /// </summary> public bool GenerateCounterExample { get; set; } /// <summary> /// Collect fault sets when conducting a MinimalCriticalSetAnalysis. /// </summary> public bool CollectFaultSets { get; set; } /// <summary> /// Gets or sets a value indicating whether only progress reports should be output. /// </summary> internal bool ProgressReportsOnly { get; set; } /// <summary> /// The TextWriter used to log the process. /// </summary> public System.IO.TextWriter DefaultTraceOutput { get; set; } /// <summary> /// Write GraphViz models of the state space to the DefaultTraceOutput when creating the models. /// </summary> public bool WriteGraphvizModels { get; set; } /// <summary> /// Write the layout of the state vector. /// </summary> public bool WriteStateVectorLayout { get; set; } /// <summary> /// The default configuration. /// </summary> public static readonly AnalysisConfiguration Default = new AnalysisConfiguration { AllowFaultsOnInitialTransitions = false, UseOptionProbabilitiesInSimulation = false, EnableEarlyTermination = false, CpuCount = Int32.MaxValue, ProgressReportsOnly = false, DefaultTraceOutput = Console.Out, WriteGraphvizModels = false, WriteStateVectorLayout = false, ModelCapacity = _defaultModelCapacity, StackCapacity = DefaultStackCapacity, SuccessorCapacity = DefaultSuccessorStateCapacity, UseCompactStateStorage = false, GenerateCounterExample = true, CollectFaultSets = true, StateDetected = null, UseAtomarPropositionsAsStateLabels = true, EnableStaticPruningOptimization = true, LimitOfActiveFaults = null, LtmcModelChecker = LtmcModelChecker.BuiltInLtmc, LtmdpModelChecker = LtmdpModelChecker.BuiltInLtmdp }; /// <summary> /// Gets or sets the number of states and transitions that can be stored during model checking. /// </summary> public ModelCapacity ModelCapacity { get; set; } /// <summary> /// Gets or sets the number of states that can be stored on the stack during model checking. /// </summary> public long StackCapacity { get { return Math.Max(_stackCapacity, MinCapacity); } set { Requires.That(value >= MinCapacity, $"{nameof(StackCapacity)} must be at least {MinCapacity}."); _stackCapacity = value; } } /// <summary> /// Gets or sets the number of successor states that can be computed for each state. /// </summary> public long SuccessorCapacity { get { return Math.Max(_successorStateCapacity, MinCapacity); } set { Requires.That(value >= MinCapacity, $"{nameof(SuccessorCapacity)} must be at least {MinCapacity}."); _successorStateCapacity = value; } } /// <summary> /// Gets or sets the number of CPUs that are used for model checking. The value is automatically clamped /// to the interval of [1, #CPUs]. /// </summary> public int CpuCount { get { return _cpuCount; } set { _cpuCount = Math.Min(Environment.ProcessorCount, Math.Max(1, value)); } } /// <summary> /// Useful for debugging purposes. When a state is detected the first time then call the associated action. /// The delegate is only called in debug mode. /// A great usage example is to set "StateDetected = (state) => { if (state==190292) Debugger.Break();};" /// It makes sense to set CpuCount to 1 to omit races and ensure that a state always gets the same state /// number. /// </summary> public Action<int> StateDetected { get; set; } /// <summary> /// Determine if a formula like "Model.X==1 || Model.Y==true" should be split into the smaller parts /// "Model.X==1" and "Model.Y==true". If set to false then the maximal possible expressions are used. /// </summary> public bool UseAtomarPropositionsAsStateLabels { get; set; } /// <summary> /// </summary> public bool EnableStaticPruningOptimization { get; set; } /// <summary> /// </summary> public int? LimitOfActiveFaults{ get; set; } /// <summary> /// </summary> public LtmcModelChecker LtmcModelChecker { get; set; } /// <summary> /// </summary> public LtmdpModelChecker LtmdpModelChecker { get; set; } } }
// 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 SubtractInt64() { var test = new SimpleBinaryOpTest__SubtractInt64(); 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 SimpleBinaryOpTest__SubtractInt64 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int Op2ElementCount = VectorSize / sizeof(Int64); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable; static SimpleBinaryOpTest__SubtractInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SubtractInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Subtract( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Subtract( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Subtract( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractInt64(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if ((long)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((long)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Gallery; namespace Microsoft.Azure.Gallery { public partial class GalleryClient : ServiceClient<GalleryClient>, IGalleryClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IItemOperations _items; /// <summary> /// Operations for working with gallery items. /// </summary> public virtual IItemOperations Items { get { return this._items; } } /// <summary> /// Initializes a new instance of the GalleryClient class. /// </summary> public GalleryClient() : base() { this._items = new ItemOperations(this); this._apiVersion = "2015-04-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the GalleryClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public GalleryClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the GalleryClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public GalleryClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://gallery.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the GalleryClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public GalleryClient(HttpClient httpClient) : base(httpClient) { this._items = new ItemOperations(this); this._apiVersion = "2015-04-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the GalleryClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public GalleryClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the GalleryClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public GalleryClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://gallery.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another GalleryClient /// instance /// </summary> /// <param name='client'> /// Instance of GalleryClient to clone to /// </param> protected override void Clone(ServiceClient<GalleryClient> client) { base.Clone(client); if (client is GalleryClient) { GalleryClient clonedClient = ((GalleryClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// // 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 System.Globalization; using System.Threading; namespace NLog { using System; using System.Diagnostics; using System.Runtime.CompilerServices; using Internal.Fakeables; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Creates and manages instances of <see cref="T:NLog.Logger" /> objects. /// </summary> public sealed class LogManager { private static readonly LogFactory globalFactory = new LogFactory(); private static IAppDomain _currentAppDomain; private static GetCultureInfo _defaultCultureInfo = () => CultureInfo.CurrentCulture; private static readonly System.Collections.Generic.List<System.Reflection.Assembly> _hiddenAssemblies = new System.Collections.Generic.List<System.Reflection.Assembly>(); /// <summary> /// Delegate used to the the culture to use. /// </summary> /// <returns></returns> public delegate CultureInfo GetCultureInfo(); #if !SILVERLIGHT && !MONO /// <summary> /// Initializes static members of the LogManager class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")] static LogManager() { try { SetupTerminationEvents(); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Error setting up termiation events: {0}", exception); } } #endif /// <summary> /// Prevents a default instance of the LogManager class from being created. /// </summary> private LogManager() { } /// <summary> /// Occurs when logging <see cref="Configuration" /> changes. /// </summary> public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged { add { globalFactory.ConfigurationChanged += value; } remove { globalFactory.ConfigurationChanged -= value; } } #if !SILVERLIGHT /// <summary> /// Occurs when logging <see cref="Configuration" /> gets reloaded. /// </summary> public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded { add { globalFactory.ConfigurationReloaded += value; } remove { globalFactory.ConfigurationReloaded -= value; } } #endif /// <summary> /// Gets or sets a value indicating whether NLog should throw exceptions. /// By default exceptions are not thrown under any circumstances. /// </summary> public static bool ThrowExceptions { get { return globalFactory.ThrowExceptions; } set { globalFactory.ThrowExceptions = value; } } internal static IAppDomain CurrentAppDomain { get { return _currentAppDomain ?? (_currentAppDomain = AppDomainWrapper.CurrentDomain); } set { #if !SILVERLIGHT _currentAppDomain.DomainUnload -= TurnOffLogging; _currentAppDomain.ProcessExit -= TurnOffLogging; #endif _currentAppDomain = value; } } /// <summary> /// Gets or sets the current logging configuration. /// </summary> public static LoggingConfiguration Configuration { get { return globalFactory.Configuration; } set { globalFactory.Configuration = value; } } /// <summary> /// Gets or sets the global log threshold. Log events below this threshold are not logged. /// </summary> public static LogLevel GlobalThreshold { get { return globalFactory.GlobalThreshold; } set { globalFactory.GlobalThreshold = value; } } /// <summary> /// Gets or sets the default culture to use. /// </summary> public static GetCultureInfo DefaultCultureInfo { get { return _defaultCultureInfo; } set { _defaultCultureInfo = value; } } internal static System.Reflection.Assembly[] HiddenAssemblies { get { return _hiddenAssemblies.ToArray(); } } /// <summary> /// Adds the given assembly which will be skipped /// when NLog is trying to find the calling method on stack trace. /// </summary> /// <param name="assembly">The assembly to skip.</param> [MethodImpl(MethodImplOptions.NoInlining)] public static void AddHiddenAssembly(System.Reflection.Assembly assembly) { if (_hiddenAssemblies.Contains(assembly)) { return; } _hiddenAssemblies.Add(assembly); } /// <summary> /// Gets the logger named after the currently-being-initialized class. /// </summary> /// <returns>The logger.</returns> /// <remarks>This is a slow-running method. /// Make sure you're not doing this in a loop.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] public static Logger GetCurrentClassLogger() { string loggerName; Type declaringType; int framesToSkip = 1; do { #if SILVERLIGHT StackFrame frame = new StackTrace().GetFrame(framesToSkip); #else StackFrame frame = new StackFrame(framesToSkip, false); #endif var method = frame.GetMethod(); declaringType = method.DeclaringType; if (declaringType == null) { loggerName = method.Name; break; } framesToSkip++; loggerName = declaringType.FullName; } while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase)); return globalFactory.GetLogger(loggerName); } /// <summary> /// Gets the logger named after the currently-being-initialized class. /// </summary> /// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param> /// <returns>The logger.</returns> /// <remarks>This is a slow-running method. /// Make sure you're not doing this in a loop.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] public static Logger GetCurrentClassLogger(Type loggerType) { Type declaringType; int framesToSkip = 1; do { #if SILVERLIGHT StackFrame frame = new StackTrace().GetFrame(framesToSkip); #else StackFrame frame = new StackFrame(framesToSkip, false); #endif declaringType = frame.GetMethod().DeclaringType; framesToSkip++; } while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase)); return globalFactory.GetLogger(declaringType.FullName, loggerType); } /// <summary> /// Creates a logger that discards all log messages. /// </summary> /// <returns>Null logger which discards all log messages.</returns> public static Logger CreateNullLogger() { return globalFactory.CreateNullLogger(); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns> public static Logger GetLogger(string name) { return globalFactory.GetLogger(name); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns> public static Logger GetLogger(string name, Type loggerType) { return globalFactory.GetLogger(name, loggerType); } /// <summary> /// Loops through all loggers previously returned by GetLogger. /// and recalculates their target and filter list. Useful after modifying the configuration programmatically /// to ensure that all loggers have been properly configured. /// </summary> public static void ReconfigExistingLoggers() { globalFactory.ReconfigExistingLoggers(); } #if !SILVERLIGHT /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> public static void Flush() { globalFactory.Flush(); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(TimeSpan timeout) { globalFactory.Flush(timeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(int timeoutMilliseconds) { globalFactory.Flush(timeoutMilliseconds); } #endif /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public static void Flush(AsyncContinuation asyncContinuation) { globalFactory.Flush(asyncContinuation); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { globalFactory.Flush(asyncContinuation, timeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { globalFactory.Flush(asyncContinuation, timeoutMilliseconds); } /// <summary>Decreases the log enable counter and if it reaches -1 /// the logs are disabled.</summary> /// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater /// than or equal to <see cref="DisableLogging"/> calls.</remarks> /// <returns>An object that iplements IDisposable whose Dispose() method /// reenables logging. To be used with C# <c>using ()</c> statement.</returns> public static IDisposable DisableLogging() { return globalFactory.DisableLogging(); } /// <summary>Increases the log enable counter and if it reaches 0 the logs are disabled.</summary> /// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater /// than or equal to <see cref="DisableLogging"/> calls.</remarks> public static void EnableLogging() { globalFactory.EnableLogging(); } /// <summary> /// Returns <see langword="true" /> if logging is currently enabled. /// </summary> /// <returns>A value of <see langword="true" /> if logging is currently enabled, /// <see langword="false"/> otherwise.</returns> /// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater /// than or equal to <see cref="DisableLogging"/> calls.</remarks> public static bool IsLoggingEnabled() { return globalFactory.IsLoggingEnabled(); } /// <summary> /// Dispose all targets, and shutdown logging. /// </summary> public static void Shutdown() { foreach (var target in Configuration.AllTargets) { target.Dispose(); } } #if !SILVERLIGHT && !MONO private static void SetupTerminationEvents() { CurrentAppDomain.ProcessExit += TurnOffLogging; CurrentAppDomain.DomainUnload += TurnOffLogging; } private static void TurnOffLogging(object sender, EventArgs args) { // reset logging configuration to null // this causes old configuration (if any) to be closed. InternalLogger.Info("Shutting down logging..."); Configuration = null; InternalLogger.Info("Logger has been shut down."); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Security; namespace System.IO.Pipelines.Compression { /// <summary> /// Provides a wrapper around the ZLib decompression API /// </summary> internal sealed class Inflater : IDisposable { private bool _finished; // Whether the end of the stream has been reached private bool _isDisposed; // Prevents multiple disposals private ZLibNative.ZLibStreamHandle _zlibStream; // The handle to the primary underlying zlib stream private readonly object _syncLock = new object(); // Used to make writing to unmanaged structures atomic private const int minWindowBits = -15; // WindowBits must be between -8..-15 to ignore the header, 8..15 for private const int maxWindowBits = 47; // zlib headers, 24..31 for GZip headers, or 40..47 for either Zlib or GZip #region Exposed Members /// <summary> /// Initialized the Inflater with the given windowBits size /// </summary> internal Inflater(int windowBits) { Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits); _finished = false; _isDisposed = false; InflateInit(windowBits); } public int AvailableOutput => (int)_zlibStream.AvailOut; public int AvailableInput => (int)_zlibStream.AvailIn; /// <summary> /// Returns true if the end of the stream has been reached. /// </summary> public bool Finished() { return _finished && _zlibStream.AvailIn == 0 && _zlibStream.AvailOut == 0; } public unsafe int Inflate(IntPtr buffer, int count) { // If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read. if (NeedsInput()) { return 0; } try { int bytesRead; if (ReadInflateOutput(buffer, count, ZLibNative.FlushCode.NoFlush, out bytesRead) == ZLibNative.ErrorCode.StreamEnd) { _finished = true; } return bytesRead; } finally { // Before returning, make sure to release input buffer if necessary: if (_zlibStream.AvailIn == 0) { DeallocateInputBufferHandle(); } } } public bool NeedsInput() { return _zlibStream.AvailIn == 0; } public void SetInput(IntPtr buffer, int count) { lock (_syncLock) { _zlibStream.NextIn = buffer; _zlibStream.AvailIn = (uint)count; _finished = false; } } [SecuritySafeCritical] private void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _zlibStream.Dispose(); } _isDisposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Inflater() { Dispose(false); } #endregion #region Helper Methods /// <summary> /// Creates the ZStream that will handle inflation /// </summary> [SecuritySafeCritical] private void InflateInit(int windowBits) { ZLibNative.ErrorCode error; try { error = ZLibNative.CreateZLibStreamForInflate(out _zlibStream, windowBits); } catch (Exception exception) // could not load the ZLib dll { throw new ZLibException("SR.ZLibErrorDLLLoadError", exception); } switch (error) { case ZLibNative.ErrorCode.Ok: // Successful initialization return; case ZLibNative.ErrorCode.MemError: // Not enough memory throw new ZLibException("SR.ZLibErrorNotEnoughMemory", "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); case ZLibNative.ErrorCode.VersionError: //zlib library is incompatible with the version assumed throw new ZLibException("SR.ZLibErrorVersionMismatch", "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); case ZLibNative.ErrorCode.StreamError: // Parameters are invalid throw new ZLibException("SR.ZLibErrorIncorrectInitParameters", "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); default: throw new ZLibException("SR.ZLibErrorUnexpected", "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); } } /// <summary> /// Wrapper around the ZLib inflate function, configuring the stream appropriately. /// </summary> private unsafe ZLibNative.ErrorCode ReadInflateOutput(IntPtr bufPtr, int length, ZLibNative.FlushCode flushCode, out int bytesRead) { lock (_syncLock) { _zlibStream.NextOut = bufPtr; _zlibStream.AvailOut = (uint)length; ZLibNative.ErrorCode errC = Inflate(flushCode); bytesRead = length - (int)_zlibStream.AvailOut; return errC; } } /// <summary> /// Wrapper around the ZLib inflate function /// </summary> [SecuritySafeCritical] private ZLibNative.ErrorCode Inflate(ZLibNative.FlushCode flushCode) { ZLibNative.ErrorCode errC; try { errC = _zlibStream.Inflate(flushCode); } catch (Exception cause) // could not load the Zlib DLL correctly { throw new ZLibException("SR.ZLibErrorDLLLoadError", cause); } switch (errC) { case ZLibNative.ErrorCode.Ok: // progress has been made inflating case ZLibNative.ErrorCode.StreamEnd: // The end of the input stream has been reached return errC; case ZLibNative.ErrorCode.BufError: // No room in the output buffer - inflate() can be called again with more space to continue return errC; case ZLibNative.ErrorCode.MemError: // Not enough memory to complete the operation throw new ZLibException("SR.ZLibErrorNotEnoughMemory", "inflate_", (int)errC, _zlibStream.GetErrorMessage()); case ZLibNative.ErrorCode.DataError: // The input data was corrupted (input stream not conforming to the zlib format or incorrect check value) throw new InvalidDataException("SR.UnsupportedCompression"); case ZLibNative.ErrorCode.StreamError: //the stream structure was inconsistent (for example if next_in or next_out was NULL), throw new ZLibException("SR.ZLibErrorInconsistentStream", "inflate_", (int)errC, _zlibStream.GetErrorMessage()); default: throw new ZLibException("SR.ZLibErrorUnexpected", "inflate_", (int)errC, _zlibStream.GetErrorMessage()); } } /// <summary> /// Frees the GCHandle being used to store the input buffer /// </summary> private void DeallocateInputBufferHandle() { lock (_syncLock) { _zlibStream.AvailIn = 0; _zlibStream.NextIn = ZLibNative.ZNullPtr; } } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/11/2009 10:18:01 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { /// <summary> /// Stereographic /// </summary> public class Stereographic : EllipticalTransform { #region Private Variables private const double TOL = 1E-8; private const int NITER = 8; private const double CONV = 1E-10; private double _akm1; private double _cosX1; private Modes _mode; private double _phits; private double _sinX1; #endregion #region Constructors /// <summary> /// Creates a new instance of Stereographic /// </summary> public Stereographic() { Name = "Stereographic"; Proj4Name = "stere"; } #endregion #region Methods /// <inheritdoc /> protected override void EllipticalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinX = 0.0, cosX = 0.0; double coslam = Math.Cos(lp[lam]); double sinlam = Math.Sin(lp[lam]); double sinphi = Math.Sin(lp[phi]); if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { double cx; sinX = Math.Sin(cx = 2 * Math.Atan(Ssfn(lp[phi], sinphi, E)) - HALF_PI); cosX = Math.Cos(cx); } if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { double a; if (_mode == Modes.Oblique) { a = _akm1 / (_cosX1 * (1 + _sinX1 * sinX + _cosX1 * cosX * coslam)); xy[y] = a * (_cosX1 * sinX - _sinX1 * cosX * coslam); } else { a = 2 * _akm1 / (1 + cosX * coslam); xy[y] = a * sinX; } xy[x] = a * cosX; } else { if (_mode == Modes.SouthPole) { lp[phi] = -lp[phi]; coslam = -coslam; sinphi = -sinphi; } xy[x] = _akm1 * Proj.Tsfn(lp[phi], sinphi, E); xy[y] = -xy[x] * coslam; } xy[x] = xy[x] * sinlam; } } /// <inheritdoc /> protected override void SphericalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinphi = Math.Sin(lp[phi]); double cosphi = Math.Cos(lp[phi]); double coslam = Math.Cos(lp[lam]); double sinlam = Math.Sin(lp[lam]); if (_mode == Modes.Equitorial || _mode == Modes.Oblique) { if (_mode == Modes.Equitorial) { xy[y] = 1 + cosphi * coslam; } else { xy[y] = 1 + _sinX1 * sinphi + _cosX1 * cosphi * coslam; } if (xy[y] <= EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; } xy[x] = (xy[y] = _akm1 / xy[y]) * cosphi * sinlam; xy[y] *= (_mode == Modes.Equitorial) ? sinphi : _cosX1 * sinphi - _sinX1 * cosphi * coslam; } else { if (_mode == Modes.NorthPole) { coslam = -coslam; lp[phi] = -lp[phi]; } if (Math.Abs(lp[phi] - HALF_PI) < TOL) { xy[x] = double.NaN; xy[y] = double.NaN; continue; } xy[x] = sinlam * (xy[y] = _akm1 * Math.Tan(FORT_PI + .5 * lp[phi])); xy[y] *= coslam; } } } /// <inheritdoc /> protected override void EllipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinphi, tp = 0.0, phiL = 0.0, halfe = 0.0, halfpi = 0.0; int j; double rho = Proj.Hypot(xy[x], xy[y]); switch (_mode) { case Modes.Oblique: case Modes.Equitorial: double cosphi = Math.Cos(tp = 2 * Math.Atan2(rho * _cosX1, _akm1)); sinphi = Math.Sin(tp); if (rho == 0.0) phiL = Math.Asin(cosphi * _sinX1); else phiL = Math.Asin(cosphi * _sinX1 + (xy[y] * sinphi * _cosX1 / rho)); tp = Math.Tan(.5 * (HALF_PI + phiL)); xy[x] *= sinphi; xy[y] = rho * _cosX1 * cosphi - xy[y] * _sinX1 * sinphi; halfpi = HALF_PI; halfe = .5 * E; break; case Modes.NorthPole: case Modes.SouthPole: if (_mode == Modes.NorthPole) xy[y] = -xy[y]; phiL = HALF_PI - 2 * Math.Atan(tp = -rho / _akm1); halfpi = -HALF_PI; halfe = -.5 * E; break; } lp[lam] = double.NaN; lp[phi] = double.NaN; for (j = NITER; j-- > 0; phiL = lp[phi]) { sinphi = E * Math.Sin(phiL); lp[phi] = 2 * Math.Atan(tp * Math.Pow((1 + sinphi) / (1 - sinphi), halfe)) - halfpi; if (Math.Abs(phiL - lp[phi]) < CONV) { if (_mode == Modes.SouthPole) lp[phi] = -lp[phi]; lp[lam] = (xy[x] == 0 && xy[y] == 0) ? 0 : Math.Atan2(xy[x], xy[y]); break; } } } } /// <inheritdoc /> protected override void SphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double c, rh; double sinc = Math.Sin(c = 2 * Math.Atan((rh = Proj.Hypot(xy[x], xy[y])) / _akm1)); double cosc = Math.Cos(c); lp[lam] = 0; switch (_mode) { case Modes.Equitorial: if (Math.Abs(rh) <= EPS10) lp[phi] = 0; else lp[phi] = Math.Asin(xy[y] * sinc / rh); if (cosc != 0 || xy[x] != 0) lp[lam] = Math.Atan2(xy[x] * sinc, cosc * rh); break; case Modes.Oblique: if (Math.Abs(rh) <= EPS10) lp[phi] = Phi0; else lp[phi] = Math.Asin(cosc * _sinX1 + xy[y] * sinc * _cosX1 / rh); if ((c = cosc - _sinX1 * Math.Sin(lp[phi])) != 0 || xy[x] != 0) lp[lam] = Math.Atan2(xy[x] * sinc * _cosX1, c * rh); break; case Modes.NorthPole: case Modes.SouthPole: if (_mode == Modes.NorthPole) xy[y] = -xy[y]; if (Math.Abs(rh) <= EPS10) { lp[phi] = Phi0; } else { lp[phi] = Math.Asin(_mode == Modes.SouthPole ? -cosc : cosc); } lp[lam] = (xy[x] == 0 && xy[y] == 0) ? 0 : Math.Atan2(xy[x], xy[y]); break; } } } /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected override void OnInit(ProjectionInfo projInfo) { if (projInfo.StandardParallel1 != null) { _phits = projInfo.Phi1; } else { _phits = HALF_PI; } double t; if (Math.Abs((t = Math.Abs(Phi0)) - HALF_PI) < EPS10) { _mode = Phi0 < 0 ? Modes.SouthPole : Modes.NorthPole; } else { _mode = t > EPS10 ? Modes.Oblique : Modes.Equitorial; } _phits = Math.Abs(_phits); if (Es != 0) { switch (_mode) { case Modes.NorthPole: case Modes.SouthPole: if (Math.Abs(_phits - HALF_PI) < EPS10) { _akm1 = 2 * K0 / Math.Sqrt(Math.Pow(1 + E, 1 + E) * Math.Pow(1 - E, 1 - E)); } else { _akm1 = Math.Cos(_phits) / Proj.Tsfn(_phits, t = Math.Sin(_phits), E); t *= E; _akm1 /= Math.Sqrt(1 - t * t); } break; case Modes.Equitorial: _akm1 = 2 * K0; break; case Modes.Oblique: t = Math.Sin(Phi0); double x = 2 * Math.Atan(Ssfn(Phi0, t, E)) - HALF_PI; t *= E; _akm1 = 2 * K0 * Math.Cos(Phi0) / Math.Sqrt(1 - t * t); _sinX1 = Math.Sin(x); _cosX1 = Math.Cos(x); break; } } else { if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { if (_mode == Modes.Oblique) { _sinX1 = Math.Sin(Phi0); _cosX1 = Math.Cos(Phi0); } _akm1 = 2 * K0; } else { _akm1 = Math.Abs(_phits - HALF_PI) >= EPS10 ? Math.Cos(_phits) / Math.Tan(FORT_PI - .5 * _phits) : 2 * K0; } } } #endregion private static double Ssfn(double phit, double sinphi, double eccen) { sinphi *= eccen; return (Math.Tan(.5 * (HALF_PI + phit)) * Math.Pow((1 - sinphi) / (1 + sinphi), .5 * eccen)); } } }
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace ZXing.Common.Detector { /// <summary> <p>A somewhat generic detector that looks for a barcode-like rectangular region within an image. /// It looks within a mostly white region of an image for a region of black and white, but mostly /// black. It returns the four corners of the region, as best it can determine.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source /// </author> internal sealed class MonochromeRectangleDetector { private const int MAX_MODULES = 32; private BitMatrix image; public MonochromeRectangleDetector(BitMatrix image) { this.image = image; } /// <summary> <p>Detects a rectangular region of black and white -- mostly black -- with a region of mostly /// white, in an image.</p> /// /// </summary> /// <returns> {@link ResultPoint}[] describing the corners of the rectangular region. The first and /// last points are opposed on the diagonal, as are the second and third. The first point will be /// the topmost point and the last, the bottommost. The second point will be leftmost and the /// third, the rightmost /// </returns> public ResultPoint[] detect() { int height = image.Height; int width = image.Width; int halfHeight = height >> 1; int halfWidth = width >> 1; int deltaY = System.Math.Max(1, height / (MAX_MODULES << 3)); int deltaX = System.Math.Max(1, width / (MAX_MODULES << 3)); int top = 0; int bottom = height; int left = 0; int right = width; ResultPoint pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, -deltaY, top, bottom, halfWidth >> 1); if (pointA == null) return null; top = (int)pointA.Y - 1; ResultPoint pointB = findCornerFromCenter(halfWidth, -deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1); if (pointB == null) return null; left = (int)pointB.X - 1; ResultPoint pointC = findCornerFromCenter(halfWidth, deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1); if (pointC == null) return null; right = (int)pointC.X + 1; ResultPoint pointD = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, deltaY, top, bottom, halfWidth >> 1); if (pointD == null) return null; bottom = (int)pointD.Y + 1; // Go try to find point A again with better information -- might have been off at first. pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, -deltaY, top, bottom, halfWidth >> 2); if (pointA == null) return null; return new ResultPoint[] { pointA, pointB, pointC, pointD }; } /// <summary> Attempts to locate a corner of the barcode by scanning up, down, left or right from a center /// point which should be within the barcode. /// /// </summary> /// <param name="centerX">center's x component (horizontal) /// </param> /// <param name="deltaX">same as deltaY but change in x per step instead /// </param> /// <param name="left">minimum value of x /// </param> /// <param name="right">maximum value of x /// </param> /// <param name="centerY">center's y component (vertical) /// </param> /// <param name="deltaY">change in y per step. If scanning up this is negative; down, positive; /// left or right, 0 /// </param> /// <param name="top">minimum value of y to search through (meaningless when di == 0) /// </param> /// <param name="bottom">maximum value of y /// </param> /// <param name="maxWhiteRun">maximum run of white pixels that can still be considered to be within /// the barcode /// </param> /// <returns> a {@link com.google.zxing.ResultPoint} encapsulating the corner that was found /// </returns> private ResultPoint findCornerFromCenter(int centerX, int deltaX, int left, int right, int centerY, int deltaY, int top, int bottom, int maxWhiteRun) { int[] lastRange = null; for (int y = centerY, x = centerX; y < bottom && y >= top && x < right && x >= left; y += deltaY, x += deltaX) { int[] range; if (deltaX == 0) { // horizontal slices, up and down range = blackWhiteRange(y, maxWhiteRun, left, right, true); } else { // vertical slices, left and right range = blackWhiteRange(x, maxWhiteRun, top, bottom, false); } if (range == null) { if (lastRange == null) { return null; } // lastRange was found if (deltaX == 0) { int lastY = y - deltaY; if (lastRange[0] < centerX) { if (lastRange[1] > centerX) { // straddle, choose one or the other based on direction return new ResultPoint(deltaY > 0 ? lastRange[0] : lastRange[1], lastY); } return new ResultPoint(lastRange[0], lastY); } else { return new ResultPoint(lastRange[1], lastY); } } else { int lastX = x - deltaX; if (lastRange[0] < centerY) { if (lastRange[1] > centerY) { return new ResultPoint(lastX, deltaX < 0 ? lastRange[0] : lastRange[1]); } return new ResultPoint(lastX, lastRange[0]); } else { return new ResultPoint(lastX, lastRange[1]); } } } lastRange = range; } return null; } /// <summary> Computes the start and end of a region of pixels, either horizontally or vertically, that could /// be part of a Data Matrix barcode. /// /// </summary> /// <param name="fixedDimension">if scanning horizontally, this is the row (the fixed vertical location) /// where we are scanning. If scanning vertically it's the column, the fixed horizontal location /// </param> /// <param name="maxWhiteRun">largest run of white pixels that can still be considered part of the /// barcode region /// </param> /// <param name="minDim">minimum pixel location, horizontally or vertically, to consider /// </param> /// <param name="maxDim">maximum pixel location, horizontally or vertically, to consider /// </param> /// <param name="horizontal">if true, we're scanning left-right, instead of up-down /// </param> /// <returns> int[] with start and end of found range, or null if no such range is found /// (e.g. only white was found) /// </returns> private int[] blackWhiteRange(int fixedDimension, int maxWhiteRun, int minDim, int maxDim, bool horizontal) { int center = (minDim + maxDim) >> 1; // Scan left/up first int start = center; while (start >= minDim) { if (horizontal ? image[start, fixedDimension] : image[fixedDimension, start]) { start--; } else { int whiteRunStart = start; do { start--; } while (start >= minDim && !(horizontal ? image[start, fixedDimension] : image[fixedDimension, start])); int whiteRunSize = whiteRunStart - start; if (start < minDim || whiteRunSize > maxWhiteRun) { start = whiteRunStart; break; } } } start++; // Then try right/down int end = center; while (end < maxDim) { if (horizontal ? image[end, fixedDimension] : image[fixedDimension, end]) { end++; } else { int whiteRunStart = end; do { end++; } while (end < maxDim && !(horizontal ? image[end, fixedDimension] : image[fixedDimension, end])); int whiteRunSize = end - whiteRunStart; if (end >= maxDim || whiteRunSize > maxWhiteRun) { end = whiteRunStart; break; } } } end--; return end > start ? new int[] { start, end } : null; } } }
// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #pragma warning disable 0219 namespace nanoFramework.Tools.VisualStudio.Extension.Serialization.PdbxFile { public class XmlSerializationWriterPdbxFile : System.Xml.Serialization.XmlSerializationWriter { public void Write12_PdbxFile(object o) { WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"PdbxFile", @""); return; } TopLevelElement(); Write11_PdbxFile(@"PdbxFile", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile)o), true, false); } void Write11_PdbxFile(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile o, bool isNullable, bool needType) { if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"PdbxFile", @""); Write10_Assembly(@"Assembly", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly)o.@Assembly), false, false); WriteEndElement(o); } void Write10_Assembly(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly o, bool isNullable, bool needType) { if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"Assembly", @""); WriteElementString(@"FileName", @"", ((global::System.String)o.@FileName)); Write2_VersionStruct(@"Version", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct)o.@Version), false); Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false); { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])o.@Classes); if (a != null) { WriteStartElement(@"Classes", @"", null, false); for (int ia = 0; ia < a.Length; ia++) { Write9_Class(@"Class", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class)a[ia]), true, false); } WriteEndElement(); } } WriteEndElement(o); } void Write9_Class(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class o, bool isNullable, bool needType) { if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"Class", @""); Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false); { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])o.@Fields); if (a != null) { WriteStartElement(@"Fields", @"", null, false); for (int ia = 0; ia < a.Length; ia++) { Write6_Field(@"Field", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field)a[ia]), true, false); } WriteEndElement(); } } { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])o.@Methods); if (a != null) { WriteStartElement(@"Methods", @"", null, false); for (int ia = 0; ia < a.Length; ia++) { Write8_Method(@"Method", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method)a[ia]), true, false); } WriteEndElement(); } } WriteEndElement(o); } void Write8_Method(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method o, bool isNullable, bool needType) { if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"Method", @""); Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false); WriteElementStringRaw(@"HasByteCode", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@HasByteCode))); { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])o.@ILMap); if (a != null) { WriteStartElement(@"ILMap", @"", null, false); for (int ia = 0; ia < a.Length; ia++) { Write7_IL(@"IL", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL)a[ia]), true, false); } WriteEndElement(); } } WriteEndElement(o); } void Write7_IL(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL o, bool isNullable, bool needType) { if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"IL", @""); WriteElementString(@"CLR", @"", ((global::System.String)o.@CLR_String)); WriteElementString(@"nanoCLR", @"", ((global::System.String)o.@nanoCLR_String)); WriteEndElement(o); } void Write4_Token(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token o, bool isNullable, bool needType) { if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"Token", @""); WriteElementString(@"CLR", @"", ((global::System.String)o.@CLR_String)); WriteElementString(@"nanoCLR", @"", ((global::System.String)o.@nanoCLR_String)); WriteEndElement(o); } void Write6_Field(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field o, bool isNullable, bool needType) { if ((object)o == null) { if (isNullable) WriteNullTagLiteral(n, ns); return; } if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"Field", @""); Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false); WriteEndElement(o); } void Write2_VersionStruct(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct o, bool needType) { if (!needType) { System.Type t = o.GetType(); if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct)) { } else { throw CreateUnknownTypeException(o); } } WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"VersionStruct", @""); WriteElementStringRaw(@"Major", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Major))); WriteElementStringRaw(@"Minor", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Minor))); WriteElementStringRaw(@"Build", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Build))); WriteElementStringRaw(@"Revision", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Revision))); WriteEndElement(o); } protected override void InitCallbacks() { } } public class XmlSerializationReaderPdbxFile : System.Xml.Serialization.XmlSerializationReader { public object Read12_PdbxFile() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)id1_PdbxFile && (object)Reader.NamespaceURI == (object)id2_Item)) { o = Read11_PdbxFile(true, true); } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null, @":PdbxFile"); } return (object)o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile Read11_PdbxFile(bool isNullable, bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id1_PdbxFile && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile o; o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile(); bool[] paramsRead = new bool[1]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations0 = 0; int readerCount0 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id3_Assembly && (object)Reader.NamespaceURI == (object)id2_Item)) { o.@Assembly = Read10_Assembly(false, true); paramsRead[0] = true; } else { UnknownNode((object)o, @":Assembly"); } } else { UnknownNode((object)o, @":Assembly"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations0, ref readerCount0); } ReadEndElement(); return o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly Read10_Assembly(bool isNullable, bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id3_Assembly && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly o; o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly(); global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[] a_3 = null; int ca_3 = 0; bool[] paramsRead = new bool[4]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations1 = 0; int readerCount1 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id4_FileName && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@FileName = Reader.ReadElementString(); } paramsRead[0] = true; } else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id5_Version && (object)Reader.NamespaceURI == (object)id2_Item)) { o.@Version = Read2_VersionStruct(true); paramsRead[1] = true; } else if (!paramsRead[2] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item)) { o.@Token = Read4_Token(false, true); paramsRead[2] = true; } else if (((object)Reader.LocalName == (object)id7_Classes && (object)Reader.NamespaceURI == (object)id2_Item)) { if (!ReadNull()) { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[] a_3_0 = null; int ca_3_0 = 0; if ((Reader.IsEmptyElement)) { Reader.Skip(); } else { Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations2 = 0; int readerCount2 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)id8_Class && (object)Reader.NamespaceURI == (object)id2_Item)) { a_3_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])EnsureArrayIndex(a_3_0, ca_3_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class)); a_3_0[ca_3_0++] = Read9_Class(true, true); } else { UnknownNode(null, @":Class"); } } else { UnknownNode(null, @":Class"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations2, ref readerCount2); } ReadEndElement(); } o.@Classes = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])ShrinkArray(a_3_0, ca_3_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class), false); } } else { UnknownNode((object)o, @":FileName, :Version, :Token, :Classes"); } } else { UnknownNode((object)o, @":FileName, :Version, :Token, :Classes"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations1, ref readerCount1); } ReadEndElement(); return o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class Read9_Class(bool isNullable, bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id8_Class && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class o; o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class(); global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[] a_1 = null; int ca_1 = 0; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[] a_2 = null; int ca_2 = 0; bool[] paramsRead = new bool[3]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations3 = 0; int readerCount3 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item)) { o.@Token = Read4_Token(false, true); paramsRead[0] = true; } else if (((object)Reader.LocalName == (object)id9_Fields && (object)Reader.NamespaceURI == (object)id2_Item)) { if (!ReadNull()) { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[] a_1_0 = null; int ca_1_0 = 0; if ((Reader.IsEmptyElement)) { Reader.Skip(); } else { Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations4 = 0; int readerCount4 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)id10_Field && (object)Reader.NamespaceURI == (object)id2_Item)) { a_1_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])EnsureArrayIndex(a_1_0, ca_1_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field)); a_1_0[ca_1_0++] = Read6_Field(true, true); } else { UnknownNode(null, @":Field"); } } else { UnknownNode(null, @":Field"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations4, ref readerCount4); } ReadEndElement(); } o.@Fields = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])ShrinkArray(a_1_0, ca_1_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field), false); } } else if (((object)Reader.LocalName == (object)id11_Methods && (object)Reader.NamespaceURI == (object)id2_Item)) { if (!ReadNull()) { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[] a_2_0 = null; int ca_2_0 = 0; if ((Reader.IsEmptyElement)) { Reader.Skip(); } else { Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations5 = 0; int readerCount5 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)id12_Method && (object)Reader.NamespaceURI == (object)id2_Item)) { a_2_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method)); a_2_0[ca_2_0++] = Read8_Method(true, true); } else { UnknownNode(null, @":Method"); } } else { UnknownNode(null, @":Method"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations5, ref readerCount5); } ReadEndElement(); } o.@Methods = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])ShrinkArray(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method), false); } } else { UnknownNode((object)o, @":Token, :Fields, :Methods"); } } else { UnknownNode((object)o, @":Token, :Fields, :Methods"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations3, ref readerCount3); } ReadEndElement(); return o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method Read8_Method(bool isNullable, bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id12_Method && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method o; o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method(); global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[] a_2 = null; int ca_2 = 0; bool[] paramsRead = new bool[3]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations6 = 0; int readerCount6 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item)) { o.@Token = Read4_Token(false, true); paramsRead[0] = true; } else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id13_HasByteCode && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@HasByteCode = System.Xml.XmlConvert.ToBoolean(Reader.ReadElementString()); } paramsRead[1] = true; } else if (((object)Reader.LocalName == (object)id14_ILMap && (object)Reader.NamespaceURI == (object)id2_Item)) { if (!ReadNull()) { global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[] a_2_0 = null; int ca_2_0 = 0; if ((Reader.IsEmptyElement)) { Reader.Skip(); } else { Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations7 = 0; int readerCount7 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)id15_IL && (object)Reader.NamespaceURI == (object)id2_Item)) { a_2_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL)); a_2_0[ca_2_0++] = Read7_IL(true, true); } else { UnknownNode(null, @":IL"); } } else { UnknownNode(null, @":IL"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations7, ref readerCount7); } ReadEndElement(); } o.@ILMap = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])ShrinkArray(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL), false); } } else { UnknownNode((object)o, @":Token, :HasByteCode, :ILMap"); } } else { UnknownNode((object)o, @":Token, :HasByteCode, :ILMap"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations6, ref readerCount6); } ReadEndElement(); return o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL Read7_IL(bool isNullable, bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id15_IL && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL o; o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL(); bool[] paramsRead = new bool[2]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations8 = 0; int readerCount8 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id16_CLR && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@CLR_String = Reader.ReadElementString(); } paramsRead[0] = true; } else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id17_nanoCLR && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@nanoCLR_String = Reader.ReadElementString(); } paramsRead[1] = true; } else { UnknownNode((object)o, @":CLR, :nanoCLR"); } } else { UnknownNode((object)o, @":CLR, :nanoCLR"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations8, ref readerCount8); } ReadEndElement(); return o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token Read4_Token(bool isNullable, bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id6_Token && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token o; o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token(); bool[] paramsRead = new bool[2]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations9 = 0; int readerCount9 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id16_CLR && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@CLR_String = Reader.ReadElementString(); } paramsRead[0] = true; } else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id17_nanoCLR && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@nanoCLR_String = Reader.ReadElementString(); } paramsRead[1] = true; } else { UnknownNode((object)o, @":CLR, :nanoCLR"); } } else { UnknownNode((object)o, @":CLR, :nanoCLR"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations9, ref readerCount9); } ReadEndElement(); return o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field Read6_Field(bool isNullable, bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) isNull = ReadNull(); if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id10_Field && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } if (isNull) return null; global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field o; o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field(); bool[] paramsRead = new bool[1]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations10 = 0; int readerCount10 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item)) { o.@Token = Read4_Token(false, true); paramsRead[0] = true; } else { UnknownNode((object)o, @":Token"); } } else { UnknownNode((object)o, @":Token"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations10, ref readerCount10); } ReadEndElement(); return o; } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct Read2_VersionStruct(bool checkType) { System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (checkType) { if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id18_VersionStruct && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { } else throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); } global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct o; try { o = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct)System.Activator.CreateInstance(typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.NonPublic, null, new object[0], null); } catch (System.MissingMethodException) { throw CreateInaccessibleConstructorException(@"global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct"); } catch (System.Security.SecurityException) { throw CreateCtorHasSecurityException(@"global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct"); } bool[] paramsRead = new bool[4]; while (Reader.MoveToNextAttribute()) { if (!IsXmlnsAttribute(Reader.Name)) { UnknownNode((object)o); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return o; } Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations11 = 0; int readerCount11 = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (!paramsRead[0] && ((object)Reader.LocalName == (object)id19_Major && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@Major = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString()); } paramsRead[0] = true; } else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id20_Minor && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@Minor = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString()); } paramsRead[1] = true; } else if (!paramsRead[2] && ((object)Reader.LocalName == (object)id21_Build && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@Build = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString()); } paramsRead[2] = true; } else if (!paramsRead[3] && ((object)Reader.LocalName == (object)id22_Revision && (object)Reader.NamespaceURI == (object)id2_Item)) { { o.@Revision = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString()); } paramsRead[3] = true; } else { UnknownNode((object)o, @":Major, :Minor, :Build, :Revision"); } } else { UnknownNode((object)o, @":Major, :Minor, :Build, :Revision"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations11, ref readerCount11); } ReadEndElement(); return o; } protected override void InitCallbacks() { } string id17_nanoCLR; string id9_Fields; string id13_HasByteCode; string id18_VersionStruct; string id14_ILMap; string id5_Version; string id22_Revision; string id10_Field; string id8_Class; string id19_Major; string id12_Method; string id6_Token; string id2_Item; string id20_Minor; string id1_PdbxFile; string id15_IL; string id21_Build; string id7_Classes; string id3_Assembly; string id16_CLR; string id11_Methods; string id4_FileName; protected override void InitIDs() { id17_nanoCLR = Reader.NameTable.Add(@"nanoCLR"); id9_Fields = Reader.NameTable.Add(@"Fields"); id13_HasByteCode = Reader.NameTable.Add(@"HasByteCode"); id18_VersionStruct = Reader.NameTable.Add(@"VersionStruct"); id14_ILMap = Reader.NameTable.Add(@"ILMap"); id5_Version = Reader.NameTable.Add(@"Version"); id22_Revision = Reader.NameTable.Add(@"Revision"); id10_Field = Reader.NameTable.Add(@"Field"); id8_Class = Reader.NameTable.Add(@"Class"); id19_Major = Reader.NameTable.Add(@"Major"); id12_Method = Reader.NameTable.Add(@"Method"); id6_Token = Reader.NameTable.Add(@"Token"); id2_Item = Reader.NameTable.Add(@""); id20_Minor = Reader.NameTable.Add(@"Minor"); id1_PdbxFile = Reader.NameTable.Add(@"PdbxFile"); id15_IL = Reader.NameTable.Add(@"IL"); id21_Build = Reader.NameTable.Add(@"Build"); id7_Classes = Reader.NameTable.Add(@"Classes"); id3_Assembly = Reader.NameTable.Add(@"Assembly"); id16_CLR = Reader.NameTable.Add(@"CLR"); id11_Methods = Reader.NameTable.Add(@"Methods"); id4_FileName = Reader.NameTable.Add(@"FileName"); } } public abstract class XmlSerializer1 : System.Xml.Serialization.XmlSerializer { protected override System.Xml.Serialization.XmlSerializationReader CreateReader() { return new XmlSerializationReaderPdbxFile(); } protected override System.Xml.Serialization.XmlSerializationWriter CreateWriter() { return new XmlSerializationWriterPdbxFile(); } } public sealed class PdbxFileSerializer : XmlSerializer1 { public override System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { return xmlReader.IsStartElement(@"PdbxFile", @""); } protected override void Serialize(object o, System.Xml.Serialization.XmlSerializationWriter writer) { ((XmlSerializationWriterPdbxFile)writer).Write12_PdbxFile(o); } protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) { return ((XmlSerializationReaderPdbxFile)reader).Read12_PdbxFile(); } } public class XmlSerializerContract : global::System.Xml.Serialization.XmlSerializerImplementation { public override global::System.Xml.Serialization.XmlSerializationReader Reader { get { return new XmlSerializationReaderPdbxFile(); } } public override global::System.Xml.Serialization.XmlSerializationWriter Writer { get { return new XmlSerializationWriterPdbxFile(); } } System.Collections.Hashtable readMethods = null; public override System.Collections.Hashtable ReadMethods { get { if (readMethods == null) { System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); _tmp[@"nanoFramework.Tools.VisualStudio.Extension.Pdbx+PdbxFile::"] = @"Read12_PdbxFile"; if (readMethods == null) readMethods = _tmp; } return readMethods; } } System.Collections.Hashtable writeMethods = null; public override System.Collections.Hashtable WriteMethods { get { if (writeMethods == null) { System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); _tmp[@"nanoFramework.Tools.VisualStudio.Extension.Pdbx+PdbxFile::"] = @"Write12_PdbxFile"; if (writeMethods == null) writeMethods = _tmp; } return writeMethods; } } System.Collections.Hashtable typedSerializers = null; public override System.Collections.Hashtable TypedSerializers { get { if (typedSerializers == null) { System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); _tmp.Add(@"nanoFramework.Tools.VisualStudio.Extension.Pdbx+PdbxFile::", new PdbxFileSerializer()); if (typedSerializers == null) typedSerializers = _tmp; } return typedSerializers; } } public override System.Boolean CanSerialize(System.Type type) { if (type == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile)) return true; return false; } public override System.Xml.Serialization.XmlSerializer GetSerializer(System.Type type) { if (type == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile)) return new PdbxFileSerializer(); return null; } } } #pragma warning restore 0219
using System.Xml.Serialization; using System.Collections; using System; using umbraco.BusinessLogic.Utils; using System.Xml.Schema; using umbraco.interfaces; using System.Collections.Generic; using System.Web.Script.Serialization; using System.Text; using umbraco.businesslogic.Utils; using umbraco.BasePages; using Umbraco.Core.IO; namespace umbraco.cms.presentation.Trees { public enum SerializedTreeType { XmlTree, JSONTree, JsTree } /// <summary> /// Used for serializing data to XML as the data structure for the JavaScript tree /// </summary> [XmlRoot(ElementName = "tree", IsNullable = false), Serializable] public class XmlTree { public XmlTree() { //set to the XTree provider by default. //m_TreeType = SerializedTreeType.XmlTree; //m_TreeType = SerializedTreeType.JSONTree; m_TreeType = SerializedTreeType.JsTree; Init(); } /// <summary> /// Use this constructor to force a tree provider to be used /// </summary> /// <param name="treeType"></param> public XmlTree(SerializedTreeType treeType) { m_TreeType = treeType; Init(); } private void Init() { m_JSSerializer = new JSONSerializer { MaxJsonLength = int.MaxValue }; switch (m_TreeType) { case SerializedTreeType.XmlTree: break; case SerializedTreeType.JSONTree: m_JSSerializer.RegisterConverters(new List<JavaScriptConverter>() { new JSONTreeConverter(), new JSONTreeNodeConverter() }); break; case SerializedTreeType.JsTree: m_JSSerializer.RegisterConverters(new List<JavaScriptConverter>() { new JsTreeNodeConverter() }); break; } } private JSONSerializer m_JSSerializer; private SerializedTreeType m_TreeType; /// <summary> /// Returns the string representation of the tree structure depending on the SerializedTreeType /// specified. /// </summary> /// <returns></returns> public override string ToString() { return ToString(m_TreeType); } public string ToString(SerializedTreeType type) { switch (type) { case SerializedTreeType.XmlTree: return SerializableData.Serialize(this, typeof(XmlTree)); case SerializedTreeType.JsTree: return m_JSSerializer.Serialize(this.treeCollection); case SerializedTreeType.JSONTree: return m_JSSerializer.Serialize(this); } return ""; } public void Add(XmlTreeNode obj) { treeCollection.Add(obj); } [XmlIgnore] public XmlTreeNode this[int index] { get { return (XmlTreeNode)treeCollection[index]; } } [XmlIgnore] public int Count { get { return treeCollection.Count; } } public void Clear() { treeCollection.Clear(); } public XmlTreeNode Remove(int index) { XmlTreeNode obj = treeCollection[index]; treeCollection.Remove(obj); return obj; } public void Remove(XmlTreeNode obj) { treeCollection.Remove(obj); } private List<XmlTreeNode> __treeCollection; [XmlElement(Type = typeof(XmlTreeNode), ElementName = "tree", IsNullable = false, Form = XmlSchemaForm.Qualified)] public List<XmlTreeNode> treeCollection { get { if (__treeCollection == null) __treeCollection = new List<XmlTreeNode>(); return __treeCollection; } set { __treeCollection = value; } } [System.Runtime.InteropServices.DispIdAttribute(-4)] public IEnumerator GetEnumerator() { return (treeCollection as IEnumerable).GetEnumerator(); } } /// <summary> /// Used for serializing data to XML as the data structure for the JavaScript tree /// </summary> [Serializable] public class XmlTreeNode : IXmlSerializable { private XmlTreeNode() { m_nodeStyle = new NodeStyle(); } /// <summary> /// creates a new XmlTreeNode with the default parameters from the BaseTree /// </summary> /// <param name="bTree"></param> /// <returns></returns> public static XmlTreeNode Create(BaseTree bTree) { XmlTreeNode xNode = new XmlTreeNode(); xNode.Menu = bTree.AllowedActions.FindAll(delegate(IAction a) { return true; }); //return a duplicate copy of the list xNode.NodeType = bTree.TreeAlias; xNode.Source = string.Empty; xNode.IsRoot = false; //generally the tree type and node type are the same but in some cased they are not. xNode.m_treeType = bTree.TreeAlias; return xNode; } /// <summary> /// creates a new XmlTreeNode with the default parameters for the BaseTree root node /// </summary> /// <param name="bTree"></param> /// <returns></returns> public static XmlTreeNode CreateRoot(BaseTree bTree) { XmlTreeNode xNode = new XmlTreeNode(); xNode.NodeID = bTree.StartNodeID.ToString(); xNode.Source = bTree.GetTreeServiceUrl(); xNode.Menu = bTree.RootNodeActions.FindAll(delegate(IAction a) { return true; }); //return a duplicate copy of the list xNode.NodeType = bTree.TreeAlias; xNode.Text = BaseTree.GetTreeHeader(bTree.TreeAlias); //by default, all root nodes will open the dashboard to their application xNode.Action = "javascript:" + ClientTools.Scripts.OpenDashboard(bTree.app); xNode.IsRoot = true; //generally the tree type and node type are the same but in some cased they are not. xNode.m_treeType = bTree.TreeAlias; return xNode; } private NodeStyle m_nodeStyle; private bool? m_notPublished; private bool? m_isProtected; private List<IAction> m_menu; private string m_text; private string m_action; [Obsolete("This is never used. From version 3 and below probably")] private string m_rootSrc; private string m_src; private string m_iconClass = ""; private string m_icon; private string m_openIcon; private string m_nodeType; private string m_nodeID; private string m_treeType; /// <summary> /// Set to true when a node is created with CreateRootNode /// </summary> internal bool IsRoot { get; private set; } /// <summary> /// Generally the tree type and node type are the same but in some cased they are not so /// we need to store the tree type too which is read only. /// </summary> public string TreeType { get { return m_treeType; } internal set { m_treeType = value; } } public bool HasChildren { get { return m_HasChildren ?? !string.IsNullOrEmpty(this.Source); //defaults to true if source is specified } set { m_HasChildren = value; } } private bool? m_HasChildren = null; public string NodeID { get { return m_nodeID; } set { m_nodeID = value; } } /// <summary> /// The tree node text /// </summary> public string Text { get { return m_text; } set { m_text = value; } } /// <summary> /// The CSS class of the icon to use for the node /// </summary> public string IconClass { get { return m_iconClass; } set { m_iconClass = value; } } /// <summary> /// The JavaScript action for the node /// </summary> public string Action { get { return m_action; } set { m_action = value; } } /// <summary> /// A string of letters representing actions for the context menu /// </summary> public List<IAction> Menu { get { return m_menu; } set { m_menu = value; } } /// <summary> /// The xml source for the child nodes (a URL) /// </summary> public string Source { get { return m_src; } set { m_src = value; } } /// <summary> /// The path to the icon to display for the node /// </summary> public string Icon { get { return m_icon; } set { m_icon = value; } } /// <summary> /// The path to the icon to display for the node if the node is showing it's children /// </summary> public string OpenIcon { get { return m_openIcon; } set { m_openIcon = value; } } /// <summary> /// Normally just the type of tree being rendered. /// This should really only be set with this property in very special cases /// where the create task for a node in the same tree as another node is different. /// </summary> public string NodeType { get { return m_nodeType; } set { m_nodeType = value; } } /// <summary> /// Used by the content tree and flagged as true if the node is not published /// </summary> [Obsolete("Use the XmlTreeNode.NodeStyle object to set node styles")] public bool? NotPublished { get { return m_notPublished; } set { m_notPublished = value; } } /// <summary> /// Used by the content tree and flagged as true if the node is protected /// </summary> [Obsolete("Use the XmlTreeNode.NodeStyle object to set node styles")] public bool? IsProtected { get { return m_isProtected; } set { m_isProtected = value; if (m_isProtected.HasValue && m_isProtected.Value) this.Style.SecureNode(); } } /// <summary> /// Returns the styling object used to add common styles to a node /// </summary> public NodeStyle Style { get { return m_nodeStyle; } } /// <summary> /// Used to add common styles to an XmlTreeNode. /// This also adds the ability to add a custom class which will add the class to the li node /// that is rendered in the tree whereas the IconClass property of the XmlTreeNode object /// adds a class to the anchor of the li node. /// </summary> public sealed class NodeStyle { internal NodeStyle() { AppliedClasses = new List<string>(); } private const string DimNodeCssClass = "dim"; private const string HighlightNodeCssClass = "overlay-new"; private const string SecureNodeCssClass = "overlay-protect"; internal List<string> AppliedClasses { get; private set; } /// <summary> /// Dims the color of the node /// </summary> public void DimNode() { if (!AppliedClasses.Contains(DimNodeCssClass)) AppliedClasses.Add(DimNodeCssClass); } /// <summary> /// Adds the star icon highlight overlay to a node /// </summary> public void HighlightNode() { if (!AppliedClasses.Contains(HighlightNodeCssClass)) AppliedClasses.Add(HighlightNodeCssClass); } /// <summary> /// Adds the padlock icon overlay to a node /// </summary> public void SecureNode() { if (!AppliedClasses.Contains(SecureNodeCssClass)) AppliedClasses.Add(SecureNodeCssClass); } /// <summary> /// Adds a custom class to the li node of the tree /// </summary> /// <param name="cssClass"></param> public void AddCustom(string cssClass) { if (!AppliedClasses.Contains(cssClass)) AppliedClasses.Add(cssClass); } } /// <summary> /// Dims the color of the node /// </summary> ///<remarks> ///This adds the class to the existing icon class as to not override anything. ///</remarks> [Obsolete("Use XmlTreeNode.Style to style nodes. Example: myNode.Style.DimNode();")] public void DimNode() { this.Style.DimNode(); } #region IXmlSerializable Members public XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { //try to parse the name into enum TreeAttributes current; try { current = (TreeAttributes)Enum.Parse(typeof(TreeAttributes), reader.Name, true); } catch { break; } switch (current) { case TreeAttributes.nodeID: this.m_nodeID = reader.Value; break; case TreeAttributes.text: this.m_text = reader.Value; break; case TreeAttributes.iconClass: this.m_iconClass = reader.Value; break; case TreeAttributes.action: this.m_action = reader.Value; break; case TreeAttributes.menu: this.m_menu = (!string.IsNullOrEmpty(reader.Value) ? umbraco.BusinessLogic.Actions.Action.FromString(reader.Value) : null); break; case TreeAttributes.rootSrc: this.m_rootSrc = reader.Value; break; case TreeAttributes.src: this.m_src = reader.Value; break; case TreeAttributes.icon: this.m_icon = reader.Value; break; case TreeAttributes.openIcon: this.m_openIcon = reader.Value; break; case TreeAttributes.nodeType: this.m_nodeType = reader.Value; break; case TreeAttributes.notPublished: if (!string.IsNullOrEmpty(reader.Value)) this.m_notPublished = bool.Parse(reader.Value); break; case TreeAttributes.isProtected: if (!string.IsNullOrEmpty(reader.Value)) this.m_isProtected = bool.Parse(reader.Value); break; case TreeAttributes.hasChildren: if (!string.IsNullOrEmpty(reader.Value)) this.HasChildren = bool.Parse(reader.Value); break; } } //need to set the hasChildren property if it is null but there is a source //this happens when the hasChildren attribute is not set because the developer didn't know it was there //only occurs for ITree obviously if (!this.HasChildren && !string.IsNullOrEmpty(this.m_src)) this.HasChildren = true; } reader.Read(); } public void WriteXml(System.Xml.XmlWriter writer) { writer.WriteAttributeString(TreeAttributes.nodeID.ToString(), this.m_nodeID); writer.WriteAttributeString(TreeAttributes.text.ToString(), this.m_text); writer.WriteAttributeString(TreeAttributes.iconClass.ToString(), this.m_iconClass); writer.WriteAttributeString(TreeAttributes.action.ToString(), this.m_action); writer.WriteAttributeString(TreeAttributes.menu.ToString(), (this.m_menu != null && this.m_menu.Count > 0 ? umbraco.BusinessLogic.Actions.Action.ToString(this.m_menu) : "")); writer.WriteAttributeString(TreeAttributes.rootSrc.ToString(), this.m_rootSrc); writer.WriteAttributeString(TreeAttributes.src.ToString(), this.m_src); writer.WriteAttributeString(TreeAttributes.icon.ToString(), this.m_icon); writer.WriteAttributeString(TreeAttributes.openIcon.ToString(), this.m_openIcon); writer.WriteAttributeString(TreeAttributes.nodeType.ToString(), this.m_nodeType); writer.WriteAttributeString(TreeAttributes.hasChildren.ToString(), HasChildren.ToString().ToLower()); if (m_notPublished.HasValue) writer.WriteAttributeString(TreeAttributes.notPublished.ToString(), this.m_notPublished.Value.ToString().ToLower()); if (m_isProtected.HasValue) writer.WriteAttributeString(TreeAttributes.isProtected.ToString(), this.m_isProtected.Value.ToString().ToLower()); } internal enum TreeAttributes { nodeID, text, iconClass, action, menu, rootSrc, src, icon, openIcon, nodeType, notPublished, isProtected, hasChildren } #endregion } /// <summary> /// Used to serialize an XmlTree object to JSON for supporting a JSON Tree View control. /// </summary> internal class JSONTreeConverter : JavaScriptConverter { /// <summary> /// Not implemented as we never need to Deserialize /// </summary> /// <param name="dictionary"></param> /// <param name="type"></param> /// <param name="serializer"></param> /// <returns></returns> public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { throw new NotImplementedException(); } /// <summary> /// Serializes an XmlTree object with the relevant values. /// </summary> /// <param name="obj"></param> /// <param name="serializer"></param> /// <returns></returns> public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { XmlTree tree = obj as XmlTree; Dictionary<string, object> resultSet = new Dictionary<string, object>(); Dictionary<string, object> resultTree = new Dictionary<string, object>(); if (tree != null) { //add a count property for the count of total nodes resultTree.Add("Count", tree.Count); List<object> nodes = new List<object>(); foreach (XmlTreeNode node in tree.treeCollection) nodes.Add(node); resultTree.Add("Nodes", nodes); } resultSet.Add("Tree", resultTree); return resultSet; } public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(XmlTree) }; } } } /// <summary> /// Used to serialize an XmlTreeNode object to JSON for supporting a JS Tree View control. /// </summary> internal class JSONTreeNodeConverter : JavaScriptConverter { /// <summary> /// Not implemented as we never need to Deserialize /// </summary> /// <param name="dictionary"></param> /// <param name="type"></param> /// <param name="serializer"></param> /// <returns></returns> public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { throw new NotImplementedException(); } /// <summary> /// Serializes an XmlTreeNode object with the relevant values. /// </summary> /// <param name="obj"></param> /// <param name="serializer"></param> /// <returns></returns> public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { XmlTreeNode node = obj as XmlTreeNode; Dictionary<string, object> result = new Dictionary<string, object>(); if (node != null) { //add the properties result.Add(XmlTreeNode.TreeAttributes.notPublished.ToString(), node.NotPublished); result.Add(XmlTreeNode.TreeAttributes.isProtected.ToString(), node.IsProtected); result.Add(XmlTreeNode.TreeAttributes.text.ToString(), node.Text); result.Add(XmlTreeNode.TreeAttributes.action.ToString(), node.Action); result.Add(XmlTreeNode.TreeAttributes.src.ToString(), node.Source); result.Add(XmlTreeNode.TreeAttributes.iconClass.ToString(), node.IconClass); result.Add(XmlTreeNode.TreeAttributes.icon.ToString(), node.Icon); result.Add(XmlTreeNode.TreeAttributes.openIcon.ToString(), node.OpenIcon); result.Add(XmlTreeNode.TreeAttributes.nodeType.ToString(), node.NodeType); result.Add(XmlTreeNode.TreeAttributes.nodeID.ToString(), node.NodeID); //Add the menu as letters. result.Add(XmlTreeNode.TreeAttributes.menu.ToString(), node.Menu != null && node.Menu.Count > 0 ? umbraco.BusinessLogic.Actions.Action.ToString(node.Menu) : ""); return result; } return new Dictionary<string, object>(); } public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(XmlTreeNode) }; } } } /// <summary> /// Used to serialize an XmlTreeNode object to JSON for supporting a JS Tree View control. /// </summary> internal class JsTreeNodeConverter : JavaScriptConverter { /// <summary> /// A reference path to where the icons are actually stored as compared to where the tree themes folder is /// </summary> private static string IconPath = IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/images/umbraco/"; /// <summary> /// Not implemented as we never need to Deserialize /// </summary> /// <param name="dictionary"></param> /// <param name="type"></param> /// <param name="serializer"></param> /// <returns></returns> public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { throw new NotImplementedException(); } /// <summary> /// Serializes an XmlTreeNode object with the relevant values. /// </summary> /// <param name="obj"></param> /// <param name="serializer"></param> /// <returns></returns> public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { XmlTreeNode node = obj as XmlTreeNode; Dictionary<string, object> result = new Dictionary<string, object>(); if (node != null) { //the data object to build the node Dictionary<string, object> data = new Dictionary<string, object>(); data.Add("title", node.Text); //the attributes object fot the tree node link (a) object created Dictionary<string, object> dataAttributes = new Dictionary<string, object>(); string cssClass = ""; if (node.Icon.StartsWith(".spr")) cssClass = "sprTree " + node.Icon.TrimStart('.'); else { //there is no sprite so add the noSpr class cssClass = "sprTree noSpr"; data.Add("icon", IconPath + node.Icon); } dataAttributes.Add("class", cssClass + (string.IsNullOrEmpty(node.IconClass) ? "" : " " + node.IconClass)); dataAttributes.Add("href", node.Action); //add a metadata dictionary object, we can store whatever we want in this! //in this case we're going to store permissions & the tree type & the child node source url //For whatever reason jsTree requires this JSON output to be quoted!?! //This also needs to be stored in the attributes object with the class above. Dictionary<string, object> metadata = new Dictionary<string, object>(); //the menu: metadata.Add("menu", node.Menu == null ? "" : umbraco.BusinessLogic.Actions.Action.ToString(node.Menu)); //the tree type: metadata.Add("nodeType", node.NodeType); //the data url for child nodes: metadata.Add("source", node.Source); //the metadata/jsTree requires this property to be in a quoted JSON syntax JSONSerializer jsSerializer = new JSONSerializer(); string strMetaData = jsSerializer.Serialize(metadata).Replace("\"", "'"); dataAttributes.Add("umb:nodedata", strMetaData); data.Add("attributes", dataAttributes); //add the data structure result.Add("data", data); //state is nothing if no children if ((node.HasChildren || node.IsRoot) && !string.IsNullOrEmpty(node.Source)) result.Add("state", "closed"); //the attributes object for the tree node (li) object created Dictionary<string, object> attributes = new Dictionary<string, object>(); attributes.Add("id", node.NodeID); attributes.Add("class", string.Join(" ", node.Style.AppliedClasses.ToArray())); if (node.IsRoot) attributes.Add("rel", "rootNode"); else attributes.Add("rel", "dataNode"); //the tree type should always be set, however if some developers have serialized their tree into an XmlTree //then there is no gaurantees that this will be set if they didn't use the create methods of XmlTreeNode. //So, we'll set the treetype to the nodetype if it is null, this means that the tree on the front end may //not function as expected when reloding a node. attributes.Add("umb:type", string.IsNullOrEmpty(node.TreeType) ? node.NodeType : node.TreeType); result.Add("attributes", attributes); return result; } return null; } public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(XmlTreeNode) }; } } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Nohros.Data; using Nohros.Data.Collections; namespace Nohros.Test.Data.Tree { [TestFixture] public class AndersonTree_ { [Test] public void Add() { AndersonTree<int, int> tree = new AndersonTree<int, int>(); tree.Add(0, 0); tree.Add(1, 1); // split must perform a left rotation and increase // the level of the node with key 1. tree.Add(2, 2); AndersonTreeNode<int, int> node = tree.FindNode(1); Assert.AreEqual(node.Level, 2); Assert.AreEqual(node.Left.Level, 1); Assert.AreEqual(node.Right.Level, 1); Assert.AreEqual(node.Left.Value, 0); Assert.AreEqual(node.Right.Value, 2); tree.Add(3, 3); tree.Add(4, 4); tree.Add(5, 5); tree.Add(6, 6); // must be balanced node = tree.FindNode(3); Assert.AreEqual(node.Value, 3); Assert.AreEqual(node.Left.Value, 1); Assert.AreEqual(node.Left.Left.Value, 0); Assert.AreEqual(node.Left.Right.Value, 2); Assert.AreEqual(node.Right.Value, 5); Assert.AreEqual(node.Right.Left.Value, 4); Assert.AreEqual(node.Right.Right.Value, 6); Assert.IsTrue(tree.ContainsKey(0)); Assert.IsTrue(tree.ContainsKey(1)); Assert.IsFalse(tree.ContainsKey(10)); Assert.IsNotNull(tree[4]); Assert.Throws(typeof(KeyNotFoundException), delegate() { int v = tree[10]; }); Assert.Throws(typeof(ArgumentException), delegate() { tree.Add(0, 0); }); // set value Assert.DoesNotThrow(delegate() { tree[0] = 20; }); int i = tree[0]; Assert.AreEqual(i, 20); } [Test] public void Clear() { AndersonTree<int, int> tree = new AndersonTree<int, int>(); tree.Add(0, 0); tree.Add(1, 1); tree.Add(2, 2); tree.Add(3, 3); tree.Add(4, 4); tree.Add(5, 5); tree.Add(6, 6); tree.Clear(); Assert.AreEqual(tree.Count, 0); } [Test] public void InOrderTraversal() { AndersonTree<int, int> tree = new AndersonTree<int, int>(); tree.Add(0, 0); tree.Add(1, 1); tree.Add(2, 2); tree.Add(3, 3); tree.Add(4, 4); tree.Add(5, 5); tree.Add(6, 6); List<AndersonTreeNode<int, int>> array = new List<AndersonTreeNode<int,int>>(6); tree.InOrderTreeWalk(delegate(AndersonTreeNode<int, int> node) { array.Add(node); return true; }); Assert.AreEqual(array[0].Value, 0); Assert.AreEqual(array[1].Value, 1); Assert.AreEqual(array[2].Value, 2); Assert.AreEqual(array[3].Value, 3); Assert.AreEqual(array[4].Value, 4); Assert.AreEqual(array[5].Value, 5); Assert.AreEqual(array[6].Value, 6); // unordered inert tree.Clear(); tree.Add(4, 4); tree.Add(0, 0); tree.Add(1, 1); tree.Add(6, 6); tree.Add(2, 2); tree.Add(5, 5); tree.Add(3, 3); Assert.AreEqual(array[0].Value, 0); Assert.AreEqual(array[1].Value, 1); Assert.AreEqual(array[2].Value, 2); Assert.AreEqual(array[3].Value, 3); Assert.AreEqual(array[4].Value, 4); Assert.AreEqual(array[5].Value, 5); Assert.AreEqual(array[6].Value, 6); } #region TreeOrderedVisitor class TreeOrderedVisitor : IVisitor<int> { public TreeOrderedVisitor() { values_ = new List<int>(); } List<int> values_; public void Visit(int value, object state) { values_.Add(value); } public bool IsCompleted { get { return false; } } public object State { get { return null; } } public List<int> Values { get { return values_; } } } #endregion [Test] public void InOrderAccept() { AndersonTree<int, int> tree = new AndersonTree<int,int>(); tree.Add(0, 0); tree.Add(1, 1); tree.Add(2, 2); tree.Add(3, 3); tree.Add(4, 4); tree.Add(5, 5); tree.Add(6, 6); TreeOrderedVisitor visitor = new TreeOrderedVisitor(); tree.Accept(new InOrderVisitor<int>(visitor), null, false); Assert.AreEqual(7, visitor.Values.Count); for (int i = 0, j = visitor.Values.Count; i < j; i++) { Assert.AreEqual(tree[i], visitor.Values[i]); } } [Test] public void ReverseInOrderAccept() { AndersonTree<int, int> tree = new AndersonTree<int, int>(); tree.Add(0, 0); tree.Add(1, 1); tree.Add(2, 2); tree.Add(3, 3); tree.Add(4, 4); tree.Add(5, 5); tree.Add(6, 6); TreeOrderedVisitor visitor = new TreeOrderedVisitor(); tree.Accept(new InOrderVisitor<int>(visitor), null, true); Assert.AreEqual(7, visitor.Values.Count); for (int i = 0, j = visitor.Values.Count; i < j; i++) { Assert.AreEqual(tree[tree.Count - i - 1], visitor.Values[i]); } } [Test] public void CopyTo() { AndersonTree<int, int> tree = new AndersonTree<int, int>(); tree.Add(0, 0); tree.Add(1, 1); tree.Add(2, 2); tree.Add(3, 3); tree.Add(4, 4); tree.Add(5, 5); tree.Add(6, 6); KeyValuePair<int, int>[] array = new KeyValuePair<int,int>[7]; Assert.DoesNotThrow(delegate() { tree.CopyTo(array, 0); }); Assert.AreEqual(array[0].Value, 0); Assert.AreEqual(array[2].Value, 2); Assert.AreEqual(array[3].Value, 3); Assert.AreEqual(array[6].Value, 6); Assert.Throws<ArgumentOutOfRangeException>(delegate() { tree.CopyTo(array, -1); }); Assert.Throws<ArgumentException>(delegate() { tree.CopyTo(array, 3); }); KeyValuePair<int, int>[] array2 = new KeyValuePair<int, int>[10]; Array.Copy(array, array2, array.Length); tree[0] = 20; tree[1] = 20; Assert.DoesNotThrow(delegate() { tree.CopyTo(array2, 3); }); Assert.AreEqual(array2[0].Value, 0); Assert.AreEqual(array2[1].Value, 1); Assert.AreEqual(array2[2].Value, 2); Assert.AreEqual(array2[3].Key, 0); Assert.AreEqual(array2[3].Value, 20); Assert.AreEqual(array2[4].Key, 1); Assert.AreEqual(array2[4].Value, 20); } [Test] public void Remove() { AndersonTree<int, int> tree = new AndersonTree<int, int>(); tree.Add(0, 0); tree.Add(1, 1); tree.Add(2, 2); tree.Add(3, 3); tree.Add(4, 4); tree.Add(5, 5); tree.Add(6, 6); tree.Add(7, 7); // removing zero will cause a break in the levels between 1 and nil, // so the level of 1 is decreased to 1. Then break is between 1 and 3, // so the level of 3 is decreased to 2. tree.Remove(0); AndersonTreeNode<int, int> node = tree.FindNode(3); // levels Assert.AreEqual(node.Level, 2); Assert.AreEqual(node.Left.Level, 1); Assert.AreEqual(node.Left.Right.Level, 1); Assert.AreEqual(node.Right.Level, 2); Assert.AreEqual(node.Right.Left.Level, 1); Assert.AreEqual(node.Right.Right.Level, 1); // values Assert.AreEqual(node.Value, 3); Assert.AreEqual(node.Left.Value, 1); Assert.AreEqual(node.Left.Right.Value, 2); Assert.AreEqual(node.Right.Value, 5); Assert.AreEqual(node.Right.Left.Value, 4); Assert.AreEqual(node.Right.Right.Value, 6); Assert.IsTrue(tree.Remove(1)); Assert.IsFalse(tree.ContainsKey(1)); Assert.Throws(typeof(KeyNotFoundException), delegate() { int val = tree[1]; }); // the real remove test node = tree.FindNode(3); // levels Assert.AreEqual(node.Level, 2); Assert.AreEqual(node.Left.Level, 1); Assert.AreEqual(node.Right.Level, 2); Assert.AreEqual(node.Right.Left.Level, 1); Assert.AreEqual(node.Right.Right.Level, 1); Assert.AreEqual(node.Right.Right.Right.Level, 1); // values Assert.AreEqual(node.Value, 3); Assert.AreEqual(node.Left.Value, 2); Assert.AreEqual(node.Right.Value, 5); Assert.AreEqual(node.Right.Left.Value, 4); Assert.AreEqual(node.Right.Right.Value, 6); Assert.AreEqual(node.Right.Right.Right.Value, 7); } [Test] public void Count() { AndersonTree<int, int> tree = new AndersonTree<int, int>(); tree.Add(0, 0); Assert.AreEqual(tree.Count, 1); } } }
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using MIConvexHull; using UnityEngine; namespace TiltBrush { // TODO: // - Why does it break so quickly? // - Initial knot uses pressure = 0, but that's a hack. Find a better way to get initial // pressure. This is especially important because otherwise it's very easy to see when // the stroke breaks. // - Optimize the geometry // - Parallel transport? public class ConcaveHullBrush : GeometryBrush { const double kToleranceMeters_PS = 1e-6; // Do not change these numbers; they are linked to determinism. const int kVerticesPerKnot_Rapidograph = 1; const int kVerticesPerKnot_QuillPen = 2; const int kVerticesPerKnot_Tetrahedron = 4; const int kVerticesPerKnot_Octahedron = 6; const int kVerticesPerKnot_Cube = 8; public class Vertex : IVertex { public double[] Position { get; set; } /// Temporary storage; only used during geometry creation public int TempIndex { get; set; } public Vector3 TempNormal { get; set; } public Vertex() { Position = new double[3]; } // Same as the constructor, but re-use a previously-constructed instance. public void SetData(Vector3 v) { Position[0] = v.x; Position[1] = v.y; Position[2] = v.z; } } public class Face : ConvexFace<Vertex, Face> { // This empty constructor is needed to work around a mono compiler bug. // Without it, the compiler thinks this class doesn't satisfy the "new()" constraint. // ReSharper disable once EmptyConstructor public Face() {} } [Serializable] public enum KnotConversion { Rapidograph, QuillPen, Tetrahedron, Octahedron, Cube, } static Vector3 AsVector3(double[] ds) { return new Vector3((float)ds[0], (float)ds[1], (float)ds[2]); } /// Number of knots to dump into each hull. Minimum is 1, but the practical minimum is 2 [Range(1, 40)] [SerializeField] int m_KnotsInHull; /// Temporary, for development /// Faceted currently looks better than smooth normals, but generates more verts and tris [SerializeField] bool m_Faceted; /// Governs how many hull input points we create per knot [SerializeField] KnotConversion m_KnotConversion; /// The set of Vertex instances created from knots. /// Each Knot corresponds to exactly GetNumVerticesPerKnot() Vertex instances. private List<Vertex> m_AllVertices; public ConcaveHullBrush() : base(bCanBatch: true, upperBoundVertsPerKnot: 1, bDoubleSided: false) { m_AllVertices = new List<Vertex>(); } // // GeometryBrush API // protected override void InitBrush(BrushDescriptor desc, TrTransform localPointerXf) { base.InitBrush(desc, localPointerXf); Debug.Assert(!desc.m_RenderBackfaces); // unsupported m_geometry.Layout = GetVertexLayout(desc); FixInitialKnotSize(); CreateVerticesFromKnots(0); } public override void ResetBrushForPreview(TrTransform localPointerXf) { base.ResetBrushForPreview(localPointerXf); FixInitialKnotSize(); CreateVerticesFromKnots(0); } // Helper for Init/Reset void FixInitialKnotSize() { // Looks terrible if the first knot has pressure 1; try pressure 0. // Even better: Use the real pressure! for (int i = 0; i < 2; ++i) { Knot k = m_knots[i]; k.point.m_Pressure = 0; m_knots[i] = k; } } public override float GetSpawnInterval(float pressure01) { return m_Desc.m_SolidMinLengthMeters_PS * POINTER_TO_LOCAL * App.METERS_TO_UNITS; } protected override void ControlPointsChanged(int iKnot0) { CreateVerticesFromKnots(iKnot0); OnChanged_MakeGeometry(iKnot0); } override public GeometryPool.VertexLayout GetVertexLayout(BrushDescriptor desc) { return new GeometryPool.VertexLayout { bUseColors = true, bUseNormals = true, bUseTangents = false, }; } // // Brush internals // void ResizeVertices(int desired) { // Be less garbagey: re-use the Vertex instances when possible. if (m_AllVertices.Count > desired) { m_AllVertices.RemoveRange(desired, m_AllVertices.Count - desired); } else { while (m_AllVertices.Count < desired) { m_AllVertices.Add(new Vertex()); } } } int GetNumVerticesPerKnot() { switch (m_KnotConversion) { case KnotConversion.Rapidograph: return kVerticesPerKnot_Rapidograph; case KnotConversion.QuillPen: return kVerticesPerKnot_QuillPen; case KnotConversion.Tetrahedron: return kVerticesPerKnot_Tetrahedron; case KnotConversion.Octahedron: return kVerticesPerKnot_Octahedron; case KnotConversion.Cube: return kVerticesPerKnot_Cube; default: return 0; } } // Creates verts for knots >= iKnot0 // Reads from m_knots; writes to m_AllVertices. void CreateVerticesFromKnots(int iKnot0) { // TODO: sanity-check that we fill in exactly this many values int verticesPerKnot = GetNumVerticesPerKnot(); ResizeVertices(m_knots.Count * verticesPerKnot); switch (m_KnotConversion) { // Just a point; ignores size case KnotConversion.Rapidograph: for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { m_AllVertices[iKnot].SetData(m_knots[iKnot].point.m_Pos); } break; // A right-left oriented line segment of "radius" size/2 case KnotConversion.QuillPen: for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { Knot knot = m_knots[iKnot]; float halfSize = 0.5f * PressuredSize(knot.point.m_Pressure); Vector3 halfExtent = halfSize * (knot.point.m_Orient * Vector3.right); int iv = iKnot * verticesPerKnot; m_AllVertices[iv + 0].SetData(knot.point.m_Pos - halfExtent); m_AllVertices[iv + 1].SetData(knot.point.m_Pos + halfExtent); } break; // A tetrahedron of "radius" size/2 // TODO: compute a parallel transport frame and use that to orient the tetrahedron? case KnotConversion.Tetrahedron: { for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { Knot k = m_knots[iKnot]; float halfSize = 0.5f * PressuredSize(k.point.m_Pressure); float h = halfSize / Mathf.Sqrt(3f); // half-extent int iv0 = iKnot * verticesPerKnot; m_AllVertices[iv0 + 0].SetData(k.point.m_Pos + k.point.m_Orient * new Vector3(-h, -h, -h)); m_AllVertices[iv0 + 1].SetData(k.point.m_Pos + k.point.m_Orient * new Vector3(+h, +h, -h)); m_AllVertices[iv0 + 2].SetData(k.point.m_Pos + k.point.m_Orient * new Vector3(+h, -h, +h)); m_AllVertices[iv0 + 3].SetData(k.point.m_Pos + k.point.m_Orient * new Vector3(-h, +h, +h)); } break; } // An octahedron of "radius" size/2 case KnotConversion.Octahedron: { for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { Knot knot = m_knots[iKnot]; float halfSize = 0.5f * PressuredSize(knot.point.m_Pressure); int iv = iKnot * verticesPerKnot; for (int axis = 0; axis < 3; ++axis) { Vector3 offset = Vector3.zero; offset[axis] = halfSize; offset = knot.point.m_Orient * offset; m_AllVertices[iv++].SetData(knot.point.m_Pos + offset); m_AllVertices[iv++].SetData(knot.point.m_Pos - offset); } } break; } // A cube whose faces/edges are size units big. // This feels more natural than making size the "radius". case KnotConversion.Cube: { for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { Knot knot = m_knots[iKnot]; float halfSize = 0.5f * PressuredSize(knot.point.m_Pressure); int iv = iKnot * verticesPerKnot; for (float xm = -1; xm <= 1; xm += 2) for (float ym = -1; ym <= 1; ym += 2) for (float zm = -1; zm <= 1; zm += 2) { Vector3 offset = new Vector3(xm * halfSize, ym * halfSize, zm * halfSize); m_AllVertices[iv++].SetData(knot.point.m_Pos + knot.point.m_Orient * offset); } } break; } } } void OnChanged_MakeGeometry(int iKnot0) { int verticesPerKnot = GetNumVerticesPerKnot(); int knotsInHull = Mathf.Max(m_KnotsInHull, 1); // Laziness. It's easier to update if we have lvalues. for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { Knot cur = m_knots[iKnot]; if (iKnot > 0) { Knot prev = m_knots[iKnot-1]; cur.iVert = (ushort)(prev.iVert + prev.nVert); cur.iTri = prev.iTri + prev.nTri; } else { cur.iVert = 0; cur.iTri = 0; } cur.nVert = 0; cur.nTri = 0; // Attempt to create hull. It can fail if the dimensionality is too low // because of too few points; and maybe also if the points are collinear/coplanar. { // Add vertices from the half-open knot range [knotRange0, knotRange1) int knotRange0 = Mathf.Max(0, iKnot + 1 - knotsInHull); int knotRange1 = iKnot + 1; List<Vertex> input = m_AllVertices.GetRange( verticesPerKnot * knotRange0, verticesPerKnot * (knotRange1 - knotRange0)); ConvexHull<Vertex, Face> hull = CreateHull(input, enableSimplify: false); if (hull != null) { if (m_Faceted) { CreateFacetedGeometry(ref cur, hull); } else { CreateSmoothGeometry(ref cur, hull); } } } m_knots[iKnot] = cur; } } ConvexHull<Vertex, Face> CreateHull(List<Vertex> input, bool enableSimplify) { if (input.Count < 3) { return null; } try { return ConvexHull.Create<Vertex, Face>( input, kToleranceMeters_PS * App.METERS_TO_UNITS * POINTER_TO_LOCAL); } catch (ArgumentOutOfRangeException) { // Too much degeneracy to create a hull (this is the exception we actually get) // The docs say Create() throws ArgumentException in this case, but instead it // reads off the end of a List<>, causing this range exception. return null; } catch (ArgumentException) { // Too much degeneracy to create a hull return null; } } void CreateFacetedGeometry(ref Knot knot, ConvexHull<Vertex, Face> hull) { m_geometry.NumVerts = knot.iVert; m_geometry.NumTriIndices = knot.iTri * 3; foreach (var face in hull.Faces) { Vertex[] faceVerts = face.Vertices; int v0 = knot.iVert + knot.nVert; foreach (var vertex in faceVerts) { AppendVert(ref knot, AsVector3(vertex.Position), AsVector3(face.Normal)); } // Tesselate the polygon into a fan int numFan = faceVerts.Length - 2; for (int iFan = 0; iFan < numFan; ++iFan) { AppendTri(ref knot, v0, v0 + (iFan + 1), v0 + (iFan + 2)); } } } void CreateSmoothGeometry(ref Knot knot, ConvexHull<Vertex, Face> hull) { m_geometry.NumVerts = knot.iVert; m_geometry.NumTriIndices = knot.iTri * 3; Vertex[] hullPoints = hull.Points.ToArray(); foreach (var vertex in hullPoints) { vertex.TempNormal = Vector3.zero; } foreach (var face in hull.Faces) { Vector3 normal = AsVector3(face.Normal); Vertex[] vs = face.Vertices; int nv = vs.Length; for (int iv = 0; iv < nv; ++iv) { // Use the angle at this vertex of the face to weight this face's // contribution to the vert's smoothed normal Vector3 vprev = AsVector3(vs[(iv-1+nv) % nv].Position); Vector3 vnext = AsVector3(vs[(iv+1+nv) % nv].Position); Vector3 vcur = AsVector3(vs[iv].Position); float angle = Vector3.Angle(vprev-vcur, vnext-vcur); vs[iv].TempNormal += normal * angle; } } foreach (var vertex in hullPoints) { vertex.TempIndex = knot.iVert + knot.nVert; AppendVert(ref knot, AsVector3(vertex.Position), vertex.TempNormal.normalized); } foreach (var face in hull.Faces) { Vertex[] vs = face.Vertices; // Tesselate the polygon into a fan int numFan = vs.Length - 2; for (int iFan = 0; iFan < numFan; ++iFan) { AppendTri(ref knot, vs[0].TempIndex, vs[1].TempIndex, vs[2].TempIndex); AppendTri(ref knot, vs[0].TempIndex, vs[2].TempIndex, vs[1].TempIndex); } } } void AppendVert(ref Knot k, Vector3 v, Vector3 n) { if ((k.iVert + k.nVert != m_geometry.m_Vertices.Count)) { Debug.Assert(false); } m_geometry.m_Vertices .Add(v); m_geometry.m_Normals .Add(n); m_geometry.m_Colors .Add(m_Color); k.nVert += 1; if (m_bDoubleSided) { m_geometry.m_Vertices .Add(v); m_geometry.m_Normals .Add(-n); // TODO: backface is a different color for visualization reasons // Probably better to use a non-culling shader instead of doubling the geo. m_geometry.m_Colors.Add(m_Color); k.nVert += 1; } } /// vp{0,1,2} are indices of vertex pairs void AppendTri(ref Knot k, int vp0, int vp1, int vp2) { if ((k.iTri + k.nTri) * 3 != m_geometry.m_Tris.Count) { Debug.Assert(false); } m_geometry.m_Tris.Add(vp0 * NS); m_geometry.m_Tris.Add(vp1 * NS); m_geometry.m_Tris.Add(vp2 * NS); k.nTri += 1; if (m_bDoubleSided) { m_geometry.m_Tris.Add(vp0 * NS + 1); m_geometry.m_Tris.Add(vp2 * NS + 1); m_geometry.m_Tris.Add(vp1 * NS + 1); k.nTri += 1; } } } } // namespace TiltBrush
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Numerics.Tests { public class standardNumericalFunctions_LogTest { private static void VerifyLogWithProperties(Complex c1, Complex c2) { VerifyLogWithProperties(c1, c2, true); } private static void VerifyLogWithProperties(Complex c1, Complex c2, bool extended) { if (c1 == Complex.Zero) { return; } VerifyLogWithBase10(c1); VerifyLogWithBase(c1); if (extended) { VerifyLogWithMultiply(c1, c2); VerifyLogWithPowerMinusOne(c1); VerifyLogWithExp(c1); } } private static void VerifyLogWithMultiply(Complex c1, Complex c2) { // Log(c1*c2) == Log(c1) + Log(c2), if -PI < Arg(c1) + Arg(c2) <= PI double equalityCondition = Math.Atan2(c1.Imaginary, c1.Real) + Math.Atan2(c2.Imaginary, c2.Real); if (equalityCondition <= -Math.PI || equalityCondition > Math.PI) { return; } Complex logComplex = Complex.Log(c1 * c2); Complex logExpectedComplex = Complex.Log(c1) + Complex.Log(c2); Support.VerifyRealImaginaryProperties(logComplex, logExpectedComplex.Real, logExpectedComplex.Imaginary, string.Format("Log({0}*{1}):{2} != {3})", c1, c2, logComplex, logExpectedComplex)); } private static void VerifyLogWithPowerMinusOne(Complex c) { // Log(c) == -Log(1/c) Complex logComplex = Complex.Log(c); Complex logPowerMinusOne = Complex.Log(1 / c); Support.VerifyRealImaginaryProperties(logComplex, -logPowerMinusOne.Real, -logPowerMinusOne.Imaginary, string.Format("Log({0}):{1} != {2} as expected", c, logComplex, -logPowerMinusOne)); } private static void VerifyLogWithExp(Complex c) { // Exp(log(c)) == c, if c != Zero Complex logComplex = Complex.Log(c); Complex expLogComplex = Complex.Exp(logComplex); Support.VerifyRealImaginaryProperties(expLogComplex, c.Real, c.Imaginary, string.Format("Exp(Log({0}):{1} != {2})", c, expLogComplex, c)); } private static void VerifyLogWithBase10(Complex complex) { Complex logValue = Complex.Log10(complex); Complex logComplex = Complex.Log(complex); double baseLog = Math.Log(10); Complex expectedLog = logComplex / baseLog; Support.VerifyRealImaginaryProperties(logValue, expectedLog.Real, expectedLog.Imaginary, string.Format("Log({0}, {1}):{2} != {3} as expected", complex, 10, logValue, expectedLog)); } private static void VerifyLogWithBase(Complex complex) { double baseValue = 0.0; double baseLog; // Verify with Random Int32 do { baseValue = Support.GetRandomInt32Value(false); } while (0 == baseValue); Complex logValue = Complex.Log(complex, baseValue); Complex logComplex = Complex.Log(complex); baseLog = Math.Log(baseValue); Complex expectedLog = logComplex / baseLog; Support.VerifyRealImaginaryProperties(logValue, expectedLog.Real, expectedLog.Imaginary, string.Format("Log({0}, {1}):{2} != {3} as expected", complex, baseValue, logValue, expectedLog)); // Verify with Random double value baseValue = 0.0; do { baseValue = Support.GetRandomDoubleValue(false); } while (0.0 == baseValue); logValue = Complex.Log(complex, baseValue); logComplex = Complex.Log(complex); baseLog = Math.Log(baseValue); expectedLog = logComplex / baseLog; Support.VerifyRealImaginaryProperties(logValue, expectedLog.Real, expectedLog.Imaginary, string.Format("Log({0}, {1}):{2} != {3} as expected", complex, baseValue, logValue, expectedLog)); } [Fact] public static void RunTests_ZeroOneImaginaryOne() { Complex logValue = Complex.Log(Complex.Zero); Support.VerifyRealImaginaryProperties(logValue, double.NegativeInfinity, 0.0, "Verify log of zero"); // Verify log10 with Zero logValue = Complex.Log10(Complex.Zero); Support.VerifyRealImaginaryProperties(logValue, double.NegativeInfinity, 0.0, "Verify log10 of zero"); // Verify log base with Zero double baseValue = Support.GetRandomInt32Value(false); logValue = Complex.Log(Complex.Zero, baseValue); Support.VerifyRealImaginaryProperties(logValue, double.NegativeInfinity, double.NaN, "Verify log base of zero"); // Verify test results with Zero - One VerifyLogWithProperties(Complex.One, Complex.Zero); // Verify test results with One - ImaginaryOne VerifyLogWithProperties(Complex.One, Complex.ImaginaryOne); } [Fact] public static void RunTests_RandomValidValues() { double real = Support.GetSmallRandomDoubleValue(false); double imaginary = Support.GetSmallRandomDoubleValue(false); Complex cFirst = new Complex(real, imaginary); real = Support.GetSmallRandomDoubleValue(true); imaginary = Support.GetSmallRandomDoubleValue(false); Complex cSecond = new Complex(real, imaginary); real = Support.GetSmallRandomDoubleValue(true); imaginary = Support.GetSmallRandomDoubleValue(true); Complex cThird = new Complex(real, imaginary); real = Support.GetSmallRandomDoubleValue(false); imaginary = Support.GetSmallRandomDoubleValue(true); Complex cFourth = new Complex(real, imaginary); // Verify test results with ComplexInFirstQuad - ComplexInFirstQuad VerifyLogWithProperties(cFirst, cFirst); // Verify test results with ComplexInFirstQuad - ComplexInSecondQuad VerifyLogWithProperties(cFirst, cSecond); // Verify test results with ComplexInFirstQuad - ComplexInThirdQuad VerifyLogWithProperties(cFirst, cThird); // Verify test results with ComplexInFirstQuad - ComplexInFourthQuad VerifyLogWithProperties(cFirst, cFourth); // Verify test results with ComplexInSecondQuad - ComplexInSecondQuad VerifyLogWithProperties(cSecond, cSecond); // Verify test results with ComplexInSecondQuad - ComplexInThirdQuad VerifyLogWithProperties(cSecond, cThird); // Verify test results with ComplexInSecondQuad - ComplexInFourthQuad VerifyLogWithProperties(cSecond, cFourth); // Verify test results with ComplexInThirdQuad - ComplexInThirdQuad VerifyLogWithProperties(cThird, cThird); // Verify test results with ComplexInThirdQuad - ComplexInFourthQuad VerifyLogWithProperties(cThird, cFourth); // Verify test results with ComplexInFourthQuad - ComplexInFourthQuad VerifyLogWithProperties(cFourth, cFourth); } [Fact] public static void RunTests_BoundaryValues() { Complex c_maxReal = new Complex(double.MaxValue, 0.0); Complex c_maxImg = new Complex(0.0, double.MaxValue); Complex c_minReal = new Complex(double.MinValue, 0.0); Complex c_minImg = new Complex(0.0, double.MinValue); // MaxReal VerifyLogWithProperties(c_maxReal, Complex.One, false); // MaxImaginary VerifyLogWithProperties(c_maxImg, Complex.ImaginaryOne, false); // MinReal VerifyLogWithProperties(c_minReal, Complex.One, false); // MinImaginary VerifyLogWithProperties(c_minImg, Complex.ImaginaryOne, false); } } }
using Lucene.Net.Documents; using Lucene.Net.Support; using System; using System.IO; using System.IO.Compression; using System.Text; namespace Lucene.Net.Util { using Lucene.Net.Randomized.Generators; using System.Threading; /* * 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 Document = Documents.Document; using Field = Field; using FieldType = FieldType; using SortedDocValuesField = SortedDocValuesField; using StringField = StringField; using TextField = TextField; /// <summary> /// Minimal port of benchmark's LneDocSource + /// DocMaker, so tests can enum docs from a line file created /// by benchmark's WriteLineDoc task /// </summary> public class LineFileDocs : IDisposable { private TextReader Reader; private static readonly int BUFFER_SIZE = 1 << 16; // 64K private readonly AtomicInteger Id = new AtomicInteger(); private readonly string Path; private readonly bool UseDocValues; /// <summary> /// If forever is true, we rewind the file at EOF (repeat /// the docs over and over) /// </summary> public LineFileDocs(Random random, string path, bool useDocValues) { this.Path = Paths.ResolveTestArtifactPath(path); this.UseDocValues = useDocValues; Open(random); } public LineFileDocs(Random random) : this(random, LuceneTestCase.TEST_LINE_DOCS_FILE, true) { } public LineFileDocs(Random random, bool useDocValues) : this(random, LuceneTestCase.TEST_LINE_DOCS_FILE, useDocValues) { } public void Dispose() { lock (this) { if (Reader != null) { Reader.Close(); Reader = null; } } } private long RandomSeekPos(Random random, long size) { if (random == null || size <= 3L) { return 0L; } return (random.NextLong() & long.MaxValue) % (size / 3); } private void Open(Random random) { lock (this) { Stream @is; bool needSkip = true, failed = false; long size = 0L, seekTo = 0L; try { @is = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read); //@is = File.OpenRead(Path); } catch (Exception FSfail) { failed = true; // if its not in classpath, we load it as absolute filesystem path (e.g. Hudson's home dir) FileInfo file = new FileInfo(Path); size = file.Length; if (Path.EndsWith(".gz")) { // if it is a gzip file, we need to use InputStream and slowly skipTo: @is = new FileStream(file.FullName, FileMode.Append, FileAccess.Write, FileShare.Read); } else { // optimized seek using RandomAccessFile: seekTo = RandomSeekPos(random, size); FileStream channel = new FileStream(Path, FileMode.Open); if (LuceneTestCase.VERBOSE) { Console.WriteLine("TEST: LineFileDocs: file seek to fp=" + seekTo + " on open"); } channel.Position = seekTo; @is = new FileStream(channel.ToString(), FileMode.Append, FileAccess.Write, FileShare.Read); needSkip = false; } } if (!failed) { // if the file comes from Classpath: size = @is.Length;// available(); } if (Path.EndsWith(".gz")) { using (var gzs = new GZipStream(@is, CompressionMode.Decompress)) { var temp = new MemoryStream(); gzs.CopyTo(temp); // Free up the previous stream @is.Close(); // Use the decompressed stream now @is = temp; } // guestimate: size = (long)(size * 2.8); } // If we only have an InputStream, we need to seek now, // but this seek is a scan, so very inefficient!!! if (needSkip) { seekTo = RandomSeekPos(random, size); if (LuceneTestCase.VERBOSE) { Console.WriteLine("TEST: LineFileDocs: stream skip to fp=" + seekTo + " on open"); } @is.Position = seekTo; } // if we seeked somewhere, read until newline char if (seekTo > 0L) { int b; byte[] bytes = new byte[sizeof(int)]; do { @is.Read(bytes, 0, sizeof(int)); b = BitConverter.ToInt32(bytes, 0); } while (b >= 0 && b != 13 && b != 10); } //CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT); MemoryStream ms = new MemoryStream(); @is.CopyTo(ms); Reader = new StringReader(Encoding.UTF8.GetString(ms.ToArray()));//, BUFFER_SIZE); if (seekTo > 0L) { // read one more line, to make sure we are not inside a Windows linebreak (\r\n): Reader.ReadLine(); } @is.Close(); } } public virtual void Reset(Random random) { lock (this) { Dispose(); Open(random); Id.Set(0); } } private const char SEP = '\t'; private sealed class DocState { internal readonly Document Doc; internal readonly Field TitleTokenized; internal readonly Field Title; internal readonly Field TitleDV; internal readonly Field Body; internal readonly Field Id; internal readonly Field Date; public DocState(bool useDocValues) { Doc = new Document(); Title = new StringField("title", "", Field.Store.NO); Doc.Add(Title); FieldType ft = new FieldType(TextField.TYPE_STORED); ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; ft.StoreTermVectorPositions = true; TitleTokenized = new Field("titleTokenized", "", ft); Doc.Add(TitleTokenized); Body = new Field("body", "", ft); Doc.Add(Body); Id = new StringField("docid", "", Field.Store.YES); Doc.Add(Id); Date = new StringField("date", "", Field.Store.YES); Doc.Add(Date); if (useDocValues) { TitleDV = new SortedDocValuesField("titleDV", new BytesRef()); Doc.Add(TitleDV); } else { TitleDV = null; } } } private readonly ThreadLocal<DocState> ThreadDocs = new ThreadLocal<DocState>(); /// <summary> /// Note: Document instance is re-used per-thread </summary> public virtual Document NextDoc() { string line; lock (this) { line = Reader.ReadLine(); if (line == null) { // Always rewind at end: if (LuceneTestCase.VERBOSE) { Console.WriteLine("TEST: LineFileDocs: now rewind file..."); } Dispose(); Open(null); line = Reader.ReadLine(); } } DocState docState = ThreadDocs.Value; if (docState == null) { docState = new DocState(UseDocValues); ThreadDocs.Value = docState; } int spot = line.IndexOf(SEP); if (spot == -1) { throw new Exception("line: [" + line + "] is in an invalid format !"); } int spot2 = line.IndexOf(SEP, 1 + spot); if (spot2 == -1) { throw new Exception("line: [" + line + "] is in an invalid format !"); } docState.Body.StringValue = line.Substring(1 + spot2, line.Length - (1 + spot2)); string title = line.Substring(0, spot); docState.Title.StringValue = title; if (docState.TitleDV != null) { docState.TitleDV.BytesValue = new BytesRef(title); } docState.TitleTokenized.StringValue = title; docState.Date.StringValue = line.Substring(1 + spot, spot2 - (1 + spot)); docState.Id.StringValue = Convert.ToString(Id.GetAndIncrement()); return docState.Doc; } } }
using System; using System.Collections.Generic; using System.Text; using BTDB.FieldHandler; using BTDB.IL; using BTDB.ODBLayer; using BTDB.StreamLayer; namespace BTDB.EventStoreLayer { class NullableTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor { readonly ITypeDescriptorCallbacks _typeSerializers; Type? _type; Type? _itemType; ITypeDescriptor? _itemDescriptor; string? _name; readonly ITypeConvertorGenerator _convertorGenerator; public NullableTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type) { _convertorGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; _type = type; _itemType = GetItemType(type); } public NullableTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ref SpanReader reader, DescriptorReader nestedDescriptorReader) : this(typeSerializers, nestedDescriptorReader(ref reader)) { } NullableTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ITypeDescriptor itemDesc) { _convertorGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; InitFromItemDescriptor(itemDesc); } void InitFromItemDescriptor(ITypeDescriptor descriptor) { if (descriptor == _itemDescriptor && _name != null) return; _itemDescriptor = descriptor; if ((descriptor.Name?.Length ?? 0) == 0) return; _itemType = _itemDescriptor.GetPreferredType(); Sealed = _itemDescriptor.Sealed; Name = $"Nullable<{_itemDescriptor.Name}>"; } public bool Equals(ITypeDescriptor other) { return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance)); } public override int GetHashCode() { #pragma warning disable RECS0025 // Non-readonly field referenced in 'GetHashCode()' // ReSharper disable once NonReadonlyMemberInGetHashCode return 17 * _itemDescriptor!.GetHashCode(); #pragma warning restore RECS0025 // Non-readonly field referenced in 'GetHashCode()' } public string Name { get { if (_name == null) InitFromItemDescriptor(_itemDescriptor!); return _name!; } private set => _name = value; } public bool FinishBuildFromType(ITypeDescriptorFactory factory) { var descriptor = factory.Create(_itemType!); if (descriptor == null) return false; InitFromItemDescriptor(descriptor); return true; } public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent) { text.Append("Nullable<"); _itemDescriptor!.BuildHumanReadableFullName(text, stack, indent); text.Append(">"); } public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack) { if (!(other is NullableTypeDescriptor o)) return false; return _itemDescriptor!.Equals(o._itemDescriptor!, stack); } public Type GetPreferredType() { if (_type == null) { _itemType = _typeSerializers.LoadAsType(_itemDescriptor!); _type = typeof(Nullable<>).MakeGenericType(_itemType); } return _type; } public Type GetPreferredType(Type targetType) { if (_type == targetType) return _type; var targetTypeArguments = targetType.GetGenericArguments(); var itemType = _typeSerializers.LoadAsType(_itemDescriptor!, targetTypeArguments[0]); return targetType.GetGenericTypeDefinition().MakeGenericType(itemType); } public bool AnyOpNeedsCtx() { return !_itemDescriptor!.StoredInline || _itemDescriptor.AnyOpNeedsCtx(); } public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType) { var genericArguments = targetType.GetGenericArguments(); var itemType = genericArguments.Length > 0 ? targetType.GetGenericArguments()[0] : typeof(object); if (itemType == typeof(object)) { var noValue = ilGenerator.DefineLabel(); var finish = ilGenerator.DefineLabel(); ilGenerator .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadBool))!) .Brfalse(noValue); _itemDescriptor!.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), typeof(object), _convertorGenerator); ilGenerator .Br(finish) .Mark(noValue) .Ldnull() .Mark(finish); } else { var localResult = ilGenerator.DeclareLocal(targetType); var finish = ilGenerator.DefineLabel(); var noValue = ilGenerator.DefineLabel(); var nullableType = typeof(Nullable<>).MakeGenericType(itemType); if (!targetType.IsAssignableFrom(nullableType)) throw new NotSupportedException(); ilGenerator .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadBool))!) .Brfalse(noValue); _itemDescriptor!.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), itemType, _convertorGenerator); ilGenerator .Newobj(nullableType.GetConstructor(new[] { itemType })!) .Stloc(localResult) .BrS(finish) .Mark(noValue) .Ldloca(localResult) .InitObj(nullableType) .Mark(finish) .Ldloc(localResult); } } public ITypeNewDescriptorGenerator? BuildNewDescriptorGenerator() { if (_itemDescriptor!.Sealed) return null; return new TypeNewDescriptorGenerator(this); } class TypeNewDescriptorGenerator : ITypeNewDescriptorGenerator { readonly NullableTypeDescriptor _nullableTypeDescriptor; public TypeNewDescriptorGenerator(NullableTypeDescriptor nullableTypeDescriptor) { _nullableTypeDescriptor = nullableTypeDescriptor; } public void GenerateTypeIterator(IILGen ilGenerator, Action<IILGen> pushObj, Action<IILGen> pushCtx, Type type) { var finish = ilGenerator.DefineLabel(); var itemType = _nullableTypeDescriptor.GetPreferredType(type).GetGenericArguments()[0]; var nullableType = typeof(Nullable<>).MakeGenericType(itemType); var localValue = ilGenerator.DeclareLocal(nullableType); ilGenerator .Do(pushObj) .Stloc(localValue) .Ldloca(localValue) .Call(nullableType.GetMethod("get_HasValue")!) .Brfalse(finish) .Ldloca(localValue) .Call(nullableType.GetMethod("get_Value")!) .Callvirt(typeof(IDescriptorSerializerLiteContext).GetMethod(nameof(IDescriptorSerializerLiteContext.StoreNewDescriptors))!) .Mark(finish); } } public ITypeDescriptor? NestedType(int index) { return index == 0 ? _itemDescriptor : null; } public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map) { InitFromItemDescriptor(map(_itemDescriptor)); } public bool Sealed { get; private set; } public bool StoredInline => true; public bool LoadNeedsHelpWithConversion => false; public void ClearMappingToType() { _type = null; _itemType = null; } public bool ContainsField(string name) { return false; } public IEnumerable<KeyValuePair<string, ITypeDescriptor>> Fields => Array.Empty<KeyValuePair<string, ITypeDescriptor>>(); public void Persist(ref SpanWriter writer, DescriptorWriter nestedDescriptorWriter) { nestedDescriptorWriter(ref writer, _itemDescriptor!); } public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type valueType) { var itemType = GetItemType(valueType); var localValue = ilGenerator.DeclareLocal(valueType); var localHasValue = ilGenerator.DeclareLocal(typeof(bool)); var finish = ilGenerator.DefineLabel(); ilGenerator .Do(pushValue) .Stloc(localValue) .Do(pushWriter) .Ldloca(localValue) .Call(valueType.GetMethod("get_HasValue")!) .Dup() .Stloc(localHasValue) .Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteBool))!) .Ldloc(localHasValue) .Brfalse(finish); _itemDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localValue).Call(valueType.GetMethod("get_Value")!), itemType); ilGenerator .Mark(finish); } static Type GetItemType(Type valueType) { return Nullable.GetUnderlyingType(valueType)!; } public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx) { var finish = ilGenerator.DefineLabel(); ilGenerator .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadBool))!) .Brfalse(finish); _itemDescriptor!.GenerateSkipEx(ilGenerator, pushReader, pushCtx); ilGenerator .Mark(finish); } public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers, Func<ITypeDescriptor, ITypeDescriptor> map) { var itemDesc = map(_itemDescriptor); if (_typeSerializers == typeSerializers && itemDesc == _itemDescriptor) return this; return new NullableTypeDescriptor(typeSerializers, itemDesc); } } }
// // AudioFileGlobalInfo.cs: // // Authors: // Marek Safar ([email protected]) // // Copyright 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; using MonoMac.Foundation; namespace MonoMac.AudioToolbox { public unsafe static class AudioFileGlobalInfo { public static AudioFileType[] ReadableTypes { get { uint size; if (AudioFileGetGlobalInfoSize (AudioFileGlobalProperty.ReadableTypes, 0, IntPtr.Zero, out size) != 0) return null; var data = new AudioFileType[size / sizeof (AudioFileType)]; fixed (AudioFileType* ptr = data) { var res = AudioFileGetGlobalInfo (AudioFileGlobalProperty.ReadableTypes, 0, IntPtr.Zero, ref size, ptr); if (res != 0) return null; return data; } } } public static AudioFileType[] WritableTypes { get { uint size; if (AudioFileGetGlobalInfoSize (AudioFileGlobalProperty.WritableTypes, 0, IntPtr.Zero, out size) != 0) return null; var data = new AudioFileType[size / sizeof (AudioFileType)]; fixed (AudioFileType* ptr = data) { var res = AudioFileGetGlobalInfo (AudioFileGlobalProperty.WritableTypes, 0, IntPtr.Zero, ref size, ptr); if (res != 0) return null; return data; } } } public static string GetFileTypeName (AudioFileType fileType) { IntPtr ptr; var size = (uint) Marshal.SizeOf (typeof (IntPtr)); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.FileTypeName, sizeof (AudioFileType), ref fileType, ref size, out ptr) != 0) return null; return CFString.FetchString (ptr); } public static AudioFormatType[] GetAvailableFormats (AudioFileType fileType) { uint size; if (AudioFileGetGlobalInfoSize (AudioFileGlobalProperty.AvailableFormatIDs, sizeof (AudioFileType), ref fileType, out size) != 0) return null; var data = new AudioFormatType[size / sizeof (AudioFormatType)]; fixed (AudioFormatType* ptr = data) { var res = AudioFileGetGlobalInfo (AudioFileGlobalProperty.AvailableFormatIDs, sizeof (AudioFormatType), ref fileType, ref size, ptr); if (res != 0) return null; return data; } } public static AudioStreamBasicDescription[] GetAvailableStreamDescriptions (AudioFileType fileType, AudioFormatType formatType) { AudioFileTypeAndFormatID input; input.FileType = fileType; input.FormatType = formatType; uint size; if (AudioFileGetGlobalInfoSize (AudioFileGlobalProperty.AvailableStreamDescriptionsForFormat, (uint)sizeof (AudioFileTypeAndFormatID), ref input, out size) != 0) return null; var data = new AudioStreamBasicDescription[size / sizeof (AudioStreamBasicDescription)]; fixed (AudioStreamBasicDescription* ptr = data) { var res = AudioFileGetGlobalInfo (AudioFileGlobalProperty.AvailableStreamDescriptionsForFormat, (uint)sizeof (AudioFileTypeAndFormatID), ref input, ref size, ptr); if (res != 0) return null; return data; } } public static string[] AllExtensions { get { IntPtr ptr; var size = (uint) Marshal.SizeOf (typeof (IntPtr)); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.AllExtensions, 0, IntPtr.Zero, ref size, out ptr) != 0) return null; return NSArray.ArrayFromHandleFunc (ptr, l => CFString.FetchString (l)); } } public static string[] AllUTIs { get { IntPtr ptr; var size = (uint) Marshal.SizeOf (typeof (IntPtr)); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.AllUTIs, 0, IntPtr.Zero, ref size, out ptr) != 0) return null; return NSArray.ArrayFromHandleFunc (ptr, l => CFString.FetchString (l)); } } public static string[] AllMIMETypes { get { IntPtr ptr; var size = (uint) Marshal.SizeOf (typeof (IntPtr)); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.AllMIMETypes, 0, IntPtr.Zero, ref size, out ptr) != 0) return null; return NSArray.ArrayFromHandleFunc (ptr, l => CFString.FetchString (l)); } } /* // TODO: Don't have HFSTypeCode public static HFSTypeCode[] AllHFSTypeCodes { get { uint size; if (AudioFileGetGlobalInfoSize (AudioFileGlobalProperty.AllHFSTypeCodes, 0, IntPtr.Zero, out size) != 0) return null; var data = new HFSTypeCode[size / sizeof (HFSTypeCode)]; fixed (AudioFileType* ptr = data) { var res = AudioFileGetGlobalInfo (AudioFileGlobalProperty.AllHFSTypeCodes, 0, IntPtr.Zero, ref size, ptr); if (res != 0) return null; return data; } } } */ public static string[] GetExtensions (AudioFileType fileType) { IntPtr ptr; var size = (uint) Marshal.SizeOf (typeof (IntPtr)); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.ExtensionsForType, sizeof (AudioFileType), ref fileType, ref size, out ptr) != 0) return null; return NSArray.ArrayFromHandleFunc (ptr, l => CFString.FetchString (l)); } public static string[] GetUTIs (AudioFileType fileType) { IntPtr ptr; var size = (uint) Marshal.SizeOf (typeof (IntPtr)); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.UTIsForType, sizeof (AudioFileType), ref fileType, ref size, out ptr) != 0) return null; return NSArray.ArrayFromHandleFunc (ptr, l => CFString.FetchString (l)); } public static string[] GetMIMETypes (AudioFileType fileType) { IntPtr ptr; var size = (uint) Marshal.SizeOf (typeof (IntPtr)); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.MIMETypesForType, sizeof (AudioFileType), ref fileType, ref size, out ptr) != 0) return null; return NSArray.ArrayFromHandleFunc (ptr, l => CFString.FetchString (l)); } /* // TODO: Always returns 0 public static AudioFileType? GetTypesForExtension (string extension) { using (var cfs = new CFString (extension)) { uint value; uint size = sizeof (AudioFileType); if (AudioFileGetGlobalInfo (AudioFileGlobalProperty.TypesForExtension, (uint) Marshal.SizeOf (typeof (IntPtr)), cfs.Handle, ref size, out value) != 0) return null; return (AudioFileType) value; } } */ [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfoSize (AudioFileGlobalProperty propertyID, uint size, IntPtr inSpecifier, out uint outDataSize); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfoSize (AudioFileGlobalProperty propertyID, uint size, ref AudioFileType inSpecifier, out uint outDataSize); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfoSize (AudioFileGlobalProperty propertyID, uint size, ref AudioFileTypeAndFormatID inSpecifier, out uint outDataSize); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfo (AudioFileGlobalProperty propertyID, uint size, IntPtr inSpecifier, ref uint ioDataSize, AudioFileType* outPropertyData); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfo (AudioFileGlobalProperty propertyID, uint size, ref AudioFileType inSpecifier, ref uint ioDataSize, AudioFormatType* outPropertyData); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfo (AudioFileGlobalProperty propertyID, uint size, ref AudioFileTypeAndFormatID inSpecifier, ref uint ioDataSize, AudioStreamBasicDescription* outPropertyData); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfo (AudioFileGlobalProperty propertyID, uint size, ref AudioFileType inSpecifier, ref uint ioDataSize, out IntPtr outPropertyData); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfo (AudioFileGlobalProperty propertyID, uint size, IntPtr inSpecifier, ref uint ioDataSize, out IntPtr outPropertyData); [DllImport (Constants.AudioToolboxLibrary)] extern static int AudioFileGetGlobalInfo (AudioFileGlobalProperty propertyID, uint size, IntPtr inSpecifier, ref uint ioDataSize, out uint outPropertyData); } struct AudioFileTypeAndFormatID { public AudioFileType FileType; public AudioFormatType FormatType; } enum AudioFileGlobalProperty : uint { ReadableTypes = 0x61667266, // 'afrf' WritableTypes = 0x61667766, // 'afwf' FileTypeName = 0x66746e6d, // 'ftnm' AvailableStreamDescriptionsForFormat = 0x73646964, // 'sdid' AvailableFormatIDs = 0x666d6964, // 'fmid' AllExtensions = 0x616c7874, // 'alxt' AllHFSTypeCodes = 0x61686673, // 'ahfs' AllUTIs = 0x61757469, // 'auti' AllMIMETypes = 0x616d696d, // 'amim' ExtensionsForType = 0x66657874, // 'fext' // HFSTypeCodesForType = 'fhfs', UTIsForType = 0x66757469, // 'futi' MIMETypesForType = 0x666d696d, // 'fmim' TypesForMIMEType = 0x746d696d, // 'tmim' TypesForUTI = 0x74757469, // 'tuti' // TypesForHFSTypeCode = 'thfs', TypesForExtension = 0x74657874, // 'text' } }
using System; using UnityEngine; [AddComponentMenu("NGUI/Interaction/NGUIGrid")] public class NGUIGrid : UIWidgetContainer { public enum Arrangement { Horizontal, Vertical } public enum Sorting { None, Alphabetic, Horizontal, Vertical, Custom } public delegate void OnReposition(); public NGUIGrid.Arrangement arrangement; public NGUIGrid.Sorting sorting; public UIWidget.Pivot pivot; public int maxPerLine; public float cellWidth = 200f; public float cellHeight = 200f; public bool animateSmoothly; public bool hideInactive = true; public bool keepWithinPanel; public NGUIGrid.OnReposition onReposition; [HideInInspector, SerializeField] private bool sorted; protected bool mReposition; protected UIPanel mPanel; protected bool mInitDone; public bool repositionNow { set { if (value) { this.mReposition = true; base.enabled = true; } } } protected virtual void Init() { this.mInitDone = true; this.mPanel = NGUITools.FindInParents<UIPanel>(base.gameObject); } protected virtual void Start() { if (!this.mInitDone) { this.Init(); } bool flag = this.animateSmoothly; this.animateSmoothly = false; this.Reposition(); this.animateSmoothly = flag; base.enabled = false; } protected virtual void Update() { if (this.mReposition) { this.Reposition(); } base.enabled = false; } public static int SortByName(Transform a, Transform b) { return string.Compare(a.name, b.name); } public static int SortHorizontal(Transform a, Transform b) { return a.localPosition.x.CompareTo(b.localPosition.x); } public static int SortVertical(Transform a, Transform b) { return b.localPosition.y.CompareTo(a.localPosition.y); } protected virtual void Sort(BetterList<Transform> list) { list.Sort(new BetterList<Transform>.CompareFunc(NGUIGrid.SortByName)); } [ContextMenu("Execute")] public virtual void Reposition() { if (Application.isPlaying && !this.mInitDone && NGUITools.GetActive(this)) { this.mReposition = true; return; } if (!this.mInitDone) { this.Init(); } this.mReposition = false; Transform transform = base.transform; int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; if (this.sorting != NGUIGrid.Sorting.None || this.sorted) { BetterList<Transform> betterList = new BetterList<Transform>(); for (int i = 0; i < transform.childCount; i++) { Transform child = transform.GetChild(i); if (child && (!this.hideInactive || NGUITools.GetActive(child.gameObject))) { betterList.Add(child); } } if (this.sorting == NGUIGrid.Sorting.Alphabetic) { betterList.Sort(new BetterList<Transform>.CompareFunc(NGUIGrid.SortByName)); } else if (this.sorting == NGUIGrid.Sorting.Horizontal) { betterList.Sort(new BetterList<Transform>.CompareFunc(NGUIGrid.SortHorizontal)); } else if (this.sorting == NGUIGrid.Sorting.Vertical) { betterList.Sort(new BetterList<Transform>.CompareFunc(NGUIGrid.SortVertical)); } else { this.Sort(betterList); } int j = 0; int size = betterList.size; while (j < size) { Transform transform2 = betterList[j]; if (NGUITools.GetActive(transform2.gameObject) || !this.hideInactive) { float z = transform2.localPosition.z; Vector3 vector = (this.arrangement != NGUIGrid.Arrangement.Horizontal) ? new Vector3(this.cellWidth * (float)num2, -this.cellHeight * (float)num, z) : new Vector3(this.cellWidth * (float)num, -this.cellHeight * (float)num2, z); if (this.animateSmoothly && Application.isPlaying) { SpringPosition.Begin(transform2.gameObject, vector, 15f).updateScrollView = true; } else { transform2.localPosition = vector; } num3 = Mathf.Max(num3, num); num4 = Mathf.Max(num4, num2); if (++num >= this.maxPerLine && this.maxPerLine > 0) { num = 0; num2++; } } j++; } } else { for (int k = 0; k < transform.childCount; k++) { Transform child2 = transform.GetChild(k); if (NGUITools.GetActive(child2.gameObject) || !this.hideInactive) { float z2 = child2.localPosition.z; Vector3 vector2 = (this.arrangement != NGUIGrid.Arrangement.Horizontal) ? new Vector3(this.cellWidth * (float)num2, -this.cellHeight * (float)num, z2) : new Vector3(this.cellWidth * (float)num, -this.cellHeight * (float)num2, z2); if (this.animateSmoothly && Application.isPlaying) { SpringPosition.Begin(child2.gameObject, vector2, 15f).updateScrollView = true; } else { child2.localPosition = vector2; } num3 = Mathf.Max(num3, num); num4 = Mathf.Max(num4, num2); if (++num >= this.maxPerLine && this.maxPerLine > 0) { num = 0; num2++; } } } } if (this.pivot != UIWidget.Pivot.TopLeft) { Vector2 pivotOffset = NGUIMath.GetPivotOffset(this.pivot); float num5; float num6; if (this.arrangement == NGUIGrid.Arrangement.Horizontal) { num5 = Mathf.Lerp(0f, (float)num3 * this.cellWidth, pivotOffset.x); num6 = Mathf.Lerp((float)(-(float)num4) * this.cellHeight, 0f, pivotOffset.y); } else { num5 = Mathf.Lerp(0f, (float)num4 * this.cellWidth, pivotOffset.x); num6 = Mathf.Lerp((float)(-(float)num3) * this.cellHeight, 0f, pivotOffset.y); } for (int l = 0; l < transform.childCount; l++) { Transform child3 = transform.GetChild(l); if (NGUITools.GetActive(child3.gameObject) || !this.hideInactive) { SpringPosition component = child3.GetComponent<SpringPosition>(); if (component != null) { SpringPosition expr_44A_cp_0 = component; expr_44A_cp_0.target.x = expr_44A_cp_0.target.x - num5; SpringPosition expr_45F_cp_0 = component; expr_45F_cp_0.target.y = expr_45F_cp_0.target.y - num6; } else { Vector3 localPosition = child3.localPosition; localPosition.x -= num5; localPosition.y -= num6; child3.localPosition = localPosition; } } } } if (this.keepWithinPanel && this.mPanel != null) { this.mPanel.ConstrainTargetToBounds(transform, true); } if (this.onReposition != null) { this.onReposition(); } } }
//--------------------------------------------------------------------- // <copyright file="OneToOneMappingSerializer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections.Generic; using System.Data.Common; using System.Data.Common.Utils; using System.Data.Mapping; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; using System.Xml; namespace System.Data.Entity.Design.Common { internal class OneToOneMappingSerializer { internal class MappingLookups { internal Dictionary<EntityType, EntityType> StoreEntityTypeToModelEntityType = new Dictionary<EntityType, EntityType>(); internal Dictionary<EdmProperty, EdmProperty> StoreEdmPropertyToModelEdmProperty = new Dictionary<EdmProperty, EdmProperty>(); internal Dictionary<EntitySet, EntitySet> StoreEntitySetToModelEntitySet = new Dictionary<EntitySet, EntitySet>(); internal Dictionary<AssociationType, AssociationType> StoreAssociationTypeToModelAssociationType = new Dictionary<AssociationType, AssociationType>(); internal Dictionary<AssociationEndMember, AssociationEndMember> StoreAssociationEndMemberToModelAssociationEndMember = new Dictionary<AssociationEndMember, AssociationEndMember>(); internal Dictionary<AssociationSet, AssociationSet> StoreAssociationSetToModelAssociationSet = new Dictionary<AssociationSet, AssociationSet>(); internal Dictionary<AssociationSetEnd, AssociationSetEnd> StoreAssociationSetEndToModelAssociationSetEnd = new Dictionary<AssociationSetEnd, AssociationSetEnd>(); internal List<CollapsedEntityAssociationSet> CollapsedEntityAssociationSets = new List<CollapsedEntityAssociationSet>(); internal List<Tuple<EdmFunction, EdmFunction>> StoreFunctionToFunctionImport = new List<Tuple<EdmFunction, EdmFunction>>(); } // this class represents a construct found in the ssdl where a link table // contained no data (all its properties were part of its keys) // it has exactly two associations // the entity type is the TO side of both associations // all the colums are used as TO columns in the constraint internal class CollapsedEntityAssociationSet { private EntitySet _storeEntitySet; private List<AssociationSet> _storeAssociationSets = new List<AssociationSet>(2); private AssociationSet _modelAssociationSet; public AssociationSet ModelAssociationSet { get { return _modelAssociationSet; } set { Debug.Assert(_modelAssociationSet == null, "why is this getting set multiple times, it should only be set after the new set is created"); _modelAssociationSet = value; } } public CollapsedEntityAssociationSet(EntitySet entitySet) { Debug.Assert(entitySet != null, "entitySet parameter is null"); _storeEntitySet = entitySet; } public EntitySet EntitySet { get { return _storeEntitySet; } } public List<AssociationSet> AssociationSets { get { return _storeAssociationSets; } } public void GetStoreAssociationSetEnd(int index, out AssociationSetEnd storeAssociationSetEnd, out RelationshipMultiplicity multiplicity, out OperationAction deleteBehavior) { Debug.Assert(index >= 0 && index < AssociationSets.Count, "out of bounds dude!!"); Debug.Assert(AssociationSets.Count == 2, "This code depends on only having exactly two AssociationSets"); GetFromAssociationSetEnd(AssociationSets[index], AssociationSets[(index+1)%2], out storeAssociationSetEnd, out multiplicity, out deleteBehavior); } private void GetFromAssociationSetEnd(AssociationSet definingSet, AssociationSet multiplicitySet, out AssociationSetEnd associationSetEnd, out RelationshipMultiplicity multiplicity, out OperationAction deleteBehavior) { // for a situation like this (CD is CascadeDelete) // // -------- CD -------- CD -------- // | A |1 <- 1| AtoB |* <- 1| B | // | |-------| |-------| | // | | | | | | // -------- -------- -------- // // You get // -------- CD -------- // | A |* <- 1| B | // | |-------| | // | | | | // -------- -------- // // Notice that the of the new "link table association" muliplicities are opposite of what comming into the original link table // this seems counter intuitive at first, but makes sense when you think all the way through it // // CascadeDelete Behavior (we can assume the runtime will always delete cascade // to the link table from the outside tables (it actually doesn't, but that is a bug)) // Store Effective // A -> AToB <- B None // A <- AToB <- B <- // A -> AToB -> B -> // A <- AToB -> B None // A <- AToB B <- // A AToB -> B -> // A -> AToB B None // A AToB <- B None // // Other CascadeDelete rules // 1. Can't have a delete from a Many multiplicity end // 2. Can't have a delete on both ends // associationSetEnd = GetAssociationSetEnd(definingSet, true); AssociationSetEnd multiplicityAssociationSetEnd = GetAssociationSetEnd(multiplicitySet, false); multiplicity = multiplicityAssociationSetEnd.CorrespondingAssociationEndMember.RelationshipMultiplicity; deleteBehavior = OperationAction.None; if (multiplicity != RelationshipMultiplicity.Many) { OperationAction otherEndBehavior = GetAssociationSetEnd(definingSet, false).CorrespondingAssociationEndMember.DeleteBehavior; if(otherEndBehavior == OperationAction.None) { // Since the other end does not have an operation // that means that only one end could possibly have an operation, that is good // so set it the operation deleteBehavior = multiplicityAssociationSetEnd.CorrespondingAssociationEndMember.DeleteBehavior; } } } private static AssociationSetEnd GetAssociationSetEnd(AssociationSet set, bool fromEnd) { Debug.Assert(set.ElementType.ReferentialConstraints.Count == 1, "no referenctial constraint for association[0]"); ReferentialConstraint constraint = set.ElementType.ReferentialConstraints[0]; Debug.Assert(set.AssociationSetEnds.Count == 2, "Associations are assumed to have two ends"); int toEndIndex, fromEndIndex; if (set.AssociationSetEnds[0].CorrespondingAssociationEndMember == constraint.FromRole) { fromEndIndex = 0; toEndIndex = 1; } else { fromEndIndex = 1; toEndIndex = 0; } if (fromEnd) { return set.AssociationSetEnds[fromEndIndex]; } else { return set.AssociationSetEnds[toEndIndex]; } } public bool MeetsRequirementsForCollapsableAssociation { get { if (_storeAssociationSets.Count != 2) return false; ReferentialConstraint constraint0; ReferentialConstraint constraint1; GetConstraints(out constraint0, out constraint1); if (!IsEntityDependentSideOfBothAssociations(constraint0, constraint1)) return false; if (!IsAtLeastOneColumnOfBothDependentRelationshipColumnSetsNonNullable(constraint0, constraint1)) return false; if (!AreAllEntityColumnsMappedAsToColumns(constraint0, constraint1)) return false; if (IsAtLeastOneColumnFKInBothAssociations(constraint0, constraint1)) return false; return true; } } private bool IsAtLeastOneColumnFKInBothAssociations(ReferentialConstraint constraint0, ReferentialConstraint constraint1) { return constraint1.ToProperties.Any(c => constraint0.ToProperties.Contains(c)); } private bool IsAtLeastOneColumnOfBothDependentRelationshipColumnSetsNonNullable(ReferentialConstraint constraint0, ReferentialConstraint constraint1) { return ToPropertyHasNonNullableColumn(constraint0) && ToPropertyHasNonNullableColumn(constraint1); } private static bool ToPropertyHasNonNullableColumn(ReferentialConstraint constraint) { foreach (EdmProperty property in constraint.ToProperties) { if (!property.Nullable) { return true; } } return false; } private bool AreAllEntityColumnsMappedAsToColumns(ReferentialConstraint constraint0, ReferentialConstraint constraint1) { Set<string> names = new Set<string>(); AddToPropertyNames(constraint0, names); AddToPropertyNames(constraint1, names); return names.Count == _storeEntitySet.ElementType.Properties.Count; } private static void AddToPropertyNames(ReferentialConstraint constraint, Set<string> names) { foreach (EdmProperty property in constraint.ToProperties) { names.Add(property.Name); } } private bool IsEntityDependentSideOfBothAssociations(ReferentialConstraint constraint0, ReferentialConstraint constraint1) { return ((RefType)constraint0.ToRole.TypeUsage.EdmType).ElementType == _storeEntitySet.ElementType && ((RefType)constraint1.ToRole.TypeUsage.EdmType).ElementType == _storeEntitySet.ElementType; } private void GetConstraints(out ReferentialConstraint constraint0, out ReferentialConstraint constraint1) { Debug.Assert(_storeAssociationSets.Count == 2, "don't call this method if you don't have two associations"); Debug.Assert(_storeAssociationSets[0].ElementType.ReferentialConstraints.Count == 1, "no referenctial constraint for association[0]"); Debug.Assert(_storeAssociationSets[1].ElementType.ReferentialConstraints.Count == 1, "no referenctial constraint for association[1]"); constraint0 = _storeAssociationSets[0].ElementType.ReferentialConstraints[0]; constraint1 = _storeAssociationSets[1].ElementType.ReferentialConstraints[0]; } } private MappingLookups _lookups; private EntityContainer _storeContainer; private EntityContainer _modelContainer; private string _xmlNamespace; internal OneToOneMappingSerializer(MappingLookups lookups, EntityContainer storeContainer, EntityContainer modelContainer, Version schemaVersion) { EDesignUtil.CheckArgumentNull(lookups, "lookups"); EDesignUtil.CheckArgumentNull(storeContainer, "storeContainer"); EDesignUtil.CheckArgumentNull(modelContainer, "modelContainer"); _lookups = lookups; _storeContainer = storeContainer; _modelContainer = modelContainer; _xmlNamespace = EntityFrameworkVersions.GetSchemaNamespace(schemaVersion, DataSpace.CSSpace); } public void WriteXml(XmlWriter writer) { EDesignUtil.CheckArgumentNull(writer, "writer"); WriteMappingStartElement(writer); WriteEntityContainerMappingElement(writer); writer.WriteEndElement(); } private void WriteEntityContainerMappingElement(XmlWriter writer) { writer.WriteStartElement(StorageMslConstructs.EntityContainerMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.StorageEntityContainerAttribute, _storeContainer.Name); writer.WriteAttributeString(StorageMslConstructs.CdmEntityContainerAttribute, _modelContainer.Name); foreach (EntitySet set in _lookups.StoreEntitySetToModelEntitySet.Keys) { EntitySet modelEntitySet = _lookups.StoreEntitySetToModelEntitySet[set]; WriteEntitySetMappingElement(writer, set, modelEntitySet); } foreach(AssociationSet set in _lookups.StoreAssociationSetToModelAssociationSet.Keys) { AssociationSet modelAssociationSet = _lookups.StoreAssociationSetToModelAssociationSet[set]; WriteAssociationSetMappingElement(writer, set, modelAssociationSet); } foreach (CollapsedEntityAssociationSet set in _lookups.CollapsedEntityAssociationSets) { WriteAssociationSetMappingElement(writer, set); } foreach (var functionMapping in _lookups.StoreFunctionToFunctionImport) { var storeFunction = functionMapping.Item1; var functionImport = functionMapping.Item2; WriteFunctionImportMappingElement(writer, storeFunction, functionImport); } writer.WriteEndElement(); } private void WriteFunctionImportMappingElement(XmlWriter writer, EdmFunction storeFunction, EdmFunction functionImport) { Debug.Assert(storeFunction.IsComposableAttribute, "storeFunction.IsComposableAttribute"); Debug.Assert(storeFunction.ReturnParameters.Count == 1, "storeFunction.ReturnParameters.Count == 1"); Debug.Assert(functionImport.IsComposableAttribute, "functionImport.IsComposableAttribute"); Debug.Assert(functionImport.ReturnParameters.Count == 1, "functionImport.ReturnParameters.Count == 1"); writer.WriteStartElement(StorageMslConstructs.FunctionImportMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.FunctionImportMappingFunctionNameAttribute, storeFunction.FullName); writer.WriteAttributeString(StorageMslConstructs.FunctionImportMappingFunctionImportNameAttribute, functionImport.Name); RowType tvfReturnType = TypeHelpers.GetTvfReturnType(storeFunction); if (tvfReturnType != null) { // Table-valued function Debug.Assert(functionImport.ReturnParameter.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType, "functionImport is expected to return Collection(ComplexType)"); var modelCollectionType = (CollectionType)functionImport.ReturnParameter.TypeUsage.EdmType; Debug.Assert(modelCollectionType.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType, "functionImport is expected to return Collection(ComplexType)"); var modelComplexType = (ComplexType)modelCollectionType.TypeUsage.EdmType; // Write ResultMapping/ComplexTypeMapping writer.WriteStartElement(StorageMslConstructs.FunctionImportMappingResultMapping, _xmlNamespace); writer.WriteStartElement(StorageMslConstructs.ComplexTypeMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.ComplexTypeMappingTypeNameAttribute, modelComplexType.FullName); foreach (EdmProperty storeProperty in tvfReturnType.Properties) { EdmProperty modelProperty = _lookups.StoreEdmPropertyToModelEdmProperty[storeProperty]; WriteScalarPropertyElement(writer, storeProperty, modelProperty); } writer.WriteEndElement(); writer.WriteEndElement(); } else { Debug.Fail("Only TVF store functions are supported."); } writer.WriteEndElement(); } private void WriteAssociationSetMappingElement(XmlWriter writer, CollapsedEntityAssociationSet collapsedAssociationSet) { if (!collapsedAssociationSet.ModelAssociationSet.ElementType.IsForeignKey) { writer.WriteStartElement(StorageMslConstructs.AssociationSetMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.AssociationSetMappingNameAttribute, collapsedAssociationSet.ModelAssociationSet.Name); writer.WriteAttributeString(StorageMslConstructs.AssociationSetMappingTypeNameAttribute, collapsedAssociationSet.ModelAssociationSet.ElementType.FullName); writer.WriteAttributeString(StorageMslConstructs.AssociationSetMappingStoreEntitySetAttribute, collapsedAssociationSet.EntitySet.Name); for (int i = 0; i < collapsedAssociationSet.AssociationSets.Count; i++) { AssociationSetEnd storeEnd; RelationshipMultiplicity multiplicity; OperationAction deleteBehavior; collapsedAssociationSet.GetStoreAssociationSetEnd(i, out storeEnd, out multiplicity, out deleteBehavior); AssociationSetEnd modelEnd = _lookups.StoreAssociationSetEndToModelAssociationSetEnd[storeEnd]; WriteEndPropertyElement(writer, storeEnd, modelEnd); } // don't need condition element writer.WriteEndElement(); } } private void WriteAssociationSetMappingElement(XmlWriter writer, AssociationSet store, AssociationSet model) { if (!model.ElementType.IsForeignKey) { writer.WriteStartElement(StorageMslConstructs.AssociationSetMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.AssociationSetMappingNameAttribute, model.Name); writer.WriteAttributeString(StorageMslConstructs.AssociationSetMappingTypeNameAttribute, model.ElementType.FullName); // all column names must be the primary key of the // end, but as columns in the Fk table. AssociationSetEnd foreignKeyTableEnd = GetAssociationSetEndForForeignKeyTable(store); writer.WriteAttributeString(StorageMslConstructs.AssociationSetMappingStoreEntitySetAttribute, foreignKeyTableEnd.EntitySet.Name); foreach (AssociationSetEnd storeEnd in store.AssociationSetEnds) { AssociationSetEnd modelEnd = _lookups.StoreAssociationSetEndToModelAssociationSetEnd[storeEnd]; WriteEndPropertyElement(writer, storeEnd, modelEnd); } ReferentialConstraint constraint = GetReferentialConstraint(store); foreach (EdmProperty fkColumn in constraint.ToProperties) { if (fkColumn.Nullable) { WriteConditionElement(writer, fkColumn); } } writer.WriteEndElement(); } } private void WriteConditionElement(XmlWriter writer, EdmProperty fkColumn) { writer.WriteStartElement(StorageMslConstructs.ConditionElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.ConditionColumnNameAttribute, fkColumn.Name); writer.WriteAttributeString(StorageMslConstructs.ConditionIsNullAttribute, "false"); writer.WriteEndElement(); } private static AssociationSetEnd GetAssociationSetEndForForeignKeyTable(AssociationSet store) { ReferentialConstraint constraint = GetReferentialConstraint(store); return store.AssociationSetEnds.GetValue(constraint.ToRole.Name, false); } internal static ReferentialConstraint GetReferentialConstraint(AssociationSet set) { // this seeems like a hack, but it is what we have right now. ReferentialConstraint constraint = null; foreach (ReferentialConstraint rc in set.ElementType.ReferentialConstraints) { Debug.Assert(constraint == null, "we should only get one"); constraint = rc; } Debug.Assert(constraint != null, "we should get at least one constraint"); return constraint; } private void WriteEndPropertyElement(XmlWriter writer, AssociationSetEnd store, AssociationSetEnd model) { writer.WriteStartElement(StorageMslConstructs.EndPropertyMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.EndPropertyMappingNameAttribute, model.Name); foreach (EdmProperty storeKeyMember in store.EntitySet.ElementType.KeyMembers) { EdmProperty modelKeyMember = _lookups.StoreEdmPropertyToModelEdmProperty[storeKeyMember]; EdmProperty storeFkTableMember = GetAssociatedFkColumn(store, storeKeyMember); WriteScalarPropertyElement(writer, storeFkTableMember, modelKeyMember); } writer.WriteEndElement(); } private static EdmProperty GetAssociatedFkColumn(AssociationSetEnd store, EdmProperty storeKeyProperty) { ReferentialConstraint constraint = GetReferentialConstraint(store.ParentAssociationSet); if (store.Name == constraint.FromRole.Name) { for (int i = 0; i < constraint.FromProperties.Count; i++) { if (constraint.FromProperties[i] == storeKeyProperty) { // return the matching Fk column return constraint.ToProperties[i]; } } } return storeKeyProperty; } private void WriteEntitySetMappingElement(XmlWriter writer, EntitySet store, EntitySet model) { writer.WriteStartElement(StorageMslConstructs.EntitySetMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.EntitySetMappingNameAttribute, model.Name); WriteEntityTypeMappingElement(writer, store, model); writer.WriteEndElement(); } private void WriteEntityTypeMappingElement(XmlWriter writer, EntitySet store, EntitySet model) { writer.WriteStartElement(StorageMslConstructs.EntityTypeMappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.EntityTypeMappingTypeNameAttribute, model.ElementType.FullName); WriteMappingFragmentElement(writer, store, model); writer.WriteEndElement(); } private void WriteMappingFragmentElement(XmlWriter writer, EntitySet store, EntitySet model) { writer.WriteStartElement(StorageMslConstructs.MappingFragmentElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.EntityTypeMappingStoreEntitySetAttribute, store.Name); foreach (EdmProperty storeProperty in store.ElementType.Properties) { // we don't add the fk properties to c-space, so some are missing, // check to see if we have a map for this one if (_lookups.StoreEdmPropertyToModelEdmProperty.ContainsKey(storeProperty)) { EdmProperty modelProperty = _lookups.StoreEdmPropertyToModelEdmProperty[storeProperty]; WriteScalarPropertyElement(writer, storeProperty, modelProperty); } } writer.WriteEndElement(); } private void WriteScalarPropertyElement(XmlWriter writer, EdmProperty store, EdmProperty model) { Debug.Assert(store.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType, "only expect scalar type properties"); Debug.Assert(model.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType, "only expect scalar type properties"); writer.WriteStartElement(StorageMslConstructs.ScalarPropertyElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.ScalarPropertyNameAttribute, model.Name); writer.WriteAttributeString(StorageMslConstructs.ScalarPropertyColumnNameAttribute, store.Name); writer.WriteEndElement(); } private void WriteMappingStartElement(XmlWriter writer) { writer.WriteStartElement(StorageMslConstructs.MappingElement, _xmlNamespace); writer.WriteAttributeString(StorageMslConstructs.MappingSpaceAttribute, "C-S"); } } }
namespace android.graphics.drawable { [global::MonoJavaBridge.JavaClass(typeof(global::android.graphics.drawable.Drawable_))] public abstract partial class Drawable : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Drawable() { InitJNI(); } protected Drawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.graphics.drawable.Drawable.Callback_))] public interface Callback : global::MonoJavaBridge.IJavaObject { void invalidateDrawable(android.graphics.drawable.Drawable arg0); void scheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1, long arg2); void unscheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.graphics.drawable.Drawable.Callback))] public sealed partial class Callback_ : java.lang.Object, Callback { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Callback_() { InitJNI(); } internal Callback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _invalidateDrawable3911; void android.graphics.drawable.Drawable.Callback.invalidateDrawable(android.graphics.drawable.Drawable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.Callback_._invalidateDrawable3911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.Callback_.staticClass, global::android.graphics.drawable.Drawable.Callback_._invalidateDrawable3911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _scheduleDrawable3912; void android.graphics.drawable.Drawable.Callback.scheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1, long arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.Callback_._scheduleDrawable3912, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.Callback_.staticClass, global::android.graphics.drawable.Drawable.Callback_._scheduleDrawable3912, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _unscheduleDrawable3913; void android.graphics.drawable.Drawable.Callback.unscheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.Callback_._unscheduleDrawable3913, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.Callback_.staticClass, global::android.graphics.drawable.Drawable.Callback_._unscheduleDrawable3913, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.drawable.Drawable.Callback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/Drawable$Callback")); global::android.graphics.drawable.Drawable.Callback_._invalidateDrawable3911 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.Callback_.staticClass, "invalidateDrawable", "(Landroid/graphics/drawable/Drawable;)V"); global::android.graphics.drawable.Drawable.Callback_._scheduleDrawable3912 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.Callback_.staticClass, "scheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V"); global::android.graphics.drawable.Drawable.Callback_._unscheduleDrawable3913 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.Callback_.staticClass, "unscheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;)V"); } } [global::MonoJavaBridge.JavaClass(typeof(global::android.graphics.drawable.Drawable.ConstantState_))] public abstract partial class ConstantState : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ConstantState() { InitJNI(); } protected ConstantState(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getChangingConfigurations3914; public abstract int getChangingConfigurations(); internal static global::MonoJavaBridge.MethodId _newDrawable3915; public abstract global::android.graphics.drawable.Drawable newDrawable(); internal static global::MonoJavaBridge.MethodId _newDrawable3916; public virtual global::android.graphics.drawable.Drawable newDrawable(android.content.res.Resources arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.ConstantState._newDrawable3916, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.ConstantState.staticClass, global::android.graphics.drawable.Drawable.ConstantState._newDrawable3916, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _ConstantState3917; public ConstantState() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.Drawable.ConstantState.staticClass, global::android.graphics.drawable.Drawable.ConstantState._ConstantState3917); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.drawable.Drawable.ConstantState.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/Drawable$ConstantState")); global::android.graphics.drawable.Drawable.ConstantState._getChangingConfigurations3914 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.ConstantState.staticClass, "getChangingConfigurations", "()I"); global::android.graphics.drawable.Drawable.ConstantState._newDrawable3915 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.ConstantState.staticClass, "newDrawable", "()Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable.ConstantState._newDrawable3916 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.ConstantState.staticClass, "newDrawable", "(Landroid/content/res/Resources;)Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable.ConstantState._ConstantState3917 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.ConstantState.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.graphics.drawable.Drawable.ConstantState))] public sealed partial class ConstantState_ : android.graphics.drawable.Drawable.ConstantState { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ConstantState_() { InitJNI(); } internal ConstantState_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getChangingConfigurations3918; public override int getChangingConfigurations() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.ConstantState_._getChangingConfigurations3918); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.ConstantState_.staticClass, global::android.graphics.drawable.Drawable.ConstantState_._getChangingConfigurations3918); } internal static global::MonoJavaBridge.MethodId _newDrawable3919; public override global::android.graphics.drawable.Drawable newDrawable() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.ConstantState_._newDrawable3919)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.ConstantState_.staticClass, global::android.graphics.drawable.Drawable.ConstantState_._newDrawable3919)) as android.graphics.drawable.Drawable; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.drawable.Drawable.ConstantState_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/Drawable$ConstantState")); global::android.graphics.drawable.Drawable.ConstantState_._getChangingConfigurations3918 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.ConstantState_.staticClass, "getChangingConfigurations", "()I"); global::android.graphics.drawable.Drawable.ConstantState_._newDrawable3919 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.ConstantState_.staticClass, "newDrawable", "()Landroid/graphics/drawable/Drawable;"); } } internal static global::MonoJavaBridge.MethodId _getState3920; public virtual int[] getState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getState3920)) as int[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getState3920)) as int[]; } internal static global::MonoJavaBridge.MethodId _setState3921; public virtual bool setState(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setState3921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setState3921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _inflate3922; public virtual void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._inflate3922, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._inflate3922, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _draw3923; public abstract void draw(android.graphics.Canvas arg0); internal static global::MonoJavaBridge.MethodId _setBounds3924; public virtual void setBounds(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setBounds3924, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setBounds3924, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _setBounds3925; public virtual void setBounds(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setBounds3925, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setBounds3925, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _copyBounds3926; public virtual void copyBounds(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._copyBounds3926, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._copyBounds3926, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _copyBounds3927; public virtual global::android.graphics.Rect copyBounds() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._copyBounds3927)) as android.graphics.Rect; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._copyBounds3927)) as android.graphics.Rect; } internal static global::MonoJavaBridge.MethodId _getBounds3928; public virtual global::android.graphics.Rect getBounds() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getBounds3928)) as android.graphics.Rect; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getBounds3928)) as android.graphics.Rect; } internal static global::MonoJavaBridge.MethodId _setChangingConfigurations3929; public virtual void setChangingConfigurations(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setChangingConfigurations3929, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setChangingConfigurations3929, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getChangingConfigurations3930; public virtual int getChangingConfigurations() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getChangingConfigurations3930); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getChangingConfigurations3930); } internal static global::MonoJavaBridge.MethodId _setDither3931; public virtual void setDither(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setDither3931, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setDither3931, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setFilterBitmap3932; public virtual void setFilterBitmap(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setFilterBitmap3932, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setFilterBitmap3932, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setCallback3933; public virtual void setCallback(android.graphics.drawable.Drawable.Callback arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setCallback3933, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setCallback3933, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _invalidateSelf3934; public virtual void invalidateSelf() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._invalidateSelf3934); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._invalidateSelf3934); } internal static global::MonoJavaBridge.MethodId _scheduleSelf3935; public virtual void scheduleSelf(java.lang.Runnable arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._scheduleSelf3935, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._scheduleSelf3935, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _unscheduleSelf3936; public virtual void unscheduleSelf(java.lang.Runnable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._unscheduleSelf3936, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._unscheduleSelf3936, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setAlpha3937; public abstract void setAlpha(int arg0); internal static global::MonoJavaBridge.MethodId _setColorFilter3938; public abstract void setColorFilter(android.graphics.ColorFilter arg0); internal static global::MonoJavaBridge.MethodId _setColorFilter3939; public virtual void setColorFilter(int arg0, android.graphics.PorterDuff.Mode arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setColorFilter3939, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setColorFilter3939, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _clearColorFilter3940; public virtual void clearColorFilter() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._clearColorFilter3940); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._clearColorFilter3940); } internal static global::MonoJavaBridge.MethodId _isStateful3941; public virtual bool isStateful() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._isStateful3941); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._isStateful3941); } internal static global::MonoJavaBridge.MethodId _getCurrent3942; public virtual global::android.graphics.drawable.Drawable getCurrent() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getCurrent3942)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getCurrent3942)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _setLevel3943; public virtual bool setLevel(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setLevel3943, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setLevel3943, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getLevel3944; public virtual int getLevel() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getLevel3944); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getLevel3944); } internal static global::MonoJavaBridge.MethodId _setVisible3945; public virtual bool setVisible(bool arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._setVisible3945, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._setVisible3945, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isVisible3946; public virtual bool isVisible() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._isVisible3946); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._isVisible3946); } internal static global::MonoJavaBridge.MethodId _getOpacity3947; public abstract int getOpacity(); internal static global::MonoJavaBridge.MethodId _resolveOpacity3948; public static int resolveOpacity(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._resolveOpacity3948, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getTransparentRegion3949; public virtual global::android.graphics.Region getTransparentRegion() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getTransparentRegion3949)) as android.graphics.Region; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getTransparentRegion3949)) as android.graphics.Region; } internal static global::MonoJavaBridge.MethodId _onStateChange3950; protected virtual bool onStateChange(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._onStateChange3950, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._onStateChange3950, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onLevelChange3951; protected virtual bool onLevelChange(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._onLevelChange3951, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._onLevelChange3951, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onBoundsChange3952; protected virtual void onBoundsChange(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._onBoundsChange3952, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._onBoundsChange3952, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getIntrinsicWidth3953; public virtual int getIntrinsicWidth() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getIntrinsicWidth3953); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getIntrinsicWidth3953); } internal static global::MonoJavaBridge.MethodId _getIntrinsicHeight3954; public virtual int getIntrinsicHeight() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getIntrinsicHeight3954); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getIntrinsicHeight3954); } internal static global::MonoJavaBridge.MethodId _getMinimumWidth3955; public virtual int getMinimumWidth() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getMinimumWidth3955); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getMinimumWidth3955); } internal static global::MonoJavaBridge.MethodId _getMinimumHeight3956; public virtual int getMinimumHeight() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getMinimumHeight3956); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getMinimumHeight3956); } internal static global::MonoJavaBridge.MethodId _getPadding3957; public virtual bool getPadding(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getPadding3957, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getPadding3957, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _mutate3958; public virtual global::android.graphics.drawable.Drawable mutate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._mutate3958)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._mutate3958)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _createFromStream3959; public static global::android.graphics.drawable.Drawable createFromStream(java.io.InputStream arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._createFromStream3959, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _createFromResourceStream3960; public static global::android.graphics.drawable.Drawable createFromResourceStream(android.content.res.Resources arg0, android.util.TypedValue arg1, java.io.InputStream arg2, java.lang.String arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._createFromResourceStream3960, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _createFromResourceStream3961; public static global::android.graphics.drawable.Drawable createFromResourceStream(android.content.res.Resources arg0, android.util.TypedValue arg1, java.io.InputStream arg2, java.lang.String arg3, android.graphics.BitmapFactory.Options arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._createFromResourceStream3961, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _createFromXml3962; public static global::android.graphics.drawable.Drawable createFromXml(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._createFromXml3962, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _createFromXmlInner3963; public static global::android.graphics.drawable.Drawable createFromXmlInner(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._createFromXmlInner3963, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _createFromPath3964; public static global::android.graphics.drawable.Drawable createFromPath(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._createFromPath3964, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _getConstantState3965; public virtual global::android.graphics.drawable.Drawable.ConstantState getConstantState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable._getConstantState3965)) as android.graphics.drawable.Drawable.ConstantState; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._getConstantState3965)) as android.graphics.drawable.Drawable.ConstantState; } internal static global::MonoJavaBridge.MethodId _Drawable3966; public Drawable() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.Drawable.staticClass, global::android.graphics.drawable.Drawable._Drawable3966); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.drawable.Drawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/Drawable")); global::android.graphics.drawable.Drawable._getState3920 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getState", "()[I"); global::android.graphics.drawable.Drawable._setState3921 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setState", "([I)Z"); global::android.graphics.drawable.Drawable._inflate3922 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V"); global::android.graphics.drawable.Drawable._draw3923 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V"); global::android.graphics.drawable.Drawable._setBounds3924 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setBounds", "(IIII)V"); global::android.graphics.drawable.Drawable._setBounds3925 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setBounds", "(Landroid/graphics/Rect;)V"); global::android.graphics.drawable.Drawable._copyBounds3926 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "copyBounds", "(Landroid/graphics/Rect;)V"); global::android.graphics.drawable.Drawable._copyBounds3927 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "copyBounds", "()Landroid/graphics/Rect;"); global::android.graphics.drawable.Drawable._getBounds3928 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getBounds", "()Landroid/graphics/Rect;"); global::android.graphics.drawable.Drawable._setChangingConfigurations3929 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setChangingConfigurations", "(I)V"); global::android.graphics.drawable.Drawable._getChangingConfigurations3930 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getChangingConfigurations", "()I"); global::android.graphics.drawable.Drawable._setDither3931 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setDither", "(Z)V"); global::android.graphics.drawable.Drawable._setFilterBitmap3932 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setFilterBitmap", "(Z)V"); global::android.graphics.drawable.Drawable._setCallback3933 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setCallback", "(Landroid/graphics/drawable/Drawable$Callback;)V"); global::android.graphics.drawable.Drawable._invalidateSelf3934 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "invalidateSelf", "()V"); global::android.graphics.drawable.Drawable._scheduleSelf3935 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "scheduleSelf", "(Ljava/lang/Runnable;J)V"); global::android.graphics.drawable.Drawable._unscheduleSelf3936 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "unscheduleSelf", "(Ljava/lang/Runnable;)V"); global::android.graphics.drawable.Drawable._setAlpha3937 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setAlpha", "(I)V"); global::android.graphics.drawable.Drawable._setColorFilter3938 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V"); global::android.graphics.drawable.Drawable._setColorFilter3939 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setColorFilter", "(ILandroid/graphics/PorterDuff$Mode;)V"); global::android.graphics.drawable.Drawable._clearColorFilter3940 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "clearColorFilter", "()V"); global::android.graphics.drawable.Drawable._isStateful3941 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "isStateful", "()Z"); global::android.graphics.drawable.Drawable._getCurrent3942 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getCurrent", "()Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._setLevel3943 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setLevel", "(I)Z"); global::android.graphics.drawable.Drawable._getLevel3944 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getLevel", "()I"); global::android.graphics.drawable.Drawable._setVisible3945 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "setVisible", "(ZZ)Z"); global::android.graphics.drawable.Drawable._isVisible3946 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "isVisible", "()Z"); global::android.graphics.drawable.Drawable._getOpacity3947 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getOpacity", "()I"); global::android.graphics.drawable.Drawable._resolveOpacity3948 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "resolveOpacity", "(II)I"); global::android.graphics.drawable.Drawable._getTransparentRegion3949 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getTransparentRegion", "()Landroid/graphics/Region;"); global::android.graphics.drawable.Drawable._onStateChange3950 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "onStateChange", "([I)Z"); global::android.graphics.drawable.Drawable._onLevelChange3951 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "onLevelChange", "(I)Z"); global::android.graphics.drawable.Drawable._onBoundsChange3952 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V"); global::android.graphics.drawable.Drawable._getIntrinsicWidth3953 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getIntrinsicWidth", "()I"); global::android.graphics.drawable.Drawable._getIntrinsicHeight3954 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getIntrinsicHeight", "()I"); global::android.graphics.drawable.Drawable._getMinimumWidth3955 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getMinimumWidth", "()I"); global::android.graphics.drawable.Drawable._getMinimumHeight3956 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getMinimumHeight", "()I"); global::android.graphics.drawable.Drawable._getPadding3957 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z"); global::android.graphics.drawable.Drawable._mutate3958 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "mutate", "()Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._createFromStream3959 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "createFromStream", "(Ljava/io/InputStream;Ljava/lang/String;)Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._createFromResourceStream3960 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "createFromResourceStream", "(Landroid/content/res/Resources;Landroid/util/TypedValue;Ljava/io/InputStream;Ljava/lang/String;)Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._createFromResourceStream3961 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "createFromResourceStream", "(Landroid/content/res/Resources;Landroid/util/TypedValue;Ljava/io/InputStream;Ljava/lang/String;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._createFromXml3962 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "createFromXml", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;)Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._createFromXmlInner3963 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "createFromXmlInner", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._createFromPath3964 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "createFromPath", "(Ljava/lang/String;)Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.Drawable._getConstantState3965 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;"); global::android.graphics.drawable.Drawable._Drawable3966 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.graphics.drawable.Drawable))] public sealed partial class Drawable_ : android.graphics.drawable.Drawable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Drawable_() { InitJNI(); } internal Drawable_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _draw3967; public override void draw(android.graphics.Canvas arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_._draw3967, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_.staticClass, global::android.graphics.drawable.Drawable_._draw3967, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setAlpha3968; public override void setAlpha(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_._setAlpha3968, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_.staticClass, global::android.graphics.drawable.Drawable_._setAlpha3968, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setColorFilter3969; public override void setColorFilter(android.graphics.ColorFilter arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_._setColorFilter3969, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_.staticClass, global::android.graphics.drawable.Drawable_._setColorFilter3969, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getOpacity3970; public override int getOpacity() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_._getOpacity3970); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.Drawable_.staticClass, global::android.graphics.drawable.Drawable_._getOpacity3970); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.drawable.Drawable_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/Drawable")); global::android.graphics.drawable.Drawable_._draw3967 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable_.staticClass, "draw", "(Landroid/graphics/Canvas;)V"); global::android.graphics.drawable.Drawable_._setAlpha3968 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable_.staticClass, "setAlpha", "(I)V"); global::android.graphics.drawable.Drawable_._setColorFilter3969 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable_.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V"); global::android.graphics.drawable.Drawable_._getOpacity3970 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.Drawable_.staticClass, "getOpacity", "()I"); } } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Updating.Relationships { public sealed class UpdateToOneRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>> { private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext; private readonly ReadWriteFakers _fakers = new(); public UpdateToOneRelationshipTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext) { _testContext = testContext; testContext.UseController<WorkItemsController>(); testContext.UseController<WorkItemGroupsController>(); testContext.UseController<RgbColorsController>(); } [Fact] public async Task Can_clear_ManyToOne_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Assignee = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object)null }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Assignee.Should().BeNull(); }); } [Fact] public async Task Can_clear_OneToOne_relationship() { // Arrange WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate(); existingGroup.Color = _fakers.RgbColor.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Groups.AddRange(existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object)null }; string route = $"/workItemGroups/{existingGroup.StringId}/relationships/color"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItemGroup groupInDatabase = await dbContext.Groups.Include(group => group.Color).FirstWithIdOrDefaultAsync(existingGroup.Id); groupInDatabase.Color.Should().BeNull(); }); } [Fact] public async Task Can_create_OneToOne_relationship_from_dependent_side() { // Arrange WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate(); existingGroup.Color = _fakers.RgbColor.Generate(); RgbColor existingColor = _fakers.RgbColor.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingGroup, existingColor); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItemGroups", id = existingGroup.StringId } }; string route = $"/rgbColors/{existingColor.StringId}/relationships/group"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(rgbColor => rgbColor.Group).ToListAsync(); RgbColor colorInDatabase1 = colorsInDatabase.Single(color => color.Id == existingGroup.Color.Id); colorInDatabase1.Group.Should().BeNull(); RgbColor colorInDatabase2 = colorsInDatabase.Single(color => color.Id == existingColor.Id); colorInDatabase2.Group.Should().NotBeNull(); colorInDatabase2.Group.Id.Should().Be(existingGroup.Id); }); } [Fact] public async Task Can_replace_OneToOne_relationship_from_principal_side() { // Arrange List<WorkItemGroup> existingGroups = _fakers.WorkItemGroup.Generate(2); existingGroups[0].Color = _fakers.RgbColor.Generate(); existingGroups[1].Color = _fakers.RgbColor.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Groups.AddRange(existingGroups); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "rgbColors", id = existingGroups[0].Color.StringId } }; string route = $"/workItemGroups/{existingGroups[1].StringId}/relationships/color"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<WorkItemGroup> groupsInDatabase = await dbContext.Groups.Include(group => group.Color).ToListAsync(); WorkItemGroup groupInDatabase1 = groupsInDatabase.Single(group => group.Id == existingGroups[0].Id); groupInDatabase1.Color.Should().BeNull(); WorkItemGroup groupInDatabase2 = groupsInDatabase.Single(group => group.Id == existingGroups[1].Id); groupInDatabase2.Color.Should().NotBeNull(); groupInDatabase2.Color.Id.Should().Be(existingGroups[0].Color.Id); List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(color => color.Group).ToListAsync(); RgbColor colorInDatabase1 = colorsInDatabase.Single(color => color.Id == existingGroups[0].Color.Id); colorInDatabase1.Group.Should().NotBeNull(); colorInDatabase1.Group.Id.Should().Be(existingGroups[1].Id); RgbColor colorInDatabase2 = colorsInDatabase.SingleOrDefault(color => color.Id == existingGroups[1].Color.Id); colorInDatabase1.Should().NotBeNull(); colorInDatabase2!.Group.Should().BeNull(); }); } [Fact] public async Task Can_replace_ManyToOne_relationship() { // Arrange List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2); existingUserAccounts[0].AssignedItems = _fakers.WorkItem.Generate(2).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.AddRange(existingUserAccounts); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingUserAccounts[1].StringId } }; string route = $"/workItems/{existingUserAccounts[0].AssignedItems.ElementAt(1).StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { int workItemId = existingUserAccounts[0].AssignedItems.ElementAt(1).Id; WorkItem workItemInDatabase2 = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(workItemId); workItemInDatabase2.Assignee.Should().NotBeNull(); workItemInDatabase2.Assignee.Id.Should().Be(existingUserAccounts[1].Id); }); } [Fact] public async Task Cannot_replace_for_missing_request_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); string requestBody = string.Empty; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Missing request body."); error.Detail.Should().BeNull(); } [Fact] public async Task Cannot_create_for_missing_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { id = Unknown.StringId.For<UserAccount, long>() } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element."); error.Detail.Should().StartWith("Expected 'type' element in 'data' element. - Request body: <<"); } [Fact] public async Task Cannot_create_for_unknown_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = Unknown.ResourceType, id = Unknown.StringId.For<UserAccount, long>() } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type."); error.Detail.Should().StartWith($"Resource type '{Unknown.ResourceType}' does not exist. - Request body: <<"); } [Fact] public async Task Cannot_create_for_missing_ID() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts" } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' element."); error.Detail.Should().StartWith("Request body: <<"); } [Fact] public async Task Cannot_create_with_unknown_ID() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); string userAccountId = Unknown.StringId.For<UserAccount, long>(); var requestBody = new { data = new { type = "userAccounts", id = userAccountId } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId}' in relationship 'assignee' does not exist."); } [Fact] public async Task Cannot_create_on_unknown_resource_type_in_url() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingWorkItem, existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } }; string route = $"/{Unknown.ResourceType}/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Should().BeEmpty(); } [Fact] public async Task Cannot_create_on_unknown_resource_ID_in_url() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } }; string workItemId = Unknown.StringId.For<WorkItem, int>(); string route = $"/workItems/{workItemId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist."); } [Fact] public async Task Cannot_create_on_unknown_relationship_in_url() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = Unknown.StringId.For<UserAccount, long>() } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/{Unknown.Relationship}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested relationship does not exist."); error.Detail.Should().Be($"Resource of type 'workItems' does not contain a relationship named '{Unknown.Relationship}'."); } [Fact] public async Task Cannot_create_on_relationship_mismatch_between_url_and_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); RgbColor existingColor = _fakers.RgbColor.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingWorkItem, existingColor); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "rgbColors", id = existingColor.StringId } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Conflict); error.Title.Should().Be("Resource type mismatch between request body and endpoint URL."); error.Detail.Should().Be("Expected resource of type 'userAccounts' in PATCH request body at endpoint " + $"'/workItems/{existingWorkItem.StringId}/relationships/assignee', instead of 'rgbColors'."); } [Fact] public async Task Cannot_create_with_data_array_in_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingWorkItem, existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts", id = existingUserAccount.StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected single data element for to-one relationship."); error.Detail.Should().StartWith("Expected single data element for 'assignee' relationship. - Request body: <<"); } [Fact] public async Task Can_clear_cyclic_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); existingWorkItem.Parent = existingWorkItem; await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object)null }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/parent"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Parent).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Parent.Should().BeNull(); }); } [Fact] public async Task Can_assign_cyclic_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/parent"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Parent).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Parent.Should().NotBeNull(); workItemInDatabase.Parent.Id.Should().Be(existingWorkItem.Id); }); } } }
/* Copyright Microsoft Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache 2 License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using MileageStats.Domain.Handlers; using MileageStats.Domain.Models; using Xunit; namespace MileageStats.Domain.Tests { public class VehicleStatisticsFixture { [Fact] public void WhenConstructed_ThenIntialized() { var target = CalculateStatistics.Calculate(new FillupEntry[]{}); Assert.NotNull(target); Assert.Equal(0.0, target.AverageCostPerMonth); Assert.Equal(0.0, target.AverageCostToDrive); Assert.Equal(0.0, target.AverageFillupPrice); Assert.Equal(0.0, target.AverageFuelEfficiency); Assert.Null(target.Name); Assert.Null(target.Odometer); Assert.Equal(0.0, target.TotalCost); Assert.Equal(0.0, target.TotalDistance); Assert.Equal(0.0, target.TotalFuelCost); Assert.Equal(0.0, target.TotalUnits); } [Fact] public void WhenNameSet_ThenValueUpdated() { var target = new VehicleStatisticsModel {Name = "Name"}; Assert.Equal("Name", target.Name); } [Fact] public void WhenVehiclePopulated_ThenOdometerCalculated() { var fillups = new[] { new FillupEntry {Date = DateTime.UtcNow.AddMonths(-5), Odometer = 10000}, new FillupEntry {Date = DateTime.UtcNow.AddMonths(-4), Odometer = 12000}, new FillupEntry {Date = DateTime.UtcNow.AddMonths(-3), Odometer = 14000}, new FillupEntry {Date = DateTime.UtcNow.AddMonths(-3), Odometer = 16000} }; var target = CalculateStatistics.Calculate(fillups); Assert.Equal(16000, target.Odometer); } [Fact] public void WhenVehiclePopulated_ThenTotalDistanceCalculated() { var fillups = new[] { new FillupEntry { Date = DateTime.UtcNow.AddMonths(-5), Odometer = 10000, Distance = null }, new FillupEntry { Date = DateTime.UtcNow.AddMonths(-4), Odometer = 12000, Distance = 2000 }, new FillupEntry { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 14000, Distance = 2000 }, new FillupEntry { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 16000, Distance = 2000 } }; var target = CalculateStatistics.Calculate(fillups); Assert.Equal(16000 - 10000, target.TotalDistance); } [Fact] public void WhenVehiclePopulated_ThenTotalUnitsCalculated() { var fillups = new[] { new FillupEntry() {Date = DateTime.UtcNow.AddMonths(-5), TotalUnits = 20.5}, new FillupEntry() {Date = DateTime.UtcNow.AddMonths(-4), TotalUnits = 22}, new FillupEntry() {Date = DateTime.UtcNow.AddMonths(-3), TotalUnits = 36.253}, new FillupEntry() {Date = DateTime.UtcNow.AddMonths(-3), TotalUnits = 21.55} }; var target = CalculateStatistics.Calculate(fillups, includeFirst:false); Assert.Equal(79.8, Math.Round(target.TotalUnits, 2)); } [Fact] public void WhenVehiclePopulated_ThenTotalFuelCostCalculated() { var fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-5), PricePerUnit = 2.95, TotalUnits = 20.5, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-4), PricePerUnit = 3.16, TotalUnits = 22, TransactionFee = 2.90 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), PricePerUnit = 1.90, TotalUnits = 36.253 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), PricePerUnit = 3.16, TotalUnits = 21.55, TransactionFee = 1.13 }); var target = CalculateStatistics.Calculate(fillups, includeFirst:false); Assert.Equal(206.5, Math.Round(target.TotalFuelCost, 2)); } [Fact] public void WhenVehiclePopulated_ThenTotalCostCalculated() { List<FillupEntry> fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-5), PricePerUnit = 2.95, TotalUnits = 20.5, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-4), PricePerUnit = 3.16, TotalUnits = 22, TransactionFee = 2.90 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), PricePerUnit = 1.90, TotalUnits = 36.253 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), PricePerUnit = 3.16, TotalUnits = 21.55, TransactionFee = 1.13 }); var target = CalculateStatistics.Calculate(fillups, includeFirst: false); // Ignore the cost of the first fillup, otherwise stats are off double totalCost = (22 * 3.16 + 36.253 * 1.90 + 21.55 * 3.16 + 2.9 + 1.13); Assert.Equal(Math.Round(totalCost, 2), Math.Round(target.TotalCost, 2)); } [Fact] public void WhenVehiclePopulated_ThenAverageFillupPriceCalculated() { var fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-5), PricePerUnit = 2.95, TotalUnits = 20.5, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-4), PricePerUnit = 3.16, TotalUnits = 22, TransactionFee = 2.90 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), PricePerUnit = 1.90, TotalUnits = 36.253 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), PricePerUnit = 3.16, TotalUnits = 21.55, TransactionFee = 1.13 }); var target = CalculateStatistics.Calculate(fillups, includeFirst:false); Assert.Equal(2.59, Math.Round(target.AverageFillupPrice, 2)); } [Fact] public void WhenVehiclePopulated_ThenAverageFuelEfficiencyCalculated() { List<FillupEntry> fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-5), Odometer = 10000, Distance = null, PricePerUnit = 2.95, TotalUnits = 20.5, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-4), Odometer = 10220, Distance = 220, PricePerUnit = 3.16, TotalUnits = 22, TransactionFee = 2.90 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 11000, Distance = 780, PricePerUnit = 1.90, TotalUnits = 36.253 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 11131, Distance = 131, PricePerUnit = 3.16, TotalUnits = 21.55, TransactionFee = 1.13 }); var target = CalculateStatistics.Calculate(fillups, includeFirst: false); double totalDistance = 11131 - 10000; // Ignore the cost of the first fillup, otherwise stats are off double totalFuel = 22 + 36.253 + 21.55; double efficiency = Math.Round(totalDistance / totalFuel, 2); Assert.Equal(efficiency, Math.Round(target.AverageFuelEfficiency, 2)); } [Fact] public void WhenVehiclePopulated_ThenAverageCostToDriveCalculated() { List<FillupEntry> fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-5), Odometer = 10000, Distance = null, PricePerUnit = 2.95, TotalUnits = 20.5, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-4), Odometer = 10220, Distance = 220, PricePerUnit = 3.16, TotalUnits = 22, TransactionFee = 2.90 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 11000, Distance = 780, PricePerUnit = 1.90, TotalUnits = 36.253 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 11132, Distance = 132, PricePerUnit = 3.16, TotalUnits = 21.55, TransactionFee = 1.13 }); var target = CalculateStatistics.Calculate(fillups, includeFirst: false); double totalDistance = 11132 - 10000; // Ignore the cost of the first fillup, otherwise stats are off double totalCost = 22 * 3.16 + 36.253 * 1.90 + 21.55 * 3.16 + 2.9 + 1.13; double costPerDistance = Math.Round(totalCost / totalDistance, 2); Assert.Equal(costPerDistance, Math.Round(target.AverageCostToDrive, 2)); } [Fact] public void WhenVehiclePopulated_ThenAverageCostPerMonthIsCalculated() { List<FillupEntry> fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-5), Odometer = 10000, Distance = null, PricePerUnit = 2.95, TotalUnits = 20.5, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-4), Odometer = 10220, Distance = 220, PricePerUnit = 3.16, TotalUnits = 22, TransactionFee = 2.90 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 11000, Distance = 780, PricePerUnit = 1.90, TotalUnits = 36.253 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 11132, Distance = 132, PricePerUnit = 3.16, TotalUnits = 21.55, TransactionFee = 1.13 }); var target = CalculateStatistics.Calculate(fillups, includeFirst: false); // Ignore the cost of the first fillup, otherwise stats are off double totalCost = Math.Round(22 * 3.16 + 36.253 * 1.90 + 21.55 * 3.16 + 2.90 + 1.13, 2); double avgCostPerMonth = Math.Round(totalCost / 5, 2); Assert.Equal(avgCostPerMonth, Math.Round(target.AverageCostPerMonth, 2)); } [Fact] public void WhenVehiclePopulatedWithIntraMonthData_ThenAverageCostPerMonthCalculatedAtOneMonth() { List<FillupEntry> fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddDays(-5), Odometer = 10000, Distance = null, PricePerUnit = 2.95, TotalUnits = 20.5, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddDays(-4), Odometer = 10220, Distance = 220, PricePerUnit = 3.16, TotalUnits = 22, TransactionFee = 2.90 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddDays(-3), Odometer = 11000, Distance = 780, PricePerUnit = 1.90, TotalUnits = 36.253 }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddDays(-3), Odometer = 11132, Distance = 132, PricePerUnit = 3.16, TotalUnits = 21.55, TransactionFee = 1.13 }); var target = CalculateStatistics.Calculate(fillups, includeFirst: false); // Ignore the cost of the first fillup, otherwise stats are off double totalGasCost = (22 * 3.16 + 36.253 * 1.90 + 21.55 * 3.16); double totalCost = Math.Round(totalGasCost + +2.90 + 1.13, 2); Assert.Equal((totalCost) / 1, Math.Round(target.AverageCostPerMonth, 2)); Assert.Equal(Math.Round(target.TotalCost, 2), Math.Round(target.AverageCostPerMonth, 2)); } [Fact] public void WhenIncludeFirstFillupTrue_ThenFirstFillupIncluded() { List<FillupEntry> fillups = new List<FillupEntry>(); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-5), Odometer = 10000, Distance = null, PricePerUnit = 1, TotalUnits = 10, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-4), Odometer = 11000, Distance = 1000, PricePerUnit = 1, TotalUnits = 10, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-3), Odometer = 12000, Distance = 1000, PricePerUnit = 1, TotalUnits = 10, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-2), Odometer = 13000, Distance = 1000, PricePerUnit = 1, TotalUnits = 10, }); fillups.Add(new FillupEntry() { Date = DateTime.UtcNow.AddMonths(-1), Odometer = 14000, Distance = 1000, PricePerUnit = 1, TotalUnits = 10, }); var target = CalculateStatistics.Calculate(fillups, includeFirst: true); double totalDistance = 14000 - 10000; // Ignore the cost of the first fillup, otherwise stats are off double totalCost = 10 * 5; double fuelCost = 10 * 5; double totalFuel = 10 * 5; double avgCostPerMonth = Math.Round(totalCost / 5, 2); double avgCostToDrive = Math.Round(totalCost / totalDistance, 2); double avgEfficiency = Math.Round(totalDistance / totalFuel, 2); Assert.Equal(avgCostPerMonth, Math.Round(target.AverageCostPerMonth, 2)); Assert.Equal(avgCostToDrive, Math.Round(target.AverageCostToDrive, 2)); Assert.Equal(1, Math.Round(target.AverageFillupPrice, 2)); Assert.Equal(avgEfficiency, Math.Round(target.AverageFuelEfficiency, 2)); Assert.Equal(14000, target.Odometer); Assert.Equal(totalCost, Math.Round(target.TotalCost, 2)); Assert.Equal(totalDistance, target.TotalDistance); Assert.Equal(fuelCost, Math.Round(target.TotalFuelCost, 2)); Assert.Equal(totalFuel, Math.Round(target.TotalUnits, 2)); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="CombinedAudienceServiceClient"/> instances.</summary> public sealed partial class CombinedAudienceServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CombinedAudienceServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CombinedAudienceServiceSettings"/>.</returns> public static CombinedAudienceServiceSettings GetDefault() => new CombinedAudienceServiceSettings(); /// <summary> /// Constructs a new <see cref="CombinedAudienceServiceSettings"/> object with default settings. /// </summary> public CombinedAudienceServiceSettings() { } private CombinedAudienceServiceSettings(CombinedAudienceServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetCombinedAudienceSettings = existing.GetCombinedAudienceSettings; OnCopy(existing); } partial void OnCopy(CombinedAudienceServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CombinedAudienceServiceClient.GetCombinedAudience</c> and /// <c>CombinedAudienceServiceClient.GetCombinedAudienceAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetCombinedAudienceSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CombinedAudienceServiceSettings"/> object.</returns> public CombinedAudienceServiceSettings Clone() => new CombinedAudienceServiceSettings(this); } /// <summary> /// Builder class for <see cref="CombinedAudienceServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CombinedAudienceServiceClientBuilder : gaxgrpc::ClientBuilderBase<CombinedAudienceServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CombinedAudienceServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CombinedAudienceServiceClientBuilder() { UseJwtAccessWithScopes = CombinedAudienceServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CombinedAudienceServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CombinedAudienceServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CombinedAudienceServiceClient Build() { CombinedAudienceServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CombinedAudienceServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CombinedAudienceServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CombinedAudienceServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CombinedAudienceServiceClient.Create(callInvoker, Settings); } private async stt::Task<CombinedAudienceServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CombinedAudienceServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CombinedAudienceServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CombinedAudienceServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CombinedAudienceServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CombinedAudienceService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage combined audiences. This service can be used to list all /// your combined audiences with metadata, but won't show the structure and /// components of the combined audience. /// </remarks> public abstract partial class CombinedAudienceServiceClient { /// <summary> /// The default endpoint for the CombinedAudienceService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CombinedAudienceService scopes.</summary> /// <remarks> /// The default CombinedAudienceService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CombinedAudienceServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="CombinedAudienceServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CombinedAudienceServiceClient"/>.</returns> public static stt::Task<CombinedAudienceServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CombinedAudienceServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CombinedAudienceServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="CombinedAudienceServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CombinedAudienceServiceClient"/>.</returns> public static CombinedAudienceServiceClient Create() => new CombinedAudienceServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CombinedAudienceServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CombinedAudienceServiceSettings"/>.</param> /// <returns>The created <see cref="CombinedAudienceServiceClient"/>.</returns> internal static CombinedAudienceServiceClient Create(grpccore::CallInvoker callInvoker, CombinedAudienceServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CombinedAudienceService.CombinedAudienceServiceClient grpcClient = new CombinedAudienceService.CombinedAudienceServiceClient(callInvoker); return new CombinedAudienceServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CombinedAudienceService client</summary> public virtual CombinedAudienceService.CombinedAudienceServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CombinedAudience GetCombinedAudience(GetCombinedAudienceRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CombinedAudience> GetCombinedAudienceAsync(GetCombinedAudienceRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CombinedAudience> GetCombinedAudienceAsync(GetCombinedAudienceRequest request, st::CancellationToken cancellationToken) => GetCombinedAudienceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the combined audience to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CombinedAudience GetCombinedAudience(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCombinedAudience(new GetCombinedAudienceRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the combined audience to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CombinedAudience> GetCombinedAudienceAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCombinedAudienceAsync(new GetCombinedAudienceRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the combined audience to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CombinedAudience> GetCombinedAudienceAsync(string resourceName, st::CancellationToken cancellationToken) => GetCombinedAudienceAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the combined audience to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CombinedAudience GetCombinedAudience(gagvr::CombinedAudienceName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCombinedAudience(new GetCombinedAudienceRequest { ResourceNameAsCombinedAudienceName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the combined audience to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CombinedAudience> GetCombinedAudienceAsync(gagvr::CombinedAudienceName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCombinedAudienceAsync(new GetCombinedAudienceRequest { ResourceNameAsCombinedAudienceName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the combined audience to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CombinedAudience> GetCombinedAudienceAsync(gagvr::CombinedAudienceName resourceName, st::CancellationToken cancellationToken) => GetCombinedAudienceAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CombinedAudienceService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage combined audiences. This service can be used to list all /// your combined audiences with metadata, but won't show the structure and /// components of the combined audience. /// </remarks> public sealed partial class CombinedAudienceServiceClientImpl : CombinedAudienceServiceClient { private readonly gaxgrpc::ApiCall<GetCombinedAudienceRequest, gagvr::CombinedAudience> _callGetCombinedAudience; /// <summary> /// Constructs a client wrapper for the CombinedAudienceService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="CombinedAudienceServiceSettings"/> used within this client. /// </param> public CombinedAudienceServiceClientImpl(CombinedAudienceService.CombinedAudienceServiceClient grpcClient, CombinedAudienceServiceSettings settings) { GrpcClient = grpcClient; CombinedAudienceServiceSettings effectiveSettings = settings ?? CombinedAudienceServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetCombinedAudience = clientHelper.BuildApiCall<GetCombinedAudienceRequest, gagvr::CombinedAudience>(grpcClient.GetCombinedAudienceAsync, grpcClient.GetCombinedAudience, effectiveSettings.GetCombinedAudienceSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetCombinedAudience); Modify_GetCombinedAudienceApiCall(ref _callGetCombinedAudience); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetCombinedAudienceApiCall(ref gaxgrpc::ApiCall<GetCombinedAudienceRequest, gagvr::CombinedAudience> call); partial void OnConstruction(CombinedAudienceService.CombinedAudienceServiceClient grpcClient, CombinedAudienceServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CombinedAudienceService client</summary> public override CombinedAudienceService.CombinedAudienceServiceClient GrpcClient { get; } partial void Modify_GetCombinedAudienceRequest(ref GetCombinedAudienceRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::CombinedAudience GetCombinedAudience(GetCombinedAudienceRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCombinedAudienceRequest(ref request, ref callSettings); return _callGetCombinedAudience.Sync(request, callSettings); } /// <summary> /// Returns the requested combined audience in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::CombinedAudience> GetCombinedAudienceAsync(GetCombinedAudienceRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCombinedAudienceRequest(ref request, ref callSettings); return _callGetCombinedAudience.Async(request, callSettings); } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.Sockets { public enum IOControlCode : long { AbsorbRouterAlert = (long)2550136837, AddMulticastGroupOnInterface = (long)2550136842, AddressListChange = (long)671088663, AddressListQuery = (long)1207959574, AddressListSort = (long)3355443225, AssociateHandle = (long)2281701377, AsyncIO = (long)2147772029, BindToInterface = (long)2550136840, DataToRead = (long)1074030207, DeleteMulticastGroupFromInterface = (long)2550136843, EnableCircularQueuing = (long)671088642, Flush = (long)671088644, GetBroadcastAddress = (long)1207959557, GetExtensionFunctionPointer = (long)3355443206, GetGroupQos = (long)3355443208, GetQos = (long)3355443207, KeepAliveValues = (long)2550136836, LimitBroadcasts = (long)2550136839, MulticastInterface = (long)2550136841, MulticastScope = (long)2281701386, MultipointLoopback = (long)2281701385, NamespaceChange = (long)2281701401, NonBlockingIO = (long)2147772030, OobDataRead = (long)1074033415, QueryTargetPnpHandle = (long)1207959576, ReceiveAll = (long)2550136833, ReceiveAllIgmpMulticast = (long)2550136835, ReceiveAllMulticast = (long)2550136834, RoutingInterfaceChange = (long)2281701397, RoutingInterfaceQuery = (long)3355443220, SetGroupQos = (long)2281701388, SetQos = (long)2281701387, TranslateHandle = (long)3355443213, UnicastInterface = (long)2550136838, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct IPPacketInformation { public System.Net.IPAddress Address { get { return default(System.Net.IPAddress); } } public int Interface { get { return default(int); } } public override bool Equals(object comparand) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { return default(bool); } public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { return default(bool); } } public enum IPProtectionLevel { EdgeRestricted = 20, Restricted = 30, Unrestricted = 10, Unspecified = -1, } public partial class IPv6MulticastOption { public IPv6MulticastOption(System.Net.IPAddress group) { } public IPv6MulticastOption(System.Net.IPAddress group, long ifindex) { } public System.Net.IPAddress Group { get { return default(System.Net.IPAddress); } set { } } public long InterfaceIndex { get { return default(long); } set { } } } public partial class LingerOption { public LingerOption(bool enable, int seconds) { } public bool Enabled { get { return default(bool); } set { } } public int LingerTime { get { return default(int); } set { } } } public partial class MulticastOption { public MulticastOption(System.Net.IPAddress group) { } public MulticastOption(System.Net.IPAddress group, int interfaceIndex) { } public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { } public System.Net.IPAddress Group { get { return default(System.Net.IPAddress); } set { } } public int InterfaceIndex { get { return default(int); } set { } } public System.Net.IPAddress LocalAddress { get { return default(System.Net.IPAddress); } set { } } } public partial class NetworkStream : System.IO.Stream { public NetworkStream(System.Net.Sockets.Socket socket) { } public NetworkStream(System.Net.Sockets.Socket socket, bool ownsSocket) { } public override bool CanRead { get { return default(bool); } } public override bool CanSeek { get { return default(bool); } } public override bool CanTimeout { get { return default(bool); } } public override bool CanWrite { get { return default(bool); } } public virtual bool DataAvailable { get { return default(bool); } } public override long Length { get { return default(long); } } public override long Position { get { return default(long); } set { } } public override int ReadTimeout { get { return default(int); } set { } } public override int WriteTimeout { get { return default(int); } set { } } protected override void Dispose(bool disposing) { } ~NetworkStream() { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public override int Read(byte[] buffer, int offset, int size) { buffer = default(byte[]); return default(int); } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); } public override long Seek(long offset, System.IO.SeekOrigin origin) { return default(long); } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int size) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } } public enum ProtocolType { Ggp = 3, Icmp = 1, IcmpV6 = 58, Idp = 22, Igmp = 2, IP = 0, IPSecAuthenticationHeader = 51, IPSecEncapsulatingSecurityPayload = 50, IPv4 = 4, IPv6 = 41, IPv6DestinationOptions = 60, IPv6FragmentHeader = 44, IPv6HopByHopOptions = 0, IPv6NoNextHeader = 59, IPv6RoutingHeader = 43, Ipx = 1000, ND = 77, Pup = 12, Raw = 255, Spx = 1256, SpxII = 1257, Tcp = 6, Udp = 17, Unknown = -1, Unspecified = 0, } public enum SelectMode { SelectError = 2, SelectRead = 0, SelectWrite = 1, } public partial class SendPacketsElement { public SendPacketsElement(byte[] buffer) { } public SendPacketsElement(byte[] buffer, int offset, int count) { } public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { } public SendPacketsElement(string filepath) { } public SendPacketsElement(string filepath, int offset, int count) { } public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { } public byte[] Buffer { get { return default(byte[]); } } public int Count { get { return default(int); } } public bool EndOfPacket { get { return default(bool); } } public string FilePath { get { return default(string); } } public int Offset { get { return default(int); } } } public partial class Socket : System.IDisposable { public Socket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public Socket(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } } public int Available { get { return default(int); } } public bool Blocking { get { return default(bool); } set { } } public bool Connected { get { return default(bool); } } public bool DontFragment { get { return default(bool); } set { } } public bool DualMode { get { return default(bool); } set { } } public bool EnableBroadcast { get { return default(bool); } set { } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public bool IsBound { get { return default(bool); } } public System.Net.Sockets.LingerOption LingerState { get { return default(System.Net.Sockets.LingerOption); } set { } } public System.Net.EndPoint LocalEndPoint { get { return default(System.Net.EndPoint); } } public bool MulticastLoopback { get { return default(bool); } set { } } public bool NoDelay { get { return default(bool); } set { } } public static bool OSSupportsIPv4 { get { return default(bool); } } public static bool OSSupportsIPv6 { get { return default(bool); } } public System.Net.Sockets.ProtocolType ProtocolType { get { return default(System.Net.Sockets.ProtocolType); } } public int ReceiveBufferSize { get { return default(int); } set { } } public int ReceiveTimeout { get { return default(int); } set { } } public System.Net.EndPoint RemoteEndPoint { get { return default(System.Net.EndPoint); } } public int SendBufferSize { get { return default(int); } set { } } public int SendTimeout { get { return default(int); } set { } } public System.Net.Sockets.SocketType SocketType { get { return default(System.Net.Sockets.SocketType); } } public short Ttl { get { return default(short); } set { } } public System.Net.Sockets.Socket Accept() { return default(System.Net.Sockets.Socket); } public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public void Bind(System.Net.EndPoint localEP) { } public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { } public void Connect(System.Net.EndPoint remoteEP) { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] addresses, int port) { } public void Connect(string host, int port) { } public bool ConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public static bool ConnectAsync(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~Socket() { } public object GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { return default(object); } public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { return default(byte[]); } public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue) { return default(int); } public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue) { return default(int); } public void Listen(int backlog) { } public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { return default(bool); } public int Receive(byte[] buffer) { return default(int); } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public int Receive(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { return default(int); } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public bool ReceiveAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public int ReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(byte[] buffer, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { ipPacketInformation = default(System.Net.Sockets.IPPacketInformation); return default(int); } public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public static void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds) { } public int Send(byte[] buffer) { return default(int); } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public int Send(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { return default(int); } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(byte[] buffer, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public bool SendToAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, bool optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, object optionValue) { } public void Shutdown(System.Net.Sockets.SocketShutdown how) { } } public partial class SocketAsyncEventArgs : System.EventArgs, System.IDisposable { public SocketAsyncEventArgs() { } public System.Net.Sockets.Socket AcceptSocket { get { return default(System.Net.Sockets.Socket); } set { } } public byte[] Buffer { get { return default(byte[]); } } public System.Collections.Generic.IList<System.ArraySegment<byte>> BufferList { get { return default(System.Collections.Generic.IList<System.ArraySegment<byte>>); } set { } } public int BytesTransferred { get { return default(int); } } public System.Exception ConnectByNameError { get { return default(System.Exception); } } public System.Net.Sockets.Socket ConnectSocket { get { return default(System.Net.Sockets.Socket); } } public int Count { get { return default(int); } } public System.Net.Sockets.SocketAsyncOperation LastOperation { get { return default(System.Net.Sockets.SocketAsyncOperation); } } public int Offset { get { return default(int); } } public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { return default(System.Net.Sockets.IPPacketInformation); } } public System.Net.EndPoint RemoteEndPoint { get { return default(System.Net.EndPoint); } set { } } public System.Net.Sockets.SendPacketsElement[] SendPacketsElements { get { return default(System.Net.Sockets.SendPacketsElement[]); } set { } } public int SendPacketsSendSize { get { return default(int); } set { } } public System.Net.Sockets.SocketError SocketError { get { return default(System.Net.Sockets.SocketError); } set { } } public System.Net.Sockets.SocketFlags SocketFlags { get { return default(System.Net.Sockets.SocketFlags); } set { } } public object UserToken { get { return default(object); } set { } } public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs> Completed { add { } remove { } } public void Dispose() { } ~SocketAsyncEventArgs() { } protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { } public void SetBuffer(byte[] buffer, int offset, int count) { } public void SetBuffer(int offset, int count) { } } public enum SocketAsyncOperation { Accept = 1, Connect = 2, Disconnect = 3, None = 0, Receive = 4, ReceiveFrom = 5, ReceiveMessageFrom = 6, Send = 7, SendPackets = 8, SendTo = 9, } [System.FlagsAttribute] public enum SocketFlags { Broadcast = 1024, ControlDataTruncated = 512, DontRoute = 4, Multicast = 2048, None = 0, OutOfBand = 1, Partial = 32768, Peek = 2, Truncated = 256, } public enum SocketOptionLevel { IP = 0, IPv6 = 41, Socket = 65535, Tcp = 6, Udp = 17, } public enum SocketOptionName { AcceptConnection = 2, AddMembership = 12, AddSourceMembership = 15, BlockSource = 17, Broadcast = 32, BsdUrgent = 2, ChecksumCoverage = 20, Debug = 1, DontFragment = 14, DontLinger = -129, DontRoute = 16, DropMembership = 13, DropSourceMembership = 16, Error = 4103, ExclusiveAddressUse = -5, Expedited = 2, HeaderIncluded = 2, HopLimit = 21, IPOptions = 1, IPProtectionLevel = 23, IpTimeToLive = 4, IPv6Only = 27, KeepAlive = 8, Linger = 128, MaxConnections = 2147483647, MulticastInterface = 9, MulticastLoopback = 11, MulticastTimeToLive = 10, NoChecksum = 1, NoDelay = 1, OutOfBandInline = 256, PacketInformation = 19, ReceiveBuffer = 4098, ReceiveLowWater = 4100, ReceiveTimeout = 4102, ReuseAddress = 4, ReuseUnicastPort = 12295, SendBuffer = 4097, SendLowWater = 4099, SendTimeout = 4101, Type = 4104, TypeOfService = 3, UnblockSource = 18, UpdateAcceptContext = 28683, UpdateConnectContext = 28688, UseLoopback = 64, } // Review note: RemoteEndPoint definition includes the Address and Port. // PacketInformation includes Address and Interface (physical interface number). // The redundancy could be removed by replacing RemoteEndPoint with Port. // Alternative: // public struct SocketReceiveFromResult // { // public int ReceivedBytes; // public IPAddress Address; // public int Port; // } public struct SocketReceiveFromResult { public int ReceivedBytes; public EndPoint RemoteEndPoint; } // Alternative: // public struct SocketReceiveMessageFromResult // { // public int ReceivedBytes; // public SocketFlags SocketFlags; // public IPAddress Address; // public int Port; // public int Interface; // } public struct SocketReceiveMessageFromResult { public int ReceivedBytes; public SocketFlags SocketFlags; public EndPoint RemoteEndPoint; public IPPacketInformation PacketInformation; } public enum SocketShutdown { Both = 2, Receive = 0, Send = 1, } public static partial class SocketTaskExtensions { public static System.Threading.Tasks.Task<Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { return default(System.Threading.Tasks.Task<Socket>); } public static System.Threading.Tasks.Task<Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket acceptSocket) { return default(System.Threading.Tasks.Task<Socket>); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { return default(System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult>); } public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { return default(System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult>); } public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<int> SendToAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(System.Threading.Tasks.Task<int>); } } public enum SocketType { Dgram = 2, Raw = 3, Rdm = 4, Seqpacket = 5, Stream = 1, Unknown = -1, } public partial class TcpClient : System.IDisposable { public TcpClient() { } public TcpClient(System.Net.Sockets.AddressFamily family) { } protected bool Active { get { return default(bool); } set { } } public int Available { get { return default(int); } } public bool Connected { get { return default(bool); } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public System.Net.Sockets.LingerOption LingerState { get { return default(System.Net.Sockets.LingerOption); } set { } } public bool NoDelay { get { return default(bool); } set { } } public int ReceiveBufferSize { get { return default(int); } set { } } public int ReceiveTimeout { get { return default(int); } set { } } public int SendBufferSize { get { return default(int); } set { } } public int SendTimeout { get { return default(int); } set { } } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task ConnectAsync(string host, int port) { return default(System.Threading.Tasks.Task); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~TcpClient() { } public System.Net.Sockets.NetworkStream GetStream() { return default(System.Net.Sockets.NetworkStream); } } public partial class TcpListener { public TcpListener(System.Net.IPAddress localaddr, int port) { } public TcpListener(System.Net.IPEndPoint localEP) { } protected bool Active { get { return default(bool); } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public System.Net.EndPoint LocalEndpoint { get { return default(System.Net.EndPoint); } } public System.Net.Sockets.Socket Server { get { return default(System.Net.Sockets.Socket); } } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptSocketAsync() { return default(System.Threading.Tasks.Task<System.Net.Sockets.Socket>); } public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { return default(System.Threading.Tasks.Task<System.Net.Sockets.TcpClient>); } public bool Pending() { return default(bool); } public void Start() { } public void Start(int backlog) { } public void Stop() { } } public partial class UdpClient : System.IDisposable { public UdpClient() { } public UdpClient(int port) { } public UdpClient(int port, System.Net.Sockets.AddressFamily family) { } public UdpClient(System.Net.IPEndPoint localEP) { } public UdpClient(System.Net.Sockets.AddressFamily family) { } protected bool Active { get { return default(bool); } set { } } public int Available { get { return default(int); } } public bool DontFragment { get { return default(bool); } set { } } public bool EnableBroadcast { get { return default(bool); } set { } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public bool MulticastLoopback { get { return default(bool); } set { } } public short Ttl { get { return default(short); } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr, int ifindex) { } public void JoinMulticastGroup(int ifindex, System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { } public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { return default(System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult>); } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint) { return default(System.Threading.Tasks.Task<int>); } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { return default(System.Threading.Tasks.Task<int>); } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult> { public UdpReceiveResult(byte[] buffer, System.Net.IPEndPoint remoteEndPoint) { throw new System.NotImplementedException(); } public byte[] Buffer { get { return default(byte[]); } } public System.Net.IPEndPoint RemoteEndPoint { get { return default(System.Net.IPEndPoint); } } public bool Equals(System.Net.Sockets.UdpReceiveResult other) { return default(bool); } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { return default(bool); } public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { return default(bool); } } }
namespace Oculus.Platform { using System; using UnityEditor; using UnityEngine; // This classes implements a UI to edit the PlatformSettings class. // The UI is accessible from a the menu bar via: Oculus Platform -> Edit Settings [CustomEditor(typeof(PlatformSettings))] public class OculusPlatformSettingsEditor : Editor { private bool isUnityEditorSettingsExpanded; private bool isBuildSettingsExpanded; private WWW getAccessTokenRequest; private void OnEnable() { isUnityEditorSettingsExpanded = PlatformSettings.UseStandalonePlatform; #if UNITY_ANDROID isBuildSettingsExpanded = true; #else isBuildSettingsExpanded = false; #endif } [UnityEditor.MenuItem("Oculus Platform/Edit Settings")] public static void Edit() { UnityEditor.Selection.activeObject = PlatformSettings.Instance; } public override void OnInspectorGUI() { // // Application IDs section // GUIContent riftAppIDLabel = new GUIContent("Oculus Rift App Id [?]", "This AppID will be used when building to the Windows target."); GUIContent gearAppIDLabel = new GUIContent("Gear VR App Id [?]", "This AppID will be used when building to the Android target"); PlatformSettings.AppID = MakeTextBox(riftAppIDLabel, PlatformSettings.AppID); PlatformSettings.MobileAppID = MakeTextBox(gearAppIDLabel, PlatformSettings.MobileAppID); if (GUILayout.Button("Create / Find your app on https://dashboard.oculus.com")) { UnityEngine.Application.OpenURL("https://dashboard.oculus.com/"); } #if UNITY_ANDROID if (String.IsNullOrEmpty(PlatformSettings.MobileAppID)) { EditorGUILayout.HelpBox("Please enter a valid Gear VR App ID.", MessageType.Error); } else { var msg = "Configured to connect with App ID " + PlatformSettings.MobileAppID; EditorGUILayout.HelpBox(msg, MessageType.Info); } #else if (String.IsNullOrEmpty(PlatformSettings.AppID)) { EditorGUILayout.HelpBox("Please enter a valid Oculus Rift App ID.", MessageType.Error); } else { var msg = "Configured to connect with App ID " + PlatformSettings.AppID; EditorGUILayout.HelpBox(msg, MessageType.Info); } #endif EditorGUILayout.Separator(); // // Unity Editor Settings section // isUnityEditorSettingsExpanded = EditorGUILayout.Foldout(isUnityEditorSettingsExpanded, "Unity Editor Settings"); if (isUnityEditorSettingsExpanded) { GUIHelper.HInset(6, () => { bool HasTestAccessToken = !String.IsNullOrEmpty(StandalonePlatformSettings.OculusPlatformTestUserAccessToken); if (PlatformSettings.UseStandalonePlatform) { if (!HasTestAccessToken && (String.IsNullOrEmpty(StandalonePlatformSettings.OculusPlatformTestUserEmail) || String.IsNullOrEmpty(StandalonePlatformSettings.OculusPlatformTestUserPassword))) { EditorGUILayout.HelpBox("Please enter a valid user credentials.", MessageType.Error); } else { var msg = "The Unity editor will use the supplied test user credentials and operate in standalone mode. Some user data will be mocked."; EditorGUILayout.HelpBox(msg, MessageType.Info); } } else { var msg = "The Unity editor will use the user credentials from the Oculus application."; EditorGUILayout.HelpBox(msg, MessageType.Info); } var useStandaloneLabel = "Use Standalone Platform [?]"; var useStandaloneHint = "If this is checked your app will use a debug platform with the User info below. " + "Otherwise your app will connect to the Oculus Platform. This setting only applies to the Unity Editor"; PlatformSettings.UseStandalonePlatform = MakeToggle(new GUIContent(useStandaloneLabel, useStandaloneHint), PlatformSettings.UseStandalonePlatform); GUI.enabled = PlatformSettings.UseStandalonePlatform; if (!HasTestAccessToken) { var emailLabel = "Test User Email: "; var emailHint = "Test users can be configured at " + "https://dashboard.oculus.com/organizations/<your org ID>/testusers " + "however any valid Oculus account email may be used."; StandalonePlatformSettings.OculusPlatformTestUserEmail = MakeTextBox(new GUIContent(emailLabel, emailHint), StandalonePlatformSettings.OculusPlatformTestUserEmail); var passwdLabel = "Test User Password: "; var passwdHint = "Password associated with the email address."; StandalonePlatformSettings.OculusPlatformTestUserPassword = MakePasswordBox(new GUIContent(passwdLabel, passwdHint), StandalonePlatformSettings.OculusPlatformTestUserPassword); var isLoggingIn = (getAccessTokenRequest != null); var loginLabel = (!isLoggingIn) ? "Login" : "Logging in..."; GUI.enabled = !isLoggingIn; if (GUILayout.Button(loginLabel)) { WWWForm form = new WWWForm(); var headers = form.headers; headers.Add("Authorization", "Bearer OC|1141595335965881|"); form.AddField("email", StandalonePlatformSettings.OculusPlatformTestUserEmail); form.AddField("password", StandalonePlatformSettings.OculusPlatformTestUserPassword); // Start the WWW request to get the access token getAccessTokenRequest = new WWW("https://graph.oculus.com/login", form.data, headers); EditorApplication.update += GetAccessToken; } GUI.enabled = true; } else { var loggedInMsg = "Currently using the credentials associated with " + StandalonePlatformSettings.OculusPlatformTestUserEmail; EditorGUILayout.HelpBox(loggedInMsg, MessageType.Info); var logoutLabel = "Clear Credentials"; if (GUILayout.Button(logoutLabel)) { StandalonePlatformSettings.OculusPlatformTestUserAccessToken = ""; } } GUI.enabled = true; }); } EditorGUILayout.Separator(); // // Build Settings section // isBuildSettingsExpanded = EditorGUILayout.Foldout(isBuildSettingsExpanded, "Build Settings"); if (isBuildSettingsExpanded) { GUIHelper.HInset(6, () => { if (!PlayerSettings.virtualRealitySupported) { EditorGUILayout.HelpBox("VR Support isn't enabled in the Player Settings", MessageType.Warning); } else { EditorGUILayout.HelpBox("VR Support is enabled", MessageType.Info); } PlayerSettings.virtualRealitySupported = MakeToggle(new GUIContent("Virtual Reality Support"), PlayerSettings.virtualRealitySupported); PlayerSettings.bundleVersion = MakeTextBox(new GUIContent("Bundle Version"), PlayerSettings.bundleVersion); #if UNITY_5_3 || UNITY_5_4 || UNITY_5_5 PlayerSettings.bundleIdentifier = MakeTextBox(new GUIContent("Bundle Identifier"), PlayerSettings.bundleIdentifier); #else BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; PlayerSettings.SetApplicationIdentifier( buildTargetGroup, MakeTextBox( new GUIContent("Bundle Identifier"), PlayerSettings.GetApplicationIdentifier(buildTargetGroup))); #endif }); } EditorGUILayout.Separator(); } // Asyncronously fetch the access token with the given credentials private void GetAccessToken() { if (getAccessTokenRequest != null && getAccessTokenRequest.isDone) { // Clear the password StandalonePlatformSettings.OculusPlatformTestUserPassword = ""; if (String.IsNullOrEmpty(getAccessTokenRequest.error)) { var Response = JsonUtility.FromJson<OculusStandalonePlatformResponse>(getAccessTokenRequest.text); StandalonePlatformSettings.OculusPlatformTestUserAccessToken = Response.access_token; } GUI.changed = true; EditorApplication.update -= GetAccessToken; getAccessTokenRequest = null; } } private string MakeTextBox(GUIContent label, string variable) { return GUIHelper.MakeControlWithLabel(label, () => { GUI.changed = false; var result = EditorGUILayout.TextField(variable); SetDirtyOnGUIChange(); return result; }); } private string MakePasswordBox(GUIContent label, string variable) { return GUIHelper.MakeControlWithLabel(label, () => { GUI.changed = false; var result = EditorGUILayout.PasswordField(variable); SetDirtyOnGUIChange(); return result; }); } private bool MakeToggle(GUIContent label, bool variable) { return GUIHelper.MakeControlWithLabel(label, () => { GUI.changed = false; var result = EditorGUILayout.Toggle(variable); SetDirtyOnGUIChange(); return result; }); } private void SetDirtyOnGUIChange() { if (GUI.changed) { EditorUtility.SetDirty(PlatformSettings.Instance); GUI.changed = false; } } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using NLog.Common; using NLog.Internal; /// <summary> /// Base class for optimized file appenders. /// </summary> [SecuritySafeCritical] internal abstract class BaseFileAppender : IDisposable { #pragma warning disable S2245 // Make sure that using this pseudorandom number generator is safe here (Not security sensitive) private readonly Random _random = new Random(); #pragma warning restore S2245 // Make sure that using this pseudorandom number generator is safe here /// <summary> /// Initializes a new instance of the <see cref="BaseFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="createParameters">The create parameters.</param> protected BaseFileAppender(string fileName, ICreateFileParameters createParameters) { CreateFileParameters = createParameters; FileName = fileName; OpenTimeUtc = DateTime.UtcNow; // to be consistent with timeToKill in FileTarget.AutoClosingTimerCallback } /// <summary> /// Gets the path of the file, including file extension. /// </summary> /// <value>The name of the file.</value> public string FileName { get; } /// <summary> /// Gets or sets the creation time for a file associated with the appender. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The creation time of the file.</returns> public DateTime CreationTimeUtc { get => _creationTimeUtc; internal set { _creationTimeUtc = value; CreationTimeSource = Time.TimeSource.Current.FromSystemTime(value); // Performance optimization to skip converting every time } } DateTime _creationTimeUtc; /// <summary> /// Gets or sets the creation time for a file associated with the appender. Synchronized by <see cref="CreationTimeUtc"/> /// The time format is based on <see cref="NLog.Time.TimeSource" /> /// </summary> public DateTime CreationTimeSource { get; private set; } /// <summary> /// Gets the last time the file associated with the appender is opened. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The time the file was last opened.</returns> public DateTime OpenTimeUtc { get; private set; } /// <summary> /// Gets the file creation parameters. /// </summary> /// <value>The file creation parameters.</value> public ICreateFileParameters CreateFileParameters { get; private set; } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes.</param> public void Write(byte[] bytes) { Write(bytes, 0, bytes.Length); } public abstract void Write(byte[] bytes, int offset, int count); /// <summary> /// Flushes this instance. /// </summary> public abstract void Flush(); /// <summary> /// Closes this instance. /// </summary> public abstract void Close(); /// <summary> /// Gets the creation time for a file associated with the appender. The time returned is in Coordinated Universal /// Time [UTC] standard. /// </summary> /// <returns>The file creation time.</returns> public abstract DateTime? GetFileCreationTimeUtc(); /// <summary> /// Gets the length in bytes of the file associated with the appender. /// </summary> /// <returns>A long value representing the length of the file in bytes.</returns> public abstract long? GetFileLength(); /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } /// <summary> /// Creates the file stream. /// </summary> /// <param name="allowFileSharedWriting">If set to <c>true</c> sets the file stream to allow shared writing.</param> /// <param name="overrideBufferSize">If larger than 0 then it will be used instead of the default BufferSize for the FileStream.</param> /// <returns>A <see cref="FileStream"/> object which can be used to write to the file.</returns> protected FileStream CreateFileStream(bool allowFileSharedWriting, int overrideBufferSize = 0) { int currentDelay = CreateFileParameters.ConcurrentWriteAttemptDelay; InternalLogger.Trace("Opening {0} with allowFileSharedWriting={1}", FileName, allowFileSharedWriting); for (int i = 0; i < CreateFileParameters.ConcurrentWriteAttempts; ++i) { try { try { return TryCreateFileStream(allowFileSharedWriting, overrideBufferSize); } catch (DirectoryNotFoundException) { //we don't check the directory on beforehand, as that will really slow down writing. if (!CreateFileParameters.CreateDirs) { throw; } var directoryName = Path.GetDirectoryName(FileName); try { Directory.CreateDirectory(directoryName); } catch (DirectoryNotFoundException) { //if creating a directory failed, don't retry for this message (e.g the ConcurrentWriteAttempts below) throw new NLogRuntimeException("Could not create directory {0}", directoryName); } return TryCreateFileStream(allowFileSharedWriting, overrideBufferSize); } } catch (IOException) { if (!CreateFileParameters.ConcurrentWrites || i + 1 == CreateFileParameters.ConcurrentWriteAttempts) { throw; // rethrow } int actualDelay = _random.Next(currentDelay); InternalLogger.Warn("Attempt #{0} to open {1} failed. Sleeping for {2}ms", i, FileName, actualDelay); currentDelay *= 2; AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(actualDelay)); } } throw new InvalidOperationException("Should not be reached."); } #if !SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ && !NETSTANDARD [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects are disposed elsewhere")] private FileStream WindowsCreateFile(string fileName, bool allowFileSharedWriting, int overrideBufferSize) { int fileShare = Win32FileNativeMethods.FILE_SHARE_READ; if (allowFileSharedWriting) { fileShare |= Win32FileNativeMethods.FILE_SHARE_WRITE; } if (CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows) { fileShare |= Win32FileNativeMethods.FILE_SHARE_DELETE; } Microsoft.Win32.SafeHandles.SafeFileHandle handle = null; FileStream fileStream = null; try { handle = Win32FileNativeMethods.CreateFile( fileName, Win32FileNativeMethods.FileAccess.GenericWrite, fileShare, IntPtr.Zero, Win32FileNativeMethods.CreationDisposition.OpenAlways, CreateFileParameters.FileAttributes, IntPtr.Zero); if (handle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } fileStream = new FileStream(handle, FileAccess.Write, overrideBufferSize > 0 ? overrideBufferSize : CreateFileParameters.BufferSize); fileStream.Seek(0, SeekOrigin.End); return fileStream; } catch { fileStream?.Dispose(); if ((handle != null) && (!handle.IsClosed)) handle.Close(); throw; } } #endif private FileStream TryCreateFileStream(bool allowFileSharedWriting, int overrideBufferSize) { UpdateCreationTime(); #if !SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ && !NETSTANDARD try { if (!CreateFileParameters.ForceManaged && PlatformDetector.IsWin32 && !PlatformDetector.IsMono) { return WindowsCreateFile(FileName, allowFileSharedWriting, overrideBufferSize); } } catch (SecurityException) { InternalLogger.Debug("Could not use native Windows create file, falling back to managed filestream: {0}", FileName); } #endif FileShare fileShare = allowFileSharedWriting ? FileShare.ReadWrite : FileShare.Read; if (CreateFileParameters.EnableFileDelete) { fileShare |= FileShare.Delete; } return new FileStream( FileName, FileMode.Append, FileAccess.Write, fileShare, overrideBufferSize > 0 ? overrideBufferSize : CreateFileParameters.BufferSize); } private void UpdateCreationTime() { FileInfo fileInfo = new FileInfo(FileName); if (fileInfo.Exists) { CreationTimeUtc = fileInfo.LookupValidFileCreationTimeUtc().Value; } else { File.Create(FileName).Dispose(); CreationTimeUtc = DateTime.UtcNow; #if !SILVERLIGHT // Set the file's creation time to avoid being thwarted by Windows' Tunneling capabilities (https://support.microsoft.com/en-us/kb/172190). File.SetCreationTimeUtc(FileName, CreationTimeUtc); #endif } } protected static bool MonitorForEnableFileDeleteEvent(string fileName, ref DateTime lastSimpleMonitorCheckTimeUtc) { long ticksDelta = DateTime.UtcNow.Ticks - lastSimpleMonitorCheckTimeUtc.Ticks; if (ticksDelta > TimeSpan.TicksPerSecond || ticksDelta < -TimeSpan.TicksPerSecond) { lastSimpleMonitorCheckTimeUtc = DateTime.UtcNow; try { if (!File.Exists(fileName)) { return true; } } catch (Exception ex) { InternalLogger.Error(ex, "Failed to check if File.Exists {0}", fileName); return true; } } return 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.Linq; using Xunit; namespace System.Reflection.Emit.Tests { public class EnumBuilderMethodTests { public static IEnumerable<object[]> DefineLiteral_TestData() { yield return new object[] { typeof(byte), (byte)0 }; yield return new object[] { typeof(byte), (byte)1 }; yield return new object[] { typeof(sbyte), (sbyte)0 }; yield return new object[] { typeof(sbyte), (sbyte)1 }; yield return new object[] { typeof(ushort), (ushort)0 }; yield return new object[] { typeof(ushort), (ushort)1 }; yield return new object[] { typeof(short), (short)0 }; yield return new object[] { typeof(short), (short)1 }; yield return new object[] { typeof(uint), (uint)0 }; yield return new object[] { typeof(uint), (uint)1 }; yield return new object[] { typeof(int), 0 }; yield return new object[] { typeof(int), 1 }; yield return new object[] { typeof(ulong), (ulong)0 }; yield return new object[] { typeof(ulong), (ulong)1 }; yield return new object[] { typeof(long), (long)0 }; yield return new object[] { typeof(long), (long)1 }; yield return new object[] { typeof(char), (char)0 }; yield return new object[] { typeof(char), (char)1 }; yield return new object[] { typeof(bool), true }; yield return new object[] { typeof(bool), false }; yield return new object[] { typeof(float), 0f }; yield return new object[] { typeof(float), 1.1f }; yield return new object[] { typeof(double), 0d }; yield return new object[] { typeof(double), 1.1d }; } [Theory] [MemberData(nameof(DefineLiteral_TestData))] public void DefineLiteral(Type underlyingType, object literalValue) { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType); FieldBuilder literal = enumBuilder.DefineLiteral("FieldOne", literalValue); Assert.Equal("FieldOne", literal.Name); Assert.Equal(enumBuilder.Name, literal.DeclaringType.Name); Assert.Equal(FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal, literal.Attributes); Assert.Equal(enumBuilder.AsType(), literal.FieldType); Type createdEnum = enumBuilder.CreateTypeInfo().AsType(); FieldInfo createdLiteral = createdEnum.GetField("FieldOne"); Assert.Equal(createdEnum, createdLiteral.FieldType); if (literalValue is bool || literalValue is float || literalValue is double) { // EnumBuilder generates invalid data for non-integer enums Assert.Throws<FormatException>(() => createdLiteral.GetValue(null)); } else { Assert.Equal(Enum.ToObject(createdEnum, literalValue), createdLiteral.GetValue(null)); } } [Fact] public void DefineLiteral_NullLiteralName_ThrowsArgumentNullException() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int)); Assert.Throws<ArgumentNullException>("fieldName", () => enumBuilder.DefineLiteral(null, 1)); } [Theory] [InlineData("")] [InlineData("\0")] [InlineData("\0abc")] public void DefineLiteral_EmptyLiteralName_ThrowsArgumentException(string literalName) { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int)); Assert.Throws<ArgumentException>("fieldName", () => enumBuilder.DefineLiteral(literalName, 1)); } public static IEnumerable<object[]> DefineLiteral_InvalidLiteralValue_ThrowsArgumentException_TestData() { yield return new object[] { typeof(int), null }; yield return new object[] { typeof(int), (short)1 }; yield return new object[] { typeof(short), 1 }; yield return new object[] { typeof(float), 1d }; yield return new object[] { typeof(double), 1f }; yield return new object[] { typeof(IntPtr), (IntPtr)1 }; yield return new object[] { typeof(UIntPtr), (UIntPtr)1 }; yield return new object[] { typeof(int).MakePointerType(), 1 }; yield return new object[] { typeof(int).MakeByRefType(), 1 }; yield return new object[] { typeof(int[]), new int[] { 1 } }; yield return new object[] { typeof(int?), 1 }; yield return new object[] { typeof(int?), null }; yield return new object[] { typeof(string), null }; } [Theory] [MemberData(nameof(DefineLiteral_InvalidLiteralValue_ThrowsArgumentException_TestData))] public void DefineLiteral_InvalidLiteralValue_ThrowsArgumentException(Type underlyingType, object literalValue) { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType); Assert.Throws<ArgumentException>(null, () => enumBuilder.DefineLiteral("LiteralName", literalValue)); } public static IEnumerable<object[]> DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation_TestData() { yield return new object[] { typeof(DateTime), DateTime.Now }; yield return new object[] { typeof(string), "" }; ; } [Theory] [MemberData(nameof(DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation_TestData))] public void DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation(Type underlyingType, object literalValue) { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType); FieldBuilder literal = enumBuilder.DefineLiteral("LiteralName", literalValue); Assert.Throws<TypeLoadException>(() => enumBuilder.CreateTypeInfo()); } [Fact] public void IsAssignableFrom() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int)); Assert.False(enumBuilder.IsAssignableFrom(null)); Assert.True(enumBuilder.IsAssignableFrom(typeof(int).GetTypeInfo())); Assert.False(enumBuilder.IsAssignableFrom(typeof(short).GetTypeInfo())); } [Fact] public void GetElementType_ThrowsNotSupportedException() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int)); Assert.Throws<NotSupportedException>(() => enumBuilder.GetElementType()); } [Fact] public void MakeArrayType() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum"); Type arrayType = enumBuilder.MakeArrayType(); Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType); Assert.Equal("TestEnum[]", arrayType.Name); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(260)] public void MakeArrayType_Int(int rank) { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum"); Type arrayType = enumBuilder.MakeArrayType(rank); string ranks = rank == 1 ? "*" : string.Empty; for (int i = 1; i < rank; i++) { ranks += ","; } Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType); Assert.Equal($"TestEnum[{ranks}]", arrayType.Name); } [Theory] [InlineData(0)] [InlineData(-1)] public void MakeArrayType_Int_RankLessThanOne_ThrowsIndexOutOfRange(int rank) { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum"); Assert.Throws<IndexOutOfRangeException>(() => enumBuilder.MakeArrayType(rank)); } [Fact] public void MakeByRefType() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum"); Type arrayType = enumBuilder.MakeByRefType(); Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType); Assert.Equal("TestEnum&", arrayType.Name); } [Fact] public void MakePointerType() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum"); Type arrayType = enumBuilder.MakePointerType(); Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType); Assert.Equal("TestEnum*", arrayType.Name); } [Fact] public void SetCustomAttribute_ConstructorInfo_ByteArray() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int)); enumBuilder.CreateTypeInfo().AsType(); ConstructorInfo attributeConstructor = typeof(BoolAttribute).GetConstructor(new Type[] { typeof(bool) }); enumBuilder.SetCustomAttribute(attributeConstructor, new byte[] { 01, 00, 01 }); Attribute[] objVals = (Attribute[])CustomAttributeExtensions.GetCustomAttributes(enumBuilder, true).ToArray(); Assert.Equal(new BoolAttribute(true), objVals[0]); } [Fact] public void SetCustomAttribute_CustomAttributeBuilder() { EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int)); enumBuilder.CreateTypeInfo().AsType(); ConstructorInfo attributeConstructor = typeof(BoolAttribute).GetConstructor(new Type[] { typeof(bool) }); CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(attributeConstructor, new object[] { true }); enumBuilder.SetCustomAttribute(attributeBuilder); object[] objVals = enumBuilder.GetCustomAttributes(true).ToArray(); Assert.Equal(new BoolAttribute(true), objVals[0]); } public class BoolAttribute : Attribute { private bool _b; public BoolAttribute(bool myBool) { _b = myBool; } } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * 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. * - Neither the name of the openmetaverse.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using OpenMetaverse; namespace OpenMetaverse { /// <summary> /// /// </summary> public enum FieldType { /// <summary></summary> U8, /// <summary></summary> U16, /// <summary></summary> U32, /// <summary></summary> U64, /// <summary></summary> S8, /// <summary></summary> S16, /// <summary></summary> S32, /// <summary></summary> F32, /// <summary></summary> F64, /// <summary></summary> UUID, /// <summary></summary> BOOL, /// <summary></summary> Vector3, /// <summary></summary> Vector3d, /// <summary></summary> Vector4, /// <summary></summary> Quaternion, /// <summary></summary> IPADDR, /// <summary></summary> IPPORT, /// <summary></summary> Variable, /// <summary></summary> Fixed, /// <summary></summary> Single, /// <summary></summary> Multiple } /// <summary> /// /// </summary> public class MapField : IComparable { /// <summary></summary> public int KeywordPosition; /// <summary></summary> public string Name; /// <summary></summary> public FieldType Type; /// <summary></summary> public int Count; /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public int CompareTo(object obj) { MapField temp = (MapField)obj; if (this.KeywordPosition > temp.KeywordPosition) { return 1; } else { if(temp.KeywordPosition == this.KeywordPosition) { return 0; } else { return -1; } } } } /// <summary> /// /// </summary> public class MapBlock : IComparable { /// <summary></summary> public int KeywordPosition; /// <summary></summary> public string Name; /// <summary></summary> public int Count; /// <summary></summary> public List<MapField> Fields; /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public int CompareTo(object obj) { MapBlock temp = (MapBlock)obj; if (this.KeywordPosition > temp.KeywordPosition) { return 1; } else { if(temp.KeywordPosition == this.KeywordPosition) { return 0; } else { return -1; } } } } /// <summary> /// /// </summary> public class MapPacket { /// <summary></summary> public ushort ID; /// <summary></summary> public string Name; /// <summary></summary> public PacketFrequency Frequency; /// <summary></summary> public bool Trusted; /// <summary></summary> public bool Encoded; /// <summary></summary> public List<MapBlock> Blocks; } /// <summary> /// /// </summary> public class ProtocolManager { /// <summary></summary> public Dictionary<FieldType, int> TypeSizes; /// <summary></summary> public Dictionary<string, int> KeywordPositions; /// <summary></summary> public MapPacket[] LowMaps; /// <summary></summary> public MapPacket[] MediumMaps; /// <summary></summary> public MapPacket[] HighMaps; private GridClient Client; /// <summary> /// /// </summary> /// <param name="mapFile"></param> /// <param name="client"></param> public ProtocolManager(string mapFile, GridClient client) { Client = client; // Initialize the map arrays LowMaps = new MapPacket[65536]; MediumMaps = new MapPacket[256]; HighMaps = new MapPacket[256]; // Build the type size hash table TypeSizes = new Dictionary<FieldType,int>(); TypeSizes.Add(FieldType.U8, 1); TypeSizes.Add(FieldType.U16, 2); TypeSizes.Add(FieldType.U32, 4); TypeSizes.Add(FieldType.U64, 8); TypeSizes.Add(FieldType.S8, 1); TypeSizes.Add(FieldType.S16, 2); TypeSizes.Add(FieldType.S32, 4); TypeSizes.Add(FieldType.F32, 4); TypeSizes.Add(FieldType.F64, 8); TypeSizes.Add(FieldType.UUID, 16); TypeSizes.Add(FieldType.BOOL, 1); TypeSizes.Add(FieldType.Vector3, 12); TypeSizes.Add(FieldType.Vector3d, 24); TypeSizes.Add(FieldType.Vector4, 16); TypeSizes.Add(FieldType.Quaternion, 16); TypeSizes.Add(FieldType.IPADDR, 4); TypeSizes.Add(FieldType.IPPORT, 2); TypeSizes.Add(FieldType.Variable, -1); TypeSizes.Add(FieldType.Fixed, -2); KeywordPositions = new Dictionary<string, int>(); LoadMapFile(mapFile); } /// <summary> /// /// </summary> /// <param name="command"></param> /// <returns></returns> public MapPacket Command(string command) { foreach (MapPacket map in HighMaps) { if (map != null) { if (command == map.Name) { return map; } } } foreach (MapPacket map in MediumMaps) { if (map != null) { if (command == map.Name) { return map; } } } foreach (MapPacket map in LowMaps) { if (map != null) { if (command == map.Name) { return map; } } } throw new Exception("Cannot find map for command \"" + command + "\""); } /// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public MapPacket Command(byte[] data) { ushort command; if (data.Length < 5) { return null; } if (data[4] == 0xFF) { if ((byte)data[5] == 0xFF) { // Low frequency command = (ushort)(data[6] * 256 + data[7]); return Command(command, PacketFrequency.Low); } else { // Medium frequency command = (ushort)data[5]; return Command(command, PacketFrequency.Medium); } } else { // High frequency command = (ushort)data[4]; return Command(command, PacketFrequency.High); } } /// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="frequency"></param> /// <returns></returns> public MapPacket Command(ushort command, PacketFrequency frequency) { switch (frequency) { case PacketFrequency.High: return HighMaps[command]; case PacketFrequency.Medium: return MediumMaps[command]; case PacketFrequency.Low: return LowMaps[command]; } throw new Exception("Cannot find map for command \"" + command + "\" with frequency \"" + frequency + "\""); } /// <summary> /// /// </summary> public void PrintMap() { PrintOneMap(LowMaps, "Low "); PrintOneMap(MediumMaps, "Medium"); PrintOneMap(HighMaps, "High "); } /// <summary> /// /// </summary> /// <param name="map"></param> /// <param name="frequency"></param> private void PrintOneMap(MapPacket[] map, string frequency) { int i; for (i = 0; i < map.Length; ++i) { if (map[i] != null) { Console.WriteLine("{0} {1,5} - {2} - {3} - {4}", frequency, i, map[i].Name, map[i].Trusted ? "Trusted" : "Untrusted", map[i].Encoded ? "Unencoded" : "Zerocoded"); foreach (MapBlock block in map[i].Blocks) { if (block.Count == -1) { Console.WriteLine("\t{0,4} {1} (Variable)", block.KeywordPosition, block.Name); } else { Console.WriteLine("\t{0,4} {1} ({2})", block.KeywordPosition, block.Name, block.Count); } foreach (MapField field in block.Fields) { Console.WriteLine("\t\t{0,4} {1} ({2} / {3})", field.KeywordPosition, field.Name, field.Type, field.Count); } } } } } /// <summary> /// /// </summary> /// <param name="mapFile"></param> /// <param name="outputFile"></param> public static void DecodeMapFile(string mapFile, string outputFile) { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; try { using (BinaryReader map = new BinaryReader(new FileStream(mapFile, FileMode.Open))) { using (BinaryWriter output = new BinaryWriter(new FileStream(outputFile, FileMode.CreateNew))) { while ((nread = map.Read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.Write(buffer, 0, nread); } } } } catch (Exception e) { throw new Exception("Map file error", e); } } /// <summary> /// /// </summary> /// <param name="mapFile"></param> private void LoadMapFile(string mapFile) { ushort low = 1; ushort medium = 1; ushort high = 1; // Load the protocol map file try { using (FileStream map = new FileStream(mapFile, FileMode.Open, FileAccess.Read)) { using (StreamReader r = new StreamReader(map)) { r.BaseStream.Seek(0, SeekOrigin.Begin); string newline; string trimmedline; bool inPacket = false; bool inBlock = false; MapPacket currentPacket = null; MapBlock currentBlock = null; char[] trimArray = new char[] { ' ', '\t' }; // While not at the end of the file while (r.Peek() > -1) { #region ParseMap newline = r.ReadLine(); trimmedline = System.Text.RegularExpressions.Regex.Replace(newline, @"\s+", " "); trimmedline = trimmedline.Trim(trimArray); if (!inPacket) { // Outside of all packet blocks if (trimmedline == "{") { inPacket = true; } } else { // Inside of a packet block if (!inBlock) { // Inside a packet block, outside of the blocks if (trimmedline == "{") { inBlock = true; } else if (trimmedline == "}") { // Reached the end of the packet currentPacket.Blocks.Sort(); inPacket = false; } else { // The packet header #region ParsePacketHeader // Splice the string in to tokens string[] tokens = trimmedline.Split(new char[] { ' ', '\t' }); if (tokens.Length > 3) { //Hash packet name to insure correct keyword ordering KeywordPosition(tokens[0]); if (tokens[1] == "Fixed") { // Remove the leading "0x" if (tokens[2].Substring(0, 2) == "0x") { tokens[2] = tokens[2].Substring(2, tokens[2].Length - 2); } uint fixedID = UInt32.Parse(tokens[2], System.Globalization.NumberStyles.HexNumber); // Truncate the id to a short fixedID ^= 0xFFFF0000; LowMaps[fixedID] = new MapPacket(); LowMaps[fixedID].ID = (ushort)fixedID; LowMaps[fixedID].Frequency = PacketFrequency.Low; LowMaps[fixedID].Name = tokens[0]; LowMaps[fixedID].Trusted = (tokens[3] == "Trusted"); LowMaps[fixedID].Encoded = (tokens[4] == "Zerocoded"); LowMaps[fixedID].Blocks = new List<MapBlock>(); currentPacket = LowMaps[fixedID]; } else if (tokens[1] == "Low") { LowMaps[low] = new MapPacket(); LowMaps[low].ID = low; LowMaps[low].Frequency = PacketFrequency.Low; LowMaps[low].Name = tokens[0]; LowMaps[low].Trusted = (tokens[2] == "Trusted"); LowMaps[low].Encoded = (tokens[3] == "Zerocoded"); LowMaps[low].Blocks = new List<MapBlock>(); currentPacket = LowMaps[low]; low++; } else if (tokens[1] == "Medium") { MediumMaps[medium] = new MapPacket(); MediumMaps[medium].ID = medium; MediumMaps[medium].Frequency = PacketFrequency.Medium; MediumMaps[medium].Name = tokens[0]; MediumMaps[medium].Trusted = (tokens[2] == "Trusted"); MediumMaps[medium].Encoded = (tokens[3] == "Zerocoded"); MediumMaps[medium].Blocks = new List<MapBlock>(); currentPacket = MediumMaps[medium]; medium++; } else if (tokens[1] == "High") { HighMaps[high] = new MapPacket(); HighMaps[high].ID = high; HighMaps[high].Frequency = PacketFrequency.High; HighMaps[high].Name = tokens[0]; HighMaps[high].Trusted = (tokens[2] == "Trusted"); HighMaps[high].Encoded = (tokens[3] == "Zerocoded"); HighMaps[high].Blocks = new List<MapBlock>(); currentPacket = HighMaps[high]; high++; } else { Logger.Log("Unknown packet frequency", Helpers.LogLevel.Error, Client); } } #endregion } } else { if (trimmedline.Length > 0 && trimmedline.Substring(0, 1) == "{") { // A field #region ParseField MapField field = new MapField(); // Splice the string in to tokens string[] tokens = trimmedline.Split(new char[] { ' ', '\t' }); field.Name = tokens[1]; field.KeywordPosition = KeywordPosition(field.Name); field.Type = (FieldType)Enum.Parse(typeof(FieldType), tokens[2], true); if (tokens[3] != "}") { field.Count = Int32.Parse(tokens[3]); } else { field.Count = 1; } // Save this field to the current block currentBlock.Fields.Add(field); #endregion } else if (trimmedline == "}") { currentBlock.Fields.Sort(); inBlock = false; } else if (trimmedline.Length != 0 && trimmedline.Substring(0, 2) != "//") { // The block header #region ParseBlockHeader currentBlock = new MapBlock(); // Splice the string in to tokens string[] tokens = trimmedline.Split(new char[] { ' ', '\t' }); currentBlock.Name = tokens[0]; currentBlock.KeywordPosition = KeywordPosition(currentBlock.Name); currentBlock.Fields = new List<MapField>(); currentPacket.Blocks.Add(currentBlock); if (tokens[1] == "Single") { currentBlock.Count = 1; } else if (tokens[1] == "Multiple") { currentBlock.Count = Int32.Parse(tokens[2]); } else if (tokens[1] == "Variable") { currentBlock.Count = -1; } else { Logger.Log("Unknown block frequency", Helpers.LogLevel.Error, Client); } #endregion } } } #endregion } } } } catch (Exception e) { throw new Exception("Map file parsing error", e); ; } } private int KeywordPosition(string keyword) { if (KeywordPositions.ContainsKey(keyword)) { return KeywordPositions[keyword]; } int hash = 0; for (int i = 1; i < keyword.Length; i++) { hash = (hash + (int)(keyword[i])) * 2; } hash *= 2; hash &= 0x1FFF; int startHash = hash; while (KeywordPositions.ContainsValue(hash)) { hash++; hash &= 0x1FFF; if (hash == startHash) { //Give up looking, went through all values and they were all taken. throw new Exception("All hash values are taken. Failed to add keyword: " + keyword); } } KeywordPositions[keyword] = hash; return hash; } } }
// // 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. // #if !SILVERLIGHT namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Net; using System.Net.Mail; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using Xunit; public class MailTargetTests : NLogTestBase { [Fact] public void SimpleEmailTest() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", CC = "[email protected];[email protected]", Bcc = "[email protected];[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); Assert.Equal("server1", mock.Host); Assert.Equal(27, mock.Port); Assert.False(mock.EnableSsl); Assert.Null(mock.Credentials); var msg = mock.MessagesSent[0]; Assert.Equal("Hello from NLog", msg.Subject); Assert.Equal("[email protected]", msg.From.Address); Assert.Equal(1, msg.To.Count); Assert.Equal("[email protected]", msg.To[0].Address); Assert.Equal(2, msg.CC.Count); Assert.Equal("[email protected]", msg.CC[0].Address); Assert.Equal("[email protected]", msg.CC[1].Address); Assert.Equal(2, msg.Bcc.Count); Assert.Equal("[email protected]", msg.Bcc[0].Address); Assert.Equal("[email protected]", msg.Bcc[1].Address); Assert.Equal(msg.Body, "Info MyLogger log message 1"); } [Fact] public void MailTarget_WithNewlineInSubject_SendsMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", CC = "[email protected];[email protected]", Bcc = "[email protected];[email protected]", Subject = "Hello from NLog\n", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; } [Fact] public void NtlmEmailTest() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Ntlm, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(CredentialCache.DefaultNetworkCredentials, mock.Credentials); } [Fact] public void BasicAuthEmailTest() { try { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Basic, SmtpUserName = "${mdc:username}", SmtpPassword = "${mdc:password}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); MappedDiagnosticsContext.Set("username", "u1"); MappedDiagnosticsContext.Set("password", "p1"); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; var credential = mock.Credentials as NetworkCredential; Assert.NotNull(credential); Assert.Equal("u1", credential.UserName); Assert.Equal("p1", credential.Password); Assert.Equal(string.Empty, credential.Domain); } finally { MappedDiagnosticsContext.Clear(); } } [Fact] public void CsvLayoutTest() { var layout = new CsvLayout() { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", AddNewLines = true, Layout = layout, }; layout.Initialize(null); mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; string expectedBody = "name;level;message\nMyLogger1;Info;log message 1\nMyLogger2;Debug;log message 2\nMyLogger3;Error;log message 3\n"; Assert.Equal(expectedBody, msg.Body); } [Fact] public void PerMessageServer() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "${logger}.mydomain.com", Body = "${message}", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal("MyLogger1.mydomain.com", mock1.Host); Assert.Equal(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal("MyLogger2.mydomain.com", mock2.Host); Assert.Equal(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.Equal("log message 2\n", msg2.Body); } [Fact] public void ErrorHandlingTest() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "${logger}", Body = "${message}", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); var exceptions2 = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "ERROR", "log message 2").WithContinuation(exceptions2.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Null(exceptions[1]); Assert.NotNull(exceptions2[0]); Assert.Equal("Some SMTP error.", exceptions2[0].Message); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal("MyLogger1", mock1.Host); Assert.Equal(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal("ERROR", mock2.Host); Assert.Equal(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.Equal("log message 2\n", msg2.Body); } /// <summary> /// Tests that it is possible to user different email address for each log message, /// for example by using ${logger}, ${event-context} or any other layout renderer. /// </summary> [Fact] public void PerMessageAddress() { var mmt = new MockMailTarget { From = "[email protected]", To = "${logger}@foo.com", Body = "${message}", SmtpServer = "server1.mydomain.com", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.Equal(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.Equal(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.Equal("[email protected]", msg1.To[0].Address); Assert.Equal("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.Equal(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.Equal("[email protected]", msg2.To[0].Address); Assert.Equal("log message 2\n", msg2.Body); } [Fact] public void CustomHeaderAndFooter() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", AddNewLines = true, Layout = "${message}", Header = "First event: ${logger}", Footer = "Last event: ${logger}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; string expectedBody = "First event: MyLogger1\nlog message 1\nlog message 2\nlog message 3\nLast event: MyLogger3\n"; Assert.Equal(expectedBody, msg.Body); } [Fact] public void DefaultSmtpClientTest() { var mailTarget = new MailTarget(); var client = mailTarget.CreateSmtpClient(); Assert.IsType(typeof(MySmtpClient), client); } [Fact] public void ReplaceNewlinesWithBreakInHtmlMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Body = "${level}${newline}${logger}${newline}${message}", Html = true, ReplaceNewlineWithBrTagInHtml = true }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.True(messageSent.IsBodyHtml); var lines = messageSent.Body.Split(new[] { "<br/>" }, StringSplitOptions.RemoveEmptyEntries); Assert.True(lines.Length == 3); } [Fact] public void NoReplaceNewlinesWithBreakInHtmlMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Body = "${level}${newline}${logger}${newline}${message}", Html = true, ReplaceNewlineWithBrTagInHtml = false }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.True(messageSent.IsBodyHtml); var lines = messageSent.Body.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); Assert.True(lines.Length == 3); } [Fact] public void MailTarget_WithPriority_SendsMailWithPrioritySet() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Priority = "high" }; mmt.Initialize(null); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { })); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.High, messageSent.Priority); } [Fact] public void MailTarget_WithoutPriority_SendsMailWithNormalPriority() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", }; mmt.Initialize(null); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { })); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.Normal, messageSent.Priority); } [Fact] public void MailTarget_WithInvalidPriority_SendsMailWithNormalPriority() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", Priority = "invalidPriority" }; mmt.Initialize(null); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { })); var messageSent = mmt.CreatedMocks[0].MessagesSent[0]; Assert.Equal(MailPriority.Normal, messageSent.Priority); } [Fact] public void MailTarget_WithValidToAndEmptyCC_SendsMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", CC = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count); } [Fact] public void MailTarget_WithValidToAndEmptyBcc_SendsMail() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Bcc = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count); } [Fact] public void MailTarget_WithEmptyTo_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "[email protected]", To = "", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.NotNull(exceptions[0]); Assert.IsType<NLogRuntimeException>(exceptions[0]); } [Fact] public void MailTarget_WithEmptyFrom_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.NotNull(exceptions[0]); Assert.IsType<NLogRuntimeException>(exceptions[0]); } [Fact] public void MailTarget_WithEmptySmtpServer_ThrowsNLogRuntimeException() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.NotNull(exceptions[0]); Assert.IsType<NLogRuntimeException>(exceptions[0]); } [Fact] public void MailTargetInitialize_WithoutSpecifiedTo_ThrowsConfigException() { var mmt = new MockMailTarget { From = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null)); } [Fact] public void MailTargetInitialize_WithoutSpecifiedFrom_ThrowsConfigException() { var mmt = new MockMailTarget { To = "[email protected]", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null)); } [Fact] public void MailTargetInitialize_WithoutSpecifiedSmtpServer_should_not_ThrowsConfigException() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = true }; } [Fact] public void MailTargetInitialize_WithoutSpecifiedSmtpServer_ThrowsConfigException_if_UseSystemNetMailSettings() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", Subject = "Hello from NLog", SmtpPort = 27, Body = "${level} ${logger} ${message}", UseSystemNetMailSettings = false }; Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null)); } [Fact] public void MailTarget_WithoutSubject_SendsMessageWithDefaultSubject() { var mmt = new MockMailTarget { From = "[email protected]", To = "[email protected]", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.Equal(1, mock.MessagesSent.Count); Assert.Equal(string.Format("Message from NLog on {0}", Environment.MachineName), mock.MessagesSent[0].Subject); } public class MockSmtpClient : ISmtpClient { public MockSmtpClient() { this.MessagesSent = new List<MailMessage>(); } public string Host { get; set; } public int Port { get; set; } public int Timeout { get; set; } public ICredentialsByHost Credentials { get; set; } public bool EnableSsl { get; set; } public List<MailMessage> MessagesSent { get; private set; } public void Send(MailMessage msg) { if (string.IsNullOrEmpty(this.Host)) { throw new InvalidOperationException("Host is null or empty."); } this.MessagesSent.Add(msg); if (Host == "ERROR") { throw new InvalidOperationException("Some SMTP error."); } } public void Dispose() { } } public class MockMailTarget : MailTarget { public List<MockSmtpClient> CreatedMocks = new List<MockSmtpClient>(); internal override ISmtpClient CreateSmtpClient() { var mock = new MockSmtpClient(); CreatedMocks.Add(mock); return mock; } } } } #endif
// 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.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { 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 TrustedIdProvidersOperations. /// </summary> public static partial class TrustedIdProvidersOperationsExtensions { /// <summary> /// Creates or updates the specified trusted identity provider. During update, /// the trusted identity provider with the specified name will be replaced /// with this new provider /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to add the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for /// differentiation of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to create the create the trusted identity provider. /// </param> public static TrustedIdProvider CreateOrUpdate(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters) { return Task.Factory.StartNew(s => ((ITrustedIdProvidersOperations)s).CreateOrUpdateAsync(resourceGroupName, accountName, trustedIdProviderName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified trusted identity provider. During update, /// the trusted identity provider with the specified name will be replaced /// with this new provider /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to add the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for /// differentiation of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to create the create the trusted identity provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TrustedIdProvider> CreateOrUpdateAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, accountName, trustedIdProviderName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified trusted identity provider from the specified Data /// Lake Store account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to delete. /// </param> public static void Delete(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName) { Task.Factory.StartNew(s => ((ITrustedIdProvidersOperations)s).DeleteAsync(resourceGroupName, accountName, trustedIdProviderName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified trusted identity provider from the specified Data /// Lake Store account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, trustedIdProviderName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Data Lake Store trusted identity provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to retrieve. /// </param> public static TrustedIdProvider Get(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName) { return Task.Factory.StartNew(s => ((ITrustedIdProvidersOperations)s).GetAsync(resourceGroupName, accountName, trustedIdProviderName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Data Lake Store trusted identity provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to retrieve. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TrustedIdProvider> GetAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, string trustedIdProviderName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, trustedIdProviderName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity providers. /// </param> public static IPage<TrustedIdProvider> ListByAccount(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew(s => ((ITrustedIdProvidersOperations)s).ListByAccountAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity providers. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TrustedIdProvider>> ListByAccountAsync(this ITrustedIdProvidersOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<TrustedIdProvider> ListByAccountNext(this ITrustedIdProvidersOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((ITrustedIdProvidersOperations)s).ListByAccountNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<TrustedIdProvider>> ListByAccountNextAsync(this ITrustedIdProvidersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * 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 OpenSim.Framework; using OpenSim.Data.MySQL; using OpenMetaverse; using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL { public class MySQLGroupsData : IGroupsData { private MySqlGroupsGroupsHandler m_Groups; private MySqlGroupsMembershipHandler m_Membership; private MySqlGroupsRolesHandler m_Roles; private MySqlGroupsRoleMembershipHandler m_RoleMembership; private MySqlGroupsInvitesHandler m_Invites; private MySqlGroupsNoticesHandler m_Notices; private MySqlGroupsPrincipalsHandler m_Principals; public MySQLGroupsData(string connectionString, string realm) { m_Groups = new MySqlGroupsGroupsHandler(connectionString, realm + "_groups", realm + "_Store"); m_Membership = new MySqlGroupsMembershipHandler(connectionString, realm + "_membership"); m_Roles = new MySqlGroupsRolesHandler(connectionString, realm + "_roles"); m_RoleMembership = new MySqlGroupsRoleMembershipHandler(connectionString, realm + "_rolemembership"); m_Invites = new MySqlGroupsInvitesHandler(connectionString, realm + "_invites"); m_Notices = new MySqlGroupsNoticesHandler(connectionString, realm + "_notices"); m_Principals = new MySqlGroupsPrincipalsHandler(connectionString, realm + "_principals"); } #region groups table public bool StoreGroup(GroupData data) { return m_Groups.Store(data); } public GroupData RetrieveGroup(UUID groupID) { GroupData[] groups = m_Groups.Get("GroupID", groupID.ToString()); if (groups.Length > 0) return groups[0]; return null; } public GroupData RetrieveGroup(string name) { GroupData[] groups = m_Groups.Get("Name", name); if (groups.Length > 0) return groups[0]; return null; } public GroupData[] RetrieveGroups(string pattern) { if (string.IsNullOrEmpty(pattern)) pattern = "1 ORDER BY Name LIMIT 100"; else pattern = string.Format("Name LIKE '%{0}%' ORDER BY Name LIMIT 100", pattern); return m_Groups.Get(pattern); } public bool DeleteGroup(UUID groupID) { return m_Groups.Delete("GroupID", groupID.ToString()); } public int GroupsCount() { return (int)m_Groups.GetCount("Location=\"\""); } #endregion #region membership table public MembershipData[] RetrieveMembers(UUID groupID) { return m_Membership.Get("GroupID", groupID.ToString()); } public MembershipData RetrieveMember(UUID groupID, string pricipalID) { MembershipData[] m = m_Membership.Get(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), pricipalID }); if (m != null && m.Length > 0) return m[0]; return null; } public MembershipData[] RetrieveMemberships(string pricipalID) { return m_Membership.Get("PrincipalID", pricipalID.ToString()); } public bool StoreMember(MembershipData data) { return m_Membership.Store(data); } public bool DeleteMember(UUID groupID, string pricipalID) { return m_Membership.Delete(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), pricipalID }); } public int MemberCount(UUID groupID) { return (int)m_Membership.GetCount("GroupID", groupID.ToString()); } #endregion #region roles table public bool StoreRole(RoleData data) { return m_Roles.Store(data); } public RoleData RetrieveRole(UUID groupID, UUID roleID) { RoleData[] data = m_Roles.Get(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); if (data != null && data.Length > 0) return data[0]; return null; } public RoleData[] RetrieveRoles(UUID groupID) { //return m_Roles.RetrieveRoles(groupID); return m_Roles.Get("GroupID", groupID.ToString()); } public bool DeleteRole(UUID groupID, UUID roleID) { return m_Roles.Delete(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); } public int RoleCount(UUID groupID) { return (int)m_Roles.GetCount("GroupID", groupID.ToString()); } #endregion #region rolememberhip table public RoleMembershipData[] RetrieveRolesMembers(UUID groupID) { RoleMembershipData[] data = m_RoleMembership.Get("GroupID", groupID.ToString()); return data; } public RoleMembershipData[] RetrieveRoleMembers(UUID groupID, UUID roleID) { RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); return data; } public RoleMembershipData[] RetrieveMemberRoles(UUID groupID, string principalID) { RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), principalID.ToString() }); return data; } public RoleMembershipData RetrieveRoleMember(UUID groupID, UUID roleID, string principalID) { RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID", "PrincipalID" }, new string[] { groupID.ToString(), roleID.ToString(), principalID.ToString() }); if (data != null && data.Length > 0) return data[0]; return null; } public int RoleMemberCount(UUID groupID, UUID roleID) { return (int)m_RoleMembership.GetCount(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); } public bool StoreRoleMember(RoleMembershipData data) { return m_RoleMembership.Store(data); } public bool DeleteRoleMember(RoleMembershipData data) { return m_RoleMembership.Delete(new string[] { "GroupID", "RoleID", "PrincipalID"}, new string[] { data.GroupID.ToString(), data.RoleID.ToString(), data.PrincipalID }); } public bool DeleteMemberAllRoles(UUID groupID, string principalID) { return m_RoleMembership.Delete(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), principalID }); } #endregion #region principals table public bool StorePrincipal(PrincipalData data) { return m_Principals.Store(data); } public PrincipalData RetrievePrincipal(string principalID) { PrincipalData[] p = m_Principals.Get("PrincipalID", principalID); if (p != null && p.Length > 0) return p[0]; return null; } public bool DeletePrincipal(string principalID) { return m_Principals.Delete("PrincipalID", principalID); } #endregion #region invites table public bool StoreInvitation(InvitationData data) { return m_Invites.Store(data); } public InvitationData RetrieveInvitation(UUID inviteID) { InvitationData[] invites = m_Invites.Get("InviteID", inviteID.ToString()); if (invites != null && invites.Length > 0) return invites[0]; return null; } public InvitationData RetrieveInvitation(UUID groupID, string principalID) { InvitationData[] invites = m_Invites.Get(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), principalID }); if (invites != null && invites.Length > 0) return invites[0]; return null; } public bool DeleteInvite(UUID inviteID) { return m_Invites.Delete("InviteID", inviteID.ToString()); } public void DeleteOldInvites() { m_Invites.DeleteOld(); } #endregion #region notices table public bool StoreNotice(NoticeData data) { return m_Notices.Store(data); } public NoticeData RetrieveNotice(UUID noticeID) { NoticeData[] notices = m_Notices.Get("NoticeID", noticeID.ToString()); if (notices != null && notices.Length > 0) return notices[0]; return null; } public NoticeData[] RetrieveNotices(UUID groupID) { NoticeData[] notices = m_Notices.Get("GroupID", groupID.ToString()); return notices; } public bool DeleteNotice(UUID noticeID) { return m_Notices.Delete("NoticeID", noticeID.ToString()); } public void DeleteOldNotices() { m_Notices.DeleteOld(); } #endregion #region combinations public MembershipData RetrievePrincipalGroupMembership(string principalID, UUID groupID) { // TODO return null; } public MembershipData[] RetrievePrincipalGroupMemberships(string principalID) { // TODO return null; } #endregion } public class MySqlGroupsGroupsHandler : MySQLGenericTableHandler<GroupData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsGroupsHandler(string connectionString, string realm, string store) : base(connectionString, realm, store) { } } public class MySqlGroupsMembershipHandler : MySQLGenericTableHandler<MembershipData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsMembershipHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } public class MySqlGroupsRolesHandler : MySQLGenericTableHandler<RoleData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsRolesHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } public class MySqlGroupsRoleMembershipHandler : MySQLGenericTableHandler<RoleMembershipData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsRoleMembershipHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } public class MySqlGroupsInvitesHandler : MySQLGenericTableHandler<InvitationData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsInvitesHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } public void DeleteOld() { uint now = (uint)Util.UnixTimeSinceEpoch(); using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm); cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old ExecuteNonQuery(cmd); } } } public class MySqlGroupsNoticesHandler : MySQLGenericTableHandler<NoticeData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsNoticesHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } public void DeleteOld() { uint now = (uint)Util.UnixTimeSinceEpoch(); using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm); cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old ExecuteNonQuery(cmd); } } } public class MySqlGroupsPrincipalsHandler : MySQLGenericTableHandler<PrincipalData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsPrincipalsHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } }
using System; using System.Collections.Generic; using System.Linq; using Plugin.Connectivity.Abstractions; using Windows.Networking.Connectivity; using System.Threading.Tasks; using Windows.Networking.Sockets; using Windows.Networking; using System.Diagnostics; using Windows.ApplicationModel.Core; using System.Threading; namespace Plugin.Connectivity { /// <summary> /// Connectivity Implementation for WinRT /// </summary> public class ConnectivityImplementation : BaseConnectivity { bool isConnected; /// <summary> /// Default constructor /// </summary> public ConnectivityImplementation() { isConnected = IsConnected; NetworkInformation.NetworkStatusChanged += NetworkStatusChanged; } async void NetworkStatusChanged(object sender) { var previous = isConnected; var newConnected = IsConnected; var dispatcher = CoreApplication.MainView.CoreWindow?.Dispatcher; if (dispatcher != null) { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (previous != newConnected) OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = newConnected }); OnConnectivityTypeChanged(new ConnectivityTypeChangedEventArgs { IsConnected = newConnected, ConnectionTypes = this.ConnectionTypes }); }); } else { if (previous != newConnected) OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = newConnected }); OnConnectivityTypeChanged(new ConnectivityTypeChangedEventArgs { IsConnected = newConnected, ConnectionTypes = this.ConnectionTypes }); } } /// <summary> /// Gets if there is an active internet connection /// </summary> public override bool IsConnected { get { var profile = NetworkInformation.GetInternetConnectionProfile(); if (profile == null) isConnected = false; else { var level = profile.GetNetworkConnectivityLevel(); isConnected = level != NetworkConnectivityLevel.None && level != NetworkConnectivityLevel.LocalAccess; } return isConnected; } } /// <summary> /// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false. /// You can use it to check remote calls though. /// </summary> /// <param name="host"></param> /// <param name="msTimeout"></param> /// <returns></returns> public override async Task<bool> IsReachable(string host, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; try { var serverHost = new HostName(host); using (var client = new StreamSocket()) { var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(msTimeout); await client.ConnectAsync(serverHost, "http").AsTask(cancellationTokenSource.Token); return true; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } } /// <summary> /// Tests if a remote host name is reachable /// </summary> /// <param name="host">Host name can be a remote IP or URL of website</param> /// <param name="port">Port to attempt to check is reachable.</param> /// <param name="msTimeout">Timeout in milliseconds.</param> /// <returns></returns> public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; host = host.Replace("http://www.", string.Empty). Replace("http://", string.Empty). Replace("https://www.", string.Empty). Replace("https://", string.Empty). TrimEnd('/'); try { using (var tcpClient = new StreamSocket()) { var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(msTimeout); await tcpClient.ConnectAsync( new Windows.Networking.HostName(host), port.ToString(), SocketProtectionLevel.PlainSocket).AsTask(cancellationTokenSource.Token); var localIp = tcpClient.Information.LocalAddress.DisplayName; var remoteIp = tcpClient.Information.RemoteAddress.DisplayName; tcpClient.Dispose(); return true; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } } /// <summary> /// Gets the list of all active connection types. /// </summary> public override IEnumerable<ConnectionType> ConnectionTypes { get { var networkInterfaceList = NetworkInformation.GetConnectionProfiles(); foreach (var networkInterfaceInfo in networkInterfaceList.Where(networkInterfaceInfo => networkInterfaceInfo.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None)) { var type = ConnectionType.Other; if (networkInterfaceInfo.NetworkAdapter != null) { switch (networkInterfaceInfo.NetworkAdapter.IanaInterfaceType) { case 6: type = ConnectionType.Desktop; break; case 71: type = ConnectionType.WiFi; break; case 243: case 244: type = ConnectionType.Cellular; break; } } yield return type; } } } /// <summary> /// Retrieves a list of available bandwidths for the platform. /// Only active connections. /// </summary> public override IEnumerable<UInt64> Bandwidths { get { var networkInterfaceList = NetworkInformation.GetConnectionProfiles(); foreach (var networkInterfaceInfo in networkInterfaceList.Where(networkInterfaceInfo => networkInterfaceInfo.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None)) { UInt64 speed = 0; if (networkInterfaceInfo.NetworkAdapter != null) { speed = (UInt64)networkInterfaceInfo.NetworkAdapter.OutboundMaxBitsPerSecond; } yield return speed; } } } private bool disposed = false; /// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> public override void Dispose(bool disposing) { if (!disposed) { if (disposing) { NetworkInformation.NetworkStatusChanged -= NetworkStatusChanged; } disposed = true; } base.Dispose(disposing); } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { public static partial class Console { public static System.ConsoleColor BackgroundColor { get { return default(System.ConsoleColor); } set { } } public static void Beep() { } public static void Beep(int frequency, int duration) { } public static int BufferHeight { get { return default(int); } set { } } public static int BufferWidth { get { return default(int); } set { } } public static event System.ConsoleCancelEventHandler CancelKeyPress { add { } remove { } } public static void Clear() { } public static int CursorLeft { get { return default(int); } set { } } public static int CursorSize { get { return default(int); } set { } } public static int CursorTop { get { return default(int); } set { } } public static bool CursorVisible { get { return default(bool); } set { } } public static System.IO.TextWriter Error { get { return default(System.IO.TextWriter); } } public static System.ConsoleColor ForegroundColor { get { return default(System.ConsoleColor); } set { } } public static bool IsErrorRedirected { get { return false; } } public static bool IsInputRedirected { get { return false; } } public static bool IsOutputRedirected { get { return false; } } public static System.IO.TextReader In { get { return default(System.IO.TextReader); } } public static bool KeyAvailable { get { return default(bool); }} public static int LargestWindowWidth { get { return default(int); } } public static int LargestWindowHeight { get { return default(int); }} public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { } public static System.IO.Stream OpenStandardError() { return default(System.IO.Stream); } public static System.IO.Stream OpenStandardInput() { return default(System.IO.Stream); } public static System.IO.Stream OpenStandardOutput() { return default(System.IO.Stream); } public static System.IO.TextWriter Out { get { return default(System.IO.TextWriter); } } public static int Read() { return default(int); } public static ConsoleKeyInfo ReadKey() { return default(ConsoleKeyInfo); } public static ConsoleKeyInfo ReadKey(bool intercept) { return default(ConsoleKeyInfo); } public static string ReadLine() { return default(string); } public static void ResetColor() { } public static void SetBufferSize(int width, int height) { } public static void SetCursorPosition(int left, int top) { } public static void SetError(System.IO.TextWriter newError) { } public static void SetIn(System.IO.TextReader newIn) { } public static void SetOut(System.IO.TextWriter newOut) { } public static void SetWindowPosition(int left, int top) { } public static void SetWindowSize(int width, int height) { } public static string Title { get { return default(string); } set { } } public static int WindowHeight { get { return default(int); } set { } } public static int WindowWidth { get { return default(int); } set { } } public static int WindowLeft { get { return default(int); } set { } } public static int WindowTop { get { return default(int); } set { } } public static void Write(bool value) { } public static void Write(char value) { } public static void Write(char[] buffer) { } public static void Write(char[] buffer, int index, int count) { } public static void Write(decimal value) { } public static void Write(double value) { } public static void Write(int value) { } public static void Write(long value) { } public static void Write(object value) { } public static void Write(float value) { } public static void Write(string value) { } public static void Write(string format, object arg0) { } public static void Write(string format, object arg0, object arg1) { } public static void Write(string format, object arg0, object arg1, object arg2) { } public static void Write(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public static void Write(uint value) { } [System.CLSCompliantAttribute(false)] public static void Write(ulong value) { } public static void WriteLine() { } public static void WriteLine(bool value) { } public static void WriteLine(char value) { } public static void WriteLine(char[] buffer) { } public static void WriteLine(char[] buffer, int index, int count) { } public static void WriteLine(decimal value) { } public static void WriteLine(double value) { } public static void WriteLine(int value) { } public static void WriteLine(long value) { } public static void WriteLine(object value) { } public static void WriteLine(float value) { } public static void WriteLine(string value) { } public static void WriteLine(string format, object arg0) { } public static void WriteLine(string format, object arg0, object arg1) { } public static void WriteLine(string format, object arg0, object arg1, object arg2) { } public static void WriteLine(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public static void WriteLine(uint value) { } [System.CLSCompliantAttribute(false)] public static void WriteLine(ulong value) { } } public sealed partial class ConsoleCancelEventArgs : System.EventArgs { internal ConsoleCancelEventArgs() { } public bool Cancel { get { return default(bool); } set { } } public System.ConsoleSpecialKey SpecialKey { get { return default(System.ConsoleSpecialKey); } } } public delegate void ConsoleCancelEventHandler(object sender, System.ConsoleCancelEventArgs e); public enum ConsoleColor { Black = 0, Blue = 9, Cyan = 11, DarkBlue = 1, DarkCyan = 3, DarkGray = 8, DarkGreen = 2, DarkMagenta = 5, DarkRed = 4, DarkYellow = 6, Gray = 7, Green = 10, Magenta = 13, Red = 12, White = 15, Yellow = 14, } public partial struct ConsoleKeyInfo { public ConsoleKeyInfo(char keyChar, ConsoleKey key, bool shift, bool alt, bool control) { } public char KeyChar { get { return default(char); } } public ConsoleKey Key { get { return default(ConsoleKey); } } public ConsoleModifiers Modifiers { get { return default(ConsoleModifiers); ; } } } public enum ConsoleKey { Backspace = 0x8, Tab = 0x9, Clear = 0xC, Enter = 0xD, Pause = 0x13, Escape = 0x1B, Spacebar = 0x20, PageUp = 0x21, PageDown = 0x22, End = 0x23, Home = 0x24, LeftArrow = 0x25, UpArrow = 0x26, RightArrow = 0x27, DownArrow = 0x28, Select = 0x29, Print = 0x2A, Execute = 0x2B, PrintScreen = 0x2C, Insert = 0x2D, Delete = 0x2E, Help = 0x2F, D0 = 0x30, // 0 through 9 D1 = 0x31, D2 = 0x32, D3 = 0x33, D4 = 0x34, D5 = 0x35, D6 = 0x36, D7 = 0x37, D8 = 0x38, D9 = 0x39, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4A, K = 0x4B, L = 0x4C, M = 0x4D, N = 0x4E, O = 0x4F, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5A, Sleep = 0x5F, NumPad0 = 0x60, NumPad1 = 0x61, NumPad2 = 0x62, NumPad3 = 0x63, NumPad4 = 0x64, NumPad5 = 0x65, NumPad6 = 0x66, NumPad7 = 0x67, NumPad8 = 0x68, NumPad9 = 0x69, Multiply = 0x6A, Add = 0x6B, Separator = 0x6C, Subtract = 0x6D, Decimal = 0x6E, Divide = 0x6F, F1 = 0x70, F2 = 0x71, F3 = 0x72, F4 = 0x73, F5 = 0x74, F6 = 0x75, F7 = 0x76, F8 = 0x77, F9 = 0x78, F10 = 0x79, F11 = 0x7A, F12 = 0x7B, F13 = 0x7C, F14 = 0x7D, F15 = 0x7E, F16 = 0x7F, F17 = 0x80, F18 = 0x81, F19 = 0x82, F20 = 0x83, F21 = 0x84, F22 = 0x85, F23 = 0x86, F24 = 0x87, Oem1 = 0xBA, OemPlus = 0xBB, OemComma = 0xBC, OemMinus = 0xBD, OemPeriod = 0xBE, Oem2 = 0xBF, Oem3 = 0xC0, Oem4 = 0xDB, Oem5 = 0xDC, Oem6 = 0xDD, Oem7 = 0xDE, Oem8 = 0xDF, OemClear = 0xFE, } [Flags] public enum ConsoleModifiers { Alt = 1, Shift = 2, Control = 4 } public enum ConsoleSpecialKey { ControlBreak = 1, ControlC = 0, } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.CollectionPropertiesShouldBeReadOnlyAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.CollectionPropertiesShouldBeReadOnlyAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class CollectionPropertiesShouldBeReadOnlyTests { private static DiagnosticResult GetBasicResultAt(int line, int column, string propertyName) => VerifyVB.Diagnostic() .WithLocation(line, column) .WithArguments(propertyName); private static DiagnosticResult GetCSharpResultAt(int line, int column, string propertyName) => VerifyCS.Diagnostic() .WithLocation(line, column) .WithArguments(propertyName); [Fact] public async Task CSharp_CA2227_Test() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A { public System.Collections.ICollection Col { get; set; } } ", GetCSharpResultAt(6, 43, "Col")); } [Fact, WorkItem(1900, "https://github.com/dotnet/roslyn-analyzers/issues/1900")] public async Task CSharp_CA2227_Test_GenericCollection() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A { public System.Collections.Generic.ICollection<int> Col { get; set; } } ", GetCSharpResultAt(6, 56, "Col")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CSharp_CA2227_Test_Internal() { await VerifyCS.VerifyAnalyzerAsync(@" using System; internal class A { public System.Collections.ICollection Col { get; set; } } public class A2 { public System.Collections.ICollection Col { get; private set; } } public class A3 { internal System.Collections.ICollection Col { get; set; } } public class A4 { private class A5 { public System.Collections.ICollection Col { get; set; } } } "); } [Fact] public async Task Basic_CA2227_Test() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Class A Public Property Col As System.Collections.ICollection End Class ", GetBasicResultAt(5, 21, "Col")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task Basic_CA2227_Test_Internal() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Friend Class A Public Property Col As System.Collections.ICollection End Class Public Class A2 Public Property Col As System.Collections.ICollection Get Return Nothing End Get Private Set(value As System.Collections.ICollection) End Set End Property End Class Public Class A3 Friend Property Col As System.Collections.ICollection Get Return Nothing End Get Set(value As System.Collections.ICollection) End Set End Property End Class Public Class A4 Private Class A5 Public Property Col As System.Collections.ICollection Get Return Nothing End Get Set(value As System.Collections.ICollection) End Set End Property End Class End Class "); } [Fact] public async Task CSharp_CA2227_Inherited() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A<T> { public System.Collections.Generic.List<T> Col { get; set; } } ", GetCSharpResultAt(6, 47, "Col")); } [Fact] public async Task CSharp_CA2227_NotPublic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class A { internal System.Collections.ICollection Col { get; set; } protected System.Collections.ICollection Col2 { get; set; } private System.Collections.ICollection Col3 { get; set; } public System.Collections.ICollection Col4 { get; } public System.Collections.ICollection Col5 { get; protected set; } public System.Collections.ICollection Col6 { get; private set; } } "); } [Fact] public async Task CSharp_CA2227_Array() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A { public int[] Col { get; set; } } "); } [Fact] public async Task CSharp_CA2227_Indexer() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A { public System.Collections.ICollection this[int i] { get { throw new NotImplementedException(); } set { } } } "); } [Fact] public async Task CSharp_CA2227_NonCollection() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A { public string Name { get; set; } } "); } [Fact] [WorkItem(1900, "https://github.com/dotnet/roslyn-analyzers/issues/1900")] [WorkItem(3313, "https://github.com/dotnet/roslyn-analyzers/issues/3313")] public async Task CA2227_ReadOnlyCollections() { // Readonly interfaces don't implement ICollection/ICollection<T> so won't report a diagnostic await VerifyCS.VerifyAnalyzerAsync(@" using System.Collections.Generic; using System.Collections.ObjectModel; public class C { public IReadOnlyCollection<string> PI1 { get; protected set; } public IReadOnlyDictionary<string, int> PI2 { get; protected set; } public ReadOnlyCollection<string> P1 { get; protected set; } public ReadOnlyDictionary<string, int> P2 { get; protected set; } public ReadOnlyObservableCollection<string> P3 { get; protected set; } }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Collections.Generic Imports System.Collections.ObjectModel Public Class C Public Property PI1 As IReadOnlyCollection(Of String) Public Property PI2 As IReadOnlyDictionary(Of String, Integer) Public Property P1 As ReadOnlyCollection(Of String) Public Property P2 As ReadOnlyDictionary(Of String, Integer) Public Property P3 As ReadOnlyObservableCollection(Of String) End Class"); } [Fact, WorkItem(1900, "https://github.com/dotnet/roslyn-analyzers/issues/1900")] public async Task CSharp_CA2227_ImmutableCollection() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Collections.Immutable; public class A { public ImmutableArray<byte> ImmArray { get; set; } public ImmutableHashSet<string> ImmSet { get; set; } public ImmutableList<int> ImmList { get; set; } public ImmutableDictionary<A, int> ImmDictionary { get; set; } } "); } [Fact, WorkItem(1900, "https://github.com/dotnet/roslyn-analyzers/issues/1900")] public async Task CSharp_CA2227_ImmutableCollection_02() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Collections.Immutable; public class A { public IImmutableStack<byte> ImmStack { get; set; } public IImmutableQueue<byte> ImmQueue { get; set; } public IImmutableSet<string> ImmSet { get; set; } public IImmutableList<int> ImmList { get; set; } public IImmutableDictionary<A, int> ImmDictionary { get; set; } } "); } [Fact, WorkItem(1900, "https://github.com/dotnet/roslyn-analyzers/issues/1900")] public async Task CSharp_CA2227_ImmutableCollection_03() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; public class A { public CustomImmutableList ImmList { get; set; } } public class CustomImmutableList : IImmutableList<int>, ICollection<int> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public bool IsReadOnly => throw new NotImplementedException(); public IImmutableList<int> Add(int value) { throw new NotImplementedException(); } public IImmutableList<int> AddRange(IEnumerable<int> items) { throw new NotImplementedException(); } public IImmutableList<int> Clear() { throw new NotImplementedException(); } public bool Contains(int item) { throw new NotImplementedException(); } public void CopyTo(int[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<int> GetEnumerator() { throw new NotImplementedException(); } public int IndexOf(int item, int index, int count, IEqualityComparer<int> equalityComparer) { throw new NotImplementedException(); } public IImmutableList<int> Insert(int index, int element) { throw new NotImplementedException(); } public IImmutableList<int> InsertRange(int index, IEnumerable<int> items) { throw new NotImplementedException(); } public int LastIndexOf(int item, int index, int count, IEqualityComparer<int> equalityComparer) { throw new NotImplementedException(); } public IImmutableList<int> Remove(int value, IEqualityComparer<int> equalityComparer) { throw new NotImplementedException(); } public bool Remove(int item) { throw new NotImplementedException(); } public IImmutableList<int> RemoveAll(Predicate<int> match) { throw new NotImplementedException(); } public IImmutableList<int> RemoveAt(int index) { throw new NotImplementedException(); } public IImmutableList<int> RemoveRange(IEnumerable<int> items, IEqualityComparer<int> equalityComparer) { throw new NotImplementedException(); } public IImmutableList<int> RemoveRange(int index, int count) { throw new NotImplementedException(); } public IImmutableList<int> Replace(int oldValue, int newValue, IEqualityComparer<int> equalityComparer) { throw new NotImplementedException(); } public IImmutableList<int> SetItem(int index, int value) { throw new NotImplementedException(); } void ICollection<int>.Add(int item) { throw new NotImplementedException(); } void ICollection<int>.Clear() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } "); } [Fact] public async Task CSharp_CA2227_DataMember() { await VerifyCS.VerifyAnalyzerAsync(@" using System; namespace System.Runtime.Serialization { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)] public sealed class DataMemberAttribute : Attribute { } } class A { [System.Runtime.Serialization.DataMember] public System.Collections.ICollection Col { get; set; } } "); } } }
using System; using UnityEditor; using UnityEngine; using System.Reflection; using Vexe.Editor.Helpers; using UnityObject = UnityEngine.Object; namespace Vexe.Editor.GUIs { public class TurtleGUI : BaseGUI { private static HorizontalBlock horizontal; private static VerticalBlock vertical; private static MethodInfo gradientFieldMethod; public override Rect LastRect { get { return GUILayoutUtility.GetLastRect(); } } public override void OnGUI(Action code, Vector4 padding, int targetId) { code(); } public override Bounds BoundsField(GUIContent content, Bounds value, Layout option) { return EditorGUILayout.BoundsField(content, value, option); } public override void Box(GUIContent content, GUIStyle style, Layout option) { GUILayout.Box(content, style, option); } public override void HelpBox(string message, MessageType type) { EditorGUILayout.HelpBox(message, type); } public override bool Button(GUIContent content, GUIStyle style, Layout option, ControlType buttonType) { return GUILayout.Button(content, style, option); } public override Color Color(GUIContent content, Color value, Layout option) { return EditorGUILayout.ColorField(content, value, option); } public override Enum EnumPopup(GUIContent content, System.Enum selected, GUIStyle style, Layout option) { return EditorGUILayout.EnumPopup(content, selected, style, option); } public override float Float(GUIContent content, float value, Layout option) { return EditorGUILayout.FloatField(content, value, option); } public override int Int(GUIContent content, int value, Layout option) { return EditorGUILayout.IntField(content, value, option); } public override bool Foldout(GUIContent content, bool value, GUIStyle style, Layout option) { var rect = GUILayoutUtility.GetRect(content, style, option); return EditorGUI.Foldout(rect, value, content, true, style); } public override void Label(GUIContent content, GUIStyle style, Layout option) { GUILayout.Label(content, style, option); } public override int MaskField(GUIContent content, int mask, string[] displayedOptions, GUIStyle style, Layout option) { return EditorGUILayout.MaskField(content, mask, displayedOptions, style, option); } public override UnityObject Object(GUIContent content, UnityObject value, System.Type type, bool allowSceneObjects, Layout option) { // If we pass an empty content, ObjectField will still reserve space for an empty label ~__~ return string.IsNullOrEmpty(content.text) ? EditorGUILayout.ObjectField(value, type, allowSceneObjects, option) : EditorGUILayout.ObjectField(content, value, type, allowSceneObjects, option); } public override int Popup(string text, int selectedIndex, string[] displayedOptions, GUIStyle style, Layout option) { return EditorGUILayout.Popup(text, selectedIndex, displayedOptions, style, option); } public override Rect Rect(GUIContent content, Rect value, Layout option) { return EditorGUILayout.RectField(content, value, option); } public override AnimationCurve Curve (GUIContent content, AnimationCurve value, Layout option) { return EditorGUILayout.CurveField (content, value, option); } public override Gradient GradientField (GUIContent content, Gradient value, Layout option) { if (value == null) value = new Gradient (); return (Gradient)gradientFieldMethod.Invoke (null, new object[] { content, value, option }); } protected override void BeginScrollView(ref Vector2 pos, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, Layout option) { pos = GUILayout.BeginScrollView(pos, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background, option); } protected override void EndScrollView() { GUILayout.EndScrollView(); } public override float FloatSlider(GUIContent content, float value, float leftValue, float rightValue, Layout option) { return EditorGUILayout.Slider(content, value, leftValue, rightValue, option); } public override void Space(float pixels) { GUILayout.Space(pixels); } public override void FlexibleSpace() { GUILayout.FlexibleSpace(); } public override string Text(GUIContent content, string value, GUIStyle style, Layout option) { return EditorGUILayout.TextField(content, value, style, option); } public override string ToolbarSearch(string value, Layout option) { return GUIHelper.ToolbarSearchField_GL(null, new object[] { value, option.ToGLOptions() }) as string; } public override bool Toggle(GUIContent content, bool value, GUIStyle style, Layout option) { return EditorGUILayout.Toggle(content, value, style, option); } public override bool ToggleLeft(GUIContent content, bool value, GUIStyle labelStyle, Layout option) { return EditorGUILayout.ToggleLeft(content, value, labelStyle, option); } static TurtleGUI() { horizontal = new HorizontalBlock(); vertical = new VerticalBlock(); Type tyEditorGUILayout = typeof(EditorGUILayout); gradientFieldMethod = tyEditorGUILayout.GetMethod("GradientField", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(GUIContent), typeof(Gradient), typeof(GUILayoutOption[]) }, null); } public TurtleGUI() { horizontal.onDisposed = EndHorizontal; vertical.onDisposed = EndVertical; } protected override HorizontalBlock BeginHorizontal(GUIStyle style) { GUILayout.BeginHorizontal(style); return horizontal; } protected override VerticalBlock BeginVertical(GUIStyle style) { GUILayout.BeginVertical(style); return vertical; } protected override void EndHorizontal() { GUILayout.EndHorizontal(); } protected override void EndVertical() { GUILayout.EndVertical(); } public override string TextArea(string value, Layout option) { return EditorGUILayout.TextArea(value, option); } public override bool InspectorTitlebar(bool foldout, UnityObject target) { return EditorGUILayout.InspectorTitlebar(foldout, target); } public override string Tag(GUIContent content, string tag, GUIStyle style, Layout layout) { return EditorGUILayout.TagField(content, tag, style, layout); } public override int LayerField(GUIContent label, int layer, GUIStyle style, Layout layout) { return EditorGUILayout.LayerField(label, layer, style, layout); } public override void Prefix(string label) { EditorGUILayout.PrefixLabel(label); } public override string ScrollableTextArea(string value, ref Vector2 scrollPos, GUIStyle style, Layout option) { throw new NotImplementedException(); } public override string TextFieldDropDown(GUIContent label, string text, string[] displayedOptions, Layout option) { throw new NotImplementedException(); } public override double Double(GUIContent content, double value, Layout option) { return EditorGUILayout.DoubleField(content, value, option); } public override long Long(GUIContent content, long value, Layout option) { return EditorGUILayout.LongField(content, value, option); } public override IDisposable If(bool condition, IDisposable body) { throw new NotImplementedException(); } public override void MinMaxSlider(GUIContent label, ref float minValue, ref float maxValue, float minLimit, float maxLimit, Layout option) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Linq; using System.Runtime.InteropServices; using System.Xml; using Bloom.Book; using Bloom.Api; using Bloom.MiscUI; using Bloom.Utils; using Bloom.web; using Gecko; using SIL.Xml; using L10NSharp; using SIL.IO; using SIL.Reporting; namespace Bloom.Edit { /// <summary> /// Displays a list page thumbnails (the left column in Edit mode) using a separate Browser configured by /// pageThumbnailList.pug to load the React component specified in pageThumbnailList.tsx. /// The code here is tightly coupled to the code in pageThumbnailList.tsx and its dependencies, /// and also to the code in PageListApi which supports various callbacks to C# from the JS. /// Todo: rename this PageThumbnailList (but in another PR, with no other changes). /// </summary> public partial class WebThumbNailList : UserControl { public HtmlThumbNailer Thumbnailer; public event EventHandler PageSelectedChanged; private Bloom.Browser _browser; internal EditingModel Model; private static string _thumbnailInterval; private string _baseForRelativePaths; // Store this so we don't have to reload the thing from disk everytime we refresh the screen. private readonly string _baseHtml; private List<IPage> _pages; private bool _usingTwoColumns; /// <summary> /// The CSS class we give the main div for each page; the same element always has an id attr which identifies the page. /// </summary> private const string GridItemClass = "gridItem"; private const string PageContainerClass = "pageContainer"; // intended to be private except for initialization by PageListView internal PageListApi PageListApi { get => _pageListApi; set { _pageListApi = value; _pageListApi.PageList = this; } } internal BloomWebSocketServer WebSocketServer { get; set; } internal class MenuItemSpec { public string Label; public Func<IPage, bool> EnableFunction; // called to determine whether the item should be enabled. public Action<IPage> ExecuteCommand; // called when the item is chosen to perform the action. } // A list of menu items that should be in both the web browser'movedPageIdAndNewIndex right-click menu and // the one we show ourselves when the arrow is clicked. internal List<MenuItemSpec> ContextMenuItems { get; set; } public WebThumbNailList() { InitializeComponent(); if (!ReallyDesignMode) { _browser = new Browser(); _browser.BackColor = Color.DarkGray; _browser.Dock = DockStyle.Fill; _browser.Location = new Point(0, 0); _browser.Name = "_browser"; _browser.Size = new Size(150, 491); _browser.TabIndex = 0; _browser.VerticalScroll.Visible = false; Controls.Add(_browser); } // set the thumbnail interval based on physical RAM if (string.IsNullOrEmpty(_thumbnailInterval)) { var memInfo = MemoryManagement.GetMemoryInformation(); // We need to divide by 1024 three times rather than dividing by Math.Pow(1024, 3) because the // later will force floating point math, producing incorrect results. var physicalMemGb = Convert.ToDecimal(memInfo.TotalPhysicalMemory) / 1024 / 1024 / 1024; if (physicalMemGb < 2.5M) // less than 2.5 GB physical RAM { _thumbnailInterval = "400"; } else if (physicalMemGb < 4M) // less than 4 GB physical RAM { _thumbnailInterval = "200"; } else // 4 GB or more physical RAM { _thumbnailInterval = "100"; } } var frame = BloomFileLocator.GetBrowserFile(false, "bookEdit", "pageThumbnailList", "pageThumbnailList.html"); var backColor = MiscUtils.ColorToHtmlCode(BackColor); _baseHtml = RobustFile.ReadAllText(frame, Encoding.UTF8).Replace("DarkGray", backColor); } public Func<GeckoContextMenuEventArgs, bool> ContextMenuProvider { get { return _browser.ContextMenuProvider; } set { _browser.ContextMenuProvider = value; } } protected bool ReallyDesignMode => (base.DesignMode || GetService(typeof(IDesignerHost)) != null) || (LicenseManager.UsageMode == LicenseUsageMode.Designtime); private Stopwatch _stopwatch; private int _reportsSent; private void InvokePageSelectedChanged(IPage page) { EventHandler handler = PageSelectedChanged; // We're not really sure which of the two times will be shorter, // since there is SOME stuff that happens in C# after telling the browser // to navigate to the new page. This counts how many of the two reports have // been sent, so we can stop the watch when we're done with it. _reportsSent = 0; if (handler != null && /*REVIEW */ page != null) { _stopwatch = Stopwatch.StartNew(); Model.EditPagePainted += HandleEditPagePainted; handler(page, null); var time = _stopwatch.ElapsedMilliseconds; if (_reportsSent++ >= 2) _stopwatch.Stop(); TroubleShooterDialog.Report($"C# part of page change took {time} milliseconds"); } } void HandleEditPagePainted(object sender, EventArgs e) { var paintTime = _stopwatch.ElapsedMilliseconds; if (_reportsSent++ >= 2) _stopwatch.Stop(); TroubleShooterDialog.Report($"page change to paint complete took {paintTime} milliseconds"); Model.EditPagePainted -= HandleEditPagePainted; } public RelocatePageEvent RelocatePageEvent { get; set; } public void EmptyThumbnailCache() { // Prevents UpdateItemsInternal() from being able to enter into the early abort (optimization) condition. // Forces a full rebuild instead. _pages = null; } public void SelectPage(IPage page) { if (InvokeRequired) Invoke((Action)(() => SelectPageInternal(page))); else SelectPageInternal(page); } private void SelectPageInternal(IPage page) { if (PageListApi != null && PageListApi.SelectedPage != page) { PageListApi.SelectedPage = page; WebSocketServer.SendString("pageThumbnailList", "selecting", page.Id); } } public void SetItems(IEnumerable<IPage> pages) { _pages = UpdateItems(pages); } private bool RoomForTwoColumns => Width > 199; protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); if (_pages != null && _pages.Count > 0 && RoomForTwoColumns != _usingTwoColumns) UpdateItems(_pages); } private void OnPaneContentsChanging(bool hasPages) { // We try to prevent some spurious javascript errors by shutting down the websocket listener before // navigating to the new root page. This may not be entirely reliable as there is a race // condition between the navigation request and the reception of the stopListening message. WebSocketServer.SendString("pageThumbnailList", "stopListening", ""); } public void UpdateAllThumbnails() { UpdateItems(_pages); } private List<IPage> UpdateItems(IEnumerable<IPage> pages) { List<IPage> result = null; if (InvokeRequired) { Invoke((Action) (() => result = UpdateItemsInternal(pages))); } else { result = UpdateItemsInternal(pages); } return result; } private List<IPage> UpdateItemsInternal(IEnumerable<IPage> pages) { var result = pages.ToList(); // When it'movedPageIdAndNewIndex safe (we're not changing books etc), just send pageListNeedsRefresh to the web socket // and return result. (We need to skip(1) for the placeholder to get a meaningful book comparison) if (_pages != null && _pages.Skip(1).FirstOrDefault()?.Book == pages.Skip(1).FirstOrDefault()?.Book) { WebSocketServer.SendString("pageThumbnailList", "pageListNeedsRefresh", ""); return result; } OnPaneContentsChanging(result.Any()); if (result.FirstOrDefault(p => p.Book != null) == null || _browser.WebBrowser == null) { // If we don't already have a GeckoWebBrowser, we'll crash below (BL-9167). But if we // haven't already been initialized, then we don't have a thumbnail display to update // anyway. _browser.Navigate(@"about:blank", false); // no pages, we just want a blank screen, if anything. return new List<IPage>(); } _usingTwoColumns = RoomForTwoColumns; var sizeClass = result.Count > 1 ? Book.Layout.FromPage(result[1].GetDivNodeForThisPage(), Book.Layout.A5Portrait).SizeAndOrientation .ClassName : "A5Portrait"; // Somehow, the React code needs to know the page size, mainly so it can put the right class on // the pageContainer element in pageThumbnail.tsx. // - It could get it by parsing the HTML page content, but that'movedPageIdAndNewIndex clumsy and also really too late: // the pages are drawn empty before the page content is ever retrieved. // - we can't use the class on the page element because it is inside the pageContainer we need to affect // - we could put a sizeClass on the body or some other higher-level element, and rewrite the CSS // rules to look for pageContainer INSIDE a certain page class. But this seems risky. // Our expectation is that this class is applied to a page-level element. We don't want to // accidentally invoke some rule that makes the whole preview pane A5Portrait-shaped. // It also violates all our expectations, and forces us to do counter-intuitive things // like making pageContainer a certain size if it is 'inside' something that is A5Portrait. // So, I ended up putting a data-pageSize attribute on the body element, and having the // code that initializes React look for it and pass pageSize to the root React element // as it should be, a property. var htmlText = _baseHtml.Replace("data-pageSize=\"A5Portrait\"", $"data-pageSize=\"{sizeClass}\""); // We will end up navigating to pageListDom var pageListDom = new HtmlDom(XmlHtmlConverter.GetXmlDomFromHtml(htmlText)); if (SIL.PlatformUtilities.Platform.IsLinux) OptimizeForLinux(pageListDom); pageListDom = Model.CurrentBook.GetHtmlDomReadyToAddPages(pageListDom); _browser.WebBrowser.DocumentCompleted += WebBrowser_DocumentCompleted; _baseForRelativePaths = pageListDom.BaseForRelativePaths; _browser.Navigate(pageListDom, source:BloomServer.SimulatedPageFileSource.Pagelist); return result.ToList(); } private static void OptimizeForLinux(HtmlDom pageListDom) { // BL-987: Add styles to optimize performance on Linux var style = pageListDom.RawDom.CreateElement("style"); style.InnerXml = "img { image-rendering: optimizeSpeed; image-rendering: -moz-crisp-edges; image-rendering: crisp-edges; }"; pageListDom.RawDom.GetElementsByTagName("head")[0].AppendChild(style); } void WebBrowser_DocumentCompleted(object sender, Gecko.Events.GeckoDocumentCompletedEventArgs e) { SelectPage(PageListApi?.SelectedPage); _browser.WebBrowser.DocumentCompleted -= WebBrowser_DocumentCompleted; // need to do this only once } internal void PageClicked(IPage page) { InvokePageSelectedChanged(page); } internal void MenuClicked(IPage page) { var menu = new ContextMenuStrip(); if (page == null) return; foreach (var item in ContextMenuItems) { var useItem = item; // for use in Click action (reference to loop variable has unpredictable results) var menuItem = new ToolStripMenuItem(item.Label); menuItem.Click += (sender, args) => useItem.ExecuteCommand(page); menuItem.Enabled = item.EnableFunction(page); menu.Items.Add(menuItem); } if (SIL.PlatformUtilities.Platform.IsLinux) { // The LostFocus event is never received by the ContextMenuStrip on Linux/Mono, and the menu // stays open when the user clicks elsewhere in the Edit tool area of the Bloom window. // To minimize user frustration, we hook up the local browser and the EditingView browser // mouse click handlers to explicitly close the menu. Perhaps fixing the Mono bug would // be better, but I'd rather not go there if I don't have to. // See https://issues.bloomlibrary.org/youtrack/issue/BL-6753. _browser.OnBrowserClick += Browser_Click; Model.GetEditingBrowser().OnBrowserClick += Browser_Click; _popupPageMenu = menu; } menu.Show(MousePosition); } ContextMenuStrip _popupPageMenu; private PageListApi _pageListApi; private void Browser_Click(object sender, EventArgs e) { if (_popupPageMenu != null) { _popupPageMenu.Close(ToolStripDropDownCloseReason.CloseCalled); _popupPageMenu = null; _browser.OnBrowserClick -= Browser_Click; Model.GetEditingBrowser().OnBrowserClick -= Browser_Click; } } /// <summary> /// Given a particular node (typically one the user right-clicked), determine whether it is clearly part of /// a particular page (inside a PageContainerClass div). /// If so, return the corresponding Page object. If not, return null. /// </summary> /// <param name="clickNode"></param> /// <returns></returns> internal IPage GetPageContaining(GeckoNode clickNode) { bool gotPageElt = false; for (var elt = clickNode as GeckoElement ?? clickNode.ParentElement; elt != null; elt = elt.ParentElement) { var classAttr = elt.Attributes["class"]; if (classAttr != null) { var className = " " + classAttr.NodeValue + " "; if (className.Contains(" " + PageContainerClass + " ")) { // Click is inside a page element: can succeed. But we want to keep going to find the parent grid // element that has the ID we're looking for. gotPageElt = true; continue; } if (className.Contains(" " + GridItemClass + " ")) { if (!gotPageElt) return null; // clicked somewhere in a grid, but not actually on the page: intended page may be ambiguous. var id = elt.Attributes["id"].NodeValue; return PageListApi?.PageFromId(id); } } } return null; } // This gets invoked by Javascript (via the PageListApi) when it determines that a particular page has been moved. // newIndex is the (zero-based) index that the page is moving to // in the whole list of pages, including the placeholder. internal void PageMoved(IPage movedPage, int newPageIndex) { // accounts for placeholder. // Enhance: may not be needed in single-column mode, if we ever restore that. newPageIndex--; if (!movedPage.CanRelocate || !_pages[newPageIndex+1].CanRelocate) { var msg = LocalizationManager.GetString("EditTab.PageList.CantMoveXMatter", "That change is not allowed. Front matter and back matter pages must remain where they are."); //previously had a caption that didn't add value, just more translation work if (movedPage.Book.LockedDown) { msg = LocalizationManager.GetString("PageList.CantMoveWhenTranslating", "Pages can not be re-ordered when you are translating a book."); msg = msg + System.Environment.NewLine + EditingView.GetInstructionsForUnlockingBook(); } MessageBox.Show(msg); WebSocketServer.SendString("pageThumbnailList", "pageListNeedsReset", ""); return; } Model.SaveNow(); var relocatePageInfo = new RelocatePageInfo(movedPage, newPageIndex); RelocatePageEvent.Raise(relocatePageInfo); UpdateItems(movedPage.Book.GetPages()); PageSelectedChanged(movedPage, new EventArgs()); } public void UpdateThumbnailAsync(IPage page) { if (page.Book.Storage.NormalBaseForRelativepaths != _baseForRelativePaths) { // book has been renamed! can't go on with old document that pretends to be in the wrong place. // Regenerate completely. UpdateItems(_pages); return; } WebSocketServer.SendString("pageThumbnailList", "pageNeedsRefresh", page.Id); } public ControlKeyEvent ControlKeyEvent { set { if (_browser != null) _browser.ControlKeyEvent = value; } } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.BitStamp.BitStamp File: BitStampMessageAdapter_MarketData.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.BitStamp { using System; using System.Linq; using Ecng.Collections; using Ecng.Common; using MoreLinq; using StockSharp.Algo; using StockSharp.BitStamp.Native; using StockSharp.Messages; /// <summary> /// The message adapter for BitStamp. /// </summary> partial class BitStampMessageAdapter { private readonly CachedSynchronizedSet<SecurityId> _subscribedDepths = new CachedSynchronizedSet<SecurityId>(); private readonly CachedSynchronizedSet<SecurityId> _subscribedTicks = new CachedSynchronizedSet<SecurityId>(); private DateTimeOffset _prevLevel1Time; private static readonly TimeSpan _level1Interval = TimeSpan.FromSeconds(10); private void SessionOnNewTrade(Trade trade) { SendOutMessage(new ExecutionMessage { ExecutionType = ExecutionTypes.Tick, SecurityId = _btcUsd, TradeId = trade.Id, TradePrice = (decimal)trade.Price, TradeVolume = (decimal)trade.Amount, ServerTime = CurrentTime.Convert(TimeZoneInfo.Utc), }); } private void SessionOnNewOrderBook(OrderBook book) { SendOutMessage(new QuoteChangeMessage { SecurityId = _btcUsd, Bids = book.Bids.Select(b => b.ToStockSharp(Sides.Buy)), Asks = book.Asks.Select(b => b.ToStockSharp(Sides.Sell)), ServerTime = CurrentTime.Convert(TimeZoneInfo.Utc), }); } private void ProcessMarketData(MarketDataMessage mdMsg) { switch (mdMsg.DataType) { case MarketDataTypes.Level1: { //if (mdMsg.IsSubscribe) // _subscribedLevel1.Add(secCode); //else // _subscribedLevel1.Remove(secCode); break; } case MarketDataTypes.MarketDepth: { if (mdMsg.IsSubscribe) { _subscribedDepths.Add(mdMsg.SecurityId); if (_subscribedDepths.Count == 1) _pusherClient.SubscribeDepths(); } else { _subscribedDepths.Remove(mdMsg.SecurityId); if (_subscribedDepths.Count == 0) _pusherClient.UnSubscribeDepths(); } break; } case MarketDataTypes.Trades: { if (mdMsg.IsSubscribe) { if (mdMsg.From != null && mdMsg.From.Value.IsToday()) { _httpClient.RequestTransactions().Select(t => new ExecutionMessage { ExecutionType = ExecutionTypes.Tick, SecurityId = _btcUsd, TradeId = t.Id, TradePrice = (decimal)t.Price, TradeVolume = (decimal)t.Amount, ServerTime = t.Time.ApplyTimeZone(TimeZoneInfo.Utc) }).ForEach(SendOutMessage); } _subscribedTicks.Add(mdMsg.SecurityId); if (_subscribedTicks.Count == 1) _pusherClient.SubscribeTrades(); } else { _subscribedTicks.Remove(mdMsg.SecurityId); if (_subscribedTicks.Count == 0) _pusherClient.UnSubscribeTrades(); } break; } default: { SendOutMarketDataNotSupported(mdMsg.TransactionId); return; } } var reply = (MarketDataMessage)mdMsg.Clone(); reply.OriginalTransactionId = mdMsg.OriginalTransactionId; SendOutMessage(reply); } private void ProcessSecurityLookup(SecurityLookupMessage message) { SendOutMessage(new SecurityMessage { OriginalTransactionId = message.TransactionId, SecurityId = _btcUsd, SecurityType = SecurityTypes.CryptoCurrency, VolumeStep = 0.00000001m, PriceStep = 0.01m, }); SendOutMessage(new SecurityMessage { OriginalTransactionId = message.TransactionId, SecurityId = _eurUsd, SecurityType = SecurityTypes.Currency, PriceStep = 0.0001m, }); SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = message.TransactionId }); } private void ProcessLevel1() { var currTime = CurrentTime; if ((currTime - _prevLevel1Time) < _level1Interval) return; _prevLevel1Time = currTime; var btcUsd = _httpClient.RequestBtcUsd(); if (btcUsd != null) { SendOutMessage(new Level1ChangeMessage { SecurityId = _btcUsd, ServerTime = btcUsd.Time.ApplyTimeZone(TimeZoneInfo.Utc) } .TryAdd(Level1Fields.HighBidPrice, (decimal)btcUsd.High) .TryAdd(Level1Fields.LowAskPrice, (decimal)btcUsd.Low) .TryAdd(Level1Fields.VWAP, (decimal)btcUsd.VWAP) .TryAdd(Level1Fields.LastTradePrice, (decimal)btcUsd.Last) .TryAdd(Level1Fields.Volume, (decimal)btcUsd.Volume) .TryAdd(Level1Fields.BestBidPrice, (decimal)btcUsd.Bid) .TryAdd(Level1Fields.BestAskPrice, (decimal)btcUsd.Ask)); } var eurUsd = _httpClient.RequestEurUsd(); if (eurUsd != null) { SendOutMessage(new Level1ChangeMessage { SecurityId = _eurUsd, ServerTime = CurrentTime.Convert(TimeZoneInfo.Utc), } .TryAdd(Level1Fields.BestBidPrice, (decimal)eurUsd.Buy) .TryAdd(Level1Fields.BestAskPrice, (decimal)eurUsd.Sell)); } } } }
#pragma warning disable SA1633 // File should have header - This is an imported file, // original header with license shall remain the same /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet * The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangSwedishModel.cpp * and adjusted to language specific support. */ namespace UtfUnknown.Core.Models.SingleByte.Swedish; internal class Iso_8859_1_SwedishModel : SwedishModel { // Generated by BuildLangModel.py // On: 2016-09-28 22:29:21.480940 // Character Mapping Table: // ILL: illegal character. // CTR: control character specific to the charset. // RET: carriage/return. // SYM: symbol (punctuation) that does not belong to word. // NUM: 0 - 9. // Other characters are ordered by probabilities // (0 is the most common character in the language). // Orders are generic to a language. So the codepoint with order X in // CHARSET1 maps to the same character as the codepoint with the same // order X in CHARSET2 for the same language. // As such, it is possible to get missing order. For instance the // ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 // even though they are both used for French. Same for the euro sign. private static byte[] CHAR_TO_ORDER_MAP = { CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, RET, CTR, CTR, RET, CTR, CTR, /* 0X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 1X */ SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* 2X */ NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, SYM, SYM, SYM, SYM, SYM, SYM, /* 3X */ SYM, 0, 22, 20, 9, 1, 14, 12, 18, 6, 23, 10, 7, 11, 3, 8, /* 4X */ 15, 30, 2, 5, 4, 16, 13, 26, 25, 24, 27, SYM, SYM, SYM, SYM, SYM, /* 5X */ SYM, 0, 22, 20, 9, 1, 14, 12, 18, 6, 23, 10, 7, 11, 3, 8, /* 6X */ 15, 30, 2, 5, 4, 16, 13, 26, 25, 24, 27, SYM, SYM, SYM, SYM, CTR, /* 7X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 8X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 9X */ SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* AX */ SYM, SYM, SYM, SYM, SYM, 128, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* BX */ 129, 44, 130, 131, 17, 19, 38, 40, 32, 28, 45, 132, 133, 134, 47, 135, /* CX */ 136, 137, 138, 139, 35, 140, 21, SYM, 37, 141, 142, 143, 31, 144, 145, 146, /* DX */ 147, 44, 148, 149, 17, 19, 38, 40, 32, 28, 45, 150, 151, 152, 47, 153, /* EX */ 154, 155, 156, 157, 35, 158, 21, SYM, 37, 159, 160, 161, 31, 162, 163, 164 /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ public Iso_8859_1_SwedishModel() : base( CHAR_TO_ORDER_MAP, CodepageName.ISO_8859_1) { } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.DataStructures; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Plugin; using Apache.Ignite.Core.Impl.Transactions; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native Ignite wrapper. /// </summary> internal class Ignite : IIgnite, ICluster { /** */ private readonly IgniteConfiguration _cfg; /** Grid name. */ private readonly string _name; /** Unmanaged node. */ private readonly IUnmanagedTarget _proc; /** Marshaller. */ private readonly Marshaller _marsh; /** Initial projection. */ private readonly ClusterGroupImpl _prj; /** Binary. */ private readonly Binary.Binary _binary; /** Binary processor. */ private readonly BinaryProcessor _binaryProc; /** Lifecycle handlers. */ private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers; /** Local node. */ private IClusterNode _locNode; /** Transactions facade. */ private readonly Lazy<TransactionsImpl> _transactions; /** Callbacks */ private readonly UnmanagedCallbacks _cbs; /** Node info cache. */ private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes = new ConcurrentDictionary<Guid, ClusterNodeImpl>(); /** Client reconnect task completion source. */ private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); /** Plugin processor. */ private readonly PluginProcessor _pluginProcessor; /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="name">Grid name.</param> /// <param name="proc">Interop processor.</param> /// <param name="marsh">Marshaller.</param> /// <param name="lifecycleHandlers">Lifecycle beans.</param> /// <param name="cbs">Callbacks.</param> public Ignite(IgniteConfiguration cfg, string name, IUnmanagedTarget proc, Marshaller marsh, IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) { Debug.Assert(cfg != null); Debug.Assert(proc != null); Debug.Assert(marsh != null); Debug.Assert(lifecycleHandlers != null); Debug.Assert(cbs != null); _cfg = cfg; _name = name; _proc = proc; _marsh = marsh; _lifecycleHandlers = lifecycleHandlers; _cbs = cbs; marsh.Ignite = this; _prj = new ClusterGroupImpl(proc, UU.ProcessorProjection(proc), marsh, this, null); _binary = new Binary.Binary(marsh); _binaryProc = new BinaryProcessor(UU.ProcessorBinaryProcessor(proc), marsh); cbs.Initialize(this); // Grid is not completely started here, can't initialize interop transactions right away. _transactions = new Lazy<TransactionsImpl>( () => new TransactionsImpl(UU.ProcessorTransactions(proc), marsh, GetLocalNode().Id)); // Set reconnected task to completed state for convenience. _clientReconnectTaskCompletionSource.SetResult(false); SetCompactFooter(); _pluginProcessor = new PluginProcessor(this); } /// <summary> /// Sets the compact footer setting. /// </summary> private void SetCompactFooter() { if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl)) { // If there is a Spring config, use setting from Spring, // since we ignore .NET config in legacy mode. var cfg0 = GetConfiguration().BinaryConfiguration; if (cfg0 != null) _marsh.CompactFooter = cfg0.CompactFooter; } } /// <summary> /// On-start routine. /// </summary> internal void OnStart() { PluginProcessor.OnIgniteStart(); foreach (var lifecycleBean in _lifecycleHandlers) lifecycleBean.OnStart(this); } /** <inheritdoc /> */ public string Name { get { return _name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ IIgnite IClusterGroup.Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _prj.ForNodes(GetLocalNode()); } /** <inheritdoc /> */ public ICompute GetCompute() { return _prj.ForServers().GetCompute(); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return ((IClusterGroup) _prj).ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return ((IClusterGroup) _prj).ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(ICollection<Guid> ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { IgniteArgumentCheck.NotNull(p, "p"); return _prj.ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _prj.ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _prj.ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _prj.ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _prj.ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _prj.ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForDaemons() { return _prj.ForDaemons(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); return _prj.ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _prj.ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _prj.ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _prj.ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _prj.ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _prj.ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _prj.GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _prj.GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _prj.GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _prj.GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy", Justification = "Proxy does not need to be disposed.")] public void Dispose() { Ignition.Stop(Name, true); } /// <summary> /// Internal stop routine. /// </summary> /// <param name="cancel">Cancel flag.</param> internal unsafe void Stop(bool cancel) { UU.IgnitionStop(_proc.Context, Name, cancel); _cbs.Cleanup(); } /// <summary> /// Called before node has stopped. /// </summary> internal void BeforeNodeStop() { var handler = Stopping; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called after node has stopped. /// </summary> internal void AfterNodeStop() { foreach (var bean in _lifecycleHandlers) bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop); var handler = Stopped; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { return Cache<TK, TV>(UU.ProcessorCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { return Cache<TK, TV>(UU.ProcessorGetOrCreateCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return GetOrCreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); configuration.Validate(Logger); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = BinaryUtils.Marshaller.StartMarshal(stream); configuration.Write(writer); if (nearConfiguration != null) { writer.WriteBoolean(true); nearConfiguration.Write(writer); } else writer.WriteBoolean(false); stream.SynchronizeOutput(); return Cache<TK, TV>(UU.ProcessorGetOrCreateCache(_proc, stream.MemoryPointer)); } } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { return Cache<TK, TV>(UU.ProcessorCreateCache(_proc, name)); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return CreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); configuration.Validate(Logger); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { // Use system marshaller: full footers, always unregistered mode. var writer = BinaryUtils.Marshaller.StartMarshal(stream); configuration.Write(writer); if (nearConfiguration != null) { writer.WriteBoolean(true); nearConfiguration.Write(writer); } else writer.WriteBoolean(false); stream.SynchronizeOutput(); return Cache<TK, TV>(UU.ProcessorCreateCache(_proc, stream.MemoryPointer)); } } /** <inheritdoc /> */ public void DestroyCache(string name) { UU.ProcessorDestroyCache(_proc, name); } /// <summary> /// Gets cache from specified native cache object. /// </summary> /// <param name="nativeCache">Native cache.</param> /// <param name="keepBinary">Keep binary flag.</param> /// <returns> /// New instance of cache wrapping specified native cache. /// </returns> public ICache<TK, TV> Cache<TK, TV>(IUnmanagedTarget nativeCache, bool keepBinary = false) { return new CacheImpl<TK, TV>(this, nativeCache, _marsh, false, keepBinary, false); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _locNode ?? (_locNode = GetNodes().FirstOrDefault(x => x.IsLocal) ?? ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal)); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _prj.PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _prj.TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _prj.Topology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _prj.ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _clientReconnectTaskCompletionSource.Task; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { return new DataStreamerImpl<TK, TV>(UU.ProcessorDataStreamer(_proc, cacheName, false), _marsh, cacheName, false); } /** <inheritdoc /> */ public IBinary GetBinary() { return _binary; } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string cacheName) { return new CacheAffinityImpl(UU.ProcessorAffinity(_proc, cacheName), _marsh, false, this); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return _transactions.Value; } /** <inheritdoc /> */ public IMessaging GetMessaging() { return _prj.GetMessaging(); } /** <inheritdoc /> */ public IEvents GetEvents() { return _prj.GetEvents(); } /** <inheritdoc /> */ public IServices GetServices() { return _prj.ForServers().GetServices(); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeLong = UU.ProcessorAtomicLong(_proc, name, initialValue, create); if (nativeLong == null) return null; return new AtomicLong(nativeLong, Marshaller, name); } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeSeq = UU.ProcessorAtomicSequence(_proc, name, initialValue, create); if (nativeSeq == null) return null; return new AtomicSequence(nativeSeq, Marshaller, name); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var refTarget = GetAtomicReferenceUnmanaged(name, initialValue, create); return refTarget == null ? null : new AtomicReference<T>(refTarget, Marshaller, name); } /// <summary> /// Gets the unmanaged atomic reference. /// </summary> /// <param name="name">The name.</param> /// <param name="initialValue">The initial value.</param> /// <param name="create">Create flag.</param> /// <returns>Unmanaged atomic reference, or null.</returns> private IUnmanagedTarget GetAtomicReferenceUnmanaged<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); // Do not allocate memory when default is not used. if (!create) return UU.ProcessorAtomicReference(_proc, name, 0, false); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); writer.Write(initialValue); Marshaller.FinishMarshal(writer); var memPtr = stream.SynchronizeOutput(); return UU.ProcessorAtomicReference(_proc, name, memPtr, true); } } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { using (var stream = IgniteManager.Memory.Allocate(1024).GetStream()) { UU.ProcessorGetIgniteConfiguration(_proc, stream.MemoryPointer); stream.SynchronizeInput(); return new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(stream), _cfg); } } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, UU.ProcessorCreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, UU.ProcessorGetOrCreateNearCache); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { using (var stream = IgniteManager.Memory.Allocate(1024).GetStream()) { UU.ProcessorGetCacheNames(_proc, stream.MemoryPointer); stream.SynchronizeInput(); var reader = _marsh.StartUnmarshal(stream); var res = new string[stream.ReadInt()]; for (int i = 0; i < res.Length; i++) res[i] = reader.ReadString(); return res; } } /** <inheritdoc /> */ public ILogger Logger { get { return _cbs.Log; } } /** <inheritdoc /> */ public event EventHandler Stopping; /** <inheritdoc /> */ public event EventHandler Stopped; /** <inheritdoc /> */ public event EventHandler ClientDisconnected; /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected; /** <inheritdoc /> */ public T GetPlugin<T>(string name) where T : class { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); return PluginProcessor.GetProvider(name).GetPlugin<T>(); } /// <summary> /// Gets or creates near cache. /// </summary> private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration, Func<IUnmanagedTarget, string, long, IUnmanagedTarget> func) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = BinaryUtils.Marshaller.StartMarshal(stream); configuration.Write(writer); stream.SynchronizeOutput(); return Cache<TK, TV>(func(_proc, name, stream.MemoryPointer)); } } /// <summary> /// Gets internal projection. /// </summary> /// <returns>Projection.</returns> internal ClusterGroupImpl ClusterGroup { get { return _prj; } } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Gets the binary processor. /// </summary> internal BinaryProcessor BinaryProcessor { get { return _binaryProc; } } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get { return _cfg; } } /// <summary> /// Handle registry. /// </summary> public HandleRegistry HandleRegistry { get { return _cbs.HandleRegistry; } } /// <summary> /// Updates the node information from stream. /// </summary> /// <param name="memPtr">Stream ptr.</param> public void UpdateNodeInfo(long memPtr) { var stream = IgniteManager.Memory.Get(memPtr).GetStream(); IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); var node = new ClusterNodeImpl(reader); node.Init(this); _nodes[node.Id] = node; } /// <summary> /// Gets the node from cache. /// </summary> /// <param name="id">Node id.</param> /// <returns>Cached node.</returns> public ClusterNodeImpl GetNode(Guid? id) { return id == null ? null : _nodes[id.Value]; } /// <summary> /// Gets the interop processor. /// </summary> internal IUnmanagedTarget InteropProcessor { get { return _proc; } } /// <summary> /// Called when local client node has been disconnected from the cluster. /// </summary> internal void OnClientDisconnected() { _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); var handler = ClientDisconnected; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called when local client node has been reconnected to the cluster. /// </summary> /// <param name="clusterRestarted">Cluster restarted flag.</param> internal void OnClientReconnected(bool clusterRestarted) { _clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted); var handler = ClientReconnected; if (handler != null) handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted)); } /// <summary> /// Gets the plugin processor. /// </summary> internal PluginProcessor PluginProcessor { get { return _pluginProcessor; } } } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Xml; using XenAdmin; using XenAdmin.Core; using XenAdmin.Network; namespace XenAPI { public partial class SR : IComparable<SR>, IEquatable<SR> { /// <summary> /// The SR types. Note that the names of these enum members correspond exactly to the SR type string as /// recognised by the server. If you add anything here, check whether it should also be added to /// SR.CanCreateWithXenCenter. Also add it to XenAPI/FriendlyNames.resx under /// Label-SR.SRTypes-*. Don't change the lower-casing! /// </summary> public enum SRTypes { local, ext, lvmoiscsi, iso, nfs, lvm, netapp, udev, lvmofc, lvmohba, egenera, egeneracd, dummy, unknown, equal, cslg, shm, iscsi, ebs, rawhba, smb, lvmofcoe, nutanix, nutanixiso, tmpfs } public const string Content_Type_ISO = "iso"; public const string SM_Config_Type_CD = "cd"; private const string XenServer_Tools_Label = "XenServer Tools"; public override string ToString() { return Name; } /// <returns>A friendly name for the SR.</returns> public override string Name { get { return I18N("name_label", name_label, true); } } /// <summary> /// Get the given SR's home, i.e. the host under which we are going to display it. May return null, if this SR should live /// at the pool level. /// </summary> public Host Home { get { if (shared || PBDs.Count != 1) return null; PBD pbd = Connection.Resolve(PBDs[0]); if (pbd == null) return null; return Connection.Resolve(pbd.host); } } public string NameWithoutHost { get { return I18N("name_label", name_label, false); } } /// <returns>A friendly description for the SR.</returns> public override string Description { get { return I18N("name_description", name_description, true); } } public bool Physical { get { SRTypes type = GetSRType(false); return type == SRTypes.local || (type == SRTypes.udev && SMConfigType == SM_Config_Type_CD); } } public string SMConfigType { get { return Get(sm_config, "type"); } } public bool IsToolsSR { get { return name_label == SR.XenServer_Tools_Label || is_tools_sr; } } public string FriendlyTypeName { get { return getFriendlyTypeName(GetSRType(false)); } } /// <summary> /// A friendly (internationalized) name for the SR type. /// </summary> public static string getFriendlyTypeName(SRTypes srType) { return PropertyManager.GetFriendlyName(string.Format("Label-SR.SRTypes-{0}", srType.ToString()), "Label-SR.SRTypes-unknown"); } /// <summary> /// Use this instead of type /// </summary> public SRTypes GetSRType(bool ignoreCase) { try { return (SRTypes)Enum.Parse(typeof(SRTypes), type, ignoreCase); } catch { return SRTypes.unknown; } } public string ConfigType { get { return Get(sm_config, "type"); } } private string I18N(string field_name, string field_value, bool with_host) { if (!other_config.ContainsKey("i18n-key")) { return field_value; } string i18n_key = other_config["i18n-key"]; string original_value_key = "i18n-original-value-" + field_name; string original_value = other_config.ContainsKey(original_value_key) ? other_config[original_value_key] : ""; if (original_value != field_value) return field_value; string hostname = with_host ? GetHostName() : null; if (hostname == null) { string pattern = PropertyManager.GetFriendlyName(string.Format("SR.{0}-{1}", field_name, i18n_key)); return pattern == null ? field_value : pattern; } else { string pattern = PropertyManager.GetFriendlyName(string.Format("SR.{0}-{1}-host", field_name, i18n_key)); return pattern == null ? field_value : string.Format(pattern, hostname); } } /// <returns>The name of the host to which this SR is attached, or null if the storage is shared /// or unattached.</returns> private string GetHostName() { if (Connection == null) return null; Host host = GetStorageHost(); return host == null ? null : host.Name; } /// <returns>The host to which the given SR belongs, or null if the SR is shared or completely disconnected.</returns> public Host GetStorageHost() { if (shared || PBDs.Count != 1) return null; PBD pbd = Connection.Resolve(PBDs[0]); return pbd == null ? null : Connection.Resolve(pbd.host); } /// <summary> /// Iterating through the PBDs, this will return the storage host of the first PBD that is currently_attached. /// This will return null if there are no PBDs or none of them is currently_attached /// </summary> /// <returns></returns> public Host GetFirstAttachedStorageHost() { if (PBDs.Count == 0) return null; var currentlyAttachedPBDs = PBDs.Select(pbdref => Connection.Resolve(pbdref)).Where(p => p != null && p.currently_attached); if (currentlyAttachedPBDs.FirstOrDefault() != null) return currentlyAttachedPBDs.Select(p => Connection.Resolve(p.host)).Where(h => h != null).FirstOrDefault(); return null; } public bool IsDetachable() { return !IsDetached && !HasRunningVMs() && CanCreateWithXenCenter; } /// <summary> /// Can create with XC, or is citrix storage link gateway. Special case alert! /// </summary> public bool CanCreateWithXenCenter { get { SRTypes type = GetSRType(false); return type == SRTypes.iso || type == SRTypes.lvmoiscsi || type == SRTypes.nfs || type == SRTypes.equal || type == SRTypes.netapp || type == SRTypes.lvmohba || type == SRTypes.cslg || type == SRTypes.smb || type == SRTypes.lvmofcoe; } } public bool IsLocalSR { get { SRTypes type = GetSRType(false); return type == SRTypes.local || type == SRTypes.ext || type == SRTypes.lvm || type == SRTypes.udev || type == SRTypes.egeneracd || type == SRTypes.dummy; } } public bool ShowForgetWarning { get { return GetSRType(false) != SRTypes.iso; } } /// <summary> /// Internal helper function. True if all the PBDs for this SR are currently_attached. /// </summary> /// <returns></returns> private bool AllPBDsAttached() { return Connection.ResolveAll(this.PBDs).All(pbd => pbd.currently_attached); } /// <summary> /// Internal helper function. True if any of the PBDs for this SR is currently_attached. /// </summary> /// <returns></returns> private bool AnyPBDAttached() { return Connection.ResolveAll(this.PBDs).Any(pbd => pbd.currently_attached); } /// <summary> /// Returns true if there are any Running or Suspended VMs attached to VDIs on this SR. /// </summary> /// <param name="connection"></param> /// <returns></returns> public bool HasRunningVMs() { foreach (VDI vdi in Connection.ResolveAll(VDIs)) { foreach (VBD vbd in Connection.ResolveAll(vdi.VBDs)) { VM vm = Connection.Resolve(vbd.VM); if (vm == null) continue; // PR-1223: ignore control domain VM on metadata VDIs, so that the SR can be detached if there are no other running VMs if (vdi.type == vdi_type.metadata && vm.is_control_domain) continue; if (vm.power_state == vm_power_state.Running) return true; } } return false; } /// <summary> /// If host is non-null, return whether this storage can be seen from the given host. /// If host is null, return whether the storage is shared, with a PBD for each host and at least one PBD plugged. /// (See CA-36285 for why this is the right test when looking for SRs on which to create a new VM). /// </summary> public virtual bool CanBeSeenFrom(Host host) { if (host == null) { return shared && Connection != null && !IsBroken(false) && AnyPBDAttached(); } foreach (PBD pbd in host.Connection.ResolveAll(PBDs)) if (pbd.currently_attached && pbd.host.opaque_ref == host.opaque_ref) return true; return false; } public PBD GetPBDFor(Host host) { foreach (PBD pbd in host.Connection.ResolveAll(PBDs)) if (pbd.host.opaque_ref == host.opaque_ref) return pbd; return null; } /// <summary> /// True if there is less than 0.5GB free. Always false for dummy and ebs SRs. /// </summary> public bool IsFull { get { SRTypes t = GetSRType(false); return t != SRTypes.dummy && t != SRTypes.ebs && FreeSpace < XenAdmin.Util.BINARY_GIGA / 2; } } public virtual long FreeSpace { get { return physical_size - physical_utilisation; } } public virtual bool ShowInVDISRList(bool showHiddenVMs) { if (content_type == Content_Type_ISO) return false; return Show(showHiddenVMs); } public bool IsDetached { get { // SR is detached when it has no PBDs or when all its PBDs are unplugged return !HasPBDs || !AnyPBDAttached(); } } public bool HasPBDs { get { // CA-15188: Show SRs with no PBDs on Orlando, as pool-eject bug has been fixed. // SRs are detached if they have no PBDs return PBDs.Count > 0; } } public override bool Show(bool showHiddenVMs) { if (name_label.StartsWith(Helpers.GuiTempObjectPrefix)) return false; SRTypes srType = GetSRType(false); // CA-15012 - dont show cd drives of type local on miami (if dont get destroyed properly on upgrade) if (srType == SRTypes.local) return false; // Hide Memory SR if (srType == SRTypes.tmpfs) return false; if (showHiddenVMs) return true; //CP-2458: hide SRs that were introduced by a DR_task if (introduced_by != null && introduced_by.opaque_ref != Helper.NullOpaqueRef) return false; return !IsHidden; } public override bool IsHidden { get { return BoolKey(other_config, HIDE_FROM_XENCENTER); } } /// <summary> /// The SR is broken when it has the wrong number of PBDs, or (optionally) not all the PBDs are attached. /// </summary> /// <param name="checkAttached">Whether to check that all the PBDs are attached</param> /// <returns></returns> public virtual bool IsBroken(bool checkAttached) { if (PBDs == null || PBDs.Count == 0 || checkAttached && !AllPBDsAttached()) { return true; } Pool pool = Helpers.GetPoolOfOne(Connection); if (pool == null || !shared) { if (PBDs.Count != 1) { // There should be exactly one PBD, since this is a non-shared SR return true; } } else { if (PBDs.Count != Connection.Cache.HostCount) { // There isn't a PBD for each host return true; } } return false; } public bool IsBroken() { return IsBroken(true); } public static bool IsDefaultSr(SR sr) { Pool pool = Helpers.GetPoolOfOne(sr.Connection); return pool != null && pool.default_SR != null && pool.default_SR.opaque_ref == sr.opaque_ref; } /// <summary> /// Returns true if a new VM may be created on this SR: the SR supports VDI_CREATE, has the right number of PBDs, and is not full. /// </summary> /// <param name="myConnection">The IXenConnection whose cache this XenObject belongs to. May not be null.</param> /// <returns></returns> public bool CanCreateVmOn() { System.Diagnostics.Trace.Assert(Connection != null, "Connection must not be null"); return SupportsVdiCreate() && !IsBroken(false) && !IsFull; } /// <summary> /// Whether the underlying SR backend supports VDI_CREATE. Will return true even if the SR is full. /// </summary> /// <param name="connection"></param> /// <returns></returns> public virtual bool SupportsVdiCreate() { // ISO SRs are deemed not to support VDI create in the GUI, even though the back end // knows that they do. See CA-40119. if (content_type == SR.Content_Type_ISO) return false; // Memory SRs should not support VDI create in the GUI if (GetSRType(false) == SR.SRTypes.tmpfs) return false; SM sm = SM.GetByType(Connection, type); return sm != null && -1 != Array.IndexOf(sm.capabilities, "VDI_CREATE"); } /// <summary> /// Parses an XML list of SRs (as returned by the SR.probe() call) into a list of SRInfos. /// </summary> public static List<SRInfo> ParseSRListXML(string xml) { List<SRInfo> results = new List<SRInfo>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); // If we've got this from an async task result, then it will be wrapped // in a <value> element. Parse the contents instead. foreach (XmlNode node in doc.GetElementsByTagName("value")) { xml = node.InnerText; doc = new XmlDocument(); doc.LoadXml(xml); break; } foreach (XmlNode node in doc.GetElementsByTagName("SR")) { string uuid = ""; long size = 0; string aggr = ""; string name_label = ""; string name_description = ""; bool pool_metadata_detected = false; foreach (XmlNode info in node.ChildNodes) { if (info.Name.ToLowerInvariant() == "uuid") { uuid = info.InnerText.Trim(); } else if (info.Name.ToLowerInvariant() == "size") { size = long.Parse(info.InnerText.Trim()); } else if (info.Name.ToLowerInvariant() == "aggregate") { aggr = info.InnerText.Trim(); } else if (info.Name.ToLowerInvariant() == "name_label") { name_label = info.InnerText.Trim(); } else if (info.Name.ToLowerInvariant() == "name_description") { name_description = info.InnerText.Trim(); } else if (info.Name.ToLowerInvariant() == "pool_metadata_detected") { bool.TryParse(info.InnerText.Trim(), out pool_metadata_detected); } } results.Add(new SRInfo(uuid, size, aggr, name_label, name_description, pool_metadata_detected)); /*if (aggr != "") results.Add(new SRInfo(uuid, size, aggr)); else results.Add(new SRInfo(uuid, size));*/ } return results; } public static List<string> ParseSupportedVersionsListXML(string xml) { var supportedVersionsResult = new List<string>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); // If we've got this from an async task result, then it will be wrapped // in a <value> element. Parse the contents instead. foreach (XmlNode node in doc.GetElementsByTagName("value")) { xml = node.InnerText; doc = new XmlDocument(); doc.LoadXml(xml); break; } foreach (XmlNode node in doc.GetElementsByTagName("SupportedVersions")) { foreach (XmlNode info in node.ChildNodes) { if (info.Name.ToLowerInvariant() == "version") { supportedVersionsResult.Add(info.InnerText.Trim()); } } } return supportedVersionsResult; } public String GetScsiID() { foreach (PBD pbd in Connection.ResolveAll(PBDs)) { if (!pbd.device_config.ContainsKey("SCSIid")) continue; return pbd.device_config["SCSIid"]; } if (!sm_config.ContainsKey("devserial")) return null; String SCSIid = sm_config["devserial"]; if (SCSIid.StartsWith("scsi-")) SCSIid = SCSIid.Remove(0, 5); // CA-22352: SCSI IDs on the general panel for a NetApp SR have a trailing comma SCSIid = SCSIid.TrimEnd(new char[] { ',' }); return SCSIid; } /// <summary> /// New Lun Per VDI mode (cf. LunPerVDI method) using the hba encapsulating type /// </summary> public virtual bool HBALunPerVDI { get { return GetSRType(true) == SRTypes.rawhba; } } /// <summary> /// Legacy LunPerVDI mode - for old servers that this was set up on /// This is no longer an option (2012) for newer servers but we need to keep this /// </summary> public bool LunPerVDI { get { // Look for the mapping from scsi id -> vdi uuid // in sm-config. foreach (String key in sm_config.Keys) if (key.Contains("LUNperVDI") || key.StartsWith("scsi-")) return true; return false; } } private const String MPATH = "mpath"; public Dictionary<VM, Dictionary<VDI, String>> GetMultiPathStatusLunPerVDI() { Dictionary<VM, Dictionary<VDI, String>> result = new Dictionary<VM, Dictionary<VDI, String>>(); if (Connection == null) return result; foreach (PBD pbd in Connection.ResolveAll(PBDs)) { if (!pbd.MultipathActive) continue; foreach (KeyValuePair<String, String> kvp in pbd.other_config) { if (!kvp.Key.StartsWith(MPATH)) continue; int current; int max; if (!PBD.ParsePathCounts(kvp.Value, out current, out max)) continue; String scsiIdKey = String.Format("scsi-{0}", kvp.Key.Substring(MPATH.Length + 1)); if (!sm_config.ContainsKey(scsiIdKey)) continue; String vdiUUID = sm_config[scsiIdKey]; VDI vdi = null; foreach (VDI candidate in Connection.ResolveAll(VDIs)) { if (candidate.uuid != vdiUUID) continue; vdi = candidate; break; } if (vdi == null) continue; foreach (VBD vbd in Connection.ResolveAll(vdi.VBDs)) { VM vm = Connection.Resolve(vbd.VM); if (vm == null) continue; if (vm.power_state != vm_power_state.Running) continue; if (!result.ContainsKey(vm)) result[vm] = new Dictionary<VDI, String>(); result[vm][vdi] = kvp.Value; } } } return result; } public Dictionary<PBD, String> GetMultiPathStatusLunPerSR() { Dictionary<PBD, String> result = new Dictionary<PBD, String>(); if (Connection == null) return result; foreach (PBD pbd in Connection.ResolveAll(PBDs)) { if (!pbd.MultipathActive) continue; String status = String.Empty; foreach (KeyValuePair<String, String> kvp in pbd.other_config) { if (!kvp.Key.StartsWith(MPATH)) continue; status = kvp.Value; break; } int current; int max; if (!PBD.ParsePathCounts(status, out current, out max)) continue; result[pbd] = status; } return result; } public bool MultipathAOK { get { if (!MultipathCapable) return true; if (LunPerVDI) { Dictionary<VM, Dictionary<VDI, String>> multipathStatus = GetMultiPathStatusLunPerVDI(); foreach (VM vm in multipathStatus.Keys) foreach (VDI vdi in multipathStatus[vm].Keys) if (!CheckMultipathString(multipathStatus[vm][vdi])) return false; } else { Dictionary<PBD, String> multipathStatus = GetMultiPathStatusLunPerSR(); foreach (PBD pbd in multipathStatus.Keys) if (pbd.MultipathActive && !CheckMultipathString(multipathStatus[pbd])) return false; } return true; } } public override string NameWithLocation { get { //return only the Name for local SRs if (Connection != null && !shared) { return Name; } return base.NameWithLocation; } } internal override string LocationString { get { return Home != null ? Home.LocationString : base.LocationString; } } private bool CheckMultipathString(String status) { int current; int max; if (!PBD.ParsePathCounts(status, out current, out max)) return true; return current >= max; } public Dictionary<String, String> GetDeviceConfig(IXenConnection connection) { foreach (PBD pbd in connection.ResolveAll(PBDs)) return pbd.device_config; return null; } public class SRInfo : IComparable<SRInfo>, IEquatable<SRInfo> { public readonly string UUID; public readonly long Size; public readonly string Aggr; public string Name; public string Description; public readonly bool PoolMetadataDetected; public SRInfo(string uuid) : this(uuid, 0, "", "", "", false) { } public SRInfo(string uuid, long size) : this(uuid, size, "", "", "", false) { } public SRInfo(string uuid, long size, string aggr) : this(uuid, size, aggr, "", "", false) { } public SRInfo(string uuid, long size, string aggr, string name, string description, bool poolMetadataDetected) { UUID = uuid; Size = size; Aggr = aggr; Name = name; Description = description; PoolMetadataDetected = poolMetadataDetected; } public int CompareTo(SRInfo other) { return (this.UUID.CompareTo(other.UUID)); } public bool Equals(SRInfo other) { return this.CompareTo(other) == 0; } public override string ToString() { return UUID; } } //public bool TypeCIFS //{ // get // { // if (Connection == null || PBDs.Count == 0) // return false; // PBD pbd = Connection.Resolve<PBD>(PBDs[0]); // if (pbd == null) // return false; // return (pbd.device_config.ContainsKey("options") && pbd.device_config["options"].Contains("-t cifs")) // || (pbd.device_config.ContainsKey("type") && pbd.device_config["type"] == "cifs"); // } //} public bool MultipathCapable { get { return "true" == Get(sm_config, "multipathable"); } } public string Target { get { SR sr = Connection.Resolve(new XenRef<SR>(this.opaque_ref)); if (sr == null) return String.Empty; foreach (PBD pbd in sr.Connection.ResolveAll(sr.PBDs)) { SRTypes type = sr.GetSRType(false); if ((type == SR.SRTypes.netapp || type == SR.SRTypes.lvmoiscsi || type == SR.SRTypes.equal) && pbd.device_config.ContainsKey("target")) // netapp or iscsi { return pbd.device_config["target"]; } else if (type == SR.SRTypes.iso && pbd.device_config.ContainsKey("location")) // cifs or nfs iso { String target = Helpers.HostnameFromLocation(pbd.device_config["location"]); // has form //ip_address/path if (String.IsNullOrEmpty(target)) continue; return target; } else if (type == SR.SRTypes.nfs && pbd.device_config.ContainsKey("server")) { return pbd.device_config["server"]; } } return String.Empty; } } public Icons GetIcon { get { if (!HasPBDs || IsHidden) { return Icons.StorageDisabled; } else if (IsDetached || IsBroken() || !MultipathAOK) { return Icons.StorageBroken; } else if (SR.IsDefaultSr(this)) { return Icons.StorageDefault; } else { return Icons.Storage; } } } /// <summary> /// The amount of memory used as compared to the available and allocated amounts as a friendly string /// </summary> public String SizeString { get { return string.Format(Messages.SR_SIZE_USED, Util.DiskSizeString(physical_utilisation), Util.DiskSizeString(physical_size), Util.DiskSizeString(virtual_allocation)); } } /// <summary> /// A friendly string indicating whether the sr is detached/broken/multipath failing/needs upgrade/ok /// </summary> public String StatusString { get { if (!HasPBDs) return Messages.DETACHED; if (IsDetached || IsBroken()) return Messages.GENERAL_SR_STATE_BROKEN; if (!MultipathAOK) return Messages.GENERAL_MULTIPATH_FAILURE; return Messages.GENERAL_STATE_OK; } } /// <summary> /// Returns true when there is a pbd containing adapterid else false /// </summary> public bool CanRepairAfterUpgradeFromLegacySL { get { if (type == "cslg") { var pbds = Connection.ResolveAll(PBDs); if (pbds != null) { return pbds.Any(pbd => pbd.device_config.ContainsKey("adapterid")); } return false; } return true; } } /// <summary> /// Whether SR supports database replication. /// </summary> public static bool SupportsDatabaseReplication(IXenConnection connection, SR sr) { try { assert_supports_database_replication(connection.Session, sr.opaque_ref); return true; } catch (Failure) { return false; } } /// <summary> /// Is an iSL type or legacy iSl adpater type /// </summary> /// <param name="sr"></param> /// <returns></returns> public static bool IsIslOrIslLegacy(SR sr) { SRTypes currentType = sr.GetSRType(true); return currentType == SRTypes.cslg || currentType == SRTypes.equal || currentType == SRTypes.netapp; } /// <summary> /// Whether the underlying SR backend supports SR_TRIM /// </summary> /// <returns></returns> public bool SupportsTrim { get { System.Diagnostics.Trace.Assert(Connection != null, "Connection must not be null"); SM sm = SM.GetByType(Connection, type); return sm != null && sm.features != null && sm.features.ContainsKey("SR_TRIM"); } } public bool IsThinProvisioned { get { return false; // DISABLED THIN PROVISIONING this.sm_config != null && this.sm_config.ContainsKey("allocation") && this.sm_config["allocation"] == "xlvhd"; } } public long PercentageCommitted { get { return (long)Math.Round(virtual_allocation / (double)physical_size * 100.0); } } #region IEquatable<SR> Members /// <summary> /// Indicates whether the current object is equal to the specified object. This calls the implementation from XenObject. /// This implementation is required for ToStringWrapper. /// </summary> public bool Equals(SR other) { return base.Equals(other); } #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\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 BroadcastScalarToVector128Int16() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector128Int16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__BroadcastScalarToVector128Int16 testClass) { var result = Avx2.BroadcastScalarToVector128(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__BroadcastScalarToVector128Int16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) { var result = Avx2.BroadcastScalarToVector128( Sse2.LoadVector128((Int16*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Vector128<Int16> _clsVar1; private Vector128<Int16> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__BroadcastScalarToVector128Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleUnaryOpTest__BroadcastScalarToVector128Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.BroadcastScalarToVector128( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.BroadcastScalarToVector128( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.BroadcastScalarToVector128( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128), new Type[] { typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.BroadcastScalarToVector128( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) { var result = Avx2.BroadcastScalarToVector128( Sse2.LoadVector128((Int16*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var result = Avx2.BroadcastScalarToVector128(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var result = Avx2.BroadcastScalarToVector128(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var result = Avx2.BroadcastScalarToVector128(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int16(); var result = Avx2.BroadcastScalarToVector128(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Int16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) { var result = Avx2.BroadcastScalarToVector128( Sse2.LoadVector128((Int16*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.BroadcastScalarToVector128(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) { var result = Avx2.BroadcastScalarToVector128( Sse2.LoadVector128((Int16*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.BroadcastScalarToVector128(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.BroadcastScalarToVector128( Sse2.LoadVector128((Int16*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((firstOp[0] != result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<Int16>(Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Scripting.Test; using Roslyn.Test.Utilities; using Xunit; #pragma warning disable RS0003 // Do not directly await a Task namespace Microsoft.CodeAnalysis.Scripting.CSharp.UnitTests { public class HostModel { public readonly int Foo; } public class InteractiveSessionTests : TestBase { private static readonly Assembly s_lazySystemRuntimeAssembly; internal static readonly Assembly SystemRuntimeAssembly = s_lazySystemRuntimeAssembly ?? (s_lazySystemRuntimeAssembly = Assembly.Load(new AssemblyName("System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"))); internal static readonly Assembly HostAssembly = typeof(InteractiveSessionTests).GetTypeInfo().Assembly; // TODO: shouldn't be needed private static readonly ScriptOptions OptionsWithFacades = ScriptOptions.Default.AddReferences(SystemRuntimeAssembly); #region Namespaces, Types [Fact] public void CompilationChain_NestedTypesClass() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Foo(string str) { outerStr = str; } class InnerClass { public string innerStr = null; public void Goo() { Foo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerClass iC = new InnerClass(); iC.Goo(); ").ContinueWith(@" System.Console.WriteLine(iC.innerStr); "); using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { script.RunAsync().Wait(); Assert.Equal("test", redirect.Output.Trim()); } } [Fact] public void CompilationChain_NestedTypesStruct() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Foo(string str) { outerStr = str; } struct InnerStruct { public string innerStr; public void Goo() { Foo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerStruct iS = new InnerStruct(); iS.Goo(); ").ContinueWith(@" System.Console.WriteLine(iS.innerStr); "); using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { script.RunAsync().Wait(); Assert.Equal("test", redirect.Output.Trim()); } } [Fact] public void CompilationChain_InterfaceTypes() { var script = CSharpScript.Create(@" interface I1 { int Goo();} class InnerClass : I1 { public int Goo() { return 1; } }").ContinueWith(@" I1 iC = new InnerClass(); ").ContinueWith(@" iC.Goo() "); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void ScriptMemberAccessFromNestedClass() { var script = CSharpScript.Create(@" object field; object Property { get; set; } void Method() { } ").ContinueWith(@" class C { public void Foo() { object f = field; object p = Property; Method(); } } "); ScriptingTestHelpers.AssertCompilationError(script, // (6,20): error CS0120: An object reference is required for the non-static field, method, or property 'field' Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("field"), // (7,20): error CS0120: An object reference is required for the non-static field, method, or property 'Property' Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("Property"), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'Method()' Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("Method()")); } #region Anonymous Types [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith<Array>(@" var c = new { f = 1 }; var d = new { g = 1 }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions2() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith(@" var c = new { f = 1 }; var d = new { g = 1 }; object.ReferenceEquals(a.GetType(), c.GetType()).ToString() + "" "" + object.ReferenceEquals(a.GetType(), b.GetType()).ToString() + "" "" + object.ReferenceEquals(b.GetType(), d.GetType()).ToString() "); Assert.Equal("True False True", script.EvaluateAsync().Result.ToString()); } [WorkItem(543863)] [Fact] public void AnonymousTypes_Redefinition() { var script = CSharpScript.Create(@" var x = new { Foo = ""foo"" }; ").ContinueWith(@" var x = new { Foo = ""foo"" }; ").ContinueWith(@" x.Foo "); var result = script.EvaluateAsync().Result; Assert.Equal("foo", result); } [Fact] public void AnonymousTypes_TopLevel_Empty() { var script = CSharpScript.Create(@" var a = new { }; ").ContinueWith(@" var b = new { }; ").ContinueWith<Array>(@" var c = new { }; var d = new { }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } #endregion #region Dynamic [Fact] public void Dynamic_Expando() { var options = OptionsWithFacades. AddReferences( typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ExpandoObject).GetTypeInfo().Assembly). AddNamespaces( "System.Dynamic"); var script = CSharpScript.Create(@" dynamic expando = new ExpandoObject(); ", options).ContinueWith(@" expando.foo = 1; ").ContinueWith(@" expando.foo "); Assert.Equal(1, script.EvaluateAsync().Result); } #endregion [Fact] public void Enums() { var script = CSharpScript.Create(@" public enum Enum1 { A, B, C } Enum1 E = Enum1.C; E "); var e = script.EvaluateAsync().Result; Assert.True(e.GetType().GetTypeInfo().IsEnum, "Expected enum"); Assert.Equal(typeof(int), Enum.GetUnderlyingType(e.GetType())); } #endregion #region Attributes [Fact] public void PInvoke() { var source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [DllImport(""foo"", EntryPoint = ""bar"", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true, SetLastError = true, BestFitMapping = true, ThrowOnUnmappableChar = true)] public static extern void M(); class C { } typeof(C) "; Type c = CSharpScript.EvaluateAsync<Type>(source).Result; var m = c.DeclaringType.GetTypeInfo().GetDeclaredMethod("M"); Assert.Equal(MethodImplAttributes.PreserveSig, m.MethodImplementationFlags); // Reflection synthesizes DllImportAttribute var dllImport = (DllImportAttribute)m.GetCustomAttributes(typeof(DllImportAttribute), inherit: false).Single(); Assert.True(dllImport.BestFitMapping); Assert.Equal(CallingConvention.Cdecl, dllImport.CallingConvention); Assert.Equal(CharSet.Unicode, dllImport.CharSet); Assert.True(dllImport.ExactSpelling); Assert.True(dllImport.SetLastError); Assert.True(dllImport.PreserveSig); Assert.True(dllImport.ThrowOnUnmappableChar); Assert.Equal("bar", dllImport.EntryPoint); Assert.Equal("foo", dllImport.Value); } #endregion // extension methods - must be private, can be top level #region Modifiers and Visibility [Fact] public void PrivateTopLevel() { var script = CSharpScript.Create<int>(@" private int foo() { return 1; } private static int bar() { return 10; } private static int f = 100; foo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" foo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" class C { public static int baz() { return bar() + f; } } C.baz() "); Assert.Equal(110, script.EvaluateAsync().Result); } [Fact] public void NestedVisibility() { var script = CSharpScript.Create(@" private class C { internal class D { internal static int foo() { return 1; } } private class E { internal static int foo() { return 1; } } public class F { internal protected static int foo() { return 1; } } internal protected class G { internal static int foo() { return 1; } } } "); Assert.Equal(1, script.ContinueWith<int>("C.D.foo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.F.foo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.G.foo()").EvaluateAsync().Result); ScriptingTestHelpers.AssertCompilationError(script.ContinueWith<int>(@"C.E.foo()"), // error CS0122: 'C.E' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "E").WithArguments("C.E")); } [Fact] public void Fields_Visibility() { var script = CSharpScript.Create(@" private int i = 2; // test comment; public int j = 2; protected int k = 2; internal protected int l = 2; internal int pi = 2; ").ContinueWith(@" i = i + i; j = j + j; k = k + k; l = l + l; ").ContinueWith(@" pi = i + j + k + l; "); Assert.Equal(4, script.ContinueWith<int>("i").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("j").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("k").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("l").EvaluateAsync().Result); Assert.Equal(16, script.ContinueWith<int>("pi").EvaluateAsync().Result); } #endregion #region Chaining [Fact] public void CompilationChain_BasicFields() { var script = CSharpScript.Create("var x = 1;").ContinueWith("x"); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalNamespaceAndUsings() { var result = CSharpScript.Create("using InteractiveFixtures.C;", OptionsWithFacades.AddReferences(HostAssembly)). ContinueWith("using InteractiveFixtures.C;"). ContinueWith("System.Environment.ProcessorCount"). EvaluateAsync().Result; Assert.Equal(Environment.ProcessorCount, result); } [Fact] public void CompilationChain_CurrentSubmissionUsings() { var s0 = CSharpScript.RunAsync("", OptionsWithFacades.AddReferences(HostAssembly)); var state = s0. ContinueWith("class X { public int foo() { return 1; } }"). ContinueWith("class X { public int foo() { return 1; } }"). ContinueWith("using InteractiveFixtures.A;"). ContinueWith("new X().foo()"); Assert.Equal(1, state.Result.ReturnValue); state = s0. ContinueWith("class X { public int foo() { return 1; } }"). ContinueWith(@" using InteractiveFixtures.A; new X().foo() "); Assert.Equal(1, state.Result.ReturnValue); } [Fact] public void CompilationChain_UsingDuplicates() { var script = CSharpScript.Create(@" using System; using System; ").ContinueWith(@" using System; using System; ").ContinueWith(@" Environment.ProcessorCount "); Assert.Equal(Environment.ProcessorCount, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalImports() { var options = ScriptOptions.Default.AddNamespaces("System"); var state = CSharpScript.RunAsync("Environment.ProcessorCount", options); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); state = state.ContinueWith("Environment.ProcessorCount"); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); } [Fact] public void CompilationChain_SubmissionSlotResize() { var state = CSharpScript.RunAsync(""); for (int i = 0; i < 17; i++) { state = state.ContinueWith(@"public int i = 1;"); } using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { state.ContinueWith(@"System.Console.WriteLine(i);").Wait(); Assert.Equal(1, int.Parse(redirect.Output)); } } [Fact] public void CompilationChain_UsingNotHidingPreviousSubmission() { int result1 = CSharpScript.Create("using System;"). ContinueWith("int Environment = 1;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result1); int result2 = CSharpScript.Create("int Environment = 1;"). ContinueWith("using System;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result2); } [Fact] public void CompilationChain_DefinitionHidesGlobal() { var result = CSharpScript.Create("int System = 1;"). ContinueWith("System"). EvaluateAsync().Result; Assert.Equal(1, result); } public class C1 { public readonly int System = 1; public readonly int Environment = 2; } /// <summary> /// Symbol declaration in host object model hides global definition. /// </summary> [Fact] public void CompilationChain_HostObjectMembersHidesGlobal() { var result = CSharpScript.RunAsync("System", globals: new C1()). Result.ReturnValue; Assert.Equal(1, result); } [Fact] public void CompilationChain_UsingNotHidingHostObjectMembers() { var result = CSharpScript.RunAsync("using System;", globals: new C1()). ContinueWith("Environment"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void CompilationChain_DefinitionHidesHostObjectMembers() { var result = CSharpScript.RunAsync("int System = 2;", globals: new C1()). ContinueWith("System"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void Submissions_ExecutionOrder1() { var s0 = CSharpScript.Create("int x = 1;"); var s1 = s0.ContinueWith("int y = 2;"); var s2 = s1.ContinueWith<int>("x + y"); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); } [Fact] public async Task Submissions_ExecutionOrder2() { var s0 = await CSharpScript.RunAsync("int x = 1;"); Assert.Throws<CompilationErrorException>(() => s0.ContinueWithAsync("invalid$syntax").Result); var s1 = await s0.ContinueWithAsync("x = 2; x = 10"); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("invalid$syntax").Result); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("x = undefined_symbol").Result); var s2 = await s1.ContinueWithAsync("int y = 2;"); Assert.Null(s2.ReturnValue); var s3 = await s2.ContinueWithAsync("x + y"); Assert.Equal(12, s3.ReturnValue); } public class HostObjectWithOverrides { public override bool Equals(object obj) => true; public override int GetHashCode() => 1234567; public override string ToString() => "HostObjectToString impl"; } [Fact] public async Task ObjectOverrides1() { var state0 = await CSharpScript.RunAsync("", OptionsWithFacades, new HostObjectWithOverrides()); var state1 = await state0.ContinueWithAsync<bool>("Equals(null)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<int>("GetHashCode()"); Assert.Equal(1234567, state2.ReturnValue); var state3 = await state2.ContinueWithAsync<string>("ToString()"); Assert.Equal("HostObjectToString impl", state3.ReturnValue); } [Fact] public async Task ObjectOverrides2() { var state0 = await CSharpScript.RunAsync("", OptionsWithFacades, new object()); var state1 = await state0.ContinueWithAsync<bool>(@" object x = 1; object y = x; ReferenceEquals(x, y)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<string>("ToString()"); Assert.Equal("System.Object", state2.ReturnValue); var state3 = await state2.ContinueWithAsync<bool>("Equals(null)"); Assert.False(state3.ReturnValue); } [Fact] public void ObjectOverrides3() { var state0 = CSharpScript.RunAsync("", OptionsWithFacades); var src1 = @" Equals(null); GetHashCode(); ToString(); ReferenceEquals(null, null);"; ScriptingTestHelpers.AssertCompilationError(state0, src1, // (2,1): error CS0103: The name 'Equals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Equals").WithArguments("Equals"), // (3,1): error CS0103: The name 'GetHashCode' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "GetHashCode").WithArguments("GetHashCode"), // (4,1): error CS0103: The name 'ToString' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ToString").WithArguments("ToString"), // (5,1): error CS0103: The name 'ReferenceEquals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ReferenceEquals").WithArguments("ReferenceEquals")); var src2 = @" public override string ToString() { return null; } "; ScriptingTestHelpers.AssertCompilationError(state0, src2, // (1,24): error CS0115: 'ToString()': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "ToString").WithArguments("ToString()")); } #endregion #region Generics [Fact, WorkItem(201759)] public void CompilationChain_GenericTypes() { var script = CSharpScript.Create(@" class InnerClass<T> { public int method(int value) { return value + 1; } public int field = 2; }").ContinueWith(@" InnerClass<int> iC = new InnerClass<int>(); ").ContinueWith(@" iC.method(iC.field) "); Assert.Equal(3, script.EvaluateAsync().Result); } [WorkItem(529243)] [Fact] public void RecursiveBaseType() { CSharpScript.EvaluateAsync(@" class A<T> { } class B<T> : A<B<B<T>>> { } "); } [WorkItem(5378, "DevDiv_Projects/Roslyn")] [Fact] public void CompilationChain_GenericMethods() { var s0 = CSharpScript.Create(@" public int foo<T, R>(T arg) { return 1; } public static T bar<T>(T i) { return i; } "); Assert.Equal(1, s0.ContinueWith(@"foo<int, int>(1)").EvaluateAsync().Result); Assert.Equal(5, s0.ContinueWith(@"bar(5)").EvaluateAsync().Result); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn() { var state = CSharpScript.RunAsync(@" public class C { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C.f)() + new System.Func<int>(new C().g)() + new System.Func<int>(new C().h)()" ); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C.gf<int>)() + new System.Func<int>(new C().gg<object>)() + new System.Func<int>(new C().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn_GenericType() { var state = CSharpScript.RunAsync(@" public class C<S> { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C<byte>.f)() + new System.Func<int>(new C<byte>().g)() + new System.Func<int>(new C<byte>().h)() "); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C<byte>.gf<int>)() + new System.Func<int>(new C<byte>().gg<object>)() + new System.Func<int>(new C<byte>().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } #endregion #region Statements and Expressions [Fact] public void IfStatement() { var result = CSharpScript.EvaluateAsync<int>(@" using static System.Console; int x; if (true) { x = 5; } else { x = 6; } x ").Result; Assert.Equal(5, result); } [Fact] public void ExprStmtParenthesesUsedToOverrideDefaultEval() { Assert.Equal(18, CSharpScript.EvaluateAsync<int>("(4 + 5) * 2").Result); Assert.Equal(1, CSharpScript.EvaluateAsync<long>("6 / (2 * 3)").Result); } [WorkItem(5397, "DevDiv_Projects/Roslyn")] [Fact] public void TopLevelLambda() { var s = CSharpScript.RunAsync(@" using System; delegate void TestDelegate(string s); "); s = s.ContinueWith(@" TestDelegate testDelB = delegate (string s) { Console.WriteLine(s); }; "); using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { s.ContinueWith(@"testDelB(""hello"");").Wait(); Assert.Equal("hello", redirect.Output.Trim()); } } [Fact] public void Closure() { var f = CSharpScript.EvaluateAsync<Func<int, int>>(@" int Foo(int arg) { return arg + 1; } System.Func<int, int> f = (arg) => { return Foo(arg); }; f ").Result; Assert.Equal(3, f(2)); } [Fact] public void Closure2() { var result = CSharpScript.EvaluateAsync<List<string>>(@" #r ""System.Core"" using System; using System.Linq; using System.Collections.Generic; List<string> result = new List<string>(); string s = ""hello""; Enumerable.ToList(Enumerable.Range(1, 2)).ForEach(x => result.Add(s)); result ").Result; AssertEx.Equal(new[] { "hello", "hello" }, result); } [Fact] public void UseDelegateMixStaticAndDynamic() { var f = CSharpScript.RunAsync("using System;"). ContinueWith("int Sqr(int x) {return x*x;}"). ContinueWith<Func<int, int>>("new Func<int,int>(Sqr)").Result.ReturnValue; Assert.Equal(4, f(2)); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Arrays() { var s = CSharpScript.RunAsync(@" int[] arr_1 = { 1, 2, 3 }; int[] arr_2 = new int[] { 1, 2, 3 }; int[] arr_3 = new int[5]; ").ContinueWith(@" arr_2[0] = 5; "); Assert.Equal(3, s.ContinueWith(@"arr_1[2]").Result.ReturnValue); Assert.Equal(5, s.ContinueWith(@"arr_2[0]").Result.ReturnValue); Assert.Equal(0, s.ContinueWith(@"arr_3[0]").Result.ReturnValue); } [Fact] public void FieldInitializers() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); int b = 2; int a; int x = 1, y = b; static int g = 1; static int f = g + 1; a = x + y; result.Add(a); int z = 4 + f; result.Add(z); result.Add(a * z); result ").Result; Assert.Equal(3, result.Count); Assert.Equal(3, result[0]); Assert.Equal(6, result[1]); Assert.Equal(18, result[2]); } [Fact] public void FieldInitializersWithBlocks() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); const int constant = 1; { int x = constant; result.Add(x); } int field = 2; { int x = field; result.Add(x); } result.Add(constant); result.Add(field); result ").Result; Assert.Equal(4, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(1, result[2]); Assert.Equal(2, result[3]); } [Fact] public void TestInteractiveClosures() { var result = CSharpScript.RunAsync(@" using System.Collections.Generic; static List<int> result = new List<int>();"). ContinueWith("int x = 1;"). ContinueWith("System.Func<int> f = () => x++;"). ContinueWith("result.Add(f());"). ContinueWith("result.Add(x);"). ContinueWith<List<int>>("result").Result.ReturnValue; Assert.Equal(2, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); } [Fact] public void ExtensionMethods() { var options = ScriptOptions.Default.AddReferences( typeof(Enumerable).GetTypeInfo().Assembly); var result = CSharpScript.EvaluateAsync<int>(@" using System.Linq; string[] fruit = { ""banana"", ""orange"", ""lime"", ""apple"", ""kiwi"" }; fruit.Skip(1).Where(s => s.Length > 4).Count()", options).Result; Assert.Equal(2, result); } [Fact] public void ImplicitlyTypedFields() { var result = CSharpScript.EvaluateAsync<object[]>(@" var x = 1; var y = x; var z = foo(x); string foo(int a) { return null; } int foo(string a) { return 0; } new object[] { x, y, z } ").Result; AssertEx.Equal(new object[] { 1, 1, null }, result); } /// <summary> /// Name of PrivateImplementationDetails type needs to be unique across submissions. /// The compiler should suffix it with a MVID of the current submission module so we should be fine. /// </summary> [WorkItem(949559)] [WorkItem(540237)] [WorkItem(9229, "DevDiv_Projects/Roslyn")] [WorkItem(2721, "https://github.com/dotnet/roslyn/issues/2721")] [Fact] public async Task PrivateImplementationDetailsType() { var result1 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4 }"); AssertEx.Equal(new[] { 1, 2, 3, 4 }, result1); var result2 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4,5 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, result2); var s1 = await CSharpScript.RunAsync<int[]>("new int[] { 1,2,3,4,5,6 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6 }, s1.ReturnValue); var s2 = await s1.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7 }, s2.ReturnValue); var s3 = await s2.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7,8 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, s3.ReturnValue); } [Fact] public void NoAwait() { // No await. The return value is Task<int> rather than int. var result = CSharpScript.EvaluateAsync("System.Threading.Tasks.Task.FromResult(1)").Result; Assert.Equal(1, ((Task<int>)result).Result); } /// <summary> /// 'await' expression at top-level. /// </summary> [Fact] public void Await() { Assert.Equal(2, CSharpScript.EvaluateAsync("await System.Threading.Tasks.Task.FromResult(2)").Result); } /// <summary> /// 'await' in sub-expression. /// </summary> [Fact] public void AwaitSubExpression() { Assert.Equal(3, CSharpScript.EvaluateAsync<int>("0 + await System.Threading.Tasks.Task.FromResult(3)").Result); } [Fact] public void AwaitVoid() { var task = CSharpScript.EvaluateAsync<object>("await System.Threading.Tasks.Task.Run(() => { })"); Assert.Equal(null, task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } /// <summary> /// 'await' in lambda should be ignored. /// </summary> [Fact] public async Task AwaitInLambda() { var s0 = await CSharpScript.RunAsync(@" using System; using System.Threading.Tasks; static T F<T>(Func<Task<T>> f) { return f().Result; } static T G<T>(T t, Func<T, Task<T>> f) { return f(t).Result; }"); var s1 = await s0.ContinueWithAsync("F(async () => await Task.FromResult(4))"); Assert.Equal(4, s1.ReturnValue); var s2 = await s1.ContinueWithAsync("G(5, async x => await Task.FromResult(x))"); Assert.Equal(5, s2.ReturnValue); } [Fact] public void AwaitChain1() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddNamespaces("System.Threading.Tasks"); var state = CSharpScript.RunAsync("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact] public void AwaitChain2() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddNamespaces("System.Threading.Tasks"); var state = CSharpScript.Create("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). RunAsync(). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } #endregion #region References [Fact] public void ReferenceDirective_FileWithDependencies() { string file1 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; string file2 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).Path; // ICSPropImpl in CSClasses01.dll implements ICSProp in CSInterfces01.dll. object result = CSharpScript.EvaluateAsync(@" #r """ + file1 + @""" #r """ + file2 + @""" new Metadata.ICSPropImpl() ").Result; Assert.NotNull(result); } [Fact] public void ReferenceDirective_RelativeToBaseParent() { string path = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; string fileName = Path.GetFileName(path); string dir = Path.Combine(Path.GetDirectoryName(path), "subdir"); var script = CSharpScript.Create($@"#r ""..\{fileName}""", ScriptOptions.Default.WithPath(Path.Combine(dir, "a.csx"))); script.GetCompilation().VerifyDiagnostics(); } [Fact] public void ReferenceDirective_RelativeToBaseRoot() { string path = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; string root = Path.GetPathRoot(path); string unrooted = path.Substring(root.Length); string dir = Path.Combine(root, "foo", "bar", "baz"); var script = CSharpScript.Create($@"#r ""\{unrooted}""", ScriptOptions.Default.WithPath(Path.Combine(dir, "a.csx"))); script.GetCompilation().VerifyDiagnostics(); } #endregion #region UsingDeclarations [Fact] public void UsingAlias() { object result = CSharpScript.EvaluateAsync(@" using D = System.Collections.Generic.Dictionary<string, int>; D d = new D(); d ").Result; Assert.True(result is Dictionary<string, int>, "Expected Dictionary<string, int>"); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings1() { var options = ScriptOptions.Default. AddNamespaces("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); object result = CSharpScript.EvaluateAsync("new int[] { 1, 2, 3 }.First()", options).Result; Assert.Equal(1, result); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings2() { var options = ScriptOptions.Default. AddNamespaces("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); var s1 = CSharpScript.RunAsync("new int[] { 1, 2, 3 }.First()", options); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith("new List<int>()", options.AddNamespaces("System.Collections.Generic")); Assert.IsType<List<int>>(s2.Result.ReturnValue); } [Fact] public void AddNamespaces_Errors() { // no immediate error, error is reported if the namespace can't be found when compiling: var options = ScriptOptions.Default.AddNamespaces("?1", "?2"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS0246: The type or namespace name '?1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?1"), // error CS0246: The type or namespace name '?2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?2")); options = ScriptOptions.Default.AddNamespaces(""); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); options = ScriptOptions.Default.AddNamespaces(".abc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ".abc")); options = ScriptOptions.Default.AddNamespaces("a\0bc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "a\0bc")); } #endregion #region Host Object Binding and Conversions public class C<T> { } [Fact] public void Submission_HostConversions() { Assert.Equal(2, CSharpScript.EvaluateAsync<int>("1+1").Result); Assert.Equal(null, CSharpScript.EvaluateAsync<string>("null").Result); try { CSharpScript.RunAsync<C<int>>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { // error CS0400: The type or namespace name 'Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source.InteractiveSessionTests+C`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Roslyn.Compilers.CSharp.Emit.UnitTests, Version=42.42.42.42, Culture=neutral, PublicKeyToken=fc793a00266884fb' could not be found in the global namespace (are you missing an assembly reference?) Assert.Equal(ErrorCode.ERR_GlobalSingleTypeNameNotFound, (ErrorCode)e.Diagnostics.Single().Code); // Can't use Verify() because the version number of the test dll is different in the build lab. } var options = OptionsWithFacades.AddReferences(HostAssembly); var cint = CSharpScript.EvaluateAsync<C<int>>("null", options).Result; Assert.Equal(null, cint); Assert.Equal(null, CSharpScript.EvaluateAsync<int?>("null", options).Result); try { CSharpScript.RunAsync<int>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // null Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int")); } try { CSharpScript.RunAsync<string>("1+1"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0029: Cannot implicitly convert type 'int' to 'string' // 1+1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1+1").WithArguments("int", "string")); } } [Fact] public void Submission_HostVarianceConversions() { var value = CSharpScript.EvaluateAsync<IEnumerable<Exception>>(@" using System; using System.Collections.Generic; new List<ArgumentException>() ").Result; Assert.Equal(null, value.FirstOrDefault()); } public class B { public int x = 1, w = 4; } public class C : B, I { public static readonly int StaticField = 123; public int Y => 2; public string N { get; set; } = "2"; public int Z() => 3; public override int GetHashCode() => 123; } public interface I { string N { get; set; } int Z(); } private class PrivateClass : I { public string N { get; set; } = null; public int Z() => 3; } public class M<T> { private int F() => 3; public T G() => default(T); } [Fact] public void HostObjectBinding_PublicClassMembers() { var c = new C(); var s0 = CSharpScript.RunAsync<int>("x + Y + Z()", OptionsWithFacades, globals: c); Assert.Equal(6, s0.Result.ReturnValue); var s1 = s0.ContinueWith<int>("x"); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith<int>("int x = 20;"); var s3 = s2.ContinueWith<int>("x"); Assert.Equal(20, s3.Result.ReturnValue); } [Fact] public void HostObjectBinding_PublicGenericClassMembers() { var m = new M<string>(); var result = CSharpScript.EvaluateAsync<string>("G()", OptionsWithFacades, globals: m); Assert.Equal(null, result.Result); } [Fact] public async Task HostObjectBinding_Interface() { var c = new C(); var s0 = await CSharpScript.RunAsync<int>("Z()", OptionsWithFacades, c, typeof(I)); Assert.Equal(3, s0.ReturnValue); ScriptingTestHelpers.AssertCompilationError(s0, @"x + Y", // The name '{0}' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y")); var s1 = await s0.ContinueWithAsync<string>("N"); Assert.Equal("2", s1.ReturnValue); } [Fact] public void HostObjectBinding_PrivateClass() { var c = new PrivateClass(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", OptionsWithFacades, c), // (1,1): error CS0122: '<Fully Qualified Name of PrivateClass>.Z()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Z").WithArguments(typeof(PrivateClass).FullName.Replace("+", ".") + ".Z()")); } [Fact] public void HostObjectBinding_PrivateMembers() { object c = new M<int>(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", OptionsWithFacades, c), // (1,1): error CS0103: The name 'z' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Z").WithArguments("Z")); } [Fact] public void HostObjectBinding_PrivateClassImplementingPublicInterface() { var c = new PrivateClass(); var result = CSharpScript.EvaluateAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, result.Result); } [Fact] public void HostObjectBinding_StaticMembers() { var s0 = CSharpScript.RunAsync("static int foo = StaticField;", globals: new C()); var s1 = s0.ContinueWith("static int bar { get { return foo; } }"); var s2 = s1.ContinueWith("class C { public static int baz() { return bar; } }"); var s3 = s2.ContinueWith("C.baz()"); Assert.Equal(123, s3.Result.ReturnValue); } public class D { public int foo(int a) { return 0; } } /// <summary> /// Host object members don't form a method group with submission members. /// </summary> [Fact] public void HostObjectBinding_Overloads() { var s0 = CSharpScript.RunAsync("int foo(double a) { return 2; }", globals: new D()); var s1 = s0.ContinueWith("foo(1)"); Assert.Equal(2, s1.Result.ReturnValue); var s2 = s1.ContinueWith("foo(1.0)"); Assert.Equal(2, s2.Result.ReturnValue); } [Fact] public void HostObjectInRootNamespace() { var obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r0 = CSharpScript.EvaluateAsync<int>("X + Y + Z", globals: obj); Assert.Equal(6, r0.Result); obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r1 = CSharpScript.EvaluateAsync<int>("X", globals: obj); Assert.Equal(1, r1.Result); } #endregion } }
using System; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Threading; using AutoTest.Messages; using System.IO; using AutoTest.UI.TextFormatters; namespace AutoTest.UI { public class FeedbackProvider { private readonly SynchronizationContext _syncContext; private readonly object _messagLock = new object(); private bool _isRunning; private bool _progressUpdatedExternally; private ImageStates _lastInternalState = ImageStates.None; private string _progressPicture; private bool _iconVisible = true; private Action<string,int,int> _goToReference = (file,line,column) => {}; private Func<string,string,bool> _goToType = (assembly,typename) => false; private Action<CacheTestMessage> _debugTest = (t) => {}; private Action _cancelRun = () => {}; private Action _prepareForFocus = () => {}; private Action _clearList = () => {}; private Action<string> _clearBuilds = (project) => {}; private Func<bool> _isInFocus = () => false; private Action<string,ImageStates,string> _updatePicture = (picture, state, information) => {}; private Action<string,string,bool> _printMessage = (message,color,normal) => {}; private Action _storeSelected = () => {}; private Action<Func<object,object,bool>> _restoreSelected = (check) => {}; private Action<Func<CacheTestMessage,bool>> _removeTest = (check) => {}; private Action<Func<CacheBuildMessage,bool>> _removeBuildItem = (check) => {}; private Action<string,string,string,object> _addItem = (type, message, color, tag) => {}; private Action<string> _setSummary = (m) => {}; private Func<Func<object,bool>,bool> _exists = (check) => false; private Func<object> _getSelectedItem = () => null; private Func<int> _getWidth = () => 0; private IListItemBehaviour _cancelRunItem; private IListItemBehaviour _debugTestItem; private IListItemBehaviour _testDetailsLinkItem; private IListItemBehaviour _errorDescriptionItem; private bool _showErrors = true; private bool _showWarnings = true; private bool _showFailing = true; private bool _showIgnored = true; public bool CanGoToTypes { get; set; } public bool CanDebug { get; set; } public bool ShowRunInformation { get; set; } public int Width { get { return _getWidth(); } } public FeedbackProvider( IListItemBehaviour cancelRun, IListItemBehaviour debugTest, IListItemBehaviour testDetails, IListItemBehaviour errorDescription) { _syncContext = AsyncOperationManager.SynchronizationContext; _cancelRunItem = cancelRun; _debugTestItem = debugTest; _testDetailsLinkItem = testDetails; _errorDescriptionItem = errorDescription; CanGoToTypes = false; ShowRunInformation = true; } public void Initialize() { organizeListItemBehaviors(); _progressPicture = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "progress.gif"); setProgress(ImageStates.None, "", false, null, false); } public FeedbackProvider OnGoToReference(Action<string,int,int> goToReference) { _goToReference = goToReference; return this; } public FeedbackProvider OnGoToType(Func<string,string,bool> goToType) { _goToType = goToType; return this; } public FeedbackProvider OnDebugTest(Action<CacheTestMessage> debugTest) { _debugTest = debugTest; return this; } public FeedbackProvider OnCancelRun(Action cancelRun) { _cancelRun = cancelRun; return this; } public FeedbackProvider OnPrepareForFocus(Action prepareForFocus) { _prepareForFocus = prepareForFocus; return this; } public FeedbackProvider OnClearList(Action clearList) { _clearList = clearList; return this; } public FeedbackProvider OnClearBuilds(Action<string> clearBuilds) { _clearBuilds = clearBuilds; return this; } public FeedbackProvider OnIsInFocus(Func<bool> isInFocus) { _isInFocus = isInFocus; return this; } public FeedbackProvider OnUpdatePicture(Action<string,ImageStates,string> updatePicture) { _updatePicture = updatePicture; return this; } public FeedbackProvider OnPrintMessage(Action<string,string,bool> printMessage) { _printMessage = printMessage; return this; } public FeedbackProvider OnStoreSelected(Action storeSelected) { _storeSelected = storeSelected; return this; } public FeedbackProvider OnRestoreSelected(Action<Func<object,object,bool>> reStoreSelected) { _restoreSelected = reStoreSelected; return this; } public FeedbackProvider OnRemoveTest(Action<Func<CacheTestMessage,bool>> removeTest) { _removeTest = removeTest; return this; } public FeedbackProvider OnRemoveBuildItem(Action<Func<CacheBuildMessage,bool>> removeBuildItem) { _removeBuildItem = removeBuildItem; return this; } public FeedbackProvider OnAddItem(Action<string,string,string,object> addItem) { _addItem = addItem; return this; } public FeedbackProvider OnSetSummary(Action<string> setSummary) { _setSummary = setSummary; return this; } public FeedbackProvider OnExists(Func<Func<object,bool>,bool> exists) { _exists = exists; return this; } public FeedbackProvider OnGetSelectedItem(Func<object> getSelectedItem) { _getSelectedItem = getSelectedItem; return this; } public FeedbackProvider OnGetWidth(Func<int> getWidth) { _getWidth = getWidth; return this; } // Move stuff around on the form public void ReOrganize() { _syncContext.Post(message => { organizeListItemBehaviors(); }, null); } public void GoTo(object item) { if (item.GetType() == typeof(CacheBuildMessage)) goToBuildItemReference((CacheBuildMessage)item); if (item.GetType() == typeof(CacheTestMessage)) goToTestItemReference((CacheTestMessage)item); } public void GoTo(string file, int line, int column) { goToReference(file, line, column); } public bool GoTo(string assembly, string type) { return goToType(assembly, type); } public void PrepareForFocus() { _syncContext.Post(x => { _prepareForFocus(); organizeListItemBehaviors(); }, null); } public void ClearList() { _syncContext.Post(x => { _clearList(); }, null); } public void ClearBuilds() { _syncContext.Post(x => { _clearBuilds(null); }, null); } public void ClearBuilds(string proj) { _syncContext.Post(x => { _clearBuilds(proj); }, proj); } public bool IsInFocus() { return _isInFocus(); } public void SetVisibilityConfiguration(bool showErrors, bool showWarnings, bool showFailingTests, bool showIgnoredTests) { _showErrors = showErrors; _showWarnings = showWarnings; _showFailing = showFailingTests; _showIgnored = showIgnoredTests; _syncContext.Post(x => { ClearList(); }, null); } public bool isTheSameTestAs(CacheTestMessage original, CacheTestMessage item) { return original.Assembly.Equals(item.Assembly) && original.Test.Runner.Equals(item.Test.Runner) && original.Test.Name.Equals(item.Test.Name) && original.Test.DisplayName.Equals(item.Test.DisplayName); } public void ConsumeMessage(object msg) { _syncContext.Post(message => { lock (_messagLock) { try { if (message.GetType() == typeof(CacheMessages)) handle((CacheMessages)message); else if (message.GetType() == typeof(LiveTestStatusMessage)) handle((LiveTestStatusMessage)message); else if (message.GetType() == typeof(RunStartedMessage)) runStarted("Detected file changes..."); else if (message.GetType() == typeof(RunFinishedMessage)) runFinished((RunFinishedMessage)message); else if (message.GetType() == typeof(RunInformationMessage)) runInformationMessage((RunInformationMessage)message); else if (message.GetType() == typeof(BuildRunMessage)) { if (((BuildRunMessage)message).Results.Errors.Length == 0) ClearBuilds(((BuildRunMessage)message).Results.Project); // Make sure no errors remain in log } } catch { } } }, msg); } private void handle(CacheMessages cacheMessages) { Handle(cacheMessages); } private void handle(LiveTestStatusMessage liveTestStatusMessage) { Handle(liveTestStatusMessage); } private void runStarted(string x) { if (!ShowRunInformation) x = "processing changes..."; printMessage(new RunMessages(RunMessageType.Normal, x.ToString())); generateSummary(null); organizeListItemBehaviors(); clearRunnerTypeAnyItems(); setProgress(ImageStates.Progress, "processing changes...", false, null, true); _isRunning = true; organizeListItemBehaviors(); } public void SetProgress(bool on, string information, string picture) { _progressUpdatedExternally = on; var state = _lastInternalState; if (on) state = ImageStates.Progress; setProgress(state, information, true, picture); } public void SetProgress(bool on, string information, ImageStates imageState) { _progressUpdatedExternally = on; setProgress(imageState, information, true, null); } private void setProgress(ImageStates state, string information, bool external, string picture) { setProgress(state, information, external, picture, false); } private void setProgress(ImageStates state, string information, bool external, string picture, bool force) { if (!force && _progressUpdatedExternally && !external) return; if (picture == null) picture = _progressPicture; _updatePicture(picture, state, information); if (!external) _lastInternalState = state; } private void runFinished(RunFinishedMessage x) { if (((RunFinishedMessage)x).Report.Aborted) { if (ShowRunInformation) { var i = getRunFinishedInfo((RunFinishedMessage)x); var runType = i.Succeeded ? RunMessageType.Succeeded : RunMessageType.Failed; setProgress(runType == RunMessageType.Succeeded ? ImageStates.Green : ImageStates.Red, "", false, null); printMessage(new RunMessages(runType, i.Text)); generateSummary(i.Report); } } else { var i = getRunFinishedInfo((RunFinishedMessage)x); var runType = i.Succeeded ? RunMessageType.Succeeded : RunMessageType.Failed; setProgress(runType == RunMessageType.Succeeded ? ImageStates.Green : ImageStates.Red, "", false, null); printMessage(new RunMessages(runType, i.Text)); generateSummary(i.Report); } _isRunning = false; organizeListItemBehaviors(); } private RunFinishedInfo getRunFinishedInfo(RunFinishedMessage message) { var report = message.Report; var text = string.Format( "Ran {0} build(s) ({1} succeeded, {2} failed) and {3} test(s) ({4} passed, {5} failed, {6} ignored)", report.NumberOfProjectsBuilt, report.NumberOfBuildsSucceeded, report.NumberOfBuildsFailed, report.NumberOfTestsRan, report.NumberOfTestsPassed, report.NumberOfTestsFailed, report.NumberOfTestsIgnored); var succeeded = !(report.NumberOfBuildsFailed > 0 || report.NumberOfTestsFailed > 0); return new RunFinishedInfo(text, succeeded, report); } private void runInformationMessage(RunInformationMessage x) { if (!_isRunning) return; var text = ""; var message = (RunInformationMessage)x; switch (message.Type) { case InformationType.Build: if (ShowRunInformation) text = string.Format("building {0}", Path.GetFileName(message.Project)); break; case InformationType.TestRun: text = "testing..."; break; case InformationType.PreProcessing: if (ShowRunInformation) text = "locating affected tests"; break; } if (text != "") { setProgress(ImageStates.Progress, text.ToString(), false, null); printMessage(new RunMessages(RunMessageType.Normal, text.ToString())); } } public void PrintMessage(RunMessages message) { _syncContext.Post(x => printMessage((RunMessages)x), message); } private void printMessage(RunMessages message) { var msg = message; var normal = true; var color = "Black"; if (msg.Type == RunMessageType.Succeeded) { color = "Green"; normal = false; } if (msg.Type == RunMessageType.Failed) { color = "Red"; normal = false; } _printMessage(msg.Message, color, normal); } private new void Handle(CacheMessages cache) { _storeSelected(); removeItems(cache); if (_showErrors) { foreach (var error in cache.ErrorsToAdd) addFeedbackItem("Build error", formatBuildResult(error), Color.Red, error); } if (_showFailing) { foreach (var failed in cache.FailedToAdd) addFeedbackItem("Test failed", formatTestResult(failed), Color.Red, failed); } if (_showWarnings) { foreach (var warning in cache.WarningsToAdd) addFeedbackItem("Build warning", formatBuildResult(warning), Color.Black, warning); } if (_showIgnored) { foreach (var ignored in cache.IgnoredToAdd) addFeedbackItem("Test ignored", formatTestResult(ignored), Color.Black, ignored); } _restoreSelected(isSame); } private new void Handle(LiveTestStatusMessage liveStatus) { if (!_isRunning) return; _storeSelected(); var ofCount = liveStatus.TotalNumberOfTests > 0 ? string.Format(" of {0}", liveStatus.TotalNumberOfTests) : ""; var testName = liveStatus.CurrentTest; if (testName.Trim().Length > 0) testName += " in "; printMessage(new RunMessages(RunMessageType.Normal, string.Format("testing {3}{0} ({1}{2} tests completed)", Path.GetFileNameWithoutExtension(liveStatus.CurrentAssembly), liveStatus.TestsCompleted, ofCount, testName))); if (_showFailing) { foreach (var test in liveStatus.FailedButNowPassingTests) { var testItem = new CacheTestMessage(test.Assembly, test.Test); _removeTest((t) => isTheSameTestAs(testItem, t)); } foreach (var test in liveStatus.FailedTests) { var testItem = new CacheTestMessage(test.Assembly, test.Test); _removeTest((t) => isTheSameTestAs(testItem, t)); addFeedbackItem("Test failed", formatTestResult(testItem), Color.Red, testItem); } } _restoreSelected(isSame); } private void clearRunnerTypeAnyItems() { _removeTest((t) => t.Test.Runner == TestRunner.Any); } private void removeItems(CacheMessages cache) { foreach (var item in cache.ErrorsToRemove) _removeBuildItem((itm) => itm.Equals(item)); foreach (var item in cache.WarningsToRemove) _removeBuildItem((itm) => itm.Equals(item)); foreach (var item in cache.TestsToRemove) _removeTest((t) => { return t.Assembly.Equals(item.Assembly) && t.Test.Runner.Equals(item.Test.Runner) && t.Test.Name.Equals(item.Test.Name); }); } private void addFeedbackItem(string type, string message, Color colour, object tag) { if (testExists(tag)) return; _addItem(type, message, colour.Name, tag); } private bool isWindows() { return Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE || Environment.OSVersion.Platform == PlatformID.Xbox; } private bool testExists(object tag) { if (tag.GetType() != typeof(CacheTestMessage)) return false; var test = (CacheTestMessage)tag; return _exists((item) => item.GetType() == typeof(CacheTestMessage) && isTheSameTestAs(test, item as CacheTestMessage)); } private bool isSame(object obj1, object obj2) { if (obj1.GetType() != obj2.GetType()) return false; if (obj1.GetType() == typeof(CacheBuildMessage)) return ((CacheBuildMessage)obj1).Equals((CacheBuildMessage)obj2); if (obj1.GetType() == typeof(CacheTestMessage)) return isTheSameTestAs((CacheTestMessage)obj1, (CacheTestMessage)obj2); return false; } private string formatBuildResult(CacheBuildMessage item) { return string.Format("{0}, {1}", item.BuildItem.ErrorMessage, item.BuildItem.File); } private string formatTestResult(CacheTestMessage item) { return string.Format("{0} -> ({1}) {2}", item.Test.Status, item.Test.Runner.ToString(), item.Test.DisplayName); } private void organizeListItemBehaviors() { var selected = _getSelectedItem(); using (var handler = new ListItemBehaviourHandler( this, _cancelRunItem, _debugTestItem, _testDetailsLinkItem, _errorDescriptionItem)) { handler.Organize(selected, _isRunning); } } private void goToBuildItemReference(CacheBuildMessage buildItem) { goToReference(buildItem.BuildItem.File, buildItem.BuildItem.LineNumber, buildItem.BuildItem.LinePosition); } private void goToTestItemReference(CacheTestMessage testItem) { if (testItem.Test.StackTrace.Length > 0) { var exactLine = getMatchingStackLine(testItem); if (exactLine != null) { goToReference(exactLine.File, exactLine.LineNumber, 0); return; } if (CanGoToTypes) if (goToType(testItem.Assembly, testItem.Test.Name)) return; } } private IStackLine getMatchingStackLine(CacheTestMessage testItem) { foreach (var line in testItem.Test.StackTrace) { if (line.Method.Equals(testItem.Test.Name)) return line; } var lastWithLine = testItem.Test.StackTrace.LastOrDefault(x => x.LineNumber > 0); if (lastWithLine != null) return lastWithLine; return null; } private void goToReference(string file, int lineNumber, int column) { _goToReference(file, lineNumber, column); } private bool goToType(string assembly, string typename) { var type = typename.Replace("+", "."); return _goToType(assembly, type); } private void generateSummary(RunReport report) { if (report == null) { _setSummary(""); return; } var builder = new SummaryBuilder(report); _setSummary(builder.Build()); } } }
using System; using System.Diagnostics; using System.Linq; using System.Web; using Erwine.Leonard.T.LoggingModule.ExtensionMethods; namespace Erwine.Leonard.T.LoggingModule { public class CustomTraceManagerModule : IHttpModule { private object _syncRoot = new object(); private HttpApplication _context = null; public TraceSource TraceSource { get; private set; } public CustomTraceManagerModule() { } ~CustomTraceManagerModule() { object syncRoot; System.Threading.Thread.BeginCriticalRegion(); try { syncRoot = this._syncRoot; System.Threading.Thread.EndCriticalRegion(); } catch { System.Threading.Thread.EndCriticalRegion(); throw; } if (syncRoot != null) this.Dispose(false); } public static CustomTraceManagerModule GetCurrent() { return HttpContext.Current.ApplicationInstance.Modules.OfType<CustomTraceManagerModule>().FirstOrDefault(); } #region IHttpModule Members public void Init(HttpApplication context) { if (this._syncRoot == null) throw new ObjectDisposedException(this.GetType().FullName); lock (this._syncRoot) { if (this._context != null) this._DetachContext(); this._context = context; string sourceName; try { sourceName = context.GetType().Namespace; } catch { sourceName = null; } this.TraceSource = new TraceSource((String.IsNullOrWhiteSpace(sourceName)) ? context.GetType().Name : sourceName); context.BeginRequest += this.Application_BeginRequest; context.AuthenticateRequest += this.Application_AuthenticateRequest; context.PostAuthenticateRequest += this.Application_PostAuthenticateRequest; context.AuthorizeRequest += this.Application_AuthorizeRequest; context.PostAuthorizeRequest += this.Application_PostAuthorizeRequest; context.AcquireRequestState += this.Application_AcquireRequestState; context.PostAcquireRequestState += this.Application_PostAcquireRequestState; context.PreRequestHandlerExecute += this.Application_PreRequestHandlerExecute; context.PostRequestHandlerExecute += this.Application_PostRequestHandlerExecute; context.EndRequest += this.Application_EndRequest; context.Error += this.Application_Error; } } private void _DetachContext() { if (this._context == null) return; this._context.BeginRequest -= this.Application_BeginRequest; this._context.AuthenticateRequest -= this.Application_AuthenticateRequest; this._context.PostAuthenticateRequest -= this.Application_PostAuthenticateRequest; this._context.AuthorizeRequest -= this.Application_AuthorizeRequest; this._context.PostAuthorizeRequest -= this.Application_PostAuthorizeRequest; this._context.AcquireRequestState -= this.Application_AcquireRequestState; this._context.PostAcquireRequestState -= this.Application_PostAcquireRequestState; this._context.PreRequestHandlerExecute -= this.Application_PreRequestHandlerExecute; this._context.PostRequestHandlerExecute -= this.Application_PostRequestHandlerExecute; this._context.EndRequest -= this.Application_EndRequest; this._context.Error -= this.Application_Error; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (!isDisposing) return; object syncRoot; System.Threading.Thread.BeginCriticalRegion(); try { syncRoot = this._syncRoot; this._syncRoot = null; System.Threading.Thread.EndCriticalRegion(); } catch { System.Threading.Thread.EndCriticalRegion(); throw; } if (syncRoot == null) throw new ObjectDisposedException(this.GetType().FullName); lock (syncRoot) { if (this._context != null) this._DetachContext(); this._context = null; } } #endregion #region Application Event Handlers private void Application_BeginRequest(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_BeginRequest); } private void Application_AuthenticateRequest(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_AuthenticateRequest); } private void Application_PostAuthenticateRequest(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_PostAuthenticateRequest); } private void Application_AuthorizeRequest(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_AuthorizeRequest); } private void Application_PostAuthorizeRequest(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_PostAuthorizeRequest); } private void Application_AcquireRequestState(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_AcquireRequestState); } private void Application_PostAcquireRequestState(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_PostAcquireRequestState); } private void Application_PreRequestHandlerExecute(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_PreRequestHandlerExecute); } private void Application_PostRequestHandlerExecute(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_PostRequestHandlerExecute); } private void Application_EndRequest(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Lifecycle_Application_EndRequest); } private void Application_Error(object sender, EventArgs e) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, TraceEventId.Application_Error); } #endregion #region Event tracing members #region Instance private void _TraceData(TraceEventType traceEventType, TraceEventId traceEventId, object data) { if (this.TraceSource == null) throw new ObjectDisposedException(this.GetType().FullName); lock (this._syncRoot) this.TraceSource.TraceData(traceEventType, (int)(traceEventId), TraceDataObject.EnsureSerializable(data)); } private void _TraceData(TraceEventType traceEventType, TraceEventId traceEventId, params object[] data) { if (this.TraceSource == null) throw new ObjectDisposedException(this.GetType().FullName); lock (this._syncRoot) this.TraceSource.TraceData(traceEventType, (int)(traceEventId), (data == null) ? new object[0] : data.Select(d => TraceDataObject.EnsureSerializable(data)).ToArray()); } private void _TraceEvent(TraceEventType traceEventType, TraceEventId traceEventId, string message) { if (this.TraceSource == null) throw new ObjectDisposedException(this.GetType().FullName); lock (this._syncRoot) { if (message == null) this.TraceSource.TraceEvent(traceEventType, (int)(traceEventId)); else this.TraceSource.TraceEvent(traceEventType, (int)(traceEventId), message); } } private void _TraceTransfer(TraceEventId traceEventId, string message, Guid relatedActivityId) { if (this.TraceSource == null) throw new ObjectDisposedException(this.GetType().FullName); lock (this._syncRoot) this.TraceSource.TraceTransfer((int)(traceEventId), message, relatedActivityId); } #endregion #region Critical public static void TraceCritical(TraceEventId eventId) { CustomTraceManagerModule.TraceEvent(TraceEventType.Critical, eventId); } public static void TraceCritical(TraceEventId eventId, string message, Exception exception = null) { if (exception == null) CustomTraceManagerModule.TraceEvent(TraceEventType.Critical, eventId, message); else CustomTraceManagerModule.TraceData(TraceEventType.Critical, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, message)); } public static void TraceCritical(TraceEventId eventId, string message, Exception exception, object data0, params object[] nData) { CustomTraceManagerModule.TraceData(TraceEventType.Critical, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, message, (nData == null) ? new object[] { data0 } : (new object[] { data0 }).Concat(nData).ToArray())); } public static void TraceCritical(TraceEventId eventId, Exception exception, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Critical, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, data)); } public static void TraceCritical(TraceEventId eventId, object data) { CustomTraceManagerModule.TraceData(TraceEventType.Critical, eventId, data); } public static void TraceCritical(TraceEventId eventId, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Critical, eventId, data); } #endregion #region Error public static void TraceError(TraceEventId eventId) { CustomTraceManagerModule.TraceEvent(TraceEventType.Error, eventId); } public static void TraceError(TraceEventId eventId, string message, Exception exception = null) { if (exception == null) CustomTraceManagerModule.TraceEvent(TraceEventType.Error, eventId, message); else CustomTraceManagerModule.TraceData(TraceEventType.Error, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, message)); } public static void TraceError(TraceEventId eventId, string message, Exception exception, object data0, params object[] nData) { CustomTraceManagerModule.TraceData(TraceEventType.Error, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, message, (nData == null) ? new object[] { data0 } : (new object[] { data0 }).Concat(nData).ToArray())); } public static void TraceError(TraceEventId eventId, Exception exception, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Error, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, data)); } public static void TraceError(TraceEventId eventId, object data) { CustomTraceManagerModule.TraceData(TraceEventType.Error, eventId, data); } public static void TraceError(TraceEventId eventId, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Error, eventId, data); } #endregion #region Warning public static void TraceWarning(TraceEventId eventId) { CustomTraceManagerModule.TraceEvent(TraceEventType.Warning, eventId); } public static void TraceWarning(TraceEventId eventId, string message, Exception exception = null) { if (exception == null) CustomTraceManagerModule.TraceEvent(TraceEventType.Warning, eventId, message); else CustomTraceManagerModule.TraceData(TraceEventType.Warning, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, message)); } public static void TraceWarning(TraceEventId eventId, string message, Exception exception, object data0, params object[] nData) { CustomTraceManagerModule.TraceData(TraceEventType.Warning, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, message, (nData == null) ? new object[] { data0 } : (new object[] { data0 }).Concat(nData).ToArray())); } public static void TraceWarning(TraceEventId eventId, Exception exception, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Warning, eventId, TraceDataObject.CreateExceptionEventData(eventId, exception, data)); } public static void TraceWarning(TraceEventId eventId, object data) { CustomTraceManagerModule.TraceData(TraceEventType.Warning, eventId, data); } public static void TraceWarning(TraceEventId eventId, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Warning, eventId, data); } #endregion #region Information public static void TraceInformation(TraceEventId eventId) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, eventId); } public static void TraceInformation(TraceEventId eventId, string message) { CustomTraceManagerModule.TraceEvent(TraceEventType.Information, eventId, message); } public static void TraceInformation(TraceEventId eventId, object data) { CustomTraceManagerModule.TraceData(TraceEventType.Information, eventId, data); } public static void TraceInformation(TraceEventId eventId, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Information, eventId, data); } #endregion #region Verbose public static void TraceVerbose(TraceEventId eventId) { CustomTraceManagerModule.TraceEvent(TraceEventType.Verbose, eventId); } public static void TraceVerbose(TraceEventId eventId, string message) { CustomTraceManagerModule.TraceEvent(TraceEventType.Verbose, eventId, message); } public static void TraceVerbose(TraceEventId eventId, object data) { CustomTraceManagerModule.TraceData(TraceEventType.Verbose, eventId, data); } public static void TraceVerbose(TraceEventId eventId, params object[] data) { CustomTraceManagerModule.TraceData(TraceEventType.Verbose, eventId, data); } #endregion public static void TraceData(TraceEventType traceEventType, TraceEventId traceEventId, object data) { CustomTraceManagerModule module = CustomTraceManagerModule.GetCurrent(); if (module != null && module.TraceSource != null) module._TraceData(traceEventType, traceEventId, data); else CustomTraceManagerModule._TraceEventLL(traceEventType, traceEventId, data); } public static void TraceData(TraceEventType traceEventType, TraceEventId traceEventId, params object[] data) { CustomTraceManagerModule module = CustomTraceManagerModule.GetCurrent(); if (module != null && module.TraceSource != null) module._TraceData(traceEventType, traceEventId, data); else CustomTraceManagerModule._TraceEventLL(traceEventType, traceEventId, data); } public static void TraceEvent(TraceEventType traceEventType, TraceEventId traceEventId) { CustomTraceManagerModule.TraceEvent(traceEventType, traceEventId, traceEventId.GetEnumDescription()); } public static void TraceEvent(TraceEventType traceEventType, TraceEventId traceEventId, string message) { CustomTraceManagerModule module = CustomTraceManagerModule.GetCurrent(); if (module != null && module.TraceSource != null) module._TraceEvent(traceEventType, traceEventId, message); else CustomTraceManagerModule._TraceEventLL(traceEventType, traceEventId, message); } private static void _TraceEventLL(TraceEventType traceEventType, TraceEventId traceEventId, string message) { switch (traceEventType) { case TraceEventType.Critical: Trace.TraceError(String.Format("Critical - ID {0}: {1}", traceEventId, message)); break; case TraceEventType.Error: Trace.TraceError(String.Format("ID {0}: {1}", traceEventId, message)); break; case TraceEventType.Warning: Trace.TraceWarning(String.Format("ID {0}: {1}", traceEventId, message)); break; case TraceEventType.Information: Trace.TraceInformation(String.Format("ID {0}: {1}", traceEventId, message)); break; default: Trace.WriteLine(String.Format("ID {0}: {1}", traceEventId, message), traceEventType.ToString("F")); break; } } private static void _TraceEventLL(TraceEventType traceEventType, TraceEventId traceEventId, params object[] data) { CustomTraceManagerModule._TraceEventLL(traceEventType, traceEventId, (new TraceDataObject(data)).ToString()); } public static void TraceEvent(TraceEventType traceEventType, TraceEventId traceEventId, string message, string detail) { string m = message, d = null; if (String.IsNullOrWhiteSpace(m)) { if (String.IsNullOrWhiteSpace(detail)) { CustomTraceManagerModule.TraceEvent(traceEventType, traceEventId); return; } m = detail; } else d = detail; if (String.IsNullOrWhiteSpace(d)) CustomTraceManagerModule.TraceEvent(traceEventType, traceEventId, m); else CustomTraceManagerModule.TraceData(traceEventType, traceEventId, new MessageAndDetail(m, d)); } public static void TraceTransfer(TraceEventId traceEventId, Guid relatedActivityId) { CustomTraceManagerModule.TraceTransfer(traceEventId, null, relatedActivityId); } public static void TraceTransfer(TraceEventId traceEventId, string message, Guid relatedActivityId) { CustomTraceManagerModule module = CustomTraceManagerModule.GetCurrent(); if (module != null && module.TraceSource != null) module._TraceTransfer(traceEventId, (String.IsNullOrWhiteSpace(message)) ? traceEventId.GetEnumDescription() : message, relatedActivityId); else CustomTraceManagerModule._TraceEventLL(TraceEventType.Transfer, traceEventId, String.Format("{0} ({1})", (String.IsNullOrWhiteSpace(message)) ? traceEventId.GetEnumDescription() : message, relatedActivityId)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; #region Sequential #region sequential stuct definition [StructLayout(LayoutKind.Sequential)] public struct S_INTArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_UINTArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_SHORTArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_WORDArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_LONG64Array_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public long[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_ULONG64Array_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_DOUBLEArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_FLOATArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_BYTEArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_CHARArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_LPSTRArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_LPCSTRArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_BSTRArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)] public string[] arr; } //struct array in a struct [StructLayout(LayoutKind.Sequential)] public struct TestStruct { public int x; public double d; public long l; public string str; } [StructLayout(LayoutKind.Sequential)] public struct S_StructArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_BOOLArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } #endregion #region sequential class definition [StructLayout(LayoutKind.Sequential)] public class C_INTArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_UINTArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_SHORTArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_WORDArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_LONG64Array_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public long[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_ULONG64Array_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_DOUBLEArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_FLOATArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_BYTEArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_CHARArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_LPSTRArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_LPCSTRArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_BSTRArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)] public string[] arr; } //struct array in a class [StructLayout(LayoutKind.Sequential)] public class C_StructArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_BOOLArray_Seq { [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } #endregion #endregion #region Explicit #region explicit stuct definition [StructLayout(LayoutKind.Explicit)] public struct S_INTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_UINTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_SHORTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_WORDArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_LONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.I8)] public long[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_ULONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_DOUBLEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_FLOATArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_BYTEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_CHARArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_LPSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_LPCSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_BSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)] public string[] arr; } //struct array in a struct [StructLayout(LayoutKind.Explicit)] public struct S_StructArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_BOOLArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } #endregion #region explicit class definition [StructLayout(LayoutKind.Explicit)] public class C_INTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_UINTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_SHORTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_WORDArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Explicit, Pack = 8)] public class C_LONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public long[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_ULONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_DOUBLEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_FLOATArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_BYTEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_CHARArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_LPSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_LPCSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_BSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.BStr)] public string[] arr; } //struct array in a class [StructLayout(LayoutKind.Explicit)] public class C_StructArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_BOOLArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.LPArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } #endregion #endregion
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org. // **************************************************************** using System; using System.Reflection; using NUnit.Core.Extensibility; namespace NUnit.Core.Builders { /// <summary> /// Class to build ether a parameterized or a normal NUnitTestMethod. /// There are four cases that the builder must deal with: /// 1. The method needs no params and none are provided /// 2. The method needs params and they are provided /// 3. The method needs no params but they are provided in error /// 4. The method needs params but they are not provided /// This could have been done using two different builders, but it /// turned out to be simpler to have just one. The BuildFrom method /// takes a different branch depending on whether any parameters are /// provided, but all four cases are dealt with in lower-level methods /// </summary> public class NUnitTestCaseBuilder : ITestCaseBuilder2 { private readonly bool allowOldStyleTests = NUnitConfiguration.AllowOldStyleTests; #region ITestCaseBuilder Methods /// <summary> /// Determines if the method can be used to build an NUnit test /// test method of some kind. The method must normally be marked /// with an identifying attriute for this to be true. If the test /// config file sets AllowOldStyleTests to true, then any method beginning /// "test..." (case-insensitive) is treated as a test unless /// it is also marked as a setup or teardown method. /// /// Note that this method does not check that the signature /// of the method for validity. If we did that here, any /// test methods with invalid signatures would be passed /// over in silence in the test run. Since we want such /// methods to be reported, the check for validity is made /// in BuildFrom rather than here. /// </summary> /// <param name="method">A MethodInfo for the method being used as a test method</param> /// <param name="suite">The test suite being built, to which the new test would be added</param> /// <returns>True if the builder can create a test case from this method</returns> public bool CanBuildFrom(MethodInfo method) { return Reflect.HasAttribute(method, NUnitFramework.TestAttribute, false) || Reflect.HasAttribute(method, NUnitFramework.TestCaseAttribute, false) || Reflect.HasAttribute(method, NUnitFramework.TestCaseSourceAttribute, false) || Reflect.HasAttribute(method, NUnitFramework.TheoryAttribute, false) || allowOldStyleTests && method.Name.ToLower().StartsWith("test") && !Reflect.HasAttribute(method, NUnitFramework.SetUpAttribute, true) && !Reflect.HasAttribute(method, NUnitFramework.TearDownAttribute, true) && !Reflect.HasAttribute(method, NUnitFramework.FixtureSetUpAttribute, true) && !Reflect.HasAttribute(method, NUnitFramework.FixtureTearDownAttribute, true); } /// <summary> /// Build a Test from the provided MethodInfo. Depending on /// whether the method takes arguments and on the availability /// of test case data, this method may return a single test /// or a group of tests contained in a ParameterizedMethodSuite. /// </summary> /// <param name="method">The MethodInfo for which a test is to be built</param> /// <param name="suite">The test fixture being populated, or null</param> /// <returns>A Test representing one or more method invocations</returns> public Test BuildFrom(MethodInfo method) { return BuildFrom(method, null); } #region ITestCaseBuilder2 Members public bool CanBuildFrom(MethodInfo method, Test parentSuite) { return CanBuildFrom(method); } public Test BuildFrom(MethodInfo method, Test parentSuite) { return CoreExtensions.Host.TestCaseProviders.HasTestCasesFor(method) ? BuildParameterizedMethodSuite(method, parentSuite) : BuildSingleTestMethod(method, parentSuite, null); } #endregion /// <summary> /// Builds a ParameterizedMetodSuite containing individual /// test cases for each set of parameters provided for /// this method. /// </summary> /// <param name="method">The MethodInfo for which a test is to be built</param> /// <returns>A ParameterizedMethodSuite populated with test cases</returns> public static Test BuildParameterizedMethodSuite(MethodInfo method, Test parentSuite) { ParameterizedMethodSuite methodSuite = new ParameterizedMethodSuite(method); NUnitFramework.ApplyCommonAttributes(method, methodSuite); foreach (object source in CoreExtensions.Host.TestCaseProviders.GetTestCasesFor(method, parentSuite)) { ParameterSet parms; if (source == null) { parms = new ParameterSet(); parms.Arguments = new object[] { null }; } else parms = source as ParameterSet; if (parms == null) { if (source.GetType().GetInterface("NUnit.Framework.ITestCaseData") != null) parms = ParameterSet.FromDataSource(source); else { parms = new ParameterSet(); ParameterInfo[] parameters = method.GetParameters(); Type sourceType = source.GetType(); if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(sourceType)) parms.Arguments = new object[] { source }; else if (source is object[]) parms.Arguments = (object[])source; else if (source is Array) { Array array = (Array)source; if (array.Rank == 1) { parms.Arguments = new object[array.Length]; for (int i = 0; i < array.Length; i++) parms.Arguments[i] = (object)array.GetValue(i); } } else parms.Arguments = new object[] { source }; } } TestMethod test = BuildSingleTestMethod(method, parentSuite, parms); methodSuite.Add(test); } return methodSuite; } /// <summary> /// Builds a single NUnitTestMethod, either as a child of the fixture /// or as one of a set of test cases under a ParameterizedTestMethodSuite. /// </summary> /// <param name="method">The MethodInfo from which to construct the TestMethod</param> /// <param name="parms">The ParameterSet to be used, or null</param> /// <returns></returns> public static NUnitTestMethod BuildSingleTestMethod(MethodInfo method, Test parentSuite, ParameterSet parms) { NUnitTestMethod testMethod = new NUnitTestMethod(method); string prefix = method.ReflectedType.FullName; if (parentSuite != null) { prefix = parentSuite.TestName.FullName; testMethod.TestName.FullName = prefix + "." + testMethod.TestName.Name; } if (CheckTestMethodSignature(testMethod, parms)) { if (parms == null) NUnitFramework.ApplyCommonAttributes(method, testMethod); NUnitFramework.ApplyExpectedExceptionAttribute(method, testMethod); } if (parms != null) { // NOTE: After the call to CheckTestMethodSignature, the Method // property of testMethod may no longer be the same as the // original MethodInfo, so we reassign it here. method = testMethod.Method; if (parms.TestName != null) { testMethod.TestName.Name = parms.TestName; testMethod.TestName.FullName = prefix + "." + parms.TestName; } else if (parms.OriginalArguments != null) { string name = MethodHelper.GetDisplayName(method, parms.OriginalArguments); testMethod.TestName.Name = name; testMethod.TestName.FullName = prefix + "." + name; } if (parms.Ignored) { testMethod.RunState = RunState.Ignored; testMethod.IgnoreReason = parms.IgnoreReason; } if (parms.ExpectedExceptionName != null) testMethod.exceptionProcessor = new ExpectedExceptionProcessor(testMethod, parms); foreach (string key in parms.Properties.Keys) testMethod.Properties[key] = parms.Properties[key]; // Description is stored in parms.Properties if (parms.Description != null) testMethod.Description = parms.Description; } if (testMethod.BuilderException != null) testMethod.RunState = RunState.NotRunnable; return testMethod; } #endregion #region Helper Methods /// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> private static bool CheckTestMethodSignature(TestMethod testMethod, ParameterSet parms) { if (testMethod.Method.IsAbstract) { testMethod.RunState = RunState.NotRunnable; testMethod.IgnoreReason = "Method is abstract"; return false; } if (!testMethod.Method.IsPublic) { testMethod.RunState = RunState.NotRunnable; testMethod.IgnoreReason = "Method is not public"; return false; } ParameterInfo[] parameters = testMethod.Method.GetParameters(); int argsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.arguments = parms.Arguments; testMethod.expectedResult = parms.Result; testMethod.hasExpectedResult = parms.HasExpectedResult; testMethod.RunState = parms.RunState; testMethod.IgnoreReason = parms.NotRunReason; testMethod.BuilderException = parms.ProviderException; arglist = parms.Arguments; if (arglist != null) argsProvided = arglist.Length; if (testMethod.RunState != RunState.Runnable) return false; } if (!testMethod.Method.ReturnType.Equals(typeof(void)) && (parms == null || !parms.HasExpectedResult && parms.ExpectedExceptionName == null)) { testMethod.RunState = RunState.NotRunnable; testMethod.IgnoreReason = "Method has non-void return value"; return false; } if (argsProvided > 0 && argsNeeded == 0) { testMethod.RunState = RunState.NotRunnable; testMethod.IgnoreReason = "Arguments provided for method not taking any"; return false; } if (argsProvided == 0 && argsNeeded > 0) { testMethod.RunState = RunState.NotRunnable; testMethod.IgnoreReason = "No arguments were provided"; return false; } //if (argsProvided > argsNeeded) //{ // ParameterInfo lastParameter = parameters[argsNeeded - 1]; // Type lastParameterType = lastParameter.ParameterType; // if (lastParameterType.IsArray && lastParameter.IsDefined(typeof(ParamArrayAttribute), false)) // { // object[] newArglist = new object[argsNeeded]; // for (int i = 0; i < argsNeeded; i++) // newArglist[i] = arglist[i]; // int length = argsProvided - argsNeeded + 1; // Array array = Array.CreateInstance(lastParameterType.GetElementType(), length); // for (int i = 0; i < length; i++) // array.SetValue(arglist[argsNeeded + i - 1], i); // newArglist[argsNeeded - 1] = array; // testMethod.arguments = arglist = newArglist; // argsProvided = argsNeeded; // } //} if (argsProvided != argsNeeded ) { testMethod.RunState = RunState.NotRunnable; testMethod.IgnoreReason = "Wrong number of arguments provided"; return false; } #if NET_2_0 if (testMethod.Method.IsGenericMethodDefinition) { Type[] typeArguments = GetTypeArgumentsForMethod(testMethod.Method, arglist); foreach (object o in typeArguments) if (o == null) { testMethod.RunState = RunState.NotRunnable; testMethod.IgnoreReason = "Unable to determine type arguments for fixture"; return false; } testMethod.method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (arglist[i].GetType() != parameters[i].ParameterType && arglist[i] is IConvertible) { try { arglist[i] = Convert.ChangeType(arglist[i], parameters[i].ParameterType); } catch (Exception) { // Do nothing - the incompatible argument will be reported below } } } } #endif return true; } #if NET_2_0 private static Type[] GetTypeArgumentsForMethod(MethodInfo method, object[] arglist) { Type[] typeParameters = method.GetGenericArguments(); Type[] typeArguments = new Type[typeParameters.Length]; ParameterInfo[] parameters = method.GetParameters(); for (int typeIndex = 0; typeIndex < typeArguments.Length; typeIndex++) { Type typeParameter = typeParameters[typeIndex]; for (int argIndex = 0; argIndex < parameters.Length; argIndex++) { if (parameters[argIndex].ParameterType.Equals(typeParameter)) typeArguments[typeIndex] = TypeHelper.BestCommonType( typeArguments[typeIndex], arglist[argIndex].GetType()); } } return typeArguments; } #endif #endregion } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using OpenSim.Framework; using OpenMetaverse; namespace Halcyon.Data.Inventory.MySQL { [TestFixture] class UnitTests { private MySqlInventoryStorage _storage; [SetUp] public void Setup() { _storage = new MySqlInventoryStorage("Data Source=localhost;User=root;Password=secret"); } [TestCase] public void TestBasicCreateFolder() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Test Root 1"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Zero; folder.Type = 1; _storage.CreateFolder(folder); List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId); Assert.IsTrue(skel.Count == 1); Assert.AreEqual(skel[0].ID, folder.ID); InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID); AssertFolderEqual(folder, folderCopy, true); Assert.AreEqual(1, folderCopy.Version); _storage.SaveFolder(folderCopy); InventoryFolderBase folderCopy2 = _storage.GetFolderAttributes(folder.ID); AssertFolderEqual(folder, folderCopy2, true); Assert.AreEqual(2, folderCopy2.Version); } [TestCase] public void TestSkeletonDataMatchesFolderProps() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "TestFolder"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Random(); folder.Type = -1; _storage.CreateFolder(folder); List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId); Assert.IsTrue(skel.Count == 1); AssertFolderEqual(skel[0], folder, true); InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID); AssertFolderEqual(folder, folderCopy, true); AssertFolderEqual(skel[0], folderCopy, true); Assert.AreEqual(1, folderCopy.Version); } [TestCase] public void TestUpdateFolderKeepsIndexUpdated() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Test Folder zzzzzz"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Random(); folder.Type = -1; _storage.CreateFolder(folder); folder.Name = "Updated TestFolderZZZ"; _storage.SaveFolder(folder); List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId); Assert.AreEqual(1, skel.Count); Assert.AreEqual(2, skel[0].Version); AssertFolderEqual(folder, skel[0], true); UUID newParent = UUID.Random(); _storage.MoveFolder(folder, newParent); InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID); skel = _storage.GetInventorySkeleton(userId); Assert.AreEqual(1, skel.Count); Assert.AreEqual(3, skel[0].Version); Assert.AreEqual(newParent, folderCopy.ParentID); AssertFolderEqual(folderCopy, skel[0], true); } private void AssertFolderEqual(InventoryFolderBase f1, InventoryFolderBase f2, bool checkParent) { Assert.AreEqual(f1.ID, f2.ID); Assert.AreEqual(f1.Level, f2.Level); Assert.AreEqual(f1.Name, f2.Name); Assert.AreEqual(f1.Owner, f2.Owner); if (checkParent) { Assert.AreEqual(f1.ParentID, f2.ParentID); } Assert.AreEqual(f1.Type, f2.Type); } [TestCase] public void TestMoveFolderToNewParent() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Test Root 1"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Zero; folder.Type = 1; _storage.CreateFolder(folder); InventoryFolderBase firstLeaf = new InventoryFolderBase(); firstLeaf.ID = UUID.Random(); firstLeaf.Name = "Leaf 1"; firstLeaf.Level = InventoryFolderBase.FolderLevel.Leaf; firstLeaf.Owner = userId; firstLeaf.ParentID = folder.ID; firstLeaf.Type = 1; InventoryFolderBase secondLeaf = new InventoryFolderBase(); secondLeaf.ID = UUID.Random(); secondLeaf.Name = "Leaf 2"; secondLeaf.Level = InventoryFolderBase.FolderLevel.Leaf; secondLeaf.Owner = userId; secondLeaf.ParentID = folder.ID; secondLeaf.Type = 1; _storage.CreateFolder(firstLeaf); _storage.CreateFolder(secondLeaf); InventoryFolderBase secondLeafCopy = _storage.GetFolderAttributes(secondLeaf.ID); AssertFolderEqual(secondLeaf, secondLeafCopy, true); Assert.AreEqual(1, secondLeafCopy.Version); _storage.MoveFolder(secondLeaf, firstLeaf.ID); InventoryFolderBase secondLeafWithNewParent = _storage.GetFolderAttributes(secondLeaf.ID); AssertFolderEqual(secondLeaf, secondLeafWithNewParent, false); Assert.AreEqual(firstLeaf.ID, secondLeafWithNewParent.ParentID); Assert.AreEqual(2, secondLeafWithNewParent.Version); InventoryFolderBase firstLeafWithSecondLeafChild = _storage.GetFolder(firstLeaf.ID); AssertFolderEqual(firstLeafWithSecondLeafChild, firstLeaf, true); Assert.AreEqual(1, firstLeafWithSecondLeafChild.SubFolders.Count); Assert.AreEqual(secondLeaf.Name, firstLeafWithSecondLeafChild.SubFolders[0].Name); Assert.AreEqual(secondLeaf.ID, firstLeafWithSecondLeafChild.SubFolders[0].ID); Assert.AreEqual(2, firstLeafWithSecondLeafChild.Version); } [TestCase] public void TestFolderChangeUpdateParent() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Test Root 1"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Zero; folder.Type = 1; _storage.CreateFolder(folder); InventoryFolderBase firstLeaf = new InventoryFolderBase(); firstLeaf.ID = UUID.Random(); firstLeaf.Name = "Leaf 1"; firstLeaf.Level = InventoryFolderBase.FolderLevel.Leaf; firstLeaf.Owner = userId; firstLeaf.ParentID = folder.ID; firstLeaf.Type = 1; _storage.CreateFolder(firstLeaf); firstLeaf.Name = "Leaf 1, Updated"; _storage.SaveFolder(firstLeaf); InventoryFolderBase folderWithUpdatedChild = _storage.GetFolder(folder.ID); Assert.AreEqual(1, folderWithUpdatedChild.SubFolders.Count); Assert.AreEqual(firstLeaf.Name, folderWithUpdatedChild.SubFolders[0].Name); Assert.AreEqual(firstLeaf.ID, folderWithUpdatedChild.SubFolders[0].ID); } [TestCase] public void TestSendFolderToTrash() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Trash Folder"; folder.Level = InventoryFolderBase.FolderLevel.TopLevel; folder.Owner = userId; folder.ParentID = UUID.Zero; folder.Type = (short)OpenMetaverse.FolderType.Trash; _storage.CreateFolder(folder); InventoryFolderBase trashFolderRetrieved = _storage.GetFolder(folder.ID); Assert.AreEqual((short)OpenMetaverse.FolderType.Trash, trashFolderRetrieved.Type); InventoryFolderBase firstLeaf = new InventoryFolderBase(); firstLeaf.ID = UUID.Random(); firstLeaf.Name = "Leaf 1"; firstLeaf.Level = InventoryFolderBase.FolderLevel.Leaf; firstLeaf.Owner = userId; firstLeaf.ParentID = UUID.Zero; firstLeaf.Type = 1; _storage.CreateFolder(firstLeaf); _storage.SendFolderToTrash(firstLeaf, UUID.Zero); InventoryFolderBase leafFolderAfterTrashed = _storage.GetFolder(firstLeaf.ID); Assert.AreEqual(folder.ID, leafFolderAfterTrashed.ParentID); InventoryFolderBase trashFolderAfterLeafTrashed = _storage.GetFolder(folder.ID); Assert.AreEqual(1, trashFolderAfterLeafTrashed.SubFolders.Count); Assert.AreEqual(leafFolderAfterTrashed.ID, trashFolderAfterLeafTrashed.SubFolders[0].ID); Assert.AreEqual(leafFolderAfterTrashed.Name, trashFolderAfterLeafTrashed.SubFolders[0].Name); } [TestCase] public void TestBasicCreateItem() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Root Folder"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Zero; folder.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder); UUID assetId = UUID.Random(); UUID itemId = UUID.Random(); InventoryItemBase item = new InventoryItemBase { AssetID = assetId, AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = 0xFF, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = 0xFFF, Description = "A good item, of goodness", EveryOnePermissions = 0xFFFF, Flags = 0x12, Folder = folder.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = itemId, InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; _storage.CreateItem(item); InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero); AssertItemEqual(itemCopy, item); InventoryFolderBase folderWithItem = _storage.GetFolder(folder.ID); Assert.AreEqual(1, folderWithItem.Items.Count); Assert.AreEqual(2, folderWithItem.Version); AssertItemEqual(itemCopy, folderWithItem.Items[0]); } [TestCase] public void TestSaveItem() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Root Folder"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Zero; folder.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder); UUID assetId = UUID.Random(); UUID itemId = UUID.Random(); InventoryItemBase item = new InventoryItemBase { AssetID = assetId, AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = 0xFF, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = 0xFFF, Description = "A good item, of goodness", EveryOnePermissions = 0xFFFF, Flags = 0x12, Folder = folder.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = itemId, InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; _storage.CreateItem(item); InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero); AssertItemEqual(itemCopy, item); item.AssetID = assetId; item.AssetType = (int)OpenMetaverse.AssetType.Sound; item.BasePermissions = 0xAA; item.CreationDate = Util.UnixTimeSinceEpoch(); item.CreatorId = userId.ToString(); item.CurrentPermissions = 0xAAA; item.Description = "A good itemddddd"; item.EveryOnePermissions = 0xAAAA; item.Flags = 0x24; item.Folder = folder.ID; item.GroupID = UUID.Random(); item.GroupOwned = true; item.GroupPermissions = 0x456; item.ID = itemId; item.InvType = (int)OpenMetaverse.InventoryType.Sound; item.Name = "Itemjkhdsahjkadshkjasds"; item.NextPermissions = 0xA; item.Owner = userId; item.SalePrice = 10; item.SaleType = 8; _storage.SaveItem(item); itemCopy = _storage.GetItem(itemId, UUID.Zero); AssertItemEqual(itemCopy, item); InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID); Assert.AreEqual(3, folderCopy.Version); } [TestCase] public void TestSaveItemInt32Extremes() { UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "Root Folder"; folder.Level = InventoryFolderBase.FolderLevel.Root; folder.Owner = userId; folder.ParentID = UUID.Zero; folder.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder); UUID assetId = UUID.Random(); UUID itemId = UUID.Random(); InventoryItemBase item = new InventoryItemBase { AssetID = assetId, AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), Folder = folder.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = itemId, InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; _storage.CreateItem(item); InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero); AssertItemEqual(itemCopy, item); } [Test] [Repeat(10)] public void TestBasicMoveItem() { UUID userId = UUID.Random(); InventoryFolderBase folder1 = new InventoryFolderBase(); folder1.ID = UUID.Random(); folder1.Name = "Folder1"; folder1.Level = InventoryFolderBase.FolderLevel.Root; folder1.Owner = userId; folder1.ParentID = UUID.Zero; folder1.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder1); InventoryFolderBase folder2 = new InventoryFolderBase(); folder2.ID = UUID.Random(); folder2.Name = "Folder1"; folder2.Level = InventoryFolderBase.FolderLevel.Root; folder2.Owner = userId; folder2.ParentID = UUID.Zero; folder2.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder2); UUID assetId = UUID.Random(); UUID itemId = UUID.Random(); InventoryItemBase item = new InventoryItemBase { AssetID = assetId, AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), Folder = folder1.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = itemId, InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; _storage.CreateItem(item); /// /// NOTE: The race mentioned here should be fixed. I replaced the UnixTimeSinceEpochInMicroseconds /// Implementation to fix it. I am leaving the comments here as historical information. /// The sleep is no longer needed /// //I'm seeing a race here, that could be explained by //the timestamps in the ItemParents CF being the same between //the create and the move call. The index is left in a state //still pointing at the old folder //we sleep to mitigate this problem since we should never see a create //and a move executed in the same tick in a real inventory situation //this highlights the need for all clocks on the network to be synchronized //System.Threading.Thread.Sleep(30); _storage.MoveItem(item, folder2); InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero); AssertItemEqual(item, itemCopy); Assert.AreEqual(folder2.ID, item.Folder); InventoryFolderBase containingFolder = _storage.GetFolder(folder2.ID); Assert.AreEqual(2, containingFolder.Version); Assert.AreEqual(1, containingFolder.Items.Count); AssertItemEqual(item, containingFolder.Items[0]); InventoryFolderBase oldFolder = _storage.GetFolder(folder1.ID); Assert.AreEqual(0, oldFolder.Items.Count); Assert.AreEqual(3, oldFolder.Version); } [Test] public void TestItemPurge() { UUID userId = UUID.Random(); InventoryFolderBase folder1 = new InventoryFolderBase(); folder1.ID = UUID.Random(); folder1.Name = "Folder1"; folder1.Level = InventoryFolderBase.FolderLevel.Root; folder1.Owner = userId; folder1.ParentID = UUID.Zero; folder1.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder1); Amib.Threading.SmartThreadPool pool = new Amib.Threading.SmartThreadPool(1000, 20); pool.Start(); for (int i = 0; i < 1000; i++) { pool.QueueWorkItem(() => { UUID assetId = UUID.Random(); UUID itemId = UUID.Random(); InventoryItemBase item = new InventoryItemBase { AssetID = assetId, AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), Folder = folder1.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = itemId, InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; _storage.PurgeItem(item); _storage.CreateItem(item); _storage.PurgeItem(item); _storage.CreateItem(item); _storage.PurgeItem(item); var ex = Assert.Throws<InventoryObjectMissingException>(delegate() { InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero); }); Assert.AreEqual("Item was not found in the index", ex.ErrorDetails); }); } pool.WaitForIdle(); InventoryFolderBase newFolder = _storage.GetFolder(folder1.ID); Assert.AreEqual(0, newFolder.Items.Count); Assert.AreEqual(5001, newFolder.Version); } [Test] public void TestPurgeCreateConsistent() { Amib.Threading.SmartThreadPool pool = new Amib.Threading.SmartThreadPool(1000, 20); pool.Start(); var userId = UUID.Parse("01EAE367-3A88-48B2-A226-AB3234EE506B"); InventoryFolderBase folder1 = new InventoryFolderBase(); folder1.ID = UUID.Parse("F1EAE367-3A88-48B2-A226-AB3234EE506B"); folder1.Name = "Folder1"; folder1.Level = InventoryFolderBase.FolderLevel.Root; folder1.Owner = userId; folder1.ParentID = UUID.Zero; folder1.Type = (short)OpenMetaverse.FolderType.Root; try { _storage.GetFolderAttributes(folder1.ID); } catch (InventoryObjectMissingException e) { _storage.CreateFolder(folder1); } for (int i = 0; i < 100; i++) { UUID assetId = UUID.Random(); UUID itemId = UUID.Random(); InventoryItemBase item = new InventoryItemBase { AssetID = assetId, AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), Folder = folder1.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = itemId, InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; pool.QueueWorkItem(() => { _storage.CreateItem(item); }); pool.QueueWorkItem(() => { _storage.PurgeItem(item); }); pool.QueueWorkItem(() => { _storage.CreateItem(item); }); pool.QueueWorkItem(() => { _storage.PurgeItem(item); }); pool.WaitForIdle(); InventoryFolderBase newFolder = _storage.GetFolder(folder1.ID); //either the item should completely exist or not if (newFolder.Items.Exists((InventoryItemBase litem) => { return litem.ID == itemId; })) { Assert.DoesNotThrow(delegate() { InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero); }); //cleanup _storage.PurgeItem(item); } else { var ex = Assert.Throws<InventoryObjectMissingException>(delegate() { InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero); }); Assert.AreEqual("Item was not found in the index", ex.ErrorDetails); } } InventoryFolderBase finalFolder = _storage.GetFolder(folder1.ID); Assert.AreEqual(0, finalFolder.Items.Count); } [TestCase] public void TestItemMove() { UUID userId = UUID.Random(); InventoryFolderBase folder1 = new InventoryFolderBase(); folder1.ID = UUID.Random(); folder1.Name = "Folder1"; folder1.Level = InventoryFolderBase.FolderLevel.Root; folder1.Owner = userId; folder1.ParentID = UUID.Zero; folder1.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder1); InventoryFolderBase folder2 = new InventoryFolderBase(); folder2.ID = UUID.Random(); folder2.Name = "Folder2"; folder2.Level = InventoryFolderBase.FolderLevel.Root; folder2.Owner = userId; folder2.ParentID = UUID.Zero; folder2.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(folder1); _storage.CreateFolder(folder2); UUID assetId = UUID.Random(); UUID itemId = UUID.Random(); InventoryItemBase item = new InventoryItemBase { AssetID = assetId, AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), Folder = folder1.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = itemId, InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; _storage.CreateItem(item); _storage.MoveItem(item, folder2); InventoryFolderBase newFolder1 = _storage.GetFolder(folder1.ID); InventoryFolderBase newFolder2 = _storage.GetFolder(folder2.ID); AssertFolderEqual(folder1, newFolder1, true); AssertFolderEqual(folder2, newFolder2, true); Assert.AreEqual(0, newFolder1.Items.Count); Assert.AreEqual(1, newFolder2.Items.Count); InventoryItemBase newItem = _storage.GetItem(item.ID, UUID.Zero); item.Folder = newFolder2.ID; AssertItemEqual(item, newItem); } [TestCase] public void TestSendItemToTrash() { UUID userId = UUID.Random(); InventoryFolderBase rootFolder = new InventoryFolderBase(); rootFolder.ID = UUID.Random(); rootFolder.Name = "Root Folder"; rootFolder.Level = InventoryFolderBase.FolderLevel.Root; rootFolder.Owner = userId; rootFolder.ParentID = UUID.Zero; rootFolder.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(rootFolder); InventoryFolderBase trashFolder = new InventoryFolderBase(); trashFolder.ID = UUID.Random(); trashFolder.Name = "Trash Folder"; trashFolder.Level = InventoryFolderBase.FolderLevel.TopLevel; trashFolder.Owner = userId; trashFolder.ParentID = rootFolder.ID; trashFolder.Type = (short)OpenMetaverse.FolderType.Trash; _storage.CreateFolder(trashFolder); InventoryItemBase item = new InventoryItemBase { AssetID = UUID.Random(), AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), Folder = rootFolder.ID, GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = UUID.Random(), InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "Item of Goodness", NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; _storage.SendItemToTrash(item, UUID.Zero); InventoryItemBase trashedItem = _storage.GetItem(item.ID, UUID.Zero); Assert.AreEqual(trashedItem.Folder, trashFolder.ID); AssertItemEqual(item, trashedItem); } [TestCase] public void TestFolderPurgeContents() { UUID userId = UUID.Random(); InventoryFolderBase rootFolder = new InventoryFolderBase(); rootFolder.ID = UUID.Random(); rootFolder.Name = "Root Folder"; rootFolder.Level = InventoryFolderBase.FolderLevel.Root; rootFolder.Owner = userId; rootFolder.ParentID = UUID.Zero; rootFolder.Type = (short)OpenMetaverse.FolderType.Root; _storage.CreateFolder(rootFolder); InventoryFolderBase trashFolder = new InventoryFolderBase(); trashFolder.ID = UUID.Random(); trashFolder.Name = "Trash Folder"; trashFolder.Level = InventoryFolderBase.FolderLevel.TopLevel; trashFolder.Owner = userId; trashFolder.ParentID = rootFolder.ID; trashFolder.Type = (short)OpenMetaverse.FolderType.Trash; _storage.CreateFolder(trashFolder); //generate 50 folders with 500 items in them List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); List<InventoryItemBase> items = new List<InventoryItemBase>(); Random r = new Random(); for (int i = 0; i < 50; i++) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "RandomFolder" + i.ToString(); folder.Level = InventoryFolderBase.FolderLevel.Leaf; folder.Owner = userId; folder.Type = (short)OpenMetaverse.FolderType.Trash; int index = r.Next(-1, folders.Count - 1); if (index == -1) { folder.ParentID = trashFolder.ID; } else { folder.ParentID = folders[index].ID; } folders.Add(folder); } for (int i = 0; i < 200; i++) { InventoryItemBase item = new InventoryItemBase { AssetID = UUID.Random(), AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = UUID.Random(), InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "RandomItem" + i.ToString(), NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1 }; int index = r.Next(-1, folders.Count - 1); if (index == -1) { item.Folder = trashFolder.ID; } else { item.Folder = folders[index].ID; } items.Add(item); } foreach (InventoryFolderBase folder in folders) { _storage.CreateFolder(folder); } foreach (InventoryItemBase item in items) { _storage.CreateItem(item); } //verify the trash folder is now full of stuff InventoryFolderBase fullTrash = _storage.GetFolder(trashFolder.ID); Assert.That(fullTrash.SubFolders.Count > 0); //make sure all folders are accounted for List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId); Assert.AreEqual(52, skel.Count); //do some raw queries to verify we have good indexing happening foreach (InventoryItemBase item in items) { Guid parent = _storage.FindItemParentFolderId(item.ID); Assert.AreEqual(parent, item.Folder.Guid); } //purge the trash _storage.PurgeFolderContents(trashFolder); //verify the index is empty except for the trash and the root skel = _storage.GetInventorySkeleton(userId); Assert.AreEqual(2, skel.Count); //verify none of the items are accessable anymore foreach (InventoryItemBase item in items) { Assert.Throws<InventoryObjectMissingException>(delegate() { _storage.GetItem(item.ID, UUID.Zero); }); Assert.Throws<InventoryObjectMissingException>(delegate() { _storage.GetItem(item.ID, item.Folder); }); } //verify the root folder doesn't show any items or subfolders InventoryFolderBase emptyTrash = _storage.GetFolder(trashFolder.ID); Assert.AreEqual(0, emptyTrash.Items.Count); Assert.AreEqual(0, emptyTrash.SubFolders.Count); } [TestCase] public void TestFolderIndexPagination() { TestFolderIndexPagination(1); TestFolderIndexPagination(1023); TestFolderIndexPagination(1024); TestFolderIndexPagination(1025); TestFolderIndexPagination(2047); TestFolderIndexPagination(2048); TestFolderIndexPagination(2049); } private void TestFolderIndexPagination(int FOLDER_COUNT) { UUID userId = UUID.Random(); List<InventoryFolderBase> folders = new List<InventoryFolderBase>(FOLDER_COUNT); for (int i = 0; i < FOLDER_COUNT; i++) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "RandomFolder" + i.ToString(); folder.Level = InventoryFolderBase.FolderLevel.TopLevel; folder.Owner = userId; folder.Type = (short)OpenMetaverse.AssetType.Unknown; folder.ParentID = UUID.Zero; _storage.CreateFolder(folder); folders.Add(folder); //add an item to the folder so that its version is 2 InventoryItemBase item = new InventoryItemBase { AssetID = UUID.Random(), AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "A good item, of goodness", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = UUID.Random(), InvType = (int)OpenMetaverse.InventoryType.Texture, Name = "RandomItem" + i.ToString(), NextPermissions = 0xF, Owner = userId, SalePrice = 100, SaleType = 1, Folder = folder.ID }; _storage.CreateItem(item); } List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId); Assert.AreEqual(FOLDER_COUNT, skel.Count); Dictionary<UUID, InventoryFolderBase> indexOfFolders = new Dictionary<UUID, InventoryFolderBase>(); foreach (InventoryFolderBase folder in skel) { indexOfFolders.Add(folder.ID, folder); Assert.AreEqual(2, folder.Version); } foreach (InventoryFolderBase folder in folders) { Assert.That(indexOfFolders.ContainsKey(folder.ID)); AssertFolderEqual(folder, indexOfFolders[folder.ID], true); } } [TestCase] public void TestSinglePurgeFolder() { UUID userId = UUID.Random(); InventoryFolderBase parentFolder = new InventoryFolderBase(); parentFolder.ID = UUID.Random(); parentFolder.Name = "RootFolder"; parentFolder.Level = InventoryFolderBase.FolderLevel.Root; parentFolder.Owner = userId; parentFolder.Type = (short)OpenMetaverse.FolderType.Root; parentFolder.ParentID = UUID.Zero; InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "RandomFolder"; folder.Level = InventoryFolderBase.FolderLevel.TopLevel; folder.Owner = userId; folder.Type = (short)OpenMetaverse.AssetType.Unknown; folder.ParentID = parentFolder.ID; _storage.CreateFolder(parentFolder); _storage.CreateFolder(folder); //System.Threading.Thread.Sleep(30); _storage.PurgeFolder(folder); List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId); Assert.AreEqual(1, skel.Count); Assert.Throws<InventoryObjectMissingException>(delegate() { _storage.GetFolder(folder.ID); }); InventoryFolderBase updatedParent = _storage.GetFolder(parentFolder.ID); Assert.AreEqual(0, updatedParent.SubFolders.Count); } [TestCase] public void TestMultiPurgeFolder() { const int FOLDER_COUNT = 20; UUID userId = UUID.Random(); List<InventoryFolderBase> folders = new List<InventoryFolderBase>(FOLDER_COUNT); for (int i = 0; i < FOLDER_COUNT; i++) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "RandomFolder" + i.ToString(); folder.Level = InventoryFolderBase.FolderLevel.TopLevel; folder.Owner = userId; folder.Type = (short)OpenMetaverse.AssetType.Unknown; folder.ParentID = UUID.Zero; _storage.CreateFolder(folder); folders.Add(folder); } System.Threading.Thread.Sleep(30); _storage.PurgeFolders(folders); List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId); Assert.AreEqual(0, skel.Count); foreach (InventoryFolderBase folder in folders) { Assert.Throws<InventoryObjectMissingException>(delegate() { _storage.GetFolder(folder.ID); }); } } [TestCase] public void TestGestureTracking() { const int NUM_GESTURES = 100; List<InventoryItemBase> gestures = new List<InventoryItemBase>(); Dictionary<UUID, InventoryItemBase> gestureIndex = new Dictionary<UUID, InventoryItemBase>(); UUID userId = UUID.Random(); InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "RandomFolder"; folder.Level = InventoryFolderBase.FolderLevel.TopLevel; folder.Owner = userId; folder.Type = (short)OpenMetaverse.AssetType.Unknown; folder.ParentID = UUID.Zero; _storage.CreateFolder(folder); for (int i = 0; i < NUM_GESTURES; i++) { InventoryItemBase item = new InventoryItemBase { AssetID = UUID.Random(), AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "Gesture", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = UUID.Random(), InvType = (int)OpenMetaverse.InventoryType.Gesture, Name = "RandomItem" + i.ToString(), NextPermissions = 0xF, Owner = userId, Folder = folder.ID }; gestures.Add(item); gestureIndex.Add(item.ID, item); _storage.CreateItem(item); } _storage.ActivateGestures(userId, (from item in gestures select item.ID)); //make sure all the gestures show active List<InventoryItemBase> items = _storage.GetActiveGestureItems(userId); Assert.AreEqual(NUM_GESTURES, items.Count); foreach (InventoryItemBase item in items) { Assert.That(gestureIndex.ContainsKey(item.ID)); AssertItemEqual(gestureIndex[item.ID], item); gestureIndex.Remove(item.ID); } Assert.AreEqual(0, gestureIndex.Count); _storage.DeactivateGestures(userId, (from item in gestures select item.ID)); items = _storage.GetActiveGestureItems(userId); Assert.AreEqual(0, items.Count); } private void AssertItemEqual(InventoryItemBase i1, InventoryItemBase i2) { Assert.AreEqual(i1.AssetID, i2.AssetID); Assert.AreEqual(i1.AssetType, i2.AssetType); Assert.AreEqual(i1.BasePermissions, i2.BasePermissions); Assert.AreEqual(i1.ContainsMultipleItems, i2.ContainsMultipleItems); Assert.AreEqual(i1.CreationDate, i2.CreationDate); Assert.AreEqual(i1.CreatorId, i2.CreatorId); Assert.AreEqual(i1.CreatorIdAsUuid, i2.CreatorIdAsUuid); Assert.AreEqual(i1.CurrentPermissions, i2.CurrentPermissions); Assert.AreEqual(i1.Description, i2.Description); Assert.AreEqual(i1.EveryOnePermissions, i2.EveryOnePermissions); Assert.AreEqual(i1.Flags, i2.Flags); Assert.AreEqual(i1.Folder, i2.Folder); Assert.AreEqual(i1.GroupID, i2.GroupID); Assert.AreEqual(i1.GroupOwned, i2.GroupOwned); Assert.AreEqual(i1.GroupPermissions, i2.GroupPermissions); Assert.AreEqual(i1.ID, i2.ID); Assert.AreEqual(i1.InvType, i2.InvType); Assert.AreEqual(i1.Name, i2.Name); Assert.AreEqual(i1.NextPermissions, i2.NextPermissions); Assert.AreEqual(i1.Owner, i2.Owner); Assert.AreEqual(i1.SalePrice, i2.SalePrice); Assert.AreEqual(i1.SaleType, i2.SaleType); } [TestCase] public void TestInvalidSubfolderIndexCleanup() { UUID userId = UUID.Random(); InventoryFolderBase parentFolder = new InventoryFolderBase(); parentFolder.ID = UUID.Random(); parentFolder.Name = "RootFolder"; parentFolder.Level = InventoryFolderBase.FolderLevel.Root; parentFolder.Owner = userId; parentFolder.Type = (short)OpenMetaverse.FolderType.Root; parentFolder.ParentID = UUID.Zero; InventoryFolderBase folder = new InventoryFolderBase(); folder.ID = UUID.Random(); folder.Name = "RandomFolder"; folder.Level = InventoryFolderBase.FolderLevel.TopLevel; folder.Owner = userId; folder.Type = (short)OpenMetaverse.AssetType.Unknown; folder.ParentID = parentFolder.ID; _storage.CreateFolder(parentFolder); _storage.CreateFolder(folder); InventoryFolderBase validChild = new InventoryFolderBase(); validChild.ID = UUID.Random(); validChild.Name = "ValidChild"; validChild.Level = InventoryFolderBase.FolderLevel.Leaf; validChild.Owner = userId; validChild.Type = (short)OpenMetaverse.AssetType.Unknown; validChild.ParentID = folder.ID; _storage.CreateFolder(validChild); InventoryItemBase item = new InventoryItemBase { AssetID = UUID.Random(), AssetType = (int)OpenMetaverse.AssetType.Texture, BasePermissions = UInt32.MaxValue, CreationDate = Util.UnixTimeSinceEpoch(), CreatorId = userId.ToString(), CurrentPermissions = unchecked((uint)-1), Description = "Gesture", EveryOnePermissions = Int32.MaxValue + (uint)1, Flags = unchecked((uint)Int32.MinValue), GroupID = UUID.Zero, GroupOwned = false, GroupPermissions = 0x123, ID = UUID.Random(), InvType = (int)OpenMetaverse.InventoryType.Gesture, Name = "RandomItem", NextPermissions = 0xF, Owner = userId, Folder = validChild.ID }; _storage.SaveItem(item); InventoryFolderBase invalidChild = new InventoryFolderBase(); invalidChild.ID = UUID.Random(); invalidChild.Name = "InvalidChild"; invalidChild.Level = InventoryFolderBase.FolderLevel.Leaf; folder.Owner = userId; folder.Type = (short)OpenMetaverse.AssetType.Unknown; folder.ParentID = folder.ID; _storage.UpdateParentWithNewChild(invalidChild, folder.ID.Guid, Guid.Empty, Util.UnixTimeSinceEpochInMicroseconds()); //reread the folder folder = _storage.GetFolder(folder.ID); //ensure that the dud link exists Assert.That(folder.SubFolders.Count == 2); foreach (var subfolder in folder.SubFolders) { Assert.IsTrue(subfolder.ID == invalidChild.ID || subfolder.ID == validChild.ID); } //Run a repair _storage.Maint_RepairSubfolderIndexes(userId); //verify we got rid of the dud link, but everything else is in tact folder = _storage.GetFolder(folder.ID); Assert.That(folder.SubFolders.Count == 1); Assert.AreEqual(folder.SubFolders.First().ID, validChild.ID); validChild = _storage.GetFolder(validChild.ID); Assert.AreEqual(validChild.Name, "ValidChild"); Assert.That(validChild.Items.Count == 1); Assert.AreEqual(validChild.Items[0].Name, "RandomItem"); } } }
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2013 Stefanos Apostolopoulos // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Diagnostics; using OpenTK.Platform; namespace OpenTK.Graphics { /// <summary> /// Represents and provides methods to manipulate an OpenGL render context. /// </summary> public sealed class GraphicsContext : IGraphicsContext, IGraphicsContextInternal { public static event EventHandler ContextCreationError; public class GraphicContextCreationErrorArgs : EventArgs { public GraphicContextCreationErrorArgs(string msg) { Msg = msg; } public string Msg { get; set; } } /// <summary> /// Used to retrive function pointers by name. /// </summary> /// <param name="function">The function name.</param> /// <returns>A function pointer to <paramref name="function"/>, or <c>IntPtr.Zero</c></returns> public delegate IntPtr GetAddressDelegate(string function); /// <summary> /// Used to return the handle of the current OpenGL context. /// </summary> /// <returns>The current OpenGL context, or <c>IntPtr.Zero</c> if no context is on the calling thread.</returns> public delegate ContextHandle GetCurrentContextDelegate(); private IGraphicsContext _implementation; // The actual render context implementation for the underlying platform. private bool _disposed; // Cache for the context handle. We need this for RemoveContext() // in case the user does not call Dispose(). When this happens, // RemoveContext() is called by the finalizer, in which case // the IGraphicsContext implementation may already be null // (hence we cannot call implementation.Context to retrieve // the handle.) private ContextHandle _handle_cached; private readonly static object SyncRoot = new object(); // Maps OS-specific context handles to GraphicsContext instances. private readonly static Dictionary<ContextHandle, IGraphicsContext> s_available_contexts = new Dictionary<ContextHandle, IGraphicsContext>(); ///// <summary> ///// Constructs a new GraphicsContext with the specified GraphicsMode and attaches it to the specified window. ///// </summary> ///// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param> ///// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param> //public GraphicsContext(GraphicsMode mode, IWindowInfo window) // : this(mode, window, 1, 0, GraphicsContextFlags.Default) //{ } /// <summary> /// Constructs a new GraphicsContext with the specified GraphicsMode, version and flags, and attaches it to the specified window. /// </summary> /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param> /// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param> /// <param name="major">The major version of the new GraphicsContext.</param> /// <param name="minor">The minor version of the new GraphicsContext.</param> /// <param name="flags">The GraphicsContextFlags for the GraphicsContext.</param> /// <remarks> /// Different hardware supports different flags, major and minor versions. Invalid parameters will be silently ignored. /// </remarks> public GraphicsContext(GraphicsMode mode, IWindowInfo window, int major, int minor, GraphicsContextFlags flags) : this(mode, window, FindSharedContext(), major, minor, flags) { } /// <summary> /// Constructs a new GraphicsContext with the specified GraphicsMode, version and flags, and attaches it to the specified window. A dummy context will be created if both /// the handle and the window are null. /// </summary> /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param> /// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param> /// <param name="shareContext">The GraphicsContext to share resources with, or null for explicit non-sharing.</param> /// <param name="major">The major version of the new GraphicsContext.</param> /// <param name="minor">The minor version of the new GraphicsContext.</param> /// <param name="flags">The GraphicsContextFlags for the GraphicsContext.</param> /// <remarks> /// Different hardware supports different flags, major and minor versions. Invalid parameters will be silently ignored. /// </remarks> public GraphicsContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, int major, int minor, GraphicsContextFlags flags) { bool success = false; string errMsg = null; lock (SyncRoot) { bool designMode = false; if (mode == null && window == null) { designMode = true; } else if (mode == null) { throw new ArgumentNullException("mode", "Must be a valid GraphicsMode."); } else if (window == null) { throw new ArgumentNullException("window", "Must point to a valid window."); } // Silently ignore invalid major and minor versions. if (major <= 0) { major = 1; } if (minor < 0) { minor = 0; } // Angle needs an embedded context const GraphicsContextFlags useAngleFlag = GraphicsContextFlags.Angle | GraphicsContextFlags.AngleD3D9 | GraphicsContextFlags.AngleD3D11 | GraphicsContextFlags.AngleOpenGL; flags = useAngleFlag; var useAngle = false; if ((flags & useAngleFlag) != 0) { flags |= GraphicsContextFlags.Embedded; useAngle = true; } Debug.WriteLine("Creating GraphicsContext."); try { Debug.WriteLine(""); Debug.WriteLine($"GraphicsMode: {mode}"); Debug.WriteLine($"IWindowInfo: {window}"); Debug.WriteLine($"GraphicsContextFlags: {flags}"); Debug.WriteLine($"Requested version: {major}.{minor}"); // Todo: Add a DummyFactory implementing IPlatformFactory. if (designMode) { _implementation = new Platform.Dummy.DummyGLContext(); } else { IPlatformFactory factory = null; switch ((flags & GraphicsContextFlags.Embedded) == GraphicsContextFlags.Embedded) { case false: factory = Factory.Default; break; case true: factory = useAngle ? Factory.Angle : Factory.Embedded; break; } // Note: this approach does not allow us to mix native and EGL contexts in the same process. // This should not be a problem, as this use-case is not interesting for regular applications. // Note 2: some platforms may not support a direct way of getting the current context // (this happens e.g. with DummyGLContext). In that case, we use a slow fallback which // iterates through all known contexts and checks if any is current (check GetCurrentContext // declaration). if (GetCurrentContext == null) { GetCurrentContext = factory.CreateGetCurrentGraphicsContext(); } _implementation = factory.CreateGLContext(mode, window, shareContext, DirectRendering, major, minor, flags); _handle_cached = ((IGraphicsContextInternal)_implementation).Context; factory.RegisterResource(this); } AddContext(this); success = true; } catch (Exception ex) { //some exception err here //we write a log file } finally { } } if (!success) { ContextCreationError?.Invoke(null, new GraphicContextCreationErrorArgs(errMsg)); } } /// <summary> /// Initializes a new instance of the <see cref="OpenTK.Graphics.GraphicsContext"/> class using /// an external context handle that was created by a third-party library. /// </summary> /// <param name="handle"> /// A valid, unique handle for an external OpenGL context, or <c>ContextHandle.Zero</c> to use the current context. /// It is an error to specify a handle that has been created through OpenTK or that has been passed to OpenTK before. /// </param> /// <param name="getAddress"> /// A <c>GetAddressDelegate</c> instance that accepts the name of an OpenGL function and returns /// a valid function pointer, or <c>IntPtr.Zero</c> if that function is not supported. This delegate should be /// implemented using the same toolkit that created the OpenGL context (i.e. if the context was created with /// SDL_GL_CreateContext(), then this delegate should use SDL_GL_GetProcAddress() to retrieve function /// pointers.) /// </param> /// <param name="getCurrent"> /// A <c>GetCurrentContextDelegate</c> instance that returns the handle of the current OpenGL context, /// or <c>IntPtr.Zero</c> if no context is current on the calling thread. This delegate should be implemented /// using the same toolkit that created the OpenGL context (i.e. if the context was created with /// SDL_GL_CreateContext(), then this delegate should use SDL_GL_GetCurrentContext() to retrieve /// the current context.) /// </param> public GraphicsContext(ContextHandle handle, GetAddressDelegate getAddress, GetCurrentContextDelegate getCurrent) { if (getAddress == null || getCurrent == null) { throw new ArgumentNullException(); } // Make sure OpenTK has been initialized. // Fixes https://github.com/opentk/opentk/issues/52 //Toolkit.Init(); lock (SyncRoot) { // Replace a zero-handle by the current context, if any if (handle == ContextHandle.Zero) { handle = getCurrent(); } // Make sure this handle corresponds to a valid, unique OpenGL context if (handle == ContextHandle.Zero) { throw new GraphicsContextMissingException(); } else if (s_available_contexts.ContainsKey(handle)) { throw new InvalidOperationException("Context handle has already been added"); } // We have a valid handle for an external OpenGL context, wrap it into a // DummyGLContext instance. _implementation = new Platform.Dummy.DummyGLContext(handle, getAddress); GetCurrentContext = getCurrent ?? GetCurrentContext; AddContext(this); } _implementation.LoadAll(); } ///// <summary> ///// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK. A dummy context will be created if both ///// the handle and the window are null. ///// </summary> ///// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param> ///// <param name="window">This parameter is reserved.</param> //public GraphicsContext(ContextHandle handle, IWindowInfo window) // : this(handle, window, null, 1, 0, GraphicsContextFlags.Default) //{ } ///// <summary> ///// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK. ///// </summary> ///// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param> ///// <param name="window">This parameter is reserved.</param> ///// <param name="shareContext">This parameter is reserved.</param> ///// <param name="major">This parameter is reserved.</param> ///// <param name="minor">This parameter is reserved.</param> ///// <param name="flags">This parameter is reserved..</param> //public GraphicsContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, int major, int minor, GraphicsContextFlags flags) // : this(handle, PlatformAddressPortal.GetAddressDelegate, OpenTK.Platform.Factory.Default.CreateGetCurrentGraphicsContext()) //{ } /// <summary> /// Returns a <see cref="System.String"/> representing this instance. /// </summary> /// <returns>A <see cref="System.String"/> that contains a string representation of this instance.</returns> public override string ToString() { return (this as IGraphicsContextInternal).Context.ToString(); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A System.Int32 with the hash code of this instance.</returns> public override int GetHashCode() { return (this as IGraphicsContextInternal).Context.GetHashCode(); } /// <summary> /// Compares two instances. /// </summary> /// <param name="obj">The instance to compare to.</param> /// <returns>True, if obj is equal to this instance; false otherwise.</returns> public override bool Equals(object obj) { return (obj is GraphicsContext) && (this as IGraphicsContextInternal).Context == (obj as IGraphicsContextInternal).Context; } private static void AddContext(IGraphicsContextInternal context) { ContextHandle ctx = context.Context; if (!s_available_contexts.ContainsKey(ctx)) { s_available_contexts.Add(ctx, (IGraphicsContext)context); } else { Debug.WriteLine($"A GraphicsContext with handle {ctx} already exists."); Debug.WriteLine("Did you forget to call Dispose()?"); s_available_contexts[ctx] = (IGraphicsContext)context; } } private static void RemoveContext(IGraphicsContextInternal context) { ContextHandle ctx = context.Context; if (s_available_contexts.ContainsKey(ctx)) { s_available_contexts.Remove(ctx); } else { Debug.WriteLine(""); Debug.WriteLine($"Tried to remove non-existent GraphicsContext handle {ctx}. Call Dispose() to avoid this error."); } } private static IGraphicsContext FindSharedContext() { if (GraphicsContext.ShareContexts) { // A small hack to create a shared context with the first available context. foreach (IGraphicsContext target in GraphicsContext.s_available_contexts.Values) { // Fix for bug 1874: if a GraphicsContext gets finalized // (but not disposed), it won't be removed from available_contexts // making this return null even if another valid context exists. // The workaround is to simply ignore null targets. if (target != null) { return target; } } } return null; } /// <summary> /// Checks if a GraphicsContext exists in the calling thread and throws a GraphicsContextMissingException if it doesn't. /// </summary> /// <exception cref="GraphicsContextMissingException">Generated when no GraphicsContext is current in the calling thread.</exception> public static void Assert() { if (GraphicsContext.CurrentContext == null) { throw new GraphicsContextMissingException(); } } public static GetCurrentContextDelegate GetCurrentContext; /// <summary> /// Gets the handle of the current GraphicsContext in the calling thread. /// </summary> public static ContextHandle CurrentContextHandle { get { return GetCurrentContext(); } } /// <summary> /// Gets the GraphicsContext that is current in the calling thread. /// </summary> /// <remarks> /// Note: this property will not function correctly when both desktop and EGL contexts are /// available in the same process. This scenario is very unlikely to appear in practice. /// </remarks> public static IGraphicsContext CurrentContext { get { lock (SyncRoot) { if (s_available_contexts.Count > 0) { ContextHandle handle = CurrentContextHandle; if (handle.Handle != IntPtr.Zero) { return (IGraphicsContext)s_available_contexts[handle]; } } return null; } } } /// <summary>Gets or sets a System.Boolean, indicating whether GraphicsContext resources are shared</summary> /// <remarks> /// <para>If ShareContexts is true, new GLContexts will share resources. If this value is /// false, new GLContexts will not share resources.</para> /// <para>Changing this value will not affect already created GLContexts.</para> /// </remarks> public static bool ShareContexts { get; set; } = true; /// <summary>Gets or sets a System.Boolean, indicating whether GraphicsContexts will perform direct rendering.</summary> /// <remarks> /// <para> /// If DirectRendering is true, new contexts will be constructed with direct rendering capabilities, if possible. /// If DirectRendering is false, new contexts will be constructed with indirect rendering capabilities. /// </para> /// <para>This property does not affect existing GraphicsContexts, unless they are recreated.</para> /// <para> /// This property is ignored on Operating Systems without support for indirect rendering, like Windows and OS X. /// </para> /// </remarks> public static bool DirectRendering { get; set; } = true; /// <summary> /// Gets or sets a System.Boolean, indicating whether automatic error checking should be performed. /// Influences the debug version of OpenTK.dll, only. /// </summary> /// <remarks>Automatic error checking will clear the OpenGL error state. Set CheckErrors to false if you use /// the OpenGL error state in your code flow (e.g. for checking supported texture formats).</remarks> public bool ErrorChecking { get; set; } = true; /// <summary> /// Swaps buffers on a context. This presents the rendered scene to the user. /// </summary> public void SwapBuffers() { _implementation.SwapBuffers(); } /// <summary> /// Makes the GraphicsContext the current rendering target. /// </summary> /// <param name="window">A valid <see cref="OpenTK.Platform.IWindowInfo" /> structure.</param> /// <remarks> /// You can use this method to bind the GraphicsContext to a different window than the one it was created from. /// </remarks> public void MakeCurrent(IWindowInfo window) { _implementation.MakeCurrent(window); } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this instance is current in the calling thread. /// </summary> public bool IsCurrent { get { return _implementation.IsCurrent; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this instance has been disposed. /// It is an error to access any instance methods if this property returns true. /// </summary> public bool IsDisposed { get { return _disposed && _implementation.IsDisposed; } private set { _disposed = value; } } /// <summary> /// Gets or sets a positive integer in the range [1, n), indicating the number of /// <see cref="DisplayDevice"/> refreshes between consecutive /// <see cref="SwapBuffers()"/> calls. The maximum value for n is /// implementation-dependent. The default value is 1. /// Invalid values will be clamped to the valid range. /// </summary> public int SwapInterval { get { return _implementation.SwapInterval; } set { _implementation.SwapInterval = value; } } /// <summary> /// Updates the graphics context. This must be called when the render target /// is resized for proper behavior on Mac OS X. /// </summary> /// <param name="window"></param> public void Update(IWindowInfo window) { _implementation.Update(window); } /// <summary> /// Loads all OpenGL entry points. /// </summary> /// <exception cref="OpenTK.Graphics.GraphicsContextException"> /// Occurs when this instance is not current on the calling thread. /// </exception> public void LoadAll() { if (GraphicsContext.CurrentContext != this) { throw new GraphicsContextException(); } _implementation.LoadAll(); } /// <summary> /// Gets the platform-specific implementation of this IGraphicsContext. /// </summary> IGraphicsContext IGraphicsContextInternal.Implementation { get { return _implementation; } } /// <summary> /// Gets a handle to the OpenGL rendering context. /// </summary> ContextHandle IGraphicsContextInternal.Context { get { if (_implementation != null) { _handle_cached = ((IGraphicsContextInternal)_implementation).Context; } return _handle_cached; } } /// <summary> /// Gets the GraphicsMode of the context. /// </summary> public GraphicsMode GraphicsMode { get { return (_implementation as IGraphicsContext).GraphicsMode; } } /// <summary> /// Retrieves the implementation-defined address of an OpenGL function. /// </summary> /// <param name="function">The name of the OpenGL function (e.g. "glGetString")</param> /// <returns> /// A pointer to the specified function or an invalid pointer if the function is not /// available in the current OpenGL context. The return value and calling convention /// depends on the underlying platform. /// </returns> IntPtr IGraphicsContextInternal.GetAddress(string function) { IntPtr name = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(function); IntPtr address = (_implementation as IGraphicsContextInternal).GetAddress(name); System.Runtime.InteropServices.Marshal.FreeHGlobal(name); return address; } /// <summary> /// Retrieves the implementation-defined address of an OpenGL function. /// </summary> /// <param name="function"> /// A pointer to a null-terminated buffer /// containing the name of the OpenGL function. /// </param> /// <returns> /// A pointer to the specified function or an invalid pointer if the function is not /// available in the current OpenGL context. The return value and calling convention /// depends on the underlying platform. /// </returns> IntPtr IGraphicsContextInternal.GetAddress(IntPtr function) { return (_implementation as IGraphicsContextInternal).GetAddress(function); } /// <summary> /// Disposes of the GraphicsContext. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool manual) { if (!IsDisposed) { lock (SyncRoot) { RemoveContext(this); } // Note: we cannot dispose the implementation // from a different thread. See wglDeleteContext. // This is also known to crash GLX implementations. if (manual) { Debug.WriteLine($"Disposing context {(this as IGraphicsContextInternal).Context.ToString()}."); if (_implementation != null) { _implementation.Dispose(); } } else { Debug.WriteLine("GraphicsContext leaked, did you forget to call Dispose()?"); } IsDisposed = true; } } /// <summary> /// Marks this context as deleted, but does not actually release unmanaged resources /// due to the threading requirements of OpenGL. Use <see cref="GraphicsContext.Dispose()"/> /// instead. /// </summary> ~GraphicsContext() { Dispose(false); } ////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// TODO: for used with glfw context /// </summary> /// <param name="handle"></param> /// <returns></returns> public static GraphicsContext CreateExternalContext(Platform.External.ExternalGraphicsContext externalGfxContext) { return new GraphicsContext(externalGfxContext); } GraphicsContext(OpenTK.Platform.External.ExternalGraphicsContext externalGraphicsContext) { _implementation = externalGraphicsContext; lock (SyncRoot) { // Angle needs an embedded context //const GraphicsContextFlags useAngleFlag = GraphicsContextFlags.Angle // | GraphicsContextFlags.AngleD3D9 // | GraphicsContextFlags.AngleD3D11 // | GraphicsContextFlags.AngleOpenGL; bool useAngle = true; try { IPlatformFactory factory = Factory.Embedded; // Note: this approach does not allow us to mix native and EGL contexts in the same process. // This should not be a problem, as this use-case is not interesting for regular applications. // Note 2: some platforms may not support a direct way of getting the current context // (this happens e.g. with DummyGLContext). In that case, we use a slow fallback which // iterates through all known contexts and checks if any is current (check GetCurrentContext // declaration). if (GetCurrentContext == null) { GetCurrentContext = externalGraphicsContext.CreateCurrentContextDel(); // factory.CreateGetCurrentGraphicsContext(); } s_available_contexts.Add((_implementation as IGraphicsContextInternal).Context, this); (this as IGraphicsContextInternal).LoadAll(); _handle_cached = ((IGraphicsContextInternal)_implementation).Context; factory.RegisterResource(this); } catch (Exception ex) { } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// } }
using UnityEngine; using System.Collections; using Pathfinding; namespace Pathfinding { [AddComponentMenu("Pathfinding/GraphUpdateScene")] /** Helper class for easily updating graphs. * * \see \ref graph-updates * for an explanation of how to use this class. */ public class GraphUpdateScene : GraphModifier { /** Do some stuff at start */ public void Start () { //If firstApplied is true, that means the graph was scanned during Awake. //So we shouldn't apply it again because then we would end up applying it two times if (!firstApplied && applyOnStart) { Apply (); } } public override void OnPostScan () { if (applyOnScan) Apply (); } /** Points which define the region to update */ public Vector3[] points; /** Private cached convex hull of the #points */ private Vector3[] convexPoints; [HideInInspector] /** Use the convex hull (XZ space) of the points. */ public bool convex = true; [HideInInspector] /** Minumum height of the bounds of the resulting Graph Update Object. * Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a * zero height graph update object would usually result in no nodes being updated. */ public float minBoundsHeight = 1; [HideInInspector] /** Penalty to add to nodes. * Be careful when setting negative values since if a node get's a negative penalty it will underflow and instead get * really large. In most cases a warning will be logged if that happens. */ public int penaltyDelta = 0; [HideInInspector] /** Set to true to set all targeted nodese walkability to #setWalkability */ public bool modifyWalkability = false; [HideInInspector] /** See #modifyWalkability */ public bool setWalkability = false; [HideInInspector] /** Apply this graph update object on start */ public bool applyOnStart = true; [HideInInspector] /** Apply this graph update object whenever a graph is rescanned */ public bool applyOnScan = true; /** Use world space for coordinates. * If true, the shape will not follow when moving around the transform. * * \see #ToggleUseWorldSpace */ [HideInInspector] public bool useWorldSpace = false; /** Update node's walkability and connectivity using physics functions. * For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph. * If enabled for grid graphs, #modifyWalkability will be ignored. * * For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object * using raycasts (if enabled). * */ [HideInInspector] public bool updatePhysics = false; /** \copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics */ [HideInInspector] public bool resetPenaltyOnPhysics = true; /** \copydoc Pathfinding::GraphUpdateObject::updateErosion */ [HideInInspector] public bool updateErosion = true; [HideInInspector] /** Lock all points to Y = #lockToYValue */ public bool lockToY = false; [HideInInspector] /** if #lockToY is enabled lock all points to this value */ public float lockToYValue = 0; [HideInInspector] /** If enabled, set all nodes' tags to #setTag */ public bool modifyTag = false; [HideInInspector] /** If #modifyTag is enabled, set all nodes' tags to this value */ public int setTag = 0; /** Private cached inversion of #setTag. * Used for InvertSettings() */ private int setTagInvert = 0; /** Has apply been called yet. * Used to prevent applying twice when both applyOnScan and applyOnStart are enabled */ private bool firstApplied = false; /** Inverts all invertable settings for this GUS. * Namely: penalty delta, walkability, tags. * * Penalty delta will be changed to negative penalty delta.\n * #setWalkability will be inverted.\n * #setTag will be stored in a private variable, and the new value will be 0. When calling this function again, the saved * value will be the new value. * * Calling this function an even number of times without changing any settings in between will be identical to no change in settings. */ public virtual void InvertSettings () { setWalkability = !setWalkability; penaltyDelta = -penaltyDelta; if (setTagInvert == 0) { setTagInvert = setTag; setTag = 0; } else { setTag = setTagInvert; setTagInvert = 0; } } /** Recalculate convex points. * Will not do anything if not #convex is enabled */ public void RecalcConvex () { if (convex) convexPoints = Polygon.ConvexHull (points); else convexPoints = null; } /** Switches between using world space and using local space. * Changes point coordinates to stay the same in world space after the change. * * \see #useWorldSpace */ public void ToggleUseWorldSpace () { useWorldSpace = !useWorldSpace; if (points == null) return; convexPoints = null; Matrix4x4 matrix = useWorldSpace ? transform.localToWorldMatrix : transform.worldToLocalMatrix; for (int i=0;i<points.Length;i++) { points[i] = matrix.MultiplyPoint3x4 (points[i]); } } /** Lock all points to a specific Y value. * * \see lockToYValue */ public void LockToY () { if (points == null) return; for (int i=0;i<points.Length;i++) points[i].y = lockToYValue; } /** Apply the update. * Will only do anything if #applyOnScan is enabled */ public void Apply (AstarPath active) { if (applyOnScan) { Apply (); } } /** Calculates the bounds for this component. * This is a relatively expensive operation, it needs to go through all points and * sometimes do matrix multiplications. */ public Bounds GetBounds () { Bounds b; if (points == null || points.Length == 0) { if (collider != null) b = collider.bounds; else if (renderer != null) b = renderer.bounds; else { //Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached"); return new Bounds(Vector3.zero, Vector3.zero); } } else { Matrix4x4 matrix = Matrix4x4.identity; if (!useWorldSpace) { matrix = transform.localToWorldMatrix; } Vector3 min = matrix.MultiplyPoint3x4(points[0]); Vector3 max = matrix.MultiplyPoint3x4(points[0]); for (int i=0;i<points.Length;i++) { Vector3 p = matrix.MultiplyPoint3x4(points[i]); min = Vector3.Min (min,p); max = Vector3.Max (max,p); } b = new Bounds ((min+max)*0.5F,max-min); } if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z); return b; } /** Updates graphs with a created GUO. * Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape * representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs. * This will not update graphs directly. See AstarPath.UpdateGraph for more info. */ public void Apply () { if (AstarPath.active == null) { Debug.LogError ("There is no AstarPath object in the scene"); return; } GraphUpdateObject guo; if (points == null || points.Length == 0) { Bounds b; if (collider != null) b = collider.bounds; else if (renderer != null) b = renderer.bounds; else { Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached"); return; } if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z); guo = new GraphUpdateObject (b); } else { Pathfinding.GraphUpdateShape shape = new Pathfinding.GraphUpdateShape (); shape.convex = convex; Vector3[] worldPoints = points; if (!useWorldSpace) { worldPoints = new Vector3[points.Length]; Matrix4x4 matrix = transform.localToWorldMatrix; for (int i=0;i<worldPoints.Length;i++) worldPoints[i] = matrix.MultiplyPoint3x4 (points[i]); } shape.points = worldPoints; Bounds b = shape.GetBounds (); if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z); guo = new GraphUpdateObject (b); guo.shape = shape; } firstApplied = true; guo.modifyWalkability = modifyWalkability; guo.setWalkability = setWalkability; guo.addPenalty = penaltyDelta; guo.updatePhysics = updatePhysics; guo.updateErosion = updateErosion; guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics; guo.modifyTag = modifyTag; guo.setTag = setTag; AstarPath.active.UpdateGraphs (guo); } /** Draws some gizmos */ public void OnDrawGizmos () { OnDrawGizmos (false); } /** Draws some gizmos */ public void OnDrawGizmosSelected () { OnDrawGizmos (true); } /** Draws some gizmos */ public void OnDrawGizmos (bool selected) { Color c = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f); if (selected) { Gizmos.color = Color.Lerp (c, new Color (1,1,1,0.2f), 0.9f); Bounds b = GetBounds (); Gizmos.DrawCube (b.center, b.size); Gizmos.DrawWireCube (b.center, b.size); } if (points == null) return; if (convex) { c.a *= 0.5f; } Gizmos.color = c; Matrix4x4 matrix = useWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix; if (convex) { c.r -= 0.1f; c.g -= 0.2f; c.b -= 0.1f; Gizmos.color = c; } if (selected || !convex) { for (int i=0;i<points.Length;i++) { Gizmos.DrawLine (matrix.MultiplyPoint3x4(points[i]),matrix.MultiplyPoint3x4(points[(i+1)%points.Length])); } } if (convex) { if (convexPoints == null) RecalcConvex (); Gizmos.color = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f); for (int i=0;i<convexPoints.Length;i++) { Gizmos.DrawLine (matrix.MultiplyPoint3x4(convexPoints[i]),matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length])); } } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets; using Xunit; public class VariableTests : NLogTestBase { [Fact] public void VariablesTest1() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name='prefix' value='[[' /> <variable name='suffix' value=']]' /> <targets> <target name='d1' type='Debug' layout='${prefix}${message}${suffix}' /> </targets> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Equal(3, layout.Renderers.Count); var lr1 = layout.Renderers[0] as LiteralLayoutRenderer; var lr2 = layout.Renderers[1] as MessageLayoutRenderer; var lr3 = layout.Renderers[2] as LiteralLayoutRenderer; Assert.NotNull(lr1); Assert.NotNull(lr2); Assert.NotNull(lr3); Assert.Equal("[[", lr1.Text); Assert.Equal("]]", lr3.Text); } /// <summary> /// Expand of property which are not layoutable <see cref="Layout"/>, but still get expanded. /// </summary> [Fact] public void VariablesTest_string_expanding() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name='test' value='hello'/> <targets> <target type='DataBase' name='test' DBProvider='${test}'/> </targets> </nlog>"); var target = configuration.FindTargetByName("test") as DatabaseTarget; Assert.NotNull(target); //dont change the ${test} as it isn't a Layout Assert.NotEqual(typeof(Layout), target.DBProvider.GetType()); Assert.Equal("hello", target.DBProvider); } [Fact] public void VariablesTest_minLevel_expanding() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name='test' value='debug'/> <rules> <logger minLevel='${test}' final='true' /> </rules> </nlog>"); var rule = configuration.LoggingRules[0]; Assert.NotNull(rule); Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Fatal)); } /// <summary> /// Expand of level attributes /// </summary> [Fact] public void VariablesTest_Level_expanding() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name='test' value='debug'/> <rules> <logger level='${test}' final='true' /> </rules> </nlog>"); var rule = configuration.LoggingRules[0]; Assert.NotNull(rule); Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Fatal)); } [Fact] public void Xml_configuration_returns_defined_variables() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name='prefix' value='[[' /> <variable name='suffix' value=']]' /> <targets> <target name='d1' type='Debug' layout='${prefix}${message}${suffix}' /> </targets> </nlog>"); LogManager.Configuration = configuration; Assert.Equal("[[", LogManager.Configuration.Variables["prefix"].OriginalText); Assert.Equal("]]", LogManager.Configuration.Variables["suffix"].OriginalText); } [Fact] public void Xml_configuration_with_inner_returns_defined_variables_withValueElement() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name='prefix'> <value><![CDATA[ newline ]]></value> </variable> <variable name='suffix'><value>]]</value></variable> </nlog>"); var nullEvent = LogEventInfo.CreateNullEvent(); // Act & Assert Assert.Equal("\nnewline\n", configuration.Variables["prefix"].Render(nullEvent).Replace("\r", "")); Assert.Equal("]]", configuration.Variables["suffix"].Render(nullEvent)); } [Fact] public void Xml_configuration_variableWithInnerAndAttribute_attributeHasPrecedence() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <variable name='var1' value='1'><value>2</value></variable> </nlog>"); var nullEvent = LogEventInfo.CreateNullEvent(); // Act & Assert Assert.Equal("1", configuration.Variables["var1"].FixedText); } [Fact] public void NLogConfigurationExceptionShouldThrown_WhenVariableNodeIsWrittenToWrongPlace() { LogManager.ThrowConfigExceptions = true; const string configurationString_VariableNodeIsInnerTargets = @"<nlog> <targets> <variable name='variableOne' value='${longdate:universalTime=True}Z | ${message}'/> <target name='d1' type='Debug' layout='${variableOne}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='d1'/> </rules> </nlog>"; const string configurationString_VariableNodeIsAfterTargets = @"<nlog> <targets> <target name='d1' type='Debug' layout='${variableOne}' /> </targets> <variable name='variableOne' value='${longdate:universalTime=True}Z | ${message}'/> <rules> <logger name='*' minlevel='Debug' writeTo='d1'/> </rules> </nlog>"; NLogConfigurationException nlogConfEx_ForInnerTargets = Assert.Throws<NLogConfigurationException>( () => XmlLoggingConfiguration.CreateFromXmlString(configurationString_VariableNodeIsInnerTargets) ); NLogConfigurationException nlogConfExForAfterTargets = Assert.Throws<NLogConfigurationException>( () => XmlLoggingConfiguration.CreateFromXmlString(configurationString_VariableNodeIsAfterTargets) ); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using NUnit.Framework; using osu.Framework.Bindables; namespace osu.Framework.Tests.Bindables { [TestFixture] public class BindableLeasingTest { private Bindable<int> original; [SetUp] public void SetUp() { original = new Bindable<int>(1); } [TestCase(false)] [TestCase(true)] public void TestLeaseAndReturn(bool revert) { var leased = original.BeginLease(revert); Assert.AreEqual(original.Value, leased.Value); leased.Value = 2; Assert.AreEqual(original.Value, 2); Assert.AreEqual(original.Value, leased.Value); Assert.AreEqual(true, leased.Return()); Assert.AreEqual(original.Value, revert ? 1 : 2); } [TestCase(false)] [TestCase(true)] public void TestLeaseReturnedOnUnbindAll(bool revert) { var leased = original.BeginLease(revert); Assert.AreEqual(original.Value, leased.Value); leased.Value = 2; Assert.AreEqual(original.Value, 2); Assert.AreEqual(original.Value, leased.Value); original.UnbindAll(); Assert.AreEqual(original.Value, revert ? 1 : 2); } [Test] public void TestConsecutiveLeases() { var leased1 = original.BeginLease(false); Assert.AreEqual(true, leased1.Return()); var leased2 = original.BeginLease(false); Assert.AreEqual(true, leased2.Return()); } [Test] public void TestModifyAfterReturnFail() { var leased = original.BeginLease(false); Assert.AreEqual(true, leased.Return()); Assert.Throws<InvalidOperationException>(() => leased.Value = 2); Assert.Throws<InvalidOperationException>(() => leased.Disabled = true); } [Test] public void TestDoubleReturnSilentlyNoops() { var leased = original.BeginLease(false); Assert.AreEqual(true, leased.Return()); Assert.AreEqual(false, leased.Return()); } [Test] public void TestDoubleLeaseFails() { original.BeginLease(false); Assert.Throws<InvalidOperationException>(() => original.BeginLease(false)); } [Test] public void TestIncorrectEndLease() { // end a lease when no lease exists. Assert.Throws<InvalidOperationException>(() => original.EndLease(null)); // end a lease with an incorrect bindable original.BeginLease(true); Assert.Throws<InvalidOperationException>(() => original.EndLease(new Bindable<int>().BeginLease(true))); } [Test] public void TestDisabledStateDuringLease() { Assert.IsFalse(original.Disabled); var leased = original.BeginLease(true); Assert.IsTrue(original.Disabled); Assert.IsTrue(leased.Disabled); // during lease, the leased bindable is also set to a disabled state (but is always bypassed when setting the value via it directly). // you can't change the disabled state of the original during a lease... Assert.Throws<InvalidOperationException>(() => original.Disabled = false); // ..but you can change it from the leased instance.. leased.Disabled = false; Assert.IsFalse(leased.Disabled); Assert.IsFalse(original.Disabled); // ..allowing modification of the original during lease. original.Value = 2; // even if not disabled, you still cannot change disabled from the original during a lease. Assert.Throws<InvalidOperationException>(() => original.Disabled = true); Assert.IsFalse(original.Disabled); Assert.IsFalse(leased.Disabled); // you must use the leased instance. leased.Disabled = true; Assert.IsTrue(original.Disabled); Assert.IsTrue(leased.Disabled); Assert.AreEqual(true, leased.Return()); Assert.IsFalse(original.Disabled); } [Test] public void TestDisabledChangeViaBindings() { original.BeginLease(true); // ensure we can't change original's disabled via a bound bindable. var bound = original.GetBoundCopy(); Assert.Throws<InvalidOperationException>(() => bound.Disabled = false); Assert.IsTrue(original.Disabled); } [Test] public void TestDisabledChangeViaBindingToLeased() { bool? changedState = null; original.DisabledChanged += d => changedState = d; var leased = original.BeginLease(true); var bound = leased.GetBoundCopy(); bound.Disabled = false; Assert.AreEqual(changedState, false); Assert.IsFalse(original.Disabled); } [Test] public void TestValueChangeViaBindings() { original.BeginLease(true); // ensure we can't change original's disabled via a bound bindable. var bound = original.GetBoundCopy(); Assert.Throws<InvalidOperationException>(() => bound.Value = 2); Assert.AreEqual(original.Value, 1); } [TestCase(false)] [TestCase(true)] public void TestDisabledRevertedAfterLease(bool revert) { bool? changedState = null; original.Disabled = true; original.DisabledChanged += d => changedState = d; var leased = original.BeginLease(revert); Assert.AreEqual(true, leased.Return()); // regardless of revert specification, disabled should always be reverted to the original value. Assert.IsTrue(original.Disabled); Assert.IsFalse(changedState.HasValue); } [Test] public void TestLeaseFromBoundBindable() { var copy = original.GetBoundCopy(); var leased = copy.BeginLease(true); // can't take a second lease from the original. Assert.Throws<InvalidOperationException>(() => original.BeginLease(false)); // can't take a second lease from the copy. Assert.Throws<InvalidOperationException>(() => copy.BeginLease(false)); leased.Value = 2; // value propagates everywhere Assert.AreEqual(original.Value, 2); Assert.AreEqual(original.Value, copy.Value); Assert.AreEqual(original.Value, leased.Value); // bound copies of the lease still allow setting value / disabled. var leasedCopy = leased.GetBoundCopy(); leasedCopy.Value = 3; Assert.AreEqual(original.Value, 3); Assert.AreEqual(original.Value, copy.Value); Assert.AreEqual(original.Value, leased.Value); Assert.AreEqual(original.Value, leasedCopy.Value); leasedCopy.Disabled = false; leasedCopy.Disabled = true; Assert.AreEqual(true, leased.Return()); original.Value = 1; Assert.AreEqual(original.Value, 1); Assert.AreEqual(original.Value, copy.Value); Assert.IsFalse(original.Disabled); } [Test] public void TestCantLeaseFromLease() { var leased = original.BeginLease(false); Assert.Throws<InvalidOperationException>(() => leased.BeginLease(false)); } [Test] public void TestCantLeaseFromBindingChain() { var bound1 = original.GetBoundCopy(); var bound2 = bound1.GetBoundCopy(); original.BeginLease(false); Assert.Throws<InvalidOperationException>(() => bound2.BeginLease(false)); } [Test] public void TestReturnFromBoundCopyOfLeaseFails() { var leased = original.BeginLease(true); var copy = leased.GetBoundCopy(); Assert.Throws<InvalidOperationException>(() => ((LeasedBindable<int>)copy).Return()); } [Test] public void TestUnbindAllReturnsLease() { var leased = original.BeginLease(true); leased.UnbindAll(); leased.UnbindAll(); } [Test] public void TestLeasedBoundToMultiple() { var leased = original.BeginLease(false); var another = new Bindable<int>(); leased.BindTo(another); another.Value = 3; Assert.AreEqual(another.Value, 3); Assert.AreEqual(another.Value, leased.Value); leased.Value = 4; Assert.AreEqual(original.Value, 4); Assert.AreEqual(another.Value, 4); Assert.AreEqual(original.Value, leased.Value); } } }
using System; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Acr.UserDialogs; using MvvmCross.Core.ViewModels; using Plugin.BLE.Abstractions; using Plugin.BLE.Abstractions.Contracts; using Plugin.BLE.Abstractions.EventArgs; using Plugin.BLE.Abstractions.Extensions; namespace BLE.Client.ViewModels { public class CharacteristicDetailViewModel : BaseViewModel { private readonly IUserDialogs _userDialogs; private bool _updatesStarted; public ICharacteristic Characteristic { get; private set; } public string CharacteristicValue => Characteristic?.Value.ToHexString().Replace("-", " "); public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public string UpdateButtonText => _updatesStarted ? "Stop updates" : "Start updates"; public string Permissions { get { if (Characteristic == null) return string.Empty; return (Characteristic.CanRead ? "Read " : "") + (Characteristic.CanWrite ? "Write " : "") + (Characteristic.CanUpdate ? "Update" : ""); } } public CharacteristicDetailViewModel(IAdapter adapter, IUserDialogs userDialogs) : base(adapter) { _userDialogs = userDialogs; } protected override async void InitFromBundle(IMvxBundle parameters) { base.InitFromBundle(parameters); Characteristic = await GetCharacteristicFromBundleAsync(parameters); } public override void Resume() { base.Resume(); if (Characteristic != null) { return; } Close(this); } public override void Suspend() { base.Suspend(); if (Characteristic != null) { StopUpdates(); } } public MvxCommand ReadCommand => new MvxCommand(ReadValueAsync); private async void ReadValueAsync() { if (Characteristic == null) return; try { _userDialogs.ShowLoading("Reading characteristic value..."); await Characteristic.ReadAsync(); RaisePropertyChanged(() => CharacteristicValue); Messages.Insert(0, $"Read value {CharacteristicValue}"); } catch (Exception ex) { _userDialogs.HideLoading(); _userDialogs.ShowError(ex.Message); Messages.Insert(0, $"Error {ex.Message}"); } finally { _userDialogs.HideLoading(); } } public MvxCommand WriteCommand => new MvxCommand(WriteValueAsync); private async void WriteValueAsync() { try { var result = await _userDialogs.PromptAsync("Input a value (as hex whitespace separated)", "Write value", placeholder: CharacteristicValue); if (!result.Ok) return; var data = GetBytes(result.Text); _userDialogs.ShowLoading("Write characteristic value"); await Characteristic.WriteAsync(data); _userDialogs.HideLoading(); RaisePropertyChanged(() => CharacteristicValue); Messages.Insert(0, $"Wrote value {CharacteristicValue}"); } catch (Exception ex) { _userDialogs.HideLoading(); _userDialogs.ShowError(ex.Message); } } private static byte[] GetBytes(string text) { return text.Split(' ').Where(token => !string.IsNullOrEmpty(token)).Select(token => Convert.ToByte(token, 16)).ToArray(); } public MvxCommand ToggleUpdatesCommand => new MvxCommand((() => { if (_updatesStarted) { StopUpdates(); } else { StartUpdates(); } })); private async void StartUpdates() { try { _updatesStarted = true; Characteristic.ValueUpdated -= CharacteristicOnValueUpdated; Characteristic.ValueUpdated += CharacteristicOnValueUpdated; await Characteristic.StartUpdatesAsync(); Messages.Insert(0, $"Start updates"); RaisePropertyChanged(() => UpdateButtonText); } catch (Exception ex) { _userDialogs.ShowError(ex.Message); } } private async void StopUpdates() { try { _updatesStarted = false; await Characteristic.StopUpdatesAsync(); Characteristic.ValueUpdated -= CharacteristicOnValueUpdated; Messages.Insert(0, $"Stop updates"); RaisePropertyChanged(() => UpdateButtonText); } catch (Exception ex) { _userDialogs.ShowError(ex.Message); } } private void CharacteristicOnValueUpdated(object sender, CharacteristicUpdatedEventArgs characteristicUpdatedEventArgs) { Messages.Insert(0, $"Updated value: {CharacteristicValue}"); RaisePropertyChanged(() => CharacteristicValue); } } }
using System.Collections.Generic; using System.Diagnostics; namespace Cocos2D { public class CCActionManager : ICCSelectorProtocol { private static CCNode[] m_pTmpKeysArray = new CCNode[128]; private bool m_bCurrentTargetSalvaged; private HashElement m_pCurrentTarget; private readonly Dictionary<object, HashElement> m_pTargets = new Dictionary<object, HashElement>(); #region SelectorProtocol Members public void Update(float dt) { int count = m_pTargets.Keys.Count; while (m_pTmpKeysArray.Length < count) { m_pTmpKeysArray = new CCNode[m_pTmpKeysArray.Length * 2]; } m_pTargets.Keys.CopyTo(m_pTmpKeysArray, 0); for (int i = 0; i < count; i++) { HashElement elt; if (!m_pTargets.TryGetValue(m_pTmpKeysArray[i], out elt)) { continue; } m_pCurrentTarget = elt; m_bCurrentTargetSalvaged = false; if (!m_pCurrentTarget.Paused) { // The 'actions' may change while inside this loop. for (m_pCurrentTarget.ActionIndex = 0; m_pCurrentTarget.ActionIndex < m_pCurrentTarget.Actions.Count; m_pCurrentTarget.ActionIndex++) { m_pCurrentTarget.CurrentAction = m_pCurrentTarget.Actions[m_pCurrentTarget.ActionIndex]; if (m_pCurrentTarget.CurrentAction == null) { continue; } m_pCurrentTarget.CurrentActionSalvaged = false; m_pCurrentTarget.CurrentAction.Step(dt); if (m_pCurrentTarget.CurrentActionSalvaged) { // The currentAction told the node to remove it. To prevent the action from // accidentally deallocating itself before finishing its step, we retained // it. Now that step is done, it's safe to release it. //m_pCurrentTarget->currentAction->release(); } else if (m_pCurrentTarget.CurrentAction.IsDone) { m_pCurrentTarget.CurrentAction.Stop(); CCAction action = m_pCurrentTarget.CurrentAction; // Make currentAction nil to prevent removeAction from salvaging it. m_pCurrentTarget.CurrentAction = null; RemoveAction(action); } m_pCurrentTarget.CurrentAction = null; } } // only delete currentTarget if no actions were scheduled during the cycle (issue #481) if (m_bCurrentTargetSalvaged && m_pCurrentTarget.Actions.Count == 0) { DeleteHashElement(m_pCurrentTarget); } } // issue #635 m_pCurrentTarget = null; } #endregion ~CCActionManager() { RemoveAllActions(); } protected void DeleteHashElement(HashElement element) { element.Actions.Clear(); m_pTargets.Remove(element.Target); element.Target = null; } protected void ActionAllocWithHashElement(HashElement element) { if (element.Actions == null) { element.Actions = new List<CCAction>(); } } protected void RemoveActionAtIndex(int index, HashElement element) { CCAction action = element.Actions[index]; if (action == element.CurrentAction && (!element.CurrentActionSalvaged)) { element.CurrentActionSalvaged = true; } element.Actions.RemoveAt(index); // update actionIndex in case we are in tick. looping over the actions if (element.ActionIndex >= index) { element.ActionIndex--; } if (element.Actions.Count == 0) { if (m_pCurrentTarget == element) { m_bCurrentTargetSalvaged = true; } else { DeleteHashElement(element); } } } public void PauseTarget(object target) { HashElement element; if (m_pTargets.TryGetValue(target, out element)) { element.Paused = true; } } public void ResumeTarget(object target) { HashElement element; if (m_pTargets.TryGetValue(target, out element)) { element.Paused = false; } } public List<object> PauseAllRunningActions() { var idsWithActions = new List<object>(); foreach (var element in m_pTargets.Values) { if (!element.Paused) { element.Paused = true; idsWithActions.Add(element.Target); } } return idsWithActions; } public void ResumeTargets(List<object> targetsToResume) { for (int i = 0; i < targetsToResume.Count; i++) { ResumeTarget(targetsToResume[i]); } } public void AddAction(CCAction action, CCNode target, bool paused) { Debug.Assert(action != null); Debug.Assert(target != null); HashElement element; if (!m_pTargets.TryGetValue(target, out element)) { element = new HashElement(); element.Paused = paused; element.Target = target; m_pTargets.Add(target, element); } ActionAllocWithHashElement(element); Debug.Assert(!element.Actions.Contains(action)); element.Actions.Add(action); action.StartWithTarget(target); } public void RemoveAllActions() { int count = m_pTargets.Keys.Count; if (m_pTmpKeysArray.Length < count) { m_pTmpKeysArray = new CCNode[m_pTmpKeysArray.Length * 2]; } m_pTargets.Keys.CopyTo(m_pTmpKeysArray, 0); for (int i = 0; i < count; i++) { RemoveAllActionsFromTarget(m_pTmpKeysArray[i]); } } public void RemoveAllActionsFromTarget(CCNode target) { if (target == null) { return; } HashElement element; if (m_pTargets.TryGetValue(target, out element)) { if (element.Actions.Contains(element.CurrentAction) && (!element.CurrentActionSalvaged)) { element.CurrentActionSalvaged = true; } element.Actions.Clear(); if (m_pCurrentTarget == element) { m_bCurrentTargetSalvaged = true; } else { DeleteHashElement(element); } } } public void RemoveAction(CCAction action) { if (action == null || action.OriginalTarget == null) { return; } object target = action.OriginalTarget; HashElement element; if (m_pTargets.TryGetValue(target, out element)) { int i = element.Actions.IndexOf(action); if (i != -1) { RemoveActionAtIndex(i, element); } else { CCLog.Log("cocos2d: removeAction: Action not found"); } } else { CCLog.Log("cocos2d: removeAction: Target not found"); } } public void RemoveActionByTag(int tag, CCNode target) { Debug.Assert((tag != (int) CCActionTag.Invalid)); Debug.Assert(target != null); HashElement element; if (m_pTargets.TryGetValue(target, out element)) { int limit = element.Actions.Count; for (int i = 0; i < limit; i++) { CCAction action = element.Actions[i]; if (action.Tag == tag && action.OriginalTarget == target) { RemoveActionAtIndex(i, element); break; } } CCLog.Log("cocos2d : removeActionByTag: Tag " + tag + " not found"); } else { CCLog.Log("cocos2d : removeActionByTag: Target not found"); } } public CCAction GetActionByTag(int tag, CCNode target) { Debug.Assert(tag != (int) CCActionTag.Invalid); HashElement element; if (m_pTargets.TryGetValue(target, out element)) { if (element.Actions != null) { int limit = element.Actions.Count; for (int i = 0; i < limit; i++) { CCAction action = element.Actions[i]; if (action.Tag == tag) { return action; } } CCLog.Log("cocos2d : getActionByTag: Tag " + tag + " not found"); } } else { CCLog.Log("cocos2d : getActionByTag: Target not found"); } return null; } public int NumberOfRunningActionsInTarget(CCNode target) { HashElement element; if (m_pTargets.TryGetValue(target, out element)) { return (element.Actions != null) ? element.Actions.Count : 0; } return 0; } protected class HashElement { public int ActionIndex; public List<CCAction> Actions; public CCAction CurrentAction; public bool CurrentActionSalvaged; public bool Paused; public object Target; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using FluentNHibernate.Mapping.Providers; using FluentNHibernate.Utils; namespace FluentNHibernate.Mapping { public abstract class ClasslikeMapBase<T> { readonly MappingProviderStore providers; protected ClasslikeMapBase(MappingProviderStore providers) { this.providers = providers; } /// <summary> /// Called when a member is mapped by a builder method. /// </summary> /// <param name="member">Member being mapped.</param> internal virtual void OnMemberMapped(Member member) {} /// <summary> /// Create a property mapping. /// </summary> /// <param name="memberExpression">Property to map</param> /// <example> /// Map(x => x.Name); /// </example> public PropertyPart Map(Expression<Func<T, object>> memberExpression) { return Map(memberExpression, null); } /// <summary> /// Create a property mapping. /// </summary> /// <param name="memberExpression">Property to map</param> /// <param name="columnName">Property column name</param> /// <example> /// Map(x => x.Name, "person_name"); /// </example> public PropertyPart Map(Expression<Func<T, object>> memberExpression, string columnName) { return Map(memberExpression.ToMember(), columnName); } PropertyPart Map(Member member, string columnName) { OnMemberMapped(member); var propertyMap = new PropertyPart(member, typeof(T)); if (!string.IsNullOrEmpty(columnName)) propertyMap.Column(columnName); providers.Properties.Add(propertyMap); return propertyMap; } /// <summary> /// Create a reference to another entity. In database terms, this is a many-to-one /// relationship. /// </summary> /// <typeparam name="TOther">Other entity</typeparam> /// <param name="memberExpression">Property on the current entity</param> /// <example> /// References(x => x.Company); /// </example> public ManyToOnePart<TOther> References<TOther>(Expression<Func<T, TOther>> memberExpression) { return References(memberExpression, null); } /// <summary> /// Create a reference to another entity. In database terms, this is a many-to-one /// relationship. /// </summary> /// <typeparam name="TOther">Other entity</typeparam> /// <param name="memberExpression">Property on the current entity</param> /// <param name="columnName">Column name</param> /// <example> /// References(x => x.Company, "company_id"); /// </example> public ManyToOnePart<TOther> References<TOther>(Expression<Func<T, TOther>> memberExpression, string columnName) { return References<TOther>(memberExpression.ToMember(), columnName); } /// <summary> /// Create a reference to another entity. In database terms, this is a many-to-one /// relationship. /// </summary> /// <typeparam name="TOther">Other entity</typeparam> /// <param name="memberExpression">Property on the current entity</param> /// <example> /// References(x => x.Company, "company_id"); /// </example> public ManyToOnePart<TOther> References<TOther>(Expression<Func<T, object>> memberExpression) { return References<TOther>(memberExpression, null); } /// <summary> /// Create a reference to another entity. In database terms, this is a many-to-one /// relationship. /// </summary> /// <typeparam name="TOther">Other entity</typeparam> /// <param name="memberExpression">Property on the current entity</param> /// <param name="columnName">Column name</param> /// <example> /// References(x => x.Company, "company_id"); /// </example> public ManyToOnePart<TOther> References<TOther>(Expression<Func<T, object>> memberExpression, string columnName) { return References<TOther>(memberExpression.ToMember(), columnName); } ManyToOnePart<TOther> References<TOther>(Member member, string columnName) { OnMemberMapped(member); var part = new ManyToOnePart<TOther>(EntityType, member); if (columnName != null) part.Column(columnName); providers.References.Add(part); return part; } /// <summary> /// Create a reference to any other entity. This is an "any" polymorphic relationship. /// </summary> /// <typeparam name="TOther">Other entity to reference</typeparam> /// <param name="memberExpression">Property</param> public AnyPart<TOther> ReferencesAny<TOther>(Expression<Func<T, TOther>> memberExpression) { return ReferencesAny<TOther>(memberExpression.ToMember()); } AnyPart<TOther> ReferencesAny<TOther>(Member member) { OnMemberMapped(member); var part = new AnyPart<TOther>(typeof(T), member); providers.Anys.Add(part); return part; } /// <summary> /// Create a reference to another entity based exclusively on the primary-key values. /// This is sometimes called a one-to-one relationship, in database terms. Generally /// you should use <see cref="References{TOther}(System.Linq.Expressions.Expression{System.Func{T,object}})"/> /// whenever possible. /// </summary> /// <typeparam name="TOther">Other entity</typeparam> /// <param name="memberExpression">Property</param> /// <example> /// HasOne(x => x.ExtendedInfo); /// </example> public OneToOnePart<TOther> HasOne<TOther>(Expression<Func<T, Object>> memberExpression) { return HasOne<TOther>(memberExpression.ToMember()); } /// <summary> /// Create a reference to another entity based exclusively on the primary-key values. /// This is sometimes called a one-to-one relationship, in database terms. Generally /// you should use <see cref="References{TOther}(System.Linq.Expressions.Expression{System.Func{T,object}})"/> /// whenever possible. /// </summary> /// <typeparam name="TOther">Other entity</typeparam> /// <param name="memberExpression">Property</param> /// <example> /// HasOne(x => x.ExtendedInfo); /// </example> public OneToOnePart<TOther> HasOne<TOther>(Expression<Func<T, TOther>> memberExpression) { return HasOne<TOther>(memberExpression.ToMember()); } OneToOnePart<TOther> HasOne<TOther>(Member member) { OnMemberMapped(member); var part = new OneToOnePart<TOther>(EntityType, member); providers.OneToOnes.Add(part); return part; } /// <summary> /// Create a dynamic component mapping. This is a dictionary that represents /// a limited number of columns in the database. /// </summary> /// <param name="memberExpression">Property containing component</param> /// <param name="dynamicComponentAction">Component setup action</param> /// <example> /// DynamicComponent(x => x.Data, comp => /// { /// comp.Map(x => (int)x["age"]); /// }); /// </example> public DynamicComponentPart<IDictionary> DynamicComponent(Expression<Func<T, IDictionary>> memberExpression, Action<DynamicComponentPart<IDictionary>> dynamicComponentAction) { return DynamicComponent(memberExpression.ToMember(), dynamicComponentAction); } DynamicComponentPart<IDictionary> DynamicComponent(Member member, Action<DynamicComponentPart<IDictionary>> dynamicComponentAction) { OnMemberMapped(member); var part = new DynamicComponentPart<IDictionary>(typeof(T), member); dynamicComponentAction(part); providers.Components.Add(part); return part; } /// <summary> /// Creates a component reference. This is a place-holder for a component that is defined externally with a /// <see cref="ComponentMap{T}"/>; the mapping defined in said <see cref="ComponentMap{T}"/> will be merged /// with any options you specify from this call. /// </summary> /// <typeparam name="TComponent">Component type</typeparam> /// <param name="member">Property exposing the component</param> /// <returns>Component reference builder</returns> public virtual ReferenceComponentPart<TComponent> Component<TComponent>(Expression<Func<T, TComponent>> member) { return Component<TComponent>(member.ToMember()); } ReferenceComponentPart<TComponent> Component<TComponent>(Member member) { OnMemberMapped(member); var part = new ReferenceComponentPart<TComponent>(member, typeof(T)); providers.Components.Add(part); return part; } /// <summary> /// Maps a component /// </summary> /// <typeparam name="TComponent">Type of component</typeparam> /// <param name="expression">Component property</param> /// <param name="action">Component mapping</param> /// <example> /// Component(x => x.Address, comp => /// { /// comp.Map(x => x.Street); /// comp.Map(x => x.City); /// }); /// </example> public ComponentPart<TComponent> Component<TComponent>(Expression<Func<T, TComponent>> expression, Action<ComponentPart<TComponent>> action) { return Component(expression.ToMember(), action); } /// <summary> /// Maps a component /// </summary> /// <typeparam name="TComponent">Type of component</typeparam> /// <param name="expression">Component property</param> /// <param name="action">Component mapping</param> /// <example> /// Component(x => x.Address, comp => /// { /// comp.Map(x => x.Street); /// comp.Map(x => x.City); /// }); /// </example> public ComponentPart<TComponent> Component<TComponent>(Expression<Func<T, object>> expression, Action<ComponentPart<TComponent>> action) { return Component(expression.ToMember(), action); } ComponentPart<TComponent> Component<TComponent>(Member member, Action<ComponentPart<TComponent>> action) { OnMemberMapped(member); var part = new ComponentPart<TComponent>(typeof(T), member); if (action != null) action(part); providers.Components.Add(part); return part; } /// <summary> /// Allows the user to add a custom component mapping to the class mapping. /// Note: not a fluent method. /// </summary> /// <remarks> /// In some cases, our users need a way to add an instance of their own implementation of IComponentMappingProvider. /// For an example of where this might be necessary, see: http://codebetter.com/blogs/jeremy.miller/archive/2010/02/16/our-extension-properties-story.aspx /// </remarks> public void Component(IComponentMappingProvider componentProvider) { providers.Components.Add(componentProvider); } private OneToManyPart<TChild> MapHasMany<TChild, TReturn>(Expression<Func<T, TReturn>> expression) { return HasMany<TChild>(expression.ToMember()); } OneToManyPart<TChild> HasMany<TChild>(Member member) { OnMemberMapped(member); var part = new OneToManyPart<TChild>(EntityType, member); providers.Collections.Add(part); return part; } /// <summary> /// Maps a collection of entities as a one-to-many /// </summary> /// <typeparam name="TChild">Child entity type</typeparam> /// <param name="memberExpression">Collection property</param> /// <example> /// HasMany(x => x.Locations); /// </example> public OneToManyPart<TChild> HasMany<TChild>(Expression<Func<T, IEnumerable<TChild>>> memberExpression) { return MapHasMany<TChild, IEnumerable<TChild>>(memberExpression); } public OneToManyPart<TChild> HasMany<TKey, TChild>(Expression<Func<T, IDictionary<TKey, TChild>>> memberExpression) { return MapHasMany<TChild, IDictionary<TKey, TChild>>(memberExpression); } /// <summary> /// Maps a collection of entities as a one-to-many /// </summary> /// <typeparam name="TChild">Child entity type</typeparam> /// <param name="memberExpression">Collection property</param> /// <example> /// HasMany(x => x.Locations); /// </example> public OneToManyPart<TChild> HasMany<TChild>(Expression<Func<T, object>> memberExpression) { return MapHasMany<TChild, object>(memberExpression); } private ManyToManyPart<TChild> MapHasManyToMany<TChild, TReturn>(Expression<Func<T, TReturn>> expression) { return HasManyToMany<TChild>(expression.ToMember()); } ManyToManyPart<TChild> HasManyToMany<TChild>(Member member) { OnMemberMapped(member); var part = new ManyToManyPart<TChild>(EntityType, member); providers.Collections.Add(part); return part; } /// <summary> /// Maps a collection of entities as a many-to-many /// </summary> /// <typeparam name="TChild">Child entity type</typeparam> /// <param name="memberExpression">Collection property</param> /// <example> /// HasManyToMany(x => x.Locations); /// </example> public ManyToManyPart<TChild> HasManyToMany<TChild>(Expression<Func<T, IEnumerable<TChild>>> memberExpression) { return MapHasManyToMany<TChild, IEnumerable<TChild>>(memberExpression); } /// <summary> /// Maps a collection of entities as a many-to-many /// </summary> /// <typeparam name="TChild">Child entity type</typeparam> /// <param name="memberExpression">Collection property</param> /// <example> /// HasManyToMany(x => x.Locations); /// </example> public ManyToManyPart<TChild> HasManyToMany<TChild>(Expression<Func<T, object>> memberExpression) { return MapHasManyToMany<TChild, object>(memberExpression); } /// <summary> /// Specify an insert stored procedure /// </summary> /// <param name="innerText">Stored procedure call</param> public StoredProcedurePart SqlInsert(string innerText) { return StoredProcedure("sql-insert", innerText); } /// <summary> /// Specify an update stored procedure /// </summary> /// <param name="innerText">Stored procedure call</param> public StoredProcedurePart SqlUpdate(string innerText) { return StoredProcedure("sql-update", innerText); } /// <summary> /// Specify an delete stored procedure /// </summary> /// <param name="innerText">Stored procedure call</param> public StoredProcedurePart SqlDelete(string innerText) { return StoredProcedure("sql-delete", innerText); } /// <summary> /// Specify an delete all stored procedure /// </summary> /// <param name="innerText">Stored procedure call</param> public StoredProcedurePart SqlDeleteAll(string innerText) { return StoredProcedure("sql-delete-all", innerText); } protected StoredProcedurePart StoredProcedure(string element, string innerText) { var part = new StoredProcedurePart(element, innerText); providers.StoredProcedures.Add(part); return part; } internal IEnumerable<IPropertyMappingProvider> Properties { get { return providers.Properties; } } internal IEnumerable<IComponentMappingProvider> Components { get { return providers.Components; } } internal Type EntityType { get { return typeof(T); } } } }
using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Management.Automation; namespace System.Management.Pash.Implementation { /// /// - class implementing comparison operations in the language /// - uses IComparer<T> interface and default implementations to perform comparisons /// - handles type mapping for objects to specific comparers based on LHS type /// - currently only handles primitive types (but should be extensible) /// - numeric types are handled by LHS or RHS type match in: double, float, long, int, char, byte, bool order /// - TODO: handle ==, != cases here as well /// - TODO: handle arrays, hashtables /// - TODO: improve test cases to ensure correctness with Microsoft Powershell /// internal static class ComparisonOperations { /// /// NOTE: dynamic doesn't seem to work in Mono (on Mac OS X) /// use generic functions and type based dispatching instead. /// EXAMPLE: /// Func<IComparer<dynamic>, dynamic, dynamic, object> opComparer = /// (IComparer<dynamic> c, dynamic l, dynamic r) => checked(c.Compare(l, r) > 0); /// return ComparisonOperation(lhs, rhs, ignoreCase, "-gt", opComparer); /// private static object GreaterThanOp<T>(IComparer<T> c, T l, T r) { return (c.Compare(l, r) > 0); } private static object GreaterThanEqualsOp<T>(IComparer<T> c, T l, T r) { return (c.Compare(l, r) >= 0); } private static object LessThanOp<T>(IComparer<T> c, T l, T r) { return (c.Compare(l, r) < 0); } private static object LessThanEqualsOp<T>(IComparer<T> c, T l, T r) { return (c.Compare(l, r) <= 0); } private static Func<IComparer<T>, T, T, object> GetComparerOp<T>(string op) { if (op.Equals("-gt")) { return GreaterThanOp<T>; } if (op.Equals("-ge")) { return GreaterThanEqualsOp<T>; } if (op.Equals("-lt")) { return LessThanOp<T>; } if (op.Equals("-le")) { return LessThanEqualsOp<T>; } throw new NotImplementedException(String.Format("Invalid Operation: {0}", op)); } /// /// - method for handling -gt, -igt, -cgt operations /// - called with unpacked lhs/rhs operands and whether to respect case /// public static object GreaterThan(object lhs, object rhs, bool ignoreCase) { return ComparisonOperation(lhs, rhs, ignoreCase, "-gt"); } /// /// - method for handling -ge, -ige, -cge operations /// - called with unpacked lhs/rhs operands and whether to respect case /// public static object GreaterThanEquals(object lhs, object rhs, bool ignoreCase) { return ComparisonOperation(lhs, rhs, ignoreCase, "-ge"); } /// /// - method for handling -lt, -ilt, -clt operations /// - called with unpacked lhs/rhs operands and whether to respect case /// public static object LessThan(object lhs, object rhs, bool ignoreCase) { return ComparisonOperation(lhs, rhs, ignoreCase, "-lt"); } /// /// - method for handling -le, -ile, -cle operations /// - called with unpacked lhs/rhs operands and whether to respect case /// public static object LessThanEquals(object lhs, object rhs, bool ignoreCase) { return ComparisonOperation(lhs, rhs, ignoreCase, "-le"); } /// /// - implements type mapping and ordering (primitive overload resolution) /// /// 7.9 Relational and type-testing Operators /// Description: /// /// Rules in Order: /// - LHS is String then (String op String) /// - LHS is DateTiem then (DateTime op DateTime) /// - LHS or RHS is Double then (Double op Double) /// - LHS or RHS is Float then (Float op Float) /// - LHS or RHS is Long then (Long op Long) /// - LHS or RHS is Int then (Int op Int) /// - LHS or RHS is Char then (Char op Char) /// - LHS or RHS is Byte then (Byte op Byte) /// - LHS or RHS is Bool then (Bool op Bool) /// Overload resolution is determined per 7.2.4. /// This operator is left associative. /// /// Examples: See ReferenceTests.RelationshipOperatorTests_7_9 /// /// Operations: gt, gte, lt, lte, eq, neq /// /// string op string, string op * /// datetime op datetime, datetime op * /// double op double, double op * /// float op float, float op * /// long op long, long op * /// int op int, int op * /// char op char, char op * /// byte op byte, byte op * /// bool op bool, bool op * /// private static object ComparisonOperation( object leftValue, object rightValue, bool ignoreCase, string op) { var lhs = PSObject.Unwrap(leftValue); var rhs = PSObject.Unwrap(rightValue); /// /// allow some null cases to be handled by RHS operand type /// if (((lhs == null) && ((rhs == null) || (rhs is string) || (rhs is DateTime) || (rhs is bool))) || (lhs is string)) { var lhsInverted = lhs; var rhsInverted = rhs; if (lhs is string) lhsInverted = StringExtensions.InvertCase(lhs as string); if (rhs is string) rhsInverted = StringExtensions.InvertCase(rhs as string); Func<IComparer<string>, string, string, object> checkedOp = GetComparerOp<string>(op); return Compare<string>(getStringComparer(ignoreCase), lhsInverted, rhsInverted, op, checkedOp); } if (((lhs == null) && (rhs is DateTime)) || (lhs is DateTime)) { return Compare<DateTime>(lhs, rhs, op); } /// /// these cases will automatically handle the null case if the RHS operand is of the correct type /// if (lhs is double || rhs is double) { return Compare<double>(lhs, rhs, op); } if (lhs is float || rhs is float) { return Compare<float>(lhs, rhs, op); } if (lhs is long || rhs is long) { return Compare<long>(lhs, rhs, op); } if (lhs is int || rhs is int) { return Compare<int>(lhs, rhs, op); } if (lhs is char || rhs is char) { return Compare<char>(lhs, rhs, op); } if (lhs is byte || rhs is byte) { return Compare<byte>(lhs, rhs, op); } if (lhs is bool || rhs is bool) { return Compare<bool>(lhs, rhs, op); } // array comparison // hashtable comparison throw new NotImplementedException(String.Format("{0} {1} {2}", lhs, op, rhs)); } /// /// returns an IComparer<T> for StringComparer based on the case sensititivity flag /// used in the -i*, -c* relationship comparison operators /// private static IComparer<string> getStringComparer(bool ignoreCase) { return ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; } /// /// - generic case Comparison /// private static object Compare<T>(object lhs, object rhs, string op) { Func<IComparer<T>, T, T, object> checkedOp = GetComparerOp<T>(op); return Compare<T>(Comparer<T>.Default, lhs, rhs, op, checkedOp); } /// /// - generic comparison function /// - callers provide the type specific comparer /// - depends on LanguagePrimitives.ConvertTo for type conversion /// - type conversion can fail in some cases (such as to DateTime) /// - performs the actual comparison operation as +ve, 0, -ve check in checkOp /// private static object Compare<T>( IComparer<T> comparer, object lhs, object rhs, string op, Func<IComparer<T>, T, T, object> checkedOp) { try { var left = LanguagePrimitives.ConvertTo<T>(lhs); var right = LanguagePrimitives.ConvertTo<T>(rhs); return checkedOp(comparer, left, right); } catch (Exception ex) { ThrowInvalidComparisonOperationException(lhs, rhs, op, ex); } return null; } /// /// constructs invalid comparison errors similar to Posh /// private static void ThrowInvalidComparisonOperationException( object left, object right, string op, Exception ex) { var msg = String.Format("Could not compare \"{0}\" to \"{1}\". {2}", left, right, ex.Message); throw new PSInvalidOperationException(msg); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.Providers.Mail; namespace WebsitePanel.Portal { public partial class MailGroupsEditGroup : WebsitePanelModuleBase { MailGroup item = null; protected void Page_Load(object sender, EventArgs e) { btnDelete.Visible = (PanelRequest.ItemID > 0); // bind item BindItem(); } private void BindItem() { try { if (!IsPostBack) { // load item if required if (PanelRequest.ItemID > 0) { // existing item try { item = ES.Services.MailServers.GetMailGroup(PanelRequest.ItemID); } catch (Exception ex) { ShowErrorMessage("MAIL_GET_GROUP", ex); return; } if (item != null) { // save package info ViewState["PackageId"] = item.PackageId; emailAddress.PackageId = item.PackageId; } else RedirectToBrowsePage(); } else { // new item ViewState["PackageId"] = PanelSecurity.PackageId; emailAddress.PackageId = PanelSecurity.PackageId; } } // load provider control LoadProviderControl((int)ViewState["PackageId"], "Mail", providerControl, "EditGroup.ascx"); if (!IsPostBack) { // bind item to controls if (item != null) { // bind item to controls emailAddress.Email = item.Name; emailAddress.EditMode = true; // other controls IMailEditGroupControl ctrl = (IMailEditGroupControl)providerControl.Controls[0]; ctrl.BindItem(item); } } } catch { ShowWarningMessage("INIT_SERVICE_ITEM_FORM"); DisableFormControls(this, btnCancel); return; } } private void SaveItem() { if (!Page.IsValid) return; // get form data MailGroup item = new MailGroup(); item.Id = PanelRequest.ItemID; item.PackageId = PanelSecurity.PackageId; item.Name = emailAddress.Email; //checking if group name is different from existing e-mail accounts MailAccount[] accounts = ES.Services.MailServers.GetMailAccounts(PanelSecurity.PackageId, true); foreach (MailAccount account in accounts) { if (item.Name == account.Name) { ShowWarningMessage("MAIL_GROUP_NAME"); return; } } //checking if group name is different from existing mail lists MailList[] lists = ES.Services.MailServers.GetMailLists(PanelSecurity.PackageId, true); foreach (MailList list in lists) { if (item.Name == list.Name) { ShowWarningMessage("MAIL_GROUP_NAME"); return; } } //checking if group name is different from existing forwardings MailAlias[] forwardings = ES.Services.MailServers.GetMailForwardings(PanelSecurity.PackageId, true); foreach (MailAlias forwarding in forwardings) { if (item.Name == forwarding.Name) { ShowWarningMessage("MAIL_GROUP_NAME"); return; } } // get other props IMailEditGroupControl ctrl = (IMailEditGroupControl)providerControl.Controls[0]; ctrl.SaveItem(item); if (PanelRequest.ItemID == 0) { // new item try { int result = ES.Services.MailServers.AddMailGroup(item); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_ADD_GROUP", ex); return; } } else { // existing item try { int result = ES.Services.MailServers.UpdateMailGroup(item); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_UPDATE_GROUP", ex); return; } } // return RedirectSpaceHomePage(); } private void DeleteItem() { // delete try { int result = ES.Services.MailServers.DeleteMailGroup(PanelRequest.ItemID); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("MAIL_DELETE_GROUP", ex); return; } // return RedirectSpaceHomePage(); } protected void btnSave_Click(object sender, EventArgs e) { SaveItem(); } protected void btnCancel_Click(object sender, EventArgs e) { // return RedirectSpaceHomePage(); } protected void btnDelete_Click(object sender, EventArgs e) { DeleteItem(); } } }
// 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.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentDictionaryTests { [Fact] public static void TestBasicScenarios() { ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(); Task[] tks = new Task[2]; tks[0] = Task.Run(() => { var ret = cd.TryAdd(1, 11); if (!ret) { ret = cd.TryUpdate(1, 11, 111); Assert.True(ret); } ret = cd.TryAdd(2, 22); if (!ret) { ret = cd.TryUpdate(2, 22, 222); Assert.True(ret); } }); tks[1] = Task.Run(() => { var ret = cd.TryAdd(2, 222); if (!ret) { ret = cd.TryUpdate(2, 222, 22); Assert.True(ret); } ret = cd.TryAdd(1, 111); if (!ret) { ret = cd.TryUpdate(1, 111, 11); Assert.True(ret); } }); Task.WaitAll(tks); } [Fact] public static void TestAddNullValue_ConcurrentDictionaryOfString_null() { // using ConcurrentDictionary<TKey, TValue> class ConcurrentDictionary<string, string> dict1 = new ConcurrentDictionary<string, string>(); dict1["key"] = null; } [Fact] public static void TestAddNullValue_IDictionaryOfString_null() { // using IDictionary<TKey, TValue> interface IDictionary<string, string> dict2 = new ConcurrentDictionary<string, string>(); dict2["key"] = null; dict2.Add("key2", null); } [Fact] public static void TestAddNullValue_IDictionary_ReferenceType_null() { // using IDictionary interface IDictionary dict3 = new ConcurrentDictionary<string, string>(); dict3["key"] = null; dict3.Add("key2", null); } [Fact] public static void TestAddNullValue_IDictionary_ValueType_null_indexer() { // using IDictionary interface and value type values Action action = () => { IDictionary dict4 = new ConcurrentDictionary<string, int>(); dict4["key"] = null; }; Assert.Throws<ArgumentException>(action); } [Fact] public static void TestAddNullValue_IDictionary_ValueType_null_add() { Action action = () => { IDictionary dict5 = new ConcurrentDictionary<string, int>(); dict5.Add("key", null); }; Assert.Throws<ArgumentException>(action); } [Fact] public static void TestAddValueOfDifferentType() { Action action = () => { IDictionary dict = new ConcurrentDictionary<string, string>(); dict["key"] = 1; }; Assert.Throws<ArgumentException>(action); action = () => { IDictionary dict = new ConcurrentDictionary<string, string>(); dict.Add("key", 1); }; Assert.Throws<ArgumentException>(action); } [Fact] public static void TestAdd1() { TestAdd1(1, 1, 1, 10000); TestAdd1(5, 1, 1, 10000); TestAdd1(1, 1, 2, 5000); TestAdd1(1, 1, 5, 2000); TestAdd1(4, 0, 4, 2000); TestAdd1(16, 31, 4, 2000); TestAdd1(64, 5, 5, 5000); TestAdd1(5, 5, 5, 2500); } private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread) { ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1); IDictionary<int, int> dict = dictConcurrent; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread)); } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); int itemCount = threads * addsPerThread; for (int i = 0; i < itemCount; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), string.Format("The set of keys in the dictionary is are not the same as the expected" + Environment.NewLine + "TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread) ); } // Finally, let's verify that the count is reported correctly. int expectedCount = threads * addsPerThread; Assert.Equal(expectedCount, dict.Count); Assert.Equal(expectedCount, dictConcurrent.ToArray().Length); } [Fact] public static void TestUpdate1() { TestUpdate1(1, 1, 10000); TestUpdate1(5, 1, 10000); TestUpdate1(1, 2, 5000); TestUpdate1(1, 5, 2001); TestUpdate1(4, 4, 2001); TestUpdate1(15, 5, 2001); TestUpdate1(64, 5, 5000); TestUpdate1(5, 5, 25000); } private static void TestUpdate1(int cLevel, int threads, int updatesPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 1; i <= updatesPerThread; i++) dict[i] = i; int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 1; j <= updatesPerThread; j++) { dict[j] = (ii + 2) * j; } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { var div = pair.Value / pair.Key; var rem = pair.Value % pair.Key; Assert.Equal(0, rem); Assert.True(div > 1 && div <= threads + 1, string.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div)); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 1; i <= updatesPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), string.Format("The set of keys in the dictionary is are not the same as the expected." + Environment.NewLine + "TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread) ); } } [Fact] public static void TestRead1() { TestRead1(1, 1, 10000); TestRead1(5, 1, 10000); TestRead1(1, 2, 5000); TestRead1(1, 5, 2001); TestRead1(4, 4, 2001); TestRead1(15, 5, 2001); TestRead1(64, 5, 5000); TestRead1(5, 5, 25000); } private static void TestRead1(int cLevel, int threads, int readsPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 0; i < readsPerThread; i += 2) dict[i] = i; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < readsPerThread; j++) { int val = 0; if (dict.TryGetValue(j, out val)) { Assert.Equal(0, j % 2); Assert.Equal(j, val); } else { Assert.Equal(1, j % 2); } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } } [Fact] public static void TestRemove1() { TestRemove1(1, 1, 10000); TestRemove1(5, 1, 1000); TestRemove1(1, 5, 2001); TestRemove1(4, 4, 2001); TestRemove1(15, 5, 2001); TestRemove1(64, 5, 5000); } private static void TestRemove1(int cLevel, int threads, int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread); int N = 2 * threads * removesPerThread; for (int i = 0; i < N; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < removesPerThread; j++) { int value; int key = 2 * (ii + j * threads); Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters); Assert.Equal(-key, value); } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < (threads * removesPerThread); i++) expectKeys.Add(2 * i + 1); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters); } // Finally, let's verify that the count is reported correctly. Assert.Equal(expectKeys.Count, dict.Count); Assert.Equal(expectKeys.Count, dict.ToArray().Length); } [Fact] public static void TestRemove2() { TestRemove2(1); TestRemove2(10); TestRemove2(5000); } private static void TestRemove2(int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); for (int i = 0; i < removesPerThread; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys. const int SIZE = 2; int running = SIZE; bool[][] seen = new bool[SIZE][]; for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread]; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int t = 0; t < SIZE; t++) { int thread = t; Task.Run( () => { for (int key = 0; key < removesPerThread; key++) { int value; if (dict.TryRemove(key, out value)) { seen[thread][key] = true; Assert.Equal(-key, value); } } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } Assert.Equal(0, dict.Count); for (int i = 0; i < removesPerThread; i++) { Assert.False(seen[0][i] == seen[1][i], string.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread) ); } } [Fact] public static void TestRemove3() { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); dict[99] = -99; ICollection<KeyValuePair<int, int>> col = dict; // Make sure we cannot "remove" a key/value pair which is not in the dictionary for (int i = 0; i < 200; i++) { if (i != 99) { Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)"); Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)"); } } // Can we remove a key/value pair successfully? Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair"); // Make sure the key/value pair is gone Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed"); // And that the dictionary is empty. We will check the count in a few different ways: Assert.Equal(0, dict.Count); Assert.Equal(0, dict.ToArray().Length); } [Fact] public static void TryRemove_KeyValuePair_ArgumentValidation() { AssertExtensions.Throws<ArgumentNullException>("item", () => new ConcurrentDictionary<string, int>().TryRemove(new KeyValuePair<string, int>(null, 42))); new ConcurrentDictionary<int, int>().TryRemove(new KeyValuePair<int, int>(0, 0)); // no error when using default value type new ConcurrentDictionary<int?, int>().TryRemove(new KeyValuePair<int?, int>(0, 0)); // or nullable } [Fact] public static void TryRemove_KeyValuePair_RemovesSuccessfullyAsAppropriate() { var dict = new ConcurrentDictionary<string, int>(); for (int i = 0; i < 2; i++) { Assert.False(dict.TryRemove(KeyValuePair.Create("key", 42))); Assert.Equal(0, dict.Count); Assert.True(dict.TryAdd("key", 42)); Assert.Equal(1, dict.Count); Assert.True(dict.TryRemove(KeyValuePair.Create("key", 42))); Assert.Equal(0, dict.Count); } Assert.True(dict.TryAdd("key", 42)); Assert.False(dict.TryRemove(KeyValuePair.Create("key", 43))); // value doesn't match } [Fact] public static void TryRemove_KeyValuePair_MatchesKeyWithDefaultComparer() { var dict = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase); dict.TryAdd("key", "value"); Assert.False(dict.TryRemove(KeyValuePair.Create("key", "VALUE"))); Assert.True(dict.TryRemove(KeyValuePair.Create("KEY", "value"))); } [Fact] public static void TestGetOrAdd() { TestGetOrAddOrUpdate(1, 1, 1, 10000, true); TestGetOrAddOrUpdate(5, 1, 1, 10000, true); TestGetOrAddOrUpdate(1, 1, 2, 5000, true); TestGetOrAddOrUpdate(1, 1, 5, 2000, true); TestGetOrAddOrUpdate(4, 0, 4, 2000, true); TestGetOrAddOrUpdate(16, 31, 4, 2000, true); TestGetOrAddOrUpdate(64, 5, 5, 5000, true); TestGetOrAddOrUpdate(5, 5, 5, 25000, true); } [Fact] public static void TestAddOrUpdate() { TestGetOrAddOrUpdate(1, 1, 1, 10000, false); TestGetOrAddOrUpdate(5, 1, 1, 10000, false); TestGetOrAddOrUpdate(1, 1, 2, 5000, false); TestGetOrAddOrUpdate(1, 1, 5, 2000, false); TestGetOrAddOrUpdate(4, 0, 4, 2000, false); TestGetOrAddOrUpdate(16, 31, 4, 2000, false); TestGetOrAddOrUpdate(64, 5, 5, 5000, false); TestGetOrAddOrUpdate(5, 5, 5, 25000, false); } private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { if (isAdd) { //call one of the overloads of GetOrAdd switch (j % 3) { case 0: dict.GetOrAdd(j, -j); break; case 1: dict.GetOrAdd(j, x => -x); break; case 2: dict.GetOrAdd(j, (x,m) => x * m, -1); break; } } else { switch (j % 3) { case 0: dict.AddOrUpdate(j, -j, (k, v) => -j); break; case 1: dict.AddOrUpdate(j, (k) => -k, (k, v) => -k); break; case 2: dict.AddOrUpdate(j, (k,m) => k*m, (k, v, m) => k * m, -1); break; } } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < addsPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), string.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})" + Environment.NewLine + "> FAILED. The set of keys in the dictionary is are not the same as the expected.", cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate")); } // Finally, let's verify that the count is reported correctly. Assert.Equal(addsPerThread, dict.Count); Assert.Equal(addsPerThread, dict.ToArray().Length); } [Fact] public static void TestBugFix669376() { var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer()); cd["test"] = 10; Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work"); } private class OrdinalStringComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { var xlower = x.ToLowerInvariant(); var ylower = y.ToLowerInvariant(); return string.CompareOrdinal(xlower, ylower) == 0; } public int GetHashCode(string obj) { return 0; } } [Fact] public static void TestConstructor() { var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }); Assert.False(dictionary.IsEmpty); Assert.Equal(1, dictionary.Keys.Count); Assert.Equal(1, dictionary.Values.Count); } [Fact] public static void TestDebuggerAttributes() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>()); ConcurrentDictionary<string, int> dict = new ConcurrentDictionary<string, int>(); dict.TryAdd("One", 1); dict.TryAdd("Two", 2); DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(dict); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); KeyValuePair<string, int>[] items = itemProperty.GetValue(info.Instance) as KeyValuePair<string, int>[]; Assert.Equal(dict, items); } [Fact] public static void TestDebuggerAttributes_Null() { Type proxyType = DebuggerAttributes.GetProxyType(new ConcurrentDictionary<string, int>()); TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null)); Assert.IsType<ArgumentNullException>(tie.InnerException); } [Fact] public static void TestNullComparer() { AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>((IEqualityComparer<EqualityApiSpy>)null)); AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>(new[] { new KeyValuePair<EqualityApiSpy, int>(new EqualityApiSpy(), 1) }, null)); AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>(1, new[] { new KeyValuePair<EqualityApiSpy, int>(new EqualityApiSpy(), 1) }, null)); AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>(1, 1, null)); void AssertDefaultComparerBehavior(ConcurrentDictionary<EqualityApiSpy, int> dictionary) { var spyKey = new EqualityApiSpy(); Assert.True(dictionary.TryAdd(spyKey, 1)); Assert.False(dictionary.TryAdd(spyKey, 1)); Assert.False(spyKey.ObjectApiUsed); Assert.True(spyKey.IEquatableApiUsed); } } private sealed class EqualityApiSpy : IEquatable<EqualityApiSpy> { public bool ObjectApiUsed { get; private set; } public bool IEquatableApiUsed { get; private set; } public override bool Equals(object obj) { ObjectApiUsed = true; return ReferenceEquals(this, obj); } public override int GetHashCode() => base.GetHashCode(); public bool Equals(EqualityApiSpy other) { IEquatableApiUsed = true; return ReferenceEquals(this, other); } } [Fact] public static void TestConstructor_Negative() { Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) })); // "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed"); // Duplicate keys. AssertExtensions.Throws<ArgumentException>(null, () => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) })); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(0, 10)); // "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(-1, 0)); // "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed"); } [Fact] public static void TestExceptions() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryAdd(null, 0)); // "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.ContainsKey(null)); // "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed"); int item; Assert.Throws<ArgumentNullException>( () => dictionary.TryRemove(null, out item)); // "TestExceptions: FAILED. TryRemove didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.TryGetValue(null, out item)); // "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => { var x = dictionary[null]; }); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<KeyNotFoundException>( () => { var x = dictionary["1"]; }); // "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 1); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, (k,m) => 0, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd("1", null, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, (k) => 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd("1", null)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k, m) => 0, (k, v, m) => 0, 42)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", (k, m) => 0, null, 42)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", null, (k, v, m) => 0, 42)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", null, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, null)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed"); // Duplicate key. dictionary.TryAdd("1", 1); AssertExtensions.Throws<ArgumentException>(null, () => ((IDictionary<string, int>)dictionary).Add("1", 2)); } [Fact] public static void TestIDictionary() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.False(dictionary.IsReadOnly); // Empty dictionary should not enumerate Assert.Empty(dictionary); const int SIZE = 10; for (int i = 0; i < SIZE; i++) dictionary.Add(i.ToString(), i); Assert.Equal(SIZE, dictionary.Count); //test contains Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain returned true for incorrect key type"); Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain returned true for incorrect key"); Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain returned false for correct key"); //test GetEnumerator int count = 0; foreach (var obj in dictionary) { DictionaryEntry entry = (DictionaryEntry)obj; string key = (string)entry.Key; int value = (int)entry.Value; int expectedValue = int.Parse(key); Assert.True(value == expectedValue, string.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue)); count++; } Assert.Equal(SIZE, count); Assert.Equal(SIZE, dictionary.Keys.Count); Assert.Equal(SIZE, dictionary.Values.Count); //Test Remove dictionary.Remove("9"); Assert.Equal(SIZE - 1, dictionary.Count); //Test this[] for (int i = 0; i < dictionary.Count; i++) Assert.Equal(i, (int)dictionary[i.ToString()]); dictionary["1"] = 100; // try a valid setter Assert.Equal(100, (int)dictionary["1"]); //non-existing key Assert.Null(dictionary["NotAKey"]); } [Fact] public static void TestIDictionary_Negative() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.Add(null, 1)); // "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed"); // Invalid key type. AssertExtensions.Throws<ArgumentException>(null, () => dictionary.Add(1, 1)); // Invalid value type. AssertExtensions.Throws<ArgumentException>(null, () => dictionary.Add("1", "1")); Assert.Throws<ArgumentNullException>( () => dictionary.Contains(null)); // "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed"); //Test Remove Assert.Throws<ArgumentNullException>( () => dictionary.Remove(null)); // "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed"); //Test this[] Assert.Throws<ArgumentNullException>( () => { object val = dictionary[null]; }); // "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 0); // "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed"); // Invalid key type. AssertExtensions.Throws<ArgumentException>(null, () => dictionary[1] = 0); // Invalid value type. AssertExtensions.Throws<ArgumentException>(null, () => dictionary["1"] = "0"); } [Fact] public static void IDictionary_Remove_NullKeyInKeyValuePair_ThrowsArgumentNullException() { IDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>(() => dictionary.Remove(new KeyValuePair<string, int>(null, 0))); } [Fact] public static void TestICollection() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); int key = -1; int value = +1; //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value); var objectArray = new object[1]; dictionary.CopyTo(objectArray, 0); Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key); Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value); var keyValueArray = new KeyValuePair<int, int>[1]; dictionary.CopyTo(keyValueArray, 0); Assert.Equal(key, keyValueArray[0].Key); Assert.Equal(value, keyValueArray[0].Value); var entryArray = new DictionaryEntry[1]; dictionary.CopyTo(entryArray, 0); Assert.Equal(key, (int)entryArray[0].Key); Assert.Equal(value, (int)entryArray[0].Value); } [Fact] public static void TestICollection_Negative() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; }); // "TestICollection: FAILED. SyncRoot property didn't throw"); Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0)); // "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed"); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1)); // "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed"); //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1); AssertExtensions.Throws<ArgumentException>(null, () => dictionary.CopyTo(new object[] { }, 0)); // "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count"); } [Fact] public static void TestClear() { var dictionary = new ConcurrentDictionary<int, int>(); for (int i = 0; i < 10; i++) dictionary.TryAdd(i, i); Assert.Equal(10, dictionary.Count); dictionary.Clear(); Assert.Equal(0, dictionary.Count); int item; Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear"); Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear"); } [Fact] public static void TestTryUpdate() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryUpdate(null, 0, 0)); // "TestTryUpdate: FAILED. TryUpdate didn't throw ANE when null key is passed"); for (int i = 0; i < 10; i++) dictionary.TryAdd(i.ToString(), i); for (int i = 0; i < 10; i++) { Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!"); Assert.Equal(i + 1, dictionary[i.ToString()]); } //test TryUpdate concurrently dictionary.Clear(); for (int i = 0; i < 1000; i++) dictionary.TryAdd(i.ToString(), i); var mres = new ManualResetEventSlim(); Task[] tasks = new Task[10]; ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true); for (int i = 0; i < tasks.Length; i++) { // We are creating the Task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. tasks[i] = Task.Factory.StartNew((obj) => { mres.Wait(); int index = (((int)obj) + 1) + 1000; updatedKeys.Value = new ThreadData(); updatedKeys.Value.ThreadIndex = index; for (int j = 0; j < dictionary.Count; j++) { if (dictionary.TryUpdate(j.ToString(), index, j)) { if (dictionary[j.ToString()] != index) { updatedKeys.Value.Succeeded = false; return; } updatedKeys.Value.Keys.Add(j.ToString()); } } }, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } mres.Set(); Task.WaitAll(tasks); int numberSucceeded = 0; int totalKeysUpdated = 0; foreach (var threadData in updatedKeys.Values) { totalKeysUpdated += threadData.Keys.Count; if (threadData.Succeeded) numberSucceeded++; } Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!"); Assert.True(totalKeysUpdated == dictionary.Count, string.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated)); foreach (var value in updatedKeys.Values) { for (int i = 0; i < value.Keys.Count; i++) Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex, string.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]])); } //test TryUpdate with non atomic values (intPtr > 8) var dict = new ConcurrentDictionary<int, Struct16>(); dict.TryAdd(1, new Struct16(1, -1)); Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdate failed for non atomic values ( > 8 bytes)"); } #region Helper Classes and Methods private class ThreadData { public int ThreadIndex; public bool Succeeded = true; public List<string> Keys = new List<string>(); } private struct Struct16 : IEqualityComparer<Struct16> { public long L1, L2; public Struct16(long l1, long l2) { L1 = l1; L2 = l2; } public bool Equals(Struct16 x, Struct16 y) { return x.L1 == y.L1 && x.L2 == y.L2; } public int GetHashCode(Struct16 obj) { return (int)L1; } } #endregion } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace NeinLinq.Tests; public class EntityFrameworkCoreExtensionTest { [Fact] public void WithRewriter_NullArgument_Throws() { var optionsBuilderError = Assert.Throws<ArgumentNullException>(() => RewriteDbContextOptionsBuilderExtensions.WithRewriter(null!, new Rewriter())); var rewriterError = Assert.Throws<ArgumentNullException>(() => RewriteDbContextOptionsBuilderExtensions.WithRewriter(new DbContextOptionsBuilder(), null!)); Assert.Equal("optionsBuilder", optionsBuilderError.ParamName); Assert.Equal("rewriter", rewriterError.ParamName); } [Fact] public void WithRewriter_PopulatesInfo() { var info = new DbContextOptionsBuilder().WithRewriter(new Rewriter()).Options.FindExtension<RewriteDbContextOptionsExtension>()?.Info; var debugInfo = new Dictionary<string, string>(); info?.PopulateDebugInfo(debugInfo); Assert.NotNull(info); Assert.False(info!.IsDatabaseProvider); Assert.Equal("Rewriter=NeinLinq.Tests.EntityFrameworkCoreExtensionTest+Rewriter", info.LogFragment); Assert.Equal(0, info.GetServiceProviderHashCode()); Assert.Equal(new Dictionary<string, string>() { ["RewriteQuery:Rewriter:0:Type"] = "NeinLinq.Tests.EntityFrameworkCoreExtensionTest+Rewriter", ["RewriteQuery:Rewriter:0:Info"] = "I'm a rewriter." }, debugInfo ); } [Fact] public void Query_WithLambdaInjection_ResolvesLambdaInjection() { var services = new ServiceCollection(); _ = services.AddDbContext<TestContext>(options => options.UseSqlite("Data Source=EntityFrameworkCoreExtensionTest.db").WithLambdaInjection(typeof(Model))); using var serviceProvider = services.BuildServiceProvider(); var context = serviceProvider.GetRequiredService<TestContext>(); _ = context.Database.EnsureDeleted(); _ = context.Database.EnsureCreated(); context.Models.AddRange( new Model { Name = "Heinz" }, new Model { Name = "Narf" }, new Model { Name = "Wat" } ); _ = context.SaveChanges(); var query = from m in context.Models where m.IsNarf select m.Id; Assert.Equal(1, query.Count()); } [Fact] public void Query_WithoutLambdaInjection_Throws() { var services = new ServiceCollection(); _ = services.AddDbContext<TestContext>(options => options.UseSqlite("Data Source=EntityFrameworkCoreExtensionTest.db")); using var serviceProvider = services.BuildServiceProvider(); var context = serviceProvider.GetRequiredService<TestContext>(); _ = context.Database.EnsureDeleted(); _ = context.Database.EnsureCreated(); var query = from d in context.Models where d.IsNarf select d.Id; _ = Assert.Throws<InvalidOperationException>(() => query.Count()); } [Fact] public void Query_WithInnerLambdaInjection_ResolvesLambdaInjection() { var services = new ServiceCollection(); _ = services.AddDbContext<TestContext>(options => options.UseSqlite("Data Source=EntityFrameworkCoreExtensionTest.db").WithLambdaInjection(typeof(Model))); using var serviceProvider = services.BuildServiceProvider(); var context = serviceProvider.GetRequiredService<TestContext>(); _ = context.Database.EnsureDeleted(); _ = context.Database.EnsureCreated(); context.Models.AddRange( new Model { Name = "Heinz" }, new Model { Name = "Narf" }, new Model { Name = "Wat" } ); _ = context.SaveChanges(); var innerQuery = context.Models.Where(m => m.IsNarf); var outerQuery = from m in context.Models join n in innerQuery on m.Id equals n.Id select n.Id; var query = context.Models.SelectMany(_ => outerQuery); Assert.Equal(3, query.Count()); } [Fact] public void Query_WithNestedLambdaInjection_ResolvesLambdaInjection() { var services = new ServiceCollection(); _ = services.AddDbContext<TestContext>(options => options.UseSqlite("Data Source=EntityFrameworkCoreExtensionTest.db").WithLambdaInjection(typeof(Model))); using var serviceProvider = services.BuildServiceProvider(); var context = serviceProvider.GetRequiredService<TestContext>(); _ = context.Database.EnsureDeleted(); _ = context.Database.EnsureCreated(); context.Models.AddRange( new Model { Name = "Heinz", Values = { new ModelValue { Value = 1, IsActive = true }, new ModelValue { Value = 2 }, new ModelValue { Value = 3 } } }, new Model { Name = "Narf", Values = { new ModelValue { Value = 4 }, new ModelValue { Value = 5, IsActive = true }, new ModelValue { Value = 6 } } }, new Model { Name = "Wat", Values = { new ModelValue { Value = 7 }, new ModelValue { Value = 8 }, new ModelValue { Value = 9, IsActive = true } } } ); _ = context.SaveChanges(); var query = from m in context.Models select new { m.Id, m.Name, m.ActiveValue }; Assert.Equal(15, query.Sum(m => m.ActiveValue)); } private class Model { public int Id { get; set; } public string? Name { get; set; } public ISet<ModelValue> Values { get; set; } = new HashSet<ModelValue>(); public bool IsNarf => throw new InvalidOperationException($"Unable to determine, whether {Name} is Narf or not."); public static Expression<Func<Model, bool>> IsNarfExpr => d => d.Name == "Narf"; public int? ActiveValue => throw new InvalidOperationException($"Unable to determine, whether {Name} has active value or not."); public static Expression<Func<Model, int?>> ActiveValueExpr => d => d.Values.Where(v => v.IsActive == ModelValue.TrueValue).Select(v => v.Value).FirstOrDefault(); } private class ModelValue { public int Id { get; set; } public int Value { get; set; } public bool IsActive { get; set; } public static bool TrueValue => true; } private class TestContext : DbContext { public DbSet<Model> Models { get; } public TestContext(DbContextOptions<TestContext> options) : base(options) { Models = Set<Model>(); } } private class Rewriter : ExpressionVisitor { public override string ToString() => "I'm a rewriter."; } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Globalization; using System.Windows; using MS.Internal; namespace System.Windows.Controls { /// <summary> /// DataGridLength is the type used for various length properties in DataGrid /// that support a variety of descriptive sizing modes in addition to numerical /// values. /// </summary> [TypeConverter(typeof(DataGridLengthConverter))] public struct DataGridLength : IEquatable<DataGridLength> { #region Constructors /// <summary> /// Initializes as an absolute value in pixels. /// </summary> /// <param name="pixels"> /// Specifies the number of 'device-independent pixels' (96 pixels-per-inch). /// </param> /// <exception cref="ArgumentException"> /// If <c>pixels</c> parameter is <c>double.NaN</c> /// or <c>pixels</c> parameter is <c>double.NegativeInfinity</c> /// or <c>pixels</c> parameter is <c>double.PositiveInfinity</c>. /// </exception> public DataGridLength(double pixels) : this(pixels, DataGridLengthUnitType.Pixel) { } /// <summary> /// Initializes to a specified value and unit. /// </summary> /// <param name="value">The value to hold.</param> /// <param name="type">The unit of <c>value</c>.</param> /// <remarks> /// <c>value</c> is ignored unless <c>type</c> is /// <c>DataGridLengthUnitType.Pixel</c> or /// <c>DataGridLengthUnitType.Star</c> /// </remarks> /// <exception cref="ArgumentException"> /// If <c>value</c> parameter is <c>double.NaN</c> /// or <c>value</c> parameter is <c>double.NegativeInfinity</c> /// or <c>value</c> parameter is <c>double.PositiveInfinity</c>. /// </exception> public DataGridLength(double value, DataGridLengthUnitType type) : this(value, type, (type == DataGridLengthUnitType.Pixel ? value : Double.NaN), (type == DataGridLengthUnitType.Pixel ? value : Double.NaN)) { } /// <summary> /// Initializes to a specified value and unit. /// </summary> /// <param name="value">The value to hold.</param> /// <param name="type">The unit of <c>value</c>.</param> /// <param name="desiredValue"></param> /// <param name="displayValue"></param> /// <remarks> /// <c>value</c> is ignored unless <c>type</c> is /// <c>DataGridLengthUnitType.Pixel</c> or /// <c>DataGridLengthUnitType.Star</c> /// </remarks> /// <exception cref="ArgumentException"> /// If <c>value</c> parameter is <c>double.NaN</c> /// or <c>value</c> parameter is <c>double.NegativeInfinity</c> /// or <c>value</c> parameter is <c>double.PositiveInfinity</c>. /// </exception> public DataGridLength(double value, DataGridLengthUnitType type, double desiredValue, double displayValue) { if (DoubleUtil.IsNaN(value) || Double.IsInfinity(value)) { throw new ArgumentException( SR.Get(SRID.DataGridLength_Infinity), "value"); } if (type != DataGridLengthUnitType.Auto && type != DataGridLengthUnitType.Pixel && type != DataGridLengthUnitType.Star && type != DataGridLengthUnitType.SizeToCells && type != DataGridLengthUnitType.SizeToHeader) { throw new ArgumentException( SR.Get(SRID.DataGridLength_InvalidType), "type"); } if (Double.IsInfinity(desiredValue)) { throw new ArgumentException( SR.Get(SRID.DataGridLength_Infinity), "desiredValue"); } if (Double.IsInfinity(displayValue)) { throw new ArgumentException( SR.Get(SRID.DataGridLength_Infinity), "displayValue"); } _unitValue = (type == DataGridLengthUnitType.Auto) ? AutoValue : value; _unitType = type; _desiredValue = desiredValue; _displayValue = displayValue; } #endregion Constructors #region Public Methods /// <summary> /// Overloaded operator, compares 2 DataGridLength's. /// </summary> /// <param name="gl1">first DataGridLength to compare.</param> /// <param name="gl2">second DataGridLength to compare.</param> /// <returns>true if specified DataGridLengths have same value /// and unit type.</returns> public static bool operator ==(DataGridLength gl1, DataGridLength gl2) { return gl1.UnitType == gl2.UnitType && gl1.Value == gl2.Value && ((gl1.DesiredValue == gl2.DesiredValue) || (DoubleUtil.IsNaN(gl1.DesiredValue) && DoubleUtil.IsNaN(gl2.DesiredValue))) && ((gl1.DisplayValue == gl2.DisplayValue) || (DoubleUtil.IsNaN(gl1.DisplayValue) && DoubleUtil.IsNaN(gl2.DisplayValue))); } /// <summary> /// Overloaded operator, compares 2 DataGridLength's. /// </summary> /// <param name="gl1">first DataGridLength to compare.</param> /// <param name="gl2">second DataGridLength to compare.</param> /// <returns>true if specified DataGridLengths have either different value or /// unit type.</returns> public static bool operator !=(DataGridLength gl1, DataGridLength gl2) { return gl1.UnitType != gl2.UnitType || gl1.Value != gl2.Value || ((gl1.DesiredValue != gl2.DesiredValue) && !(DoubleUtil.IsNaN(gl1.DesiredValue) && DoubleUtil.IsNaN(gl2.DesiredValue))) || ((gl1.DisplayValue != gl2.DisplayValue) && !(DoubleUtil.IsNaN(gl1.DisplayValue) && DoubleUtil.IsNaN(gl2.DisplayValue))); } /// <summary> /// Compares this instance of DataGridLength with another object. /// </summary> /// <param name="obj">Reference to an object for comparison.</param> /// <returns><c>true</c>if this DataGridLength instance has the same value /// and unit type as oCompare.</returns> public override bool Equals(object obj) { if (obj is DataGridLength) { DataGridLength l = (DataGridLength)obj; return this == l; } else { return false; } } /// <summary> /// Compares this instance of DataGridLength with another instance. /// </summary> /// <param name="other">Grid length instance to compare.</param> /// <returns><c>true</c>if this DataGridLength instance has the same value /// and unit type as gridLength.</returns> public bool Equals(DataGridLength other) { return this == other; } /// <summary> /// <see cref="Object.GetHashCode"/> /// </summary> /// <returns><see cref="Object.GetHashCode"/></returns> public override int GetHashCode() { return (int)_unitValue + (int)_unitType + (int)_desiredValue + (int)_displayValue; } /// <summary> /// Returns <c>true</c> if this DataGridLength instance holds /// an absolute (pixel) value. /// </summary> public bool IsAbsolute { get { return _unitType == DataGridLengthUnitType.Pixel; } } /// <summary> /// Returns <c>true</c> if this DataGridLength instance is /// automatic (not specified). /// </summary> public bool IsAuto { get { return _unitType == DataGridLengthUnitType.Auto; } } /// <summary> /// Returns <c>true</c> if this DataGridLength instance holds a weighted proportion /// of available space. /// </summary> public bool IsStar { get { return _unitType == DataGridLengthUnitType.Star; } } /// <summary> /// Returns <c>true</c> if this instance is to size to the cells of a column or row. /// </summary> public bool IsSizeToCells { get { return _unitType == DataGridLengthUnitType.SizeToCells; } } /// <summary> /// Returns <c>true</c> if this instance is to size to the header of a column or row. /// </summary> public bool IsSizeToHeader { get { return _unitType == DataGridLengthUnitType.SizeToHeader; } } /// <summary> /// Returns value part of this DataGridLength instance. /// </summary> public double Value { get { return (_unitType == DataGridLengthUnitType.Auto) ? AutoValue : _unitValue; } } /// <summary> /// Returns unit type of this DataGridLength instance. /// </summary> public DataGridLengthUnitType UnitType { get { return _unitType; } } /// <summary> /// Returns the desired value of this instance. /// </summary> public double DesiredValue { get { return _desiredValue; } } /// <summary> /// Returns the display value of this instance. /// </summary> public double DisplayValue { get { return _displayValue; } } /// <summary> /// Returns the string representation of this object. /// </summary> public override string ToString() { return DataGridLengthConverter.ConvertToString(this, CultureInfo.InvariantCulture); } #endregion #region Pre-defined values /// <summary> /// Returns a value initialized to mean "auto." /// </summary> public static DataGridLength Auto { get { return _auto; } } /// <summary> /// Returns a value initialized to mean "size to cells." /// </summary> public static DataGridLength SizeToCells { get { return _sizeToCells; } } /// <summary> /// Returns a value initialized to mean "size to header." /// </summary> public static DataGridLength SizeToHeader { get { return _sizeToHeader; } } #endregion #region Implicit Conversions /// <summary> /// Allows for values of type double to be implicitly converted /// to DataGridLength. /// </summary> /// <param name="doubleValue">The number of pixels to represent.</param> /// <returns>The DataGridLength representing the requested number of pixels.</returns> public static implicit operator DataGridLength(double value) { return new DataGridLength(value); } #endregion #region Fields private double _unitValue; // unit value storage private DataGridLengthUnitType _unitType; // unit type storage private double _desiredValue; // desired value storage private double _displayValue; // display value storage private const double AutoValue = 1.0; // static instance of Auto DataGridLength private static readonly DataGridLength _auto = new DataGridLength(AutoValue, DataGridLengthUnitType.Auto, 0d, 0d); private static readonly DataGridLength _sizeToCells = new DataGridLength(AutoValue, DataGridLengthUnitType.SizeToCells, 0d, 0d); private static readonly DataGridLength _sizeToHeader = new DataGridLength(AutoValue, DataGridLengthUnitType.SizeToHeader, 0d, 0d); #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Windows; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.NodejsTools.Profiling { /// <summary> /// Factory for creating our editor object. Extends from the IVsEditoryFactory interface /// </summary> [Guid(ProfilingGuids.ProfilingEditorFactoryString)] internal sealed class ProfilingSessionEditorFactory : IVsEditorFactory, IDisposable { private readonly NodejsProfilingPackage _editorPackage; private ServiceProvider _vsServiceProvider; public ProfilingSessionEditorFactory(NodejsProfilingPackage package) { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} constructor", this.ToString())); this._editorPackage = package; } /// <summary> /// Since we create a ServiceProvider which implements IDisposable we /// also need to implement IDisposable to make sure that the ServiceProvider's /// Dispose method gets called. /// </summary> public void Dispose() { if (_vsServiceProvider != null) { _vsServiceProvider.Dispose(); } } #region IVsEditorFactory Members /// <summary> /// Used for initialization of the editor in the environment /// </summary> /// <param name="psp">pointer to the service provider. Can be used to obtain instances of other interfaces /// </param> /// <returns></returns> public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) { _vsServiceProvider = new ServiceProvider(psp); return VSConstants.S_OK; } public object GetService(Type serviceType) { return _vsServiceProvider.GetService(serviceType); } // This method is called by the Environment (inside IVsUIShellOpenDocument:: // OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a // PHYSICAL view. A LOGICAL view identifies the purpose of the view that is // desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a // view appropriate for text view manipulation as by navigating to a find // result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type // of view implementation that an IVsEditorFactory can create. // // NOTE: Physical views are identified by a string of your choice with the // one constraint that the default/primary physical view for an editor // *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL). // // NOTE: It is essential that the implementation of MapLogicalView properly // validates that the LogicalView desired is actually supported by the editor. // If an unsupported LogicalView is requested then E_NOTIMPL must be returned. // // NOTE: The special Logical Views supported by an Editor Factory must also // be registered in the local registry hive. LOGVIEWID_Primary is implicitly // supported by all editor types and does not need to be registered. // For example, an editor that supports a ViewCode/ViewDesigner scenario // might register something like the following: // HKLM\Software\Microsoft\VisualStudio\<version>\Editors\ // {...guidEditor...}\ // LogicalViews\ // {...LOGVIEWID_TextView...} = s '' // {...LOGVIEWID_Code...} = s '' // {...LOGVIEWID_Debugging...} = s '' // {...LOGVIEWID_Designer...} = s 'Form' // public int MapLogicalView(ref Guid rguidLogicalView, out string pbstrPhysicalView) { pbstrPhysicalView = null; // initialize out parameter // we support only a single physical view if (VSConstants.LOGVIEWID_Primary == rguidLogicalView) return VSConstants.S_OK; // primary view uses NULL as pbstrPhysicalView else return VSConstants.E_NOTIMPL; // you must return E_NOTIMPL for any unrecognized rguidLogicalView values } public int Close() { return VSConstants.S_OK; } /// <summary> /// Used by the editor factory to create an editor instance. the environment first determines the /// editor factory with the highest priority for opening the file and then calls /// IVsEditorFactory.CreateEditorInstance. If the environment is unable to instantiate the document data /// in that editor, it will find the editor with the next highest priority and attempt to so that same /// thing. /// NOTE: The priority of our editor is 32 as mentioned in the attributes on the package class. /// /// Since our editor supports opening only a single view for an instance of the document data, if we /// are requested to open document data that is already instantiated in another editor, or even our /// editor, we return a value VS_E_INCOMPATIBLEDOCDATA. /// </summary> /// <param name="grfCreateDoc">Flags determining when to create the editor. Only open and silent flags /// are valid /// </param> /// <param name="pszMkDocument">path to the file to be opened</param> /// <param name="pszPhysicalView">name of the physical view</param> /// <param name="pvHier">pointer to the IVsHierarchy interface</param> /// <param name="itemid">Item identifier of this editor instance</param> /// <param name="punkDocDataExisting">This parameter is used to determine if a document buffer /// (DocData object) has already been created /// </param> /// <param name="ppunkDocView">Pointer to the IUnknown interface for the DocView object</param> /// <param name="ppunkDocData">Pointer to the IUnknown interface for the DocData object</param> /// <param name="pbstrEditorCaption">Caption mentioned by the editor for the doc window</param> /// <param name="pguidCmdUI">the Command UI Guid. Any UI element that is visible in the editor has /// to use this GUID. This is specified in the .vsct file /// </param> /// <param name="pgrfCDW">Flags for CreateDocumentWindow</param> /// <returns></returns> [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public int CreateEditorInstance( uint grfCreateDoc, string pszMkDocument, string pszPhysicalView, IVsHierarchy pvHier, uint itemid, System.IntPtr punkDocDataExisting, out System.IntPtr ppunkDocView, out System.IntPtr ppunkDocData, out string pbstrEditorCaption, out Guid pguidCmdUI, out int pgrfCDW) { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} CreateEditorInstace()", this.ToString())); // Initialize to null ppunkDocView = IntPtr.Zero; ppunkDocData = IntPtr.Zero; pguidCmdUI = ProfilingGuids.ProfilingEditorFactory; pgrfCDW = 0; pbstrEditorCaption = null; // Validate inputs if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) { return VSConstants.E_INVALIDARG; } if (punkDocDataExisting != IntPtr.Zero) { return VSConstants.VS_E_INCOMPATIBLEDOCDATA; } // Create the Document (editor) var perfWin = _editorPackage.ShowPerformanceExplorer(); ProfilingTarget target; try { using (var fs = new FileStream(pszMkDocument, FileMode.Open)) { target = (ProfilingTarget)ProfilingTarget.Serializer.Deserialize(fs); fs.Close(); } } catch (IOException e) { MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.FailedToOpenFileErrorMessageText, e.Message), Resources.NodejsToolsForVS); return VSConstants.E_FAIL; } catch (InvalidOperationException e) { MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.FailedToReadPerformanceSessionMessageText, e.Message), Resources.NodejsToolsForVS); return VSConstants.E_FAIL; } perfWin.Sessions.OpenTarget( target, pszMkDocument ); pbstrEditorCaption = String.Empty; return VSConstants.S_OK; } #endregion } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// The metrics reported by the guest (as opposed to inferred from outside) /// First published in XenServer 4.0. /// </summary> public partial class VM_guest_metrics : XenObject<VM_guest_metrics> { #region Constructors public VM_guest_metrics() { } public VM_guest_metrics(string uuid, Dictionary<string, string> os_version, Dictionary<string, string> PV_drivers_version, bool PV_drivers_up_to_date, Dictionary<string, string> memory, Dictionary<string, string> disks, Dictionary<string, string> networks, Dictionary<string, string> other, DateTime last_updated, Dictionary<string, string> other_config, bool live, tristate_type can_use_hotplug_vbd, tristate_type can_use_hotplug_vif, bool PV_drivers_detected) { this.uuid = uuid; this.os_version = os_version; this.PV_drivers_version = PV_drivers_version; this.PV_drivers_up_to_date = PV_drivers_up_to_date; this.memory = memory; this.disks = disks; this.networks = networks; this.other = other; this.last_updated = last_updated; this.other_config = other_config; this.live = live; this.can_use_hotplug_vbd = can_use_hotplug_vbd; this.can_use_hotplug_vif = can_use_hotplug_vif; this.PV_drivers_detected = PV_drivers_detected; } /// <summary> /// Creates a new VM_guest_metrics from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public VM_guest_metrics(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new VM_guest_metrics from a Proxy_VM_guest_metrics. /// </summary> /// <param name="proxy"></param> public VM_guest_metrics(Proxy_VM_guest_metrics proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given VM_guest_metrics. /// </summary> public override void UpdateFrom(VM_guest_metrics update) { uuid = update.uuid; os_version = update.os_version; PV_drivers_version = update.PV_drivers_version; PV_drivers_up_to_date = update.PV_drivers_up_to_date; memory = update.memory; disks = update.disks; networks = update.networks; other = update.other; last_updated = update.last_updated; other_config = update.other_config; live = update.live; can_use_hotplug_vbd = update.can_use_hotplug_vbd; can_use_hotplug_vif = update.can_use_hotplug_vif; PV_drivers_detected = update.PV_drivers_detected; } internal void UpdateFrom(Proxy_VM_guest_metrics proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; os_version = proxy.os_version == null ? null : Maps.convert_from_proxy_string_string(proxy.os_version); PV_drivers_version = proxy.PV_drivers_version == null ? null : Maps.convert_from_proxy_string_string(proxy.PV_drivers_version); PV_drivers_up_to_date = (bool)proxy.PV_drivers_up_to_date; memory = proxy.memory == null ? null : Maps.convert_from_proxy_string_string(proxy.memory); disks = proxy.disks == null ? null : Maps.convert_from_proxy_string_string(proxy.disks); networks = proxy.networks == null ? null : Maps.convert_from_proxy_string_string(proxy.networks); other = proxy.other == null ? null : Maps.convert_from_proxy_string_string(proxy.other); last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); live = (bool)proxy.live; can_use_hotplug_vbd = proxy.can_use_hotplug_vbd == null ? (tristate_type) 0 : (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)proxy.can_use_hotplug_vbd); can_use_hotplug_vif = proxy.can_use_hotplug_vif == null ? (tristate_type) 0 : (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)proxy.can_use_hotplug_vif); PV_drivers_detected = (bool)proxy.PV_drivers_detected; } public Proxy_VM_guest_metrics ToProxy() { Proxy_VM_guest_metrics result_ = new Proxy_VM_guest_metrics(); result_.uuid = uuid ?? ""; result_.os_version = Maps.convert_to_proxy_string_string(os_version); result_.PV_drivers_version = Maps.convert_to_proxy_string_string(PV_drivers_version); result_.PV_drivers_up_to_date = PV_drivers_up_to_date; result_.memory = Maps.convert_to_proxy_string_string(memory); result_.disks = Maps.convert_to_proxy_string_string(disks); result_.networks = Maps.convert_to_proxy_string_string(networks); result_.other = Maps.convert_to_proxy_string_string(other); result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.live = live; result_.can_use_hotplug_vbd = tristate_type_helper.ToString(can_use_hotplug_vbd); result_.can_use_hotplug_vif = tristate_type_helper.ToString(can_use_hotplug_vif); result_.PV_drivers_detected = PV_drivers_detected; return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this VM_guest_metrics /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("os_version")) os_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "os_version")); if (table.ContainsKey("PV_drivers_version")) PV_drivers_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "PV_drivers_version")); if (table.ContainsKey("PV_drivers_up_to_date")) PV_drivers_up_to_date = Marshalling.ParseBool(table, "PV_drivers_up_to_date"); if (table.ContainsKey("memory")) memory = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "memory")); if (table.ContainsKey("disks")) disks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "disks")); if (table.ContainsKey("networks")) networks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "networks")); if (table.ContainsKey("other")) other = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other")); if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("live")) live = Marshalling.ParseBool(table, "live"); if (table.ContainsKey("can_use_hotplug_vbd")) can_use_hotplug_vbd = (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), Marshalling.ParseString(table, "can_use_hotplug_vbd")); if (table.ContainsKey("can_use_hotplug_vif")) can_use_hotplug_vif = (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), Marshalling.ParseString(table, "can_use_hotplug_vif")); if (table.ContainsKey("PV_drivers_detected")) PV_drivers_detected = Marshalling.ParseBool(table, "PV_drivers_detected"); } public bool DeepEquals(VM_guest_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._os_version, other._os_version) && Helper.AreEqual2(this._PV_drivers_version, other._PV_drivers_version) && Helper.AreEqual2(this._PV_drivers_up_to_date, other._PV_drivers_up_to_date) && Helper.AreEqual2(this._memory, other._memory) && Helper.AreEqual2(this._disks, other._disks) && Helper.AreEqual2(this._networks, other._networks) && Helper.AreEqual2(this._other, other._other) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._live, other._live) && Helper.AreEqual2(this._can_use_hotplug_vbd, other._can_use_hotplug_vbd) && Helper.AreEqual2(this._can_use_hotplug_vif, other._can_use_hotplug_vif) && Helper.AreEqual2(this._PV_drivers_detected, other._PV_drivers_detected); } internal static List<VM_guest_metrics> ProxyArrayToObjectList(Proxy_VM_guest_metrics[] input) { var result = new List<VM_guest_metrics>(); foreach (var item in input) result.Add(new VM_guest_metrics(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, VM_guest_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VM_guest_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static VM_guest_metrics get_record(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_record(session.opaque_ref, _vm_guest_metrics); else return new VM_guest_metrics(session.proxy.vm_guest_metrics_get_record(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get a reference to the VM_guest_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VM_guest_metrics> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<VM_guest_metrics>.Create(session.proxy.vm_guest_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static string get_uuid(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_uuid(session.opaque_ref, _vm_guest_metrics); else return session.proxy.vm_guest_metrics_get_uuid(session.opaque_ref, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the os_version field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_os_version(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_os_version(session.opaque_ref, _vm_guest_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_os_version(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the PV_drivers_version field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_PV_drivers_version(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_pv_drivers_version(session.opaque_ref, _vm_guest_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_pv_drivers_version(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the PV_drivers_up_to_date field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> [Deprecated("XenServer 7.0")] public static bool get_PV_drivers_up_to_date(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_pv_drivers_up_to_date(session.opaque_ref, _vm_guest_metrics); else return (bool)session.proxy.vm_guest_metrics_get_pv_drivers_up_to_date(session.opaque_ref, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the memory field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_memory(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_memory(session.opaque_ref, _vm_guest_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_memory(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the disks field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_disks(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_disks(session.opaque_ref, _vm_guest_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_disks(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the networks field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_networks(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_networks(session.opaque_ref, _vm_guest_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_networks(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the other field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_other(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_other(session.opaque_ref, _vm_guest_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_other(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the last_updated field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static DateTime get_last_updated(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_last_updated(session.opaque_ref, _vm_guest_metrics); else return session.proxy.vm_guest_metrics_get_last_updated(session.opaque_ref, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_other_config(session.opaque_ref, _vm_guest_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_other_config(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the live field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static bool get_live(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_live(session.opaque_ref, _vm_guest_metrics); else return (bool)session.proxy.vm_guest_metrics_get_live(session.opaque_ref, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the can_use_hotplug_vbd field of the given VM_guest_metrics. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static tristate_type get_can_use_hotplug_vbd(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_can_use_hotplug_vbd(session.opaque_ref, _vm_guest_metrics); else return (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)session.proxy.vm_guest_metrics_get_can_use_hotplug_vbd(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the can_use_hotplug_vif field of the given VM_guest_metrics. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static tristate_type get_can_use_hotplug_vif(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_can_use_hotplug_vif(session.opaque_ref, _vm_guest_metrics); else return (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)session.proxy.vm_guest_metrics_get_can_use_hotplug_vif(session.opaque_ref, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the PV_drivers_detected field of the given VM_guest_metrics. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static bool get_PV_drivers_detected(Session session, string _vm_guest_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_pv_drivers_detected(session.opaque_ref, _vm_guest_metrics); else return (bool)session.proxy.vm_guest_metrics_get_pv_drivers_detected(session.opaque_ref, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Set the other_config field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vm_guest_metrics, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.vm_guest_metrics_set_other_config(session.opaque_ref, _vm_guest_metrics, _other_config); else session.proxy.vm_guest_metrics_set_other_config(session.opaque_ref, _vm_guest_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vm_guest_metrics, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.vm_guest_metrics_add_to_other_config(session.opaque_ref, _vm_guest_metrics, _key, _value); else session.proxy.vm_guest_metrics_add_to_other_config(session.opaque_ref, _vm_guest_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VM_guest_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vm_guest_metrics, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.vm_guest_metrics_remove_from_other_config(session.opaque_ref, _vm_guest_metrics, _key); else session.proxy.vm_guest_metrics_remove_from_other_config(session.opaque_ref, _vm_guest_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the VM_guest_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VM_guest_metrics>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_all(session.opaque_ref); else return XenRef<VM_guest_metrics>.Create(session.proxy.vm_guest_metrics_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the VM_guest_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VM_guest_metrics>, VM_guest_metrics> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_guest_metrics_get_all_records(session.opaque_ref); else return XenRef<VM_guest_metrics>.Create<Proxy_VM_guest_metrics>(session.proxy.vm_guest_metrics_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// version of the OS /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> os_version { get { return _os_version; } set { if (!Helper.AreEqual(value, _os_version)) { _os_version = value; Changed = true; NotifyPropertyChanged("os_version"); } } } private Dictionary<string, string> _os_version = new Dictionary<string, string>() {}; /// <summary> /// version of the PV drivers /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> PV_drivers_version { get { return _PV_drivers_version; } set { if (!Helper.AreEqual(value, _PV_drivers_version)) { _PV_drivers_version = value; Changed = true; NotifyPropertyChanged("PV_drivers_version"); } } } private Dictionary<string, string> _PV_drivers_version = new Dictionary<string, string>() {}; /// <summary> /// Logically equivalent to PV_drivers_detected /// </summary> public virtual bool PV_drivers_up_to_date { get { return _PV_drivers_up_to_date; } set { if (!Helper.AreEqual(value, _PV_drivers_up_to_date)) { _PV_drivers_up_to_date = value; Changed = true; NotifyPropertyChanged("PV_drivers_up_to_date"); } } } private bool _PV_drivers_up_to_date; /// <summary> /// This field exists but has no data. Use the memory and memory_internal_free RRD data-sources instead. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> memory { get { return _memory; } set { if (!Helper.AreEqual(value, _memory)) { _memory = value; Changed = true; NotifyPropertyChanged("memory"); } } } private Dictionary<string, string> _memory = new Dictionary<string, string>() {}; /// <summary> /// This field exists but has no data. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> disks { get { return _disks; } set { if (!Helper.AreEqual(value, _disks)) { _disks = value; Changed = true; NotifyPropertyChanged("disks"); } } } private Dictionary<string, string> _disks = new Dictionary<string, string>() {}; /// <summary> /// network configuration /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> networks { get { return _networks; } set { if (!Helper.AreEqual(value, _networks)) { _networks = value; Changed = true; NotifyPropertyChanged("networks"); } } } private Dictionary<string, string> _networks = new Dictionary<string, string>() {}; /// <summary> /// anything else /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other { get { return _other; } set { if (!Helper.AreEqual(value, _other)) { _other = value; Changed = true; NotifyPropertyChanged("other"); } } } private Dictionary<string, string> _other = new Dictionary<string, string>() {}; /// <summary> /// Time at which this information was last updated /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; /// <summary> /// True if the guest is sending heartbeat messages via the guest agent /// First published in XenServer 5.0. /// </summary> public virtual bool live { get { return _live; } set { if (!Helper.AreEqual(value, _live)) { _live = value; Changed = true; NotifyPropertyChanged("live"); } } } private bool _live = false; /// <summary> /// The guest's statement of whether it supports VBD hotplug, i.e. whether it is capable of responding immediately to instantiation of a new VBD by bringing online a new PV block device. If the guest states that it is not capable, then the VBD plug and unplug operations will not be allowed while the guest is running. /// First published in XenServer 7.0. /// </summary> [JsonConverter(typeof(tristate_typeConverter))] public virtual tristate_type can_use_hotplug_vbd { get { return _can_use_hotplug_vbd; } set { if (!Helper.AreEqual(value, _can_use_hotplug_vbd)) { _can_use_hotplug_vbd = value; Changed = true; NotifyPropertyChanged("can_use_hotplug_vbd"); } } } private tristate_type _can_use_hotplug_vbd = tristate_type.unspecified; /// <summary> /// The guest's statement of whether it supports VIF hotplug, i.e. whether it is capable of responding immediately to instantiation of a new VIF by bringing online a new PV network device. If the guest states that it is not capable, then the VIF plug and unplug operations will not be allowed while the guest is running. /// First published in XenServer 7.0. /// </summary> [JsonConverter(typeof(tristate_typeConverter))] public virtual tristate_type can_use_hotplug_vif { get { return _can_use_hotplug_vif; } set { if (!Helper.AreEqual(value, _can_use_hotplug_vif)) { _can_use_hotplug_vif = value; Changed = true; NotifyPropertyChanged("can_use_hotplug_vif"); } } } private tristate_type _can_use_hotplug_vif = tristate_type.unspecified; /// <summary> /// At least one of the guest's devices has successfully connected to the backend. /// First published in XenServer 7.0. /// </summary> public virtual bool PV_drivers_detected { get { return _PV_drivers_detected; } set { if (!Helper.AreEqual(value, _PV_drivers_detected)) { _PV_drivers_detected = value; Changed = true; NotifyPropertyChanged("PV_drivers_detected"); } } } private bool _PV_drivers_detected = false; } }
namespace NEventStore.Persistence.Sql.SqlDialects { using System; using System.Data; using System.Transactions; using NEventStore.Persistence.Sql; public abstract class CommonSqlDialect : ISqlDialect { public abstract string InitializeStorage { get; } public virtual string PurgeStorage { get { return CommonSqlStatements.PurgeStorage; } } public string PurgeBucket { get { return CommonSqlStatements.PurgeBucket; } } public virtual string Drop { get { return CommonSqlStatements.DropTables; } } public virtual string DeleteStream { get { return CommonSqlStatements.DeleteStream; } } public virtual string GetCommitsFromStartingRevision { get { return CommonSqlStatements.GetCommitsFromStartingRevision; } } public virtual string GetCommitsFromInstant { get { return CommonSqlStatements.GetCommitsFromInstant; } } public virtual string GetCommitsFromToInstant { get { return CommonSqlStatements.GetCommitsFromToInstant; } } public abstract string PersistCommit { get; } public virtual string DuplicateCommit { get { return CommonSqlStatements.DuplicateCommit; } } public virtual string GetStreamsRequiringSnapshots { get { return CommonSqlStatements.GetStreamsRequiringSnapshots; } } public virtual string GetSnapshot { get { return CommonSqlStatements.GetSnapshot; } } public virtual string AppendSnapshotToCommit { get { return CommonSqlStatements.AppendSnapshotToCommit; } } public virtual string GetUndispatchedCommits { get { return CommonSqlStatements.GetUndispatchedCommits; } } public virtual string MarkCommitAsDispatched { get { return CommonSqlStatements.MarkCommitAsDispatched; } } public virtual string BucketId { get { return "@BucketId"; } } public virtual string StreamId { get { return "@StreamId"; } } public virtual string StreamIdOriginal { get { return "@StreamIdOriginal"; } } public virtual string StreamRevision { get { return "@StreamRevision"; } } public virtual string MaxStreamRevision { get { return "@MaxStreamRevision"; } } public virtual string Items { get { return "@Items"; } } public virtual string CommitId { get { return "@CommitId"; } } public virtual string CommitSequence { get { return "@CommitSequence"; } } public virtual string CommitStamp { get { return "@CommitStamp"; } } public virtual string CommitStampStart { get { return "@CommitStampStart"; } } public virtual string CommitStampEnd { get { return "@CommitStampEnd"; } } public virtual string Headers { get { return "@Headers"; } } public virtual string Payload { get { return "@Payload"; } } public virtual string Threshold { get { return "@Threshold"; } } public virtual string Limit { get { return "@Limit"; } } public virtual string Skip { get { return "@Skip"; } } public virtual bool CanPage { get { return true; } } public virtual string CheckpointNumber { get { return "@CheckpointNumber"; } } public virtual string GetCommitsFromCheckpoint { get { return CommonSqlStatements.GetCommitsFromCheckpoint; } } public virtual string GetCommitsFromBucketAndCheckpoint { get { return CommonSqlStatements.GetCommitsFromBucketAndCheckpoint; } } public virtual object CoalesceParameterValue(object value) { return value; } public abstract bool IsDuplicate(Exception exception); public virtual void AddPayloadParamater(IConnectionFactory connectionFactory, IDbConnection connection, IDbStatement cmd, byte[] payload) { cmd.AddParameter(Payload, payload); } public virtual DateTime ToDateTime(object value) { value = value is decimal ? (long) (decimal) value : value; return value is long ? new DateTime((long) value) : DateTime.SpecifyKind((DateTime) value, DateTimeKind.Utc); } public virtual NextPageDelegate NextPageDelegate { get { return (q, r) => q.SetParameter(CommitSequence, r.CommitSequence()); } } public virtual IDbTransaction OpenTransaction(IDbConnection connection) { return null; } public virtual IDbStatement BuildStatement( TransactionScope scope, IDbConnection connection, IDbTransaction transaction) { return new CommonDbStatement(this, scope, connection, transaction); } } }
using System; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Threading; using LibGit2Sharp.Core.Handles; // ReSharper disable InconsistentNaming namespace LibGit2Sharp.Core { internal static class NativeMethods { public const uint GIT_PATH_MAX = 4096; private const string libgit2 = NativeDllName.Name; private static readonly LibraryLifetimeObject lifetimeObject; private static int handlesCount; /// <summary> /// Internal hack to ensure that the call to git_threads_shutdown is called after all handle finalizers /// have run to completion ensuring that no dangling git-related finalizer runs after git_threads_shutdown. /// There should never be more than one instance of this object per AppDomain. /// </summary> private sealed class LibraryLifetimeObject : CriticalFinalizerObject { // Ensure mono can JIT the .cctor and adjust the PATH before trying to load the native library. // See https://github.com/libgit2/libgit2sharp/pull/190 [MethodImpl(MethodImplOptions.NoInlining)] public LibraryLifetimeObject() { Ensure.ZeroResult(git_threads_init()); AddHandle(); } ~LibraryLifetimeObject() { RemoveHandle(); } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static void AddHandle() { Interlocked.Increment(ref handlesCount); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static void RemoveHandle() { int count = Interlocked.Decrement(ref handlesCount); if (count == 0) { git_threads_shutdown(); } } static NativeMethods() { if (!IsRunningOnLinux()) { string originalAssemblypath = new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath; string currentArchSubPath = "NativeBinaries/" + ProcessorArchitecture; string path = Path.Combine(Path.GetDirectoryName(originalAssemblypath), currentArchSubPath); const string pathEnvVariable = "PATH"; Environment.SetEnvironmentVariable(pathEnvVariable, String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable))); } // See LibraryLifetimeObject description. lifetimeObject = new LibraryLifetimeObject(); } public static string ProcessorArchitecture { get { if (Compat.Environment.Is64BitProcess) { return "amd64"; } return "x86"; } } // Should match LibGit2Sharp.Tests.TestHelpers.BaseFixture.IsRunningOnLinux() private static bool IsRunningOnLinux() { // see http://mono-project.com/FAQ%3a_Technical#Mono_Platforms var p = (int)Environment.OSVersion.Platform; return (p == 4) || (p == 6) || (p == 128); } [DllImport(libgit2)] internal static extern GitErrorSafeHandle giterr_last(); [DllImport(libgit2)] internal static extern void giterr_set_str( GitErrorCategory error_class, string errorString); [DllImport(libgit2)] internal static extern void giterr_set_oom(); [DllImport(libgit2)] internal static extern UInt32 git_blame_get_hunk_count(BlameSafeHandle blame); [DllImport(libgit2)] internal static extern IntPtr git_blame_get_hunk_byindex( BlameSafeHandle blame, UInt32 index); [DllImport(libgit2)] internal static extern int git_blame_file( out BlameSafeHandle blame, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, GitBlameOptions options); [DllImport(libgit2)] internal static extern int git_blame_free(IntPtr blame); [DllImport(libgit2)] internal static extern int git_blob_create_fromdisk( ref GitOid id, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern int git_blob_create_fromworkdir( ref GitOid id, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath relative_path); internal delegate int source_callback( IntPtr content, int max_length, IntPtr data); [DllImport(libgit2)] internal static extern int git_blob_create_fromchunks( ref GitOid oid, RepositorySafeHandle repositoryPtr, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath hintpath, source_callback fileCallback, IntPtr data); [DllImport(libgit2)] internal static extern int git_blob_filtered_content( GitBuf buf, GitObjectSafeHandle blob, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath as_path, [MarshalAs(UnmanagedType.Bool)] bool check_for_binary_data); [DllImport(libgit2)] internal static extern IntPtr git_blob_rawcontent(GitObjectSafeHandle blob); [DllImport(libgit2)] internal static extern Int64 git_blob_rawsize(GitObjectSafeHandle blob); [DllImport(libgit2)] internal static extern int git_branch_create( out ReferenceSafeHandle ref_out, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string branch_name, GitObjectSafeHandle target, // TODO: GitCommitSafeHandle? [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_branch_delete( ReferenceSafeHandle reference); internal delegate int branch_foreach_callback( IntPtr branch_name, GitBranchType branch_type, IntPtr payload); [DllImport(libgit2)] internal static extern void git_branch_iterator_free( IntPtr iterator); [DllImport(libgit2)] internal static extern int git_branch_iterator_new( out BranchIteratorSafeHandle iter_out, RepositorySafeHandle repo, GitBranchType branch_type); [DllImport(libgit2)] internal static extern int git_branch_move( out ReferenceSafeHandle ref_out, ReferenceSafeHandle reference, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string new_branch_name, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_branch_next( out ReferenceSafeHandle ref_out, out GitBranchType type_out, BranchIteratorSafeHandle iter); [DllImport(libgit2)] internal static extern int git_branch_remote_name( byte[] remote_name_out, UIntPtr buffer_size, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string canonical_branch_name); [DllImport(libgit2)] internal static extern int git_branch_upstream_name( byte[] tracking_branch_name_out, // NB: This is more properly a StringBuilder, but it's UTF8 UIntPtr buffer_size, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string referenceName); [DllImport(libgit2)] internal static extern void git_buf_free(GitBuf buf); [DllImport(libgit2)] internal static extern int git_checkout_tree( RepositorySafeHandle repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts); [DllImport(libgit2)] internal static extern int git_checkout_index( RepositorySafeHandle repo, GitObjectSafeHandle treeish, ref GitCheckoutOpts opts); [DllImport(libgit2)] internal static extern int git_clone( out RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string origin_url, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath workdir_path, GitCloneOptions opts); [DllImport(libgit2)] internal static extern IntPtr git_commit_author(GitObjectSafeHandle commit); [DllImport(libgit2)] internal static extern IntPtr git_commit_committer(GitObjectSafeHandle commit); [DllImport(libgit2)] internal static extern int git_commit_create_from_oids( out GitOid id, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string updateRef, SignatureSafeHandle author, SignatureSafeHandle committer, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string encoding, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, ref GitOid tree, int parentCount, [MarshalAs(UnmanagedType.LPArray)] [In] IntPtr[] parents); [DllImport(libgit2)] [return : MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_commit_message(GitObjectSafeHandle commit); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_commit_summary(GitObjectSafeHandle commit); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_commit_message_encoding(GitObjectSafeHandle commit); [DllImport(libgit2)] internal static extern OidSafeHandle git_commit_parent_id(GitObjectSafeHandle commit, uint n); [DllImport(libgit2)] internal static extern uint git_commit_parentcount(GitObjectSafeHandle commit); [DllImport(libgit2)] internal static extern OidSafeHandle git_commit_tree_id(GitObjectSafeHandle commit); [DllImport(libgit2)] internal static extern int git_config_delete_entry(ConfigurationSafeHandle cfg, string name); [DllImport(libgit2)] internal static extern int git_config_find_global(byte[] global_config_path, UIntPtr length); [DllImport(libgit2)] internal static extern int git_config_find_system(byte[] system_config_path, UIntPtr length); [DllImport(libgit2)] internal static extern int git_config_find_xdg(byte[] xdg_config_path, UIntPtr length); [DllImport(libgit2)] internal static extern void git_config_free(IntPtr cfg); [DllImport(libgit2)] internal static extern int git_config_get_entry( out GitConfigEntryHandle entry, ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] internal static extern int git_config_add_file_ondisk( ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, uint level, bool force); [DllImport(libgit2)] internal static extern int git_config_new(out ConfigurationSafeHandle cfg); [DllImport(libgit2)] internal static extern int git_config_open_level( out ConfigurationSafeHandle cfg, ConfigurationSafeHandle parent, uint level); [DllImport(libgit2)] internal static extern int git_config_parse_bool( [MarshalAs(UnmanagedType.Bool)] out bool value, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string valueToParse); [DllImport(libgit2)] internal static extern int git_config_parse_int32( [MarshalAs(UnmanagedType.I4)] out int value, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string valueToParse); [DllImport(libgit2)] internal static extern int git_config_parse_int64( [MarshalAs(UnmanagedType.I8)] out long value, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string valueToParse); [DllImport(libgit2)] internal static extern int git_config_set_bool( ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.Bool)] bool value); [DllImport(libgit2)] internal static extern int git_config_set_int32( ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, int value); [DllImport(libgit2)] internal static extern int git_config_set_int64( ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, long value); [DllImport(libgit2)] internal static extern int git_config_set_string( ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string value); internal delegate int config_foreach_callback( IntPtr entry, IntPtr payload); [DllImport(libgit2)] internal static extern int git_config_foreach( ConfigurationSafeHandle cfg, config_foreach_callback callback, IntPtr payload); [DllImport(libgit2)] internal static extern int git_config_iterator_glob_new( out ConfigurationIteratorSafeHandle iter, ConfigurationSafeHandle cfg, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string regexp); [DllImport(libgit2)] internal static extern int git_config_next( out IntPtr entry, ConfigurationIteratorSafeHandle iter); [DllImport(libgit2)] internal static extern void git_config_iterator_free(IntPtr iter); // Ordinarily we would decorate the `url` parameter with the StrictUtf8Marshaler like we do everywhere // else, but apparently doing a native->managed callback with the 64-bit version of CLR 2.0 can // sometimes vomit when using a custom IMarshaler. So yeah, don't do that. If you need the url, // call StrictUtf8Marshaler.FromNative manually. See the discussion here: // http://social.msdn.microsoft.com/Forums/en-US/netfx64bit/thread/1eb746c6-d695-4632-8a9e-16c4fa98d481 internal delegate int git_cred_acquire_cb( out IntPtr cred, IntPtr url, IntPtr username_from_url, uint allowed_types, IntPtr payload); [DllImport(libgit2)] internal static extern int git_cred_userpass_plaintext_new( out IntPtr cred, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof (StrictUtf8Marshaler))] string username, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof (StrictUtf8Marshaler))] string password); [DllImport(libgit2)] internal static extern void git_diff_free(IntPtr diff); [DllImport(libgit2)] internal static extern int git_diff_tree_to_tree( out DiffSafeHandle diff, RepositorySafeHandle repo, GitObjectSafeHandle oldTree, GitObjectSafeHandle newTree, GitDiffOptions options); [DllImport(libgit2)] internal static extern int git_diff_tree_to_index( out DiffSafeHandle diff, RepositorySafeHandle repo, GitObjectSafeHandle oldTree, IndexSafeHandle index, GitDiffOptions options); [DllImport(libgit2)] internal static extern int git_diff_merge( DiffSafeHandle onto, DiffSafeHandle from); [DllImport(libgit2)] internal static extern int git_diff_index_to_workdir( out DiffSafeHandle diff, RepositorySafeHandle repo, IndexSafeHandle index, GitDiffOptions options); [DllImport(libgit2)] internal static extern int git_diff_tree_to_workdir( out DiffSafeHandle diff, RepositorySafeHandle repo, GitObjectSafeHandle oldTree, GitDiffOptions options); internal delegate int git_diff_file_cb( [In] GitDiffDelta delta, float progress, IntPtr payload); internal delegate int git_diff_hunk_cb( [In] GitDiffDelta delta, [In] GitDiffHunk hunk, IntPtr payload); internal delegate int git_diff_line_cb( [In] GitDiffDelta delta, [In] GitDiffHunk hunk, [In] GitDiffLine line, IntPtr payload); [DllImport(libgit2)] internal static extern int git_diff_print( DiffSafeHandle diff, GitDiffFormat format, git_diff_line_cb printCallback, IntPtr payload); [DllImport(libgit2)] internal static extern int git_diff_blobs( GitObjectSafeHandle oldBlob, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath old_as_path, GitObjectSafeHandle newBlob, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath new_as_path, GitDiffOptions options, git_diff_file_cb fileCallback, git_diff_hunk_cb hunkCallback, git_diff_line_cb lineCallback, IntPtr payload); [DllImport(libgit2)] internal static extern int git_diff_foreach( DiffSafeHandle diff, git_diff_file_cb fileCallback, git_diff_hunk_cb hunkCallback, git_diff_line_cb lineCallback, IntPtr payload); [DllImport(libgit2)] internal static extern int git_diff_find_similar( DiffSafeHandle diff, GitDiffFindOptions options); [DllImport(libgit2)] internal static extern UIntPtr git_diff_num_deltas(DiffSafeHandle diff); [DllImport(libgit2)] internal static extern IntPtr git_diff_get_delta(DiffSafeHandle diff, UIntPtr idx); [DllImport(libgit2)] internal static extern int git_graph_ahead_behind(out UIntPtr ahead, out UIntPtr behind, RepositorySafeHandle repo, ref GitOid one, ref GitOid two); [DllImport(libgit2)] internal static extern int git_ignore_add_rule( RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof (StrictUtf8Marshaler))] string rules); [DllImport(libgit2)] internal static extern int git_ignore_clear_internal_rules(RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_ignore_path_is_ignored( out int ignored, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern int git_index_add_bypath( IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern int git_index_add( IndexSafeHandle index, GitIndexEntry entry); [DllImport(libgit2)] internal static extern int git_index_conflict_get( out IndexEntrySafeHandle ancestor, out IndexEntrySafeHandle ours, out IndexEntrySafeHandle theirs, IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern UIntPtr git_index_entrycount(IndexSafeHandle index); [DllImport(libgit2)] internal static extern int git_index_entry_stage(IndexEntrySafeHandle indexentry); [DllImport(libgit2)] internal static extern int git_index_find( out UIntPtr pos, IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern void git_index_free(IntPtr index); [DllImport(libgit2)] internal static extern IndexEntrySafeHandle git_index_get_byindex(IndexSafeHandle index, UIntPtr n); [DllImport(libgit2)] internal static extern IndexEntrySafeHandle git_index_get_bypath( IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, int stage); [DllImport(libgit2)] internal static extern int git_index_has_conflicts(IndexSafeHandle index); [DllImport(libgit2)] internal static extern int git_index_open( out IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath indexpath); [DllImport(libgit2)] internal static extern int git_index_read(IndexSafeHandle index, bool force); [DllImport(libgit2)] internal static extern int git_index_remove_bypath( IndexSafeHandle index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern int git_index_write(IndexSafeHandle index); [DllImport(libgit2)] internal static extern int git_index_write_tree(out GitOid treeOid, IndexSafeHandle index); [DllImport(libgit2)] internal static extern int git_merge_base( out GitOid mergeBase, RepositorySafeHandle repo, GitObjectSafeHandle one, GitObjectSafeHandle two); [DllImport(libgit2)] internal static extern int git_merge_head_from_ref( out GitMergeHeadHandle mergehead, RepositorySafeHandle repo, ReferenceSafeHandle reference); [DllImport(libgit2)] internal static extern int git_merge_head_from_fetchhead( out GitMergeHeadHandle mergehead, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string branch_name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote_url, ref GitOid oid); [DllImport(libgit2)] internal static extern int git_merge_head_from_oid( out GitMergeHeadHandle mergehead, RepositorySafeHandle repo, ref GitOid oid); [DllImport(libgit2)] internal static extern int git_merge( out GitMergeResultHandle mergeResult, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] [In] IntPtr[] their_heads, UIntPtr their_heads_len, ref GitMergeOpts given_opts); [DllImport(libgit2)] internal static extern int git_merge_result_is_uptodate( GitMergeResultHandle merge_result); [DllImport(libgit2)] internal static extern int git_merge_result_is_fastforward( GitMergeResultHandle merge_result); [DllImport(libgit2)] internal static extern int git_merge_result_fastforward_oid( out GitOid oid, GitMergeResultHandle merge_result); [DllImport(libgit2)] internal static extern void git_merge_result_free( IntPtr merge_result); [DllImport(libgit2)] internal static extern void git_merge_head_free( IntPtr merge_head); [DllImport(libgit2)] internal static extern int git_message_prettify( byte[] message_out, // NB: This is more properly a StringBuilder, but it's UTF8 UIntPtr buffer_size, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, bool strip_comments); [DllImport(libgit2)] internal static extern int git_note_create( out GitOid noteOid, RepositorySafeHandle repo, SignatureSafeHandle author, SignatureSafeHandle committer, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, ref GitOid oid, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string note, int force); [DllImport(libgit2)] internal static extern void git_note_free(IntPtr note); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_note_message(NoteSafeHandle note); [DllImport(libgit2)] internal static extern OidSafeHandle git_note_oid(NoteSafeHandle note); [DllImport(libgit2)] internal static extern int git_note_read( out NoteSafeHandle note, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, ref GitOid oid); [DllImport(libgit2)] internal static extern int git_note_remove( RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, SignatureSafeHandle author, SignatureSafeHandle committer, ref GitOid oid); [DllImport(libgit2)] internal static extern int git_note_default_ref( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] out string notes_ref, RepositorySafeHandle repo); internal delegate int git_note_foreach_cb( ref GitOid blob_id, ref GitOid annotated_object_id, IntPtr payload); [DllImport(libgit2)] internal static extern int git_note_foreach( RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string notes_ref, git_note_foreach_cb cb, IntPtr payload); [DllImport(libgit2)] internal static extern int git_odb_add_backend(ObjectDatabaseSafeHandle odb, IntPtr backend, int priority); [DllImport(libgit2)] internal static extern IntPtr git_odb_backend_malloc(IntPtr backend, UIntPtr len); [DllImport(libgit2)] internal static extern int git_odb_exists(ObjectDatabaseSafeHandle odb, ref GitOid id); internal delegate int git_odb_foreach_cb( IntPtr id, IntPtr payload); [DllImport(libgit2)] internal static extern int git_odb_foreach( ObjectDatabaseSafeHandle odb, git_odb_foreach_cb cb, IntPtr payload); [DllImport(libgit2)] internal static extern void git_odb_free(IntPtr odb); [DllImport(libgit2)] internal static extern void git_object_free(IntPtr obj); [DllImport(libgit2)] internal static extern OidSafeHandle git_object_id(GitObjectSafeHandle obj); [DllImport(libgit2)] internal static extern int git_object_lookup(out GitObjectSafeHandle obj, RepositorySafeHandle repo, ref GitOid id, GitObjectType type); [DllImport(libgit2)] internal static extern int git_object_peel( out GitObjectSafeHandle peeled, GitObjectSafeHandle obj, GitObjectType type); [DllImport(libgit2)] internal static extern GitObjectType git_object_type(GitObjectSafeHandle obj); [DllImport(libgit2)] internal static extern int git_patch_from_diff(out PatchSafeHandle patch, DiffSafeHandle diff, UIntPtr idx); [DllImport(libgit2)] internal static extern int git_patch_print(PatchSafeHandle patch, git_diff_line_cb print_cb, IntPtr payload); [DllImport(libgit2)] internal static extern int git_patch_line_stats( out UIntPtr total_context, out UIntPtr total_additions, out UIntPtr total_deletions, PatchSafeHandle patch); [DllImport(libgit2)] internal static extern void git_patch_free(IntPtr patch); [DllImport(libgit2)] internal static extern int git_push_new(out PushSafeHandle push, RemoteSafeHandle remote); /* Push network progress notification function */ internal delegate int git_push_transfer_progress(uint current, uint total, UIntPtr bytes, IntPtr payload); internal delegate int git_packbuilder_progress(int stage, uint current, uint total, IntPtr payload); [DllImport(libgit2)] internal static extern int git_push_set_callbacks( PushSafeHandle push, git_packbuilder_progress pack_progress_cb, IntPtr pack_progress_cb_payload, git_push_transfer_progress transfer_progress_cb, IntPtr transfer_progress_cb_payload); [DllImport(libgit2)] internal static extern int git_push_set_options(PushSafeHandle push, GitPushOptions options); [DllImport(libgit2)] internal static extern int git_push_add_refspec( PushSafeHandle push, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string pushRefSpec); [DllImport(libgit2)] internal static extern int git_push_finish(PushSafeHandle push); [DllImport(libgit2)] internal static extern void git_push_free(IntPtr push); [DllImport(libgit2)] internal static extern int git_push_status_foreach( PushSafeHandle push, push_status_foreach_cb status_cb, IntPtr data); internal delegate int push_status_foreach_cb( IntPtr reference, IntPtr msg, IntPtr data); [DllImport(libgit2)] internal static extern int git_push_unpack_ok(PushSafeHandle push); [DllImport(libgit2)] internal static extern int git_push_update_tips(PushSafeHandle push); [DllImport(libgit2)] internal static extern int git_reference_create( out ReferenceSafeHandle reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, ref GitOid oid, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_reference_symbolic_create( out ReferenceSafeHandle reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string target, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_reference_delete(ReferenceSafeHandle reference); internal delegate int ref_glob_callback( IntPtr reference_name, IntPtr payload); [DllImport(libgit2)] internal static extern int git_reference_foreach_glob( RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string glob, ref_glob_callback callback, IntPtr payload); [DllImport(libgit2)] internal static extern void git_reference_free(IntPtr reference); [DllImport(libgit2)] internal static extern int git_reference_is_valid_name( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refname); [DllImport(libgit2)] internal static extern int git_reference_lookup( out ReferenceSafeHandle reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_reference_name(ReferenceSafeHandle reference); [DllImport(libgit2)] internal static extern OidSafeHandle git_reference_target(ReferenceSafeHandle reference); [DllImport(libgit2)] internal static extern int git_reference_rename( out ReferenceSafeHandle ref_out, ReferenceSafeHandle reference, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string newName, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_reference_set_target(out ReferenceSafeHandle ref_out, ReferenceSafeHandle reference, ref GitOid id); [DllImport(libgit2)] internal static extern int git_reference_symbolic_set_target( out ReferenceSafeHandle ref_out, ReferenceSafeHandle reference, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string target); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_reference_symbolic_target(ReferenceSafeHandle reference); [DllImport(libgit2)] internal static extern GitReferenceType git_reference_type(ReferenceSafeHandle reference); [DllImport(libgit2)] internal static extern void git_reflog_free( IntPtr reflog); [DllImport(libgit2)] internal static extern int git_reflog_read( out ReflogSafeHandle ref_out, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] internal static extern UIntPtr git_reflog_entrycount (ReflogSafeHandle reflog); [DllImport(libgit2)] internal static extern ReflogEntrySafeHandle git_reflog_entry_byindex( ReflogSafeHandle reflog, UIntPtr idx); [DllImport(libgit2)] internal static extern OidSafeHandle git_reflog_entry_id_old( SafeHandle entry); [DllImport(libgit2)] internal static extern OidSafeHandle git_reflog_entry_id_new( SafeHandle entry); [DllImport(libgit2)] internal static extern IntPtr git_reflog_entry_committer( SafeHandle entry); [DllImport(libgit2)] internal static extern int git_reflog_append( ReflogSafeHandle reflog, ref GitOid id, SignatureSafeHandle committer, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string msg); [DllImport(libgit2)] internal static extern int git_reflog_write(ReflogSafeHandle reflog); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_reflog_entry_message(SafeHandle entry); [DllImport(libgit2)] internal static extern int git_refspec_rtransform( byte[] target, UIntPtr outlen, GitRefSpecHandle refSpec, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_refspec_string( GitRefSpecHandle refSpec); [DllImport(libgit2)] internal static extern RefSpecDirection git_refspec_direction(GitRefSpecHandle refSpec); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_refspec_dst( GitRefSpecHandle refSpec); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_refspec_src( GitRefSpecHandle refSpec); [DllImport(libgit2)] internal static extern bool git_refspec_force(GitRefSpecHandle refSpec); [DllImport(libgit2)] internal static extern int git_remote_autotag(RemoteSafeHandle remote); [DllImport(libgit2)] internal static extern int git_remote_connect(RemoteSafeHandle remote, GitDirection direction); [DllImport(libgit2)] internal static extern int git_remote_create( out RemoteSafeHandle remote, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] internal static extern int git_remote_create_inmemory( out RemoteSafeHandle remote, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refspec, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url); [DllImport(libgit2)] internal static extern int git_remote_create_with_fetchspec( out RemoteSafeHandle remote, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string url, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string refspec); [DllImport(libgit2)] internal static extern void git_remote_disconnect(RemoteSafeHandle remote); [DllImport(libgit2)] internal static extern int git_remote_download( RemoteSafeHandle remote); [DllImport(libgit2)] internal static extern void git_remote_free(IntPtr remote); [DllImport(libgit2)] internal static extern GitRefSpecHandle git_remote_get_refspec(RemoteSafeHandle remote, UIntPtr n); [DllImport(libgit2)] internal static extern UIntPtr git_remote_refspec_count(RemoteSafeHandle remote); [DllImport(libgit2)] internal static extern int git_remote_set_fetch_refspecs(RemoteSafeHandle remote, GitStrArrayIn array); [DllImport(libgit2)] internal static extern int git_remote_set_push_refspecs(RemoteSafeHandle remote, GitStrArrayIn array); [DllImport(libgit2)] internal static extern int git_remote_is_valid_name( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string remote_name); [DllImport(libgit2)] internal static extern int git_remote_load( out RemoteSafeHandle remote, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name); internal delegate int git_headlist_cb(ref GitRemoteHead remoteHeadPtr, IntPtr payload); [DllImport(libgit2)] internal static extern int git_remote_ls(out IntPtr heads, out UIntPtr size, RemoteSafeHandle remote); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_remote_name(RemoteSafeHandle remote); [DllImport(libgit2)] internal static extern int git_remote_save(RemoteSafeHandle remote); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_remote_url(RemoteSafeHandle remote); [DllImport(libgit2)] internal static extern void git_remote_set_autotag(RemoteSafeHandle remote, TagFetchMode option); [DllImport(libgit2)] internal static extern int git_remote_set_callbacks( RemoteSafeHandle remote, ref GitRemoteCallbacks callbacks); internal delegate int remote_progress_callback(IntPtr str, int len, IntPtr data); internal delegate int remote_completion_callback(RemoteCompletionType type, IntPtr data); internal delegate int remote_update_tips_callback( IntPtr refName, ref GitOid oldId, ref GitOid newId, IntPtr data); [DllImport(libgit2)] internal static extern int git_remote_update_tips(RemoteSafeHandle remote); [DllImport(libgit2)] internal static extern int git_repository_discover( byte[] repository_path, // NB: This is more properly a StringBuilder, but it's UTF8 UIntPtr size, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath start_path, [MarshalAs(UnmanagedType.Bool)] bool across_fs, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath ceiling_dirs); internal delegate int git_repository_fetchhead_foreach_cb( IntPtr remote_name, IntPtr remote_url, ref GitOid oid, [MarshalAs(UnmanagedType.Bool)] bool is_merge, IntPtr payload); [DllImport(libgit2)] internal static extern int git_repository_fetchhead_foreach( RepositorySafeHandle repo, git_repository_fetchhead_foreach_cb cb, IntPtr payload); [DllImport(libgit2)] internal static extern void git_repository_free(IntPtr repo); [DllImport(libgit2)] internal static extern int git_repository_head_detached(RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_repository_head_unborn(RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_repository_index(out IndexSafeHandle index, RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_repository_init_ext( out RepositorySafeHandle repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, GitRepositoryInitOptions options); [DllImport(libgit2)] internal static extern int git_repository_is_bare(RepositorySafeHandle handle); [DllImport(libgit2)] internal static extern int git_repository_is_empty(RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_repository_is_shallow(RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_repository_state_cleanup(RepositorySafeHandle repo); internal delegate int git_repository_mergehead_foreach_cb( ref GitOid oid, IntPtr payload); [DllImport(libgit2)] internal static extern int git_repository_mergehead_foreach( RepositorySafeHandle repo, git_repository_mergehead_foreach_cb cb, IntPtr payload); [DllImport(libgit2)] internal static extern int git_repository_message( byte[] message_out, UIntPtr buffer_size, RepositorySafeHandle repository); [DllImport(libgit2)] internal static extern int git_repository_odb(out ObjectDatabaseSafeHandle odb, RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_repository_open( out RepositorySafeHandle repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path); [DllImport(libgit2)] internal static extern int git_repository_open_ext( NullRepositorySafeHandle repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath path, RepositoryOpenFlags flags, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath ceilingDirs); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxFilePathNoCleanupMarshaler))] internal static extern FilePath git_repository_path(RepositorySafeHandle repository); [DllImport(libgit2)] internal static extern void git_repository_set_config( RepositorySafeHandle repository, ConfigurationSafeHandle config); [DllImport(libgit2)] internal static extern void git_repository_set_index( RepositorySafeHandle repository, IndexSafeHandle index); [DllImport(libgit2)] internal static extern int git_repository_set_workdir( RepositorySafeHandle repository, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath workdir, bool update_gitlink); [DllImport(libgit2)] internal static extern int git_repository_state( RepositorySafeHandle repository); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxFilePathNoCleanupMarshaler))] internal static extern FilePath git_repository_workdir(RepositorySafeHandle repository); [DllImport(libgit2)] internal static extern int git_reset( RepositorySafeHandle repo, GitObjectSafeHandle target, ResetMode reset_type); [DllImport(libgit2)] internal static extern int git_revparse_ext( out GitObjectSafeHandle obj, out ReferenceSafeHandle reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string spec); [DllImport(libgit2)] internal static extern void git_revwalk_free(IntPtr walker); [DllImport(libgit2)] internal static extern int git_revwalk_hide(RevWalkerSafeHandle walker, ref GitOid commit_id); [DllImport(libgit2)] internal static extern int git_revwalk_new(out RevWalkerSafeHandle walker, RepositorySafeHandle repo); [DllImport(libgit2)] internal static extern int git_revwalk_next(out GitOid id, RevWalkerSafeHandle walker); [DllImport(libgit2)] internal static extern int git_revwalk_push(RevWalkerSafeHandle walker, ref GitOid id); [DllImport(libgit2)] internal static extern void git_revwalk_reset(RevWalkerSafeHandle walker); [DllImport(libgit2)] internal static extern void git_revwalk_sorting(RevWalkerSafeHandle walk, CommitSortStrategies sort); [DllImport(libgit2)] internal static extern void git_revwalk_simplify_first_parent(RevWalkerSafeHandle walk); [DllImport(libgit2)] internal static extern void git_signature_free(IntPtr signature); [DllImport(libgit2)] internal static extern int git_signature_new( out SignatureSafeHandle signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string email, long time, int offset); [DllImport(libgit2)] internal static extern IntPtr git_signature_dup(IntPtr sig); [DllImport(libgit2)] internal static extern int git_stash_save( out GitOid id, RepositorySafeHandle repo, SignatureSafeHandle stasher, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, StashModifiers flags); internal delegate int git_stash_cb( UIntPtr index, IntPtr message, ref GitOid stash_id, IntPtr payload); [DllImport(libgit2)] internal static extern int git_stash_foreach( RepositorySafeHandle repo, git_stash_cb callback, IntPtr payload); [DllImport(libgit2)] internal static extern int git_stash_drop(RepositorySafeHandle repo, UIntPtr index); [DllImport(libgit2)] internal static extern int git_status_file( out FileStatus statusflags, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath filepath); [DllImport(libgit2)] internal static extern int git_status_list_new( out StatusListSafeHandle git_status_list, RepositorySafeHandle repo, GitStatusOptions options); [DllImport(libgit2)] internal static extern int git_status_list_entrycount( StatusListSafeHandle statusList); [DllImport(libgit2)] internal static extern StatusEntrySafeHandle git_status_byindex( StatusListSafeHandle list, UIntPtr idx); [DllImport(libgit2)] internal static extern void git_status_list_free( IntPtr statusList); [DllImport(libgit2)] internal static extern int git_submodule_lookup( out SubmoduleSafeHandle reference, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath name); internal delegate int submodule_callback( IntPtr sm, IntPtr name, IntPtr payload); [DllImport(libgit2)] internal static extern int git_submodule_foreach( RepositorySafeHandle repo, submodule_callback callback, IntPtr payload); [DllImport(libgit2)] internal static extern int git_submodule_add_to_index( SubmoduleSafeHandle submodule, bool write_index); [DllImport(libgit2)] internal static extern int git_submodule_save( SubmoduleSafeHandle submodule); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_submodule_path( SubmoduleSafeHandle submodule); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_submodule_url( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern OidSafeHandle git_submodule_index_id( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern OidSafeHandle git_submodule_head_id( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern OidSafeHandle git_submodule_wd_id( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern SubmoduleIgnore git_submodule_ignore( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern SubmoduleUpdate git_submodule_update( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern bool git_submodule_fetch_recurse_submodules( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern int git_submodule_reload( SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern int git_submodule_status( out SubmoduleStatus status, SubmoduleSafeHandle submodule); [DllImport(libgit2)] internal static extern int git_tag_annotation_create( out GitOid oid, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, SignatureSafeHandle signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message); [DllImport(libgit2)] internal static extern int git_tag_create( out GitOid oid, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, SignatureSafeHandle signature, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string message, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_tag_create_lightweight( out GitOid oid, RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string name, GitObjectSafeHandle target, [MarshalAs(UnmanagedType.Bool)] bool force); [DllImport(libgit2)] internal static extern int git_tag_delete( RepositorySafeHandle repo, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string tagName); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_tag_message(GitObjectSafeHandle tag); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_tag_name(GitObjectSafeHandle tag); [DllImport(libgit2)] internal static extern IntPtr git_tag_tagger(GitObjectSafeHandle tag); [DllImport(libgit2)] internal static extern OidSafeHandle git_tag_target_id(GitObjectSafeHandle tag); [DllImport(libgit2)] internal static extern GitObjectType git_tag_target_type(GitObjectSafeHandle tag); [DllImport(libgit2)] internal static extern int git_threads_init(); [DllImport(libgit2)] internal static extern void git_threads_shutdown(); internal delegate int git_transfer_progress_callback(ref GitTransferProgress stats, IntPtr payload); [DllImport(libgit2)] internal static extern uint git_tree_entry_filemode(SafeHandle entry); [DllImport(libgit2)] internal static extern TreeEntrySafeHandle git_tree_entry_byindex(GitObjectSafeHandle tree, UIntPtr idx); [DllImport(libgit2)] internal static extern int git_tree_entry_bypath( out TreeEntrySafeHandle_Owned tree, GitObjectSafeHandle root, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictFilePathMarshaler))] FilePath treeentry_path); [DllImport(libgit2)] internal static extern void git_tree_entry_free(IntPtr treeEntry); [DllImport(libgit2)] internal static extern OidSafeHandle git_tree_entry_id(SafeHandle entry); [DllImport(libgit2)] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(LaxUtf8NoCleanupMarshaler))] internal static extern string git_tree_entry_name(SafeHandle entry); [DllImport(libgit2)] internal static extern GitObjectType git_tree_entry_type(SafeHandle entry); [DllImport(libgit2)] internal static extern UIntPtr git_tree_entrycount(GitObjectSafeHandle tree); [DllImport(libgit2)] internal static extern int git_treebuilder_create(out TreeBuilderSafeHandle builder, IntPtr src); [DllImport(libgit2)] internal static extern int git_treebuilder_insert( IntPtr entry_out, TreeBuilderSafeHandle builder, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = UniqueId.UniqueIdentifier, MarshalTypeRef = typeof(StrictUtf8Marshaler))] string treeentry_name, ref GitOid id, uint attributes); [DllImport(libgit2)] internal static extern int git_treebuilder_write(out GitOid id, RepositorySafeHandle repo, TreeBuilderSafeHandle bld); [DllImport(libgit2)] internal static extern void git_treebuilder_free(IntPtr bld); [DllImport(libgit2)] internal static extern int git_blob_is_binary(GitObjectSafeHandle blob); } } // ReSharper restore InconsistentNaming
// 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 InsertSByte1() { var test = new SimpleUnaryOpTest__InsertSByte1(); try { if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } } catch (PlatformNotSupportedException) { test.Succeeded = true; } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__InsertSByte1 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int RetElementCount = VectorSize / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable; static SimpleUnaryOpTest__InsertSByte1() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__InsertSByte1() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)0; } _dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Insert( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Insert( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Insert( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Insert( _clsVar, (sbyte)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Sse41.Insert(firstOp, (sbyte)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, (sbyte)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, (sbyte)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__InsertSByte1(); var result = Sse41.Insert(test._fld, (sbyte)2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Insert(_fld, (sbyte)2, 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(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != 2 : result[i] != 0)) { Succeeded = false; break; } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<SByte>(Vector128<SByte><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal partial class SignatureHelpPresenter { private class SignatureHelpPresenterSession : ForegroundThreadAffinitizedObject, ISignatureHelpPresenterSession { private readonly ISignatureHelpBroker _sigHelpBroker; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public event EventHandler<EventArgs> Dismissed; public event EventHandler<SignatureHelpItemEventArgs> ItemSelected; private IBidirectionalMap<SignatureHelpItem, Signature> _signatureMap; private IList<SignatureHelpItem> _signatureHelpItems; private SignatureHelpItem _selectedItem; private ISignatureHelpSession _editorSessionOpt; private bool _ignoreSelectionStatusChangedEvent; public SignatureHelpPresenterSession( ISignatureHelpBroker sigHelpBroker, ITextView textView, ITextBuffer subjectBuffer) { _sigHelpBroker = sigHelpBroker; _textView = textView; _subjectBuffer = subjectBuffer; } public void PresentItems( ITrackingSpan triggerSpan, IList<SignatureHelpItem> signatureHelpItems, SignatureHelpItem selectedItem, int? selectedParameter) { _signatureHelpItems = signatureHelpItems; _selectedItem = selectedItem; // Create all the editor signatures for the sig help items we have. this.CreateSignatures(triggerSpan, selectedParameter); // It's a new list of items. Either create the editor session if this is the // first time, or ask the editor session that we already have to recalculate. if (_editorSessionOpt == null) { // We're tracking the caret. Don't have the editor do it. _editorSessionOpt = _sigHelpBroker.CreateSignatureHelpSession( _textView, triggerSpan.GetStartTrackingPoint(PointTrackingMode.Negative), trackCaret: false); var debugTextView = _textView as IDebuggerTextView; if (debugTextView != null && !debugTextView.IsImmediateWindow) { debugTextView.HACK_StartCompletionSession(_editorSessionOpt); } _editorSessionOpt.Dismissed += (s, e) => OnEditorSessionDismissed(); _editorSessionOpt.SelectedSignatureChanged += OnSelectedSignatureChanged; } // So here's the deal. We cannot create the editor session and give it the right // signatures (even though we know what they are). Instead, the session with // call back into the ISignatureHelpSourceProvider (which is us) to get those // values. It will pass itself along with the calls back into // ISignatureHelpSourceProvider. So, in order to make that connection work, we // add properties to the session so that we can call back into ourselves, get // the signatures and add it to the session. if (!_editorSessionOpt.Properties.ContainsProperty(s_augmentSessionKey)) { _editorSessionOpt.Properties.AddProperty(s_augmentSessionKey, this); } try { // Don't want to get any callbacks while we do this. _ignoreSelectionStatusChangedEvent = true; _editorSessionOpt.Recalculate(); // Now let the editor know what the currently selected item is. Contract.Requires(_signatureMap.ContainsKey(selectedItem)); Contract.ThrowIfNull(_signatureMap); var defaultValue = _signatureMap.GetValueOrDefault(_selectedItem); if (_editorSessionOpt != null) { _editorSessionOpt.SelectedSignature = defaultValue; } } finally { _ignoreSelectionStatusChangedEvent = false; } } private void CreateSignatures( ITrackingSpan triggerSpan, int? selectedParameter) { _signatureMap = BidirectionalMap<SignatureHelpItem, Signature>.Empty; foreach (var item in _signatureHelpItems) { _signatureMap = _signatureMap.Add(item, new Signature(triggerSpan, item, GetParameterIndexForItem(item, selectedParameter))); } } private static int GetParameterIndexForItem(SignatureHelpItem item, int? selectedParameter) { if (selectedParameter.HasValue) { if (selectedParameter.Value < item.Parameters.Length) { // If the selected parameter is within the range of parameters of this item then set // that as the current parameter. return selectedParameter.Value; } else if (item.IsVariadic) { // It wasn't in range, but the item takes an unlimited number of parameters. So // just set current parameter to the last parameter (the variadic one). return item.Parameters.Length - 1; } } // It was out of bounds, there is no current parameter now. return -1; } private void OnEditorSessionDismissed() { AssertIsForeground(); var dismissed = this.Dismissed; if (dismissed != null) { dismissed(this, new EventArgs()); } } private void OnSelectedSignatureChanged(object sender, SelectedSignatureChangedEventArgs eventArgs) { AssertIsForeground(); if (_ignoreSelectionStatusChangedEvent) { return; } SignatureHelpItem helpItem; Contract.ThrowIfFalse(_signatureMap.TryGetKey((Signature)eventArgs.NewSelectedSignature, out helpItem)); var helpItemSelected = this.ItemSelected; if (helpItemSelected != null && helpItem != null) { helpItemSelected(this, new SignatureHelpItemEventArgs(helpItem)); } } public void Dismiss() { AssertIsForeground(); if (_editorSessionOpt == null) { // No editor session, nothing to do here. return; } _editorSessionOpt.Dismiss(); _editorSessionOpt = null; } private bool ExecuteKeyboardCommand(IntellisenseKeyboardCommand command) { var target = _editorSessionOpt != null ? _editorSessionOpt.Presenter as IIntellisenseCommandTarget : null; return target != null && target.ExecuteKeyboardCommand(command); } public void SelectPreviousItem() { ExecuteKeyboardCommand(IntellisenseKeyboardCommand.Up); } public void SelectNextItem() { ExecuteKeyboardCommand(IntellisenseKeyboardCommand.Down); } // Call backs from our ISignatureHelpSourceProvider. Used to actually populate the vs // session. internal void AugmentSignatureHelpSession(IList<ISignature> signatures) { signatures.Clear(); signatures.AddRange(_signatureHelpItems.Select(_signatureMap.GetValueOrDefault)); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using Azure.Core.Pipeline; using Azure.Core.Samples; using Azure.Core.TestFramework; using NUnit.Framework; namespace Azure.Core.Tests { [NonParallelizable] public class ClientOptionsTests { [TearDown] public void TearDown() { Core.ClientOptions.ResetDefaultOptions(); } [Theory] [TestCase("true")] [TestCase("TRUE")] [TestCase("1")] public void CanDisableDistributedTracingWithEnvironmentVariable(string value) { try { Environment.SetEnvironmentVariable("AZURE_TRACING_DISABLED", value); Core.ClientOptions.ResetDefaultOptions(); var testOptions = new TestClientOptions(); Assert.False(testOptions.Diagnostics.IsDistributedTracingEnabled); } finally { Environment.SetEnvironmentVariable("AZURE_TRACING_DISABLED", null); } } [Test] public void UsesDefaultApplicationId() { try { DiagnosticsOptions.DefaultApplicationId = "Global-application-id"; var testOptions = new TestClientOptions(); Assert.AreEqual("Global-application-id", testOptions.Diagnostics.ApplicationId); } finally { DiagnosticsOptions.DefaultApplicationId = null; } } [Theory] [TestCase("true")] [TestCase("TRUE")] [TestCase("1")] public void CanDisableTelemetryWithEnvironmentVariable(string value) { try { Environment.SetEnvironmentVariable("AZURE_TELEMETRY_DISABLED", value); Core.ClientOptions.ResetDefaultOptions(); var testOptions = new TestClientOptions(); Assert.False(testOptions.Diagnostics.IsTelemetryEnabled); } finally { Environment.SetEnvironmentVariable("AZURE_TELEMETRY_DISABLED", null); } } #if NETCOREAPP [Test] public void DefaultTransportIsHttpClientTransport() { var options = new TestClientOptions(); Assert.IsInstanceOf<HttpClientTransport>(options.Transport); } #else [Test] public void DefaultTransportIsHttpWebRequestTransport() { var options = new TestClientOptions(); Assert.IsInstanceOf<HttpWebRequestTransport>(options.Transport); Assert.IsFalse(options.IsCustomTransportSet); } [Test] public void IsCustomTransportSetIsTrueAfterCallingTransportSetter() { var options = new TestClientOptions(); options.Transport = new MockTransport(); Assert.IsTrue(options.IsCustomTransportSet); } [Test] public void DefaultTransportIsHttpClientTransportIfEnvVarSet() { string oldValue = Environment.GetEnvironmentVariable("AZURE_CORE_DISABLE_HTTPWEBREQUESTTRANSPORT"); try { Environment.SetEnvironmentVariable("AZURE_CORE_DISABLE_HTTPWEBREQUESTTRANSPORT", "true"); Core.ClientOptions.ResetDefaultOptions(); var options = new TestClientOptions(); Assert.IsInstanceOf<HttpClientTransport>(options.Transport); Assert.IsFalse(options.IsCustomTransportSet); } finally { Environment.SetEnvironmentVariable("AZURE_CORE_DISABLE_HTTPWEBREQUESTTRANSPORT", oldValue); } } [Test] public void DefaultTransportIsHttpClientTransportIfSwitchIsSet() { AppContext.TryGetSwitch("Azure.Core.Pipeline.DisableHttpWebRequestTransport", out bool oldSwitch); try { AppContext.SetSwitch("Azure.Core.Pipeline.DisableHttpWebRequestTransport", true); Core.ClientOptions.ResetDefaultOptions(); var options = new TestClientOptions(); Assert.IsInstanceOf<HttpClientTransport>(options.Transport); Assert.IsFalse(options.IsCustomTransportSet); } finally { AppContext.SetSwitch("Azure.Core.Pipeline.DisableHttpWebRequestTransport", oldSwitch); } } #endif [TestCaseSource(nameof(ClientOptions))] public void GlobalConfigurationIsApplied(Func<ClientOptions, object> set, Func<ClientOptions, object> get) { var initial = get(Core.ClientOptions.Default); var expected = set(Core.ClientOptions.Default); var testOptions = new TestClientOptions(); Assert.AreNotEqual(initial, expected); Assert.AreEqual(expected, get(testOptions)); } public static IEnumerable<object[]> ClientOptions() { object[] M(Func<ClientOptions, object> set, Func<ClientOptions, object> get) => new[] { set, get }; yield return M(o => o.Transport = new MockTransport(), o => o.Transport); yield return M(o => { var policy = new PipelineSamples.StopwatchPolicy(); o.AddPolicy(policy, HttpPipelinePosition.PerCall); return policy; }, o => o.Policies?.LastOrDefault(p=>p.Position == HttpPipelinePosition.PerCall).Policy); yield return M(o => { var policy = new PipelineSamples.StopwatchPolicy(); o.AddPolicy(policy, HttpPipelinePosition.PerRetry); return policy; }, o => o.Policies?.LastOrDefault(p=>p.Position == HttpPipelinePosition.PerRetry).Policy); yield return M(o => { var policy = new PipelineSamples.StopwatchPolicy(); o.AddPolicy(policy, HttpPipelinePosition.BeforeTransport); return policy; }, o => o.Policies?.LastOrDefault(p=>p.Position == HttpPipelinePosition.BeforeTransport).Policy); yield return M(o => o.Retry.Delay = TimeSpan.FromDays(5), o => o.Retry.Delay); yield return M(o => o.Retry.Mode = RetryMode.Fixed, o => o.Retry.Mode); yield return M(o => o.Retry.MaxDelay = TimeSpan.FromDays(5), o => o.Retry.MaxDelay); yield return M(o => o.Retry.NetworkTimeout = TimeSpan.FromDays(5), o => o.Retry.NetworkTimeout); yield return M(o => o.Retry.MaxRetries = 44, o => o.Retry.MaxRetries); yield return M(o => o.Diagnostics.ApplicationId = "a", o => o.Diagnostics.ApplicationId); yield return M(o => o.Diagnostics.IsLoggingEnabled = false, o => o.Diagnostics.IsLoggingEnabled); yield return M(o => o.Diagnostics.IsTelemetryEnabled = false, o => o.Diagnostics.IsTelemetryEnabled); yield return M(o => o.Diagnostics.IsLoggingContentEnabled = true, o => o.Diagnostics.IsLoggingContentEnabled); yield return M(o => o.Diagnostics.LoggedContentSizeLimit = 100, o => o.Diagnostics.LoggedContentSizeLimit); yield return M(o => o.Diagnostics.IsDistributedTracingEnabled = false, o => o.Diagnostics.IsDistributedTracingEnabled); yield return M(o => { o.Diagnostics.LoggedHeaderNames.Add("abc"); return "abc"; }, o => o.Diagnostics.LoggedHeaderNames.LastOrDefault()); yield return M(o => { o.Diagnostics.LoggedQueryParameters.Add("abc"); return "abc"; }, o => o.Diagnostics.LoggedQueryParameters.LastOrDefault()); } private class TestClientOptions : ClientOptions { } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Serialization; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates serializers. /// </summary> public static class SerializerGenerator { private static readonly TypeFormattingOptions GeneratedTypeNameOptions = new TypeFormattingOptions( ClassSuffix, includeGenericParameters: false, includeTypeParameters: false, nestedClassSeparator: '_', includeGlobal: false); /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Serializer"; /// <summary> /// The suffix appended to the name of the generic serializer registration class. /// </summary> private const string RegistererClassSuffix = "Registerer"; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="type">The grain interface type.</param> /// <param name="onEncounteredType"> /// The callback invoked when a type is encountered. /// </param> /// <returns> /// The generated class. /// </returns> internal static IEnumerable<TypeDeclarationSyntax> GenerateClass(Type type, Action<Type> onEncounteredType) { var typeInfo = type.GetTypeInfo(); var genericTypes = typeInfo.IsGenericTypeDefinition ? typeInfo.GetGenericArguments().Select(_ => SF.TypeParameter(_.ToString())).ToArray() : new TypeParameterSyntax[0]; var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), SF.Attribute(typeof(SerializerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false)))) }; var className = CodeGeneratorCommon.ClassPrefix + type.GetParseableName(GeneratedTypeNameOptions); var fields = GetFields(type); // Mark each field type for generation foreach (var field in fields) { var fieldType = field.FieldInfo.FieldType; onEncounteredType(fieldType); } var members = new List<MemberDeclarationSyntax>(GenerateStaticFields(fields)) { GenerateDeepCopierMethod(type, fields), GenerateSerializerMethod(type, fields), GenerateDeserializerMethod(type, fields), }; if (typeInfo.IsConstructedGenericType || !typeInfo.IsGenericTypeDefinition) { members.Add(GenerateRegisterMethod(type)); members.Add(GenerateConstructor(className)); attributes.Add(SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax())); } var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())) .AddMembers(members.ToArray()) .AddConstraintClauses(type.GetTypeConstraintSyntax()); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } var classes = new List<TypeDeclarationSyntax> { classDeclaration }; if (typeInfo.IsGenericTypeDefinition) { // Create a generic representation of the serializer type. var serializerType = SF.GenericName(classDeclaration.Identifier) .WithTypeArgumentList( SF.TypeArgumentList() .AddArguments( type.GetGenericArguments() .Select(_ => SF.OmittedTypeArgument()) .Cast<TypeSyntax>() .ToArray())); var registererClassName = className + "_" + string.Join("_", type.GetTypeInfo().GenericTypeParameters.Select(_ => _.Name)) + "_" + RegistererClassSuffix; classes.Add( SF.ClassDeclaration(registererClassName) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists( SF.AttributeList() .AddAttributes( CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax()))) .AddMembers( GenerateMasterRegisterMethod(type, serializerType), GenerateConstructor(registererClassName))); } return classes; } /// <summary> /// Returns syntax for the deserializer method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deserializer method.</returns> private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action> deserializeInner = () => SerializationManager.DeserializeInner(default(Type), default(BinaryTokenStreamReader)); var streamParameter = SF.IdentifierName("stream"); var resultDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type))))); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax> { resultDeclaration }; // Value types cannot be referenced, only copied, so there is no need to box & record instances of value types. if (!type.IsValueType) { // Record the result for cyclic deserialization. Expression<Action> recordObject = () => DeserializationContext.Current.RecordObject(default(object)); var currentSerializationContext = SyntaxFactory.AliasQualifiedName( SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)), SF.IdentifierName("Orleans")) .Qualify("Serialization") .Qualify("DeserializationContext") .Qualify("Current"); body.Add( SF.ExpressionStatement( recordObject.Invoke(currentSerializationContext) .AddArgumentListArguments(SF.Argument(resultVariable)))); } // Deserialize all fields. foreach (var field in fields) { var deserialized = deserializeInner.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(field.Type)), SF.Argument(streamParameter)); body.Add( SF.ExpressionStatement( field.GetSetter( resultVariable, SF.CastExpression(field.Type, deserialized)))); } body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), resultVariable))); return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()), SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamReader).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax()))); } private static MemberDeclarationSyntax GenerateSerializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action> serializeInner = () => SerializationManager.SerializeInner(default(object), default(BinaryTokenStreamWriter), default(Type)); var body = new List<StatementSyntax> { SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.CastExpression(type.GetTypeSyntax(), SF.IdentifierName("untypedInput")))))) }; var inputExpression = SF.IdentifierName("input"); // Serialize all members. foreach (var field in fields) { body.Add( SF.ExpressionStatement( serializeInner.Invoke() .AddArgumentListArguments( SF.Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)), SF.Argument(SF.IdentifierName("stream")), SF.Argument(SF.TypeOfExpression(field.FieldInfo.FieldType.GetTypeSyntax()))))); } return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Serializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("untypedInput")).WithType(typeof(object).GetTypeSyntax()), SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamWriter).GetTypeSyntax()), SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(SerializerMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the deep copier method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deep copier method.</returns> private static MemberDeclarationSyntax GenerateDeepCopierMethod(Type type, List<FieldInfoMember> fields) { var originalVariable = SF.IdentifierName("original"); var inputVariable = SF.IdentifierName("input"); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax>(); if (type.GetCustomAttribute<ImmutableAttribute>() != null) { // Immutable types do not require copying. body.Add(SF.ReturnStatement(originalVariable)); } else { body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.ParenthesizedExpression( SF.CastExpression(type.GetTypeSyntax(), originalVariable))))))); body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))))); // Copy all members from the input to the result. foreach (var field in fields) { body.Add(SF.ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable)))); } // Record this serialization. Expression<Action> recordObject = () => SerializationContext.Current.RecordObject(default(object), default(object)); var currentSerializationContext = SyntaxFactory.AliasQualifiedName( SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)), SF.IdentifierName("Orleans")) .Qualify("Serialization") .Qualify("SerializationContext") .Qualify("Current"); body.Add( SF.ExpressionStatement( recordObject.Invoke(currentSerializationContext) .AddArgumentListArguments(SF.Argument(originalVariable), SF.Argument(resultVariable)))); body.Add(SF.ReturnStatement(resultVariable)); } return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "DeepCopier") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("original")).WithType(typeof(object).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList().AddAttributes(SF.Attribute(typeof(CopierMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the static fields of the serializer class. /// </summary> /// <param name="fields">The fields.</param> /// <returns>Syntax for the static fields of the serializer class.</returns> private static MemberDeclarationSyntax[] GenerateStaticFields(List<FieldInfoMember> fields) { var result = new List<MemberDeclarationSyntax>(); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Expression<Action<TypeInfo>> getField = _ => _.GetField(string.Empty, BindingFlags.Default); Expression<Action<Type>> getTypeInfo = _ => _.GetTypeInfo(); Expression<Action> getGetter = () => SerializationManager.GetGetter(default(FieldInfo)); Expression<Action> getReferenceSetter = () => SerializationManager.GetReferenceSetter(default(FieldInfo)); Expression<Action> getValueSetter = () => SerializationManager.GetValueSetter(default(FieldInfo)); // Expressions for specifying binding flags. var bindingFlags = SyntaxFactoryExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); // Add each field and initialize it. foreach (var field in fields) { var fieldInfo = getField.Invoke(getTypeInfo.Invoke(SF.TypeOfExpression(field.FieldInfo.DeclaringType.GetTypeSyntax()))) .AddArgumentListArguments( SF.Argument(field.FieldInfo.Name.GetLiteralExpression()), SF.Argument(bindingFlags)); var fieldInfoVariable = SF.VariableDeclarator(field.InfoFieldName).WithInitializer(SF.EqualsValueClause(fieldInfo)); var fieldInfoField = SF.IdentifierName(field.InfoFieldName); if (!field.IsGettableProperty || !field.IsSettableProperty) { result.Add( SF.FieldDeclaration( SF.VariableDeclaration(typeof(FieldInfo).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } // Declare the getter for this field. if (!field.IsGettableProperty) { var getterType = typeof(Func<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldGetterVariable = SF.VariableDeclarator(field.GetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( getterType, getGetter.Invoke().AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(getterType).AddVariables(fieldGetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } if (!field.IsSettableProperty) { if (field.FieldInfo.DeclaringType != null && field.FieldInfo.DeclaringType.IsValueType) { var setterType = typeof(SerializationManager.ValueTypeSetter<,>).MakeGenericType( field.FieldInfo.DeclaringType, field.FieldInfo.FieldType).GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getValueSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } else { var setterType = typeof(Action<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getReferenceSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } } } return result.ToArray(); } /// <summary> /// Returns syntax for initializing a new instance of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>Syntax for initializing a new instance of the provided type.</returns> private static ExpressionSyntax GetObjectCreationExpressionSyntax(Type type) { ExpressionSyntax result; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsValueType) { // Use the default value. result = SF.DefaultExpression(typeInfo.GetTypeSyntax()); } else if (type.GetConstructor(Type.EmptyTypes) != null) { // Use the default constructor. result = SF.ObjectCreationExpression(typeInfo.GetTypeSyntax()).AddArgumentListArguments(); } else { // Create an unformatted object. Expression<Func<object>> getUninitializedObject = #if NETSTANDARD1_6 () => SerializationManager.GetUninitializedObjectWithFormatterServices(default(Type)); #else () => FormatterServices.GetUninitializedObject(default(Type)); #endif result = SF.CastExpression( type.GetTypeSyntax(), getUninitializedObject.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(typeInfo.GetTypeSyntax())))); } return result; } /// <summary> /// Returns syntax for the serializer registration method. /// </summary> /// <param name="type">The type.</param> /// <returns>Syntax for the serializer registration method.</returns> private static MemberDeclarationSyntax GenerateRegisterMethod(Type type) { Expression<Action> register = () => SerializationManager.Register( default(Type), default(SerializationManager.DeepCopier), default(SerializationManager.Serializer), default(SerializationManager.Deserializer)); return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( register.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(type.GetTypeSyntax())), SF.Argument(SF.IdentifierName("DeepCopier")), SF.Argument(SF.IdentifierName("Serializer")), SF.Argument(SF.IdentifierName("Deserializer"))))); } /// <summary> /// Returns syntax for the constructor. /// </summary> /// <param name="className">The name of the class.</param> /// <returns>Syntax for the constructor.</returns> private static ConstructorDeclarationSyntax GenerateConstructor(string className) { return SF.ConstructorDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( SF.InvocationExpression(SF.IdentifierName("Register")).AddArgumentListArguments())); } /// <summary> /// Returns syntax for the generic serializer registration method for the provided type.. /// </summary> /// <param name="type">The type which is supported by this serializer.</param> /// <param name="serializerType">The type of the serializer.</param> /// <returns>Syntax for the generic serializer registration method for the provided type..</returns> private static MemberDeclarationSyntax GenerateMasterRegisterMethod(Type type, TypeSyntax serializerType) { Expression<Action> register = () => SerializationManager.Register(default(Type), default(Type)); return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( register.Invoke() .AddArgumentListArguments( SF.Argument( SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))), SF.Argument(SF.TypeOfExpression(serializerType))))); } /// <summary> /// Returns a sorted list of the fields of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>A sorted list of the fields of the provided type.</returns> private static List<FieldInfoMember> GetFields(Type type) { var result = type.GetAllFields() .Where(field => !field.IsNotSerialized) .Select((info, i) => new FieldInfoMember { FieldInfo = info, FieldNumber = i }) .ToList(); result.Sort(FieldInfoMember.Comparer.Instance); return result; } /// <summary> /// Represents a field. /// </summary> private class FieldInfoMember { private PropertyInfo property; /// <summary> /// Gets or sets the underlying <see cref="FieldInfo"/> instance. /// </summary> public FieldInfo FieldInfo { get; set; } /// <summary> /// Sets the ordinal assigned to this field. /// </summary> public int FieldNumber { private get; set; } /// <summary> /// Gets the name of the field info field. /// </summary> public string InfoFieldName { get { return "field" + this.FieldNumber; } } /// <summary> /// Gets the name of the getter field. /// </summary> public string GetterFieldName { get { return "getField" + this.FieldNumber; } } /// <summary> /// Gets the name of the setter field. /// </summary> public string SetterFieldName { get { return "setField" + this.FieldNumber; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter. /// </summary> public bool IsGettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter. /// </summary> public bool IsSettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax Type { get { return this.FieldInfo.FieldType.GetTypeSyntax(); } } /// <summary> /// Gets the <see cref="PropertyInfo"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private PropertyInfo PropertyInfo { get { if (this.property != null) { return this.property; } var propertyName = Regex.Match(this.FieldInfo.Name, "^<([^>]+)>.*$"); if (propertyName.Success && this.FieldInfo.DeclaringType != null) { var name = propertyName.Groups[1].Value; this.property = this.FieldInfo.DeclaringType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public); } return this.property; } } /// <summary> /// Gets a value indicating whether or not this field is obsolete. /// </summary> private bool IsObsolete { get { var obsoleteAttr = this.FieldInfo.GetCustomAttribute<ObsoleteAttribute>(); // Get the attribute from the property, if present. if (this.property != null && obsoleteAttr == null) { obsoleteAttr = this.property.GetCustomAttribute<ObsoleteAttribute>(); } return obsoleteAttr != null; } } /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if neccessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false) { // Retrieve the value of the field. var getValueExpression = this.GetValueExpression(instance); // Avoid deep-copying the field if possible. if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable()) { // Return the value without deep-copying it. return getValueExpression; } // Deep-copy the value. Expression<Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object)); var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax(); return SF.CastExpression( typeSyntax, deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(getValueExpression))); } /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { // If the field is the backing field for an accessible auto-property use the property directly. if (this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete) { return SF.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(this.PropertyInfo.Name), value); } var instanceArg = SF.Argument(instance); if (this.FieldInfo.DeclaringType != null && this.FieldInfo.DeclaringType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(SF.Token(SyntaxKind.RefKeyword)); } return SF.InvocationExpression(SF.IdentifierName(this.SetterFieldName)) .AddArgumentListArguments(instanceArg, SF.Argument(value)); } /// <summary> /// Returns syntax for retrieving the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> private ExpressionSyntax GetValueExpression(ExpressionSyntax instance) { // If the field is the backing field for an accessible auto-property use the property directly. ExpressionSyntax result; if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete) { result = instance.Member(this.PropertyInfo.Name); } else { // Retrieve the field using the generated getter. result = SF.InvocationExpression(SF.IdentifierName(this.GetterFieldName)) .AddArgumentListArguments(SF.Argument(instance)); } return result; } /// <summary> /// A comparer for <see cref="FieldInfoMember"/> which compares by name. /// </summary> public class Comparer : IComparer<FieldInfoMember> { /// <summary> /// The singleton instance. /// </summary> private static readonly Comparer Singleton = new Comparer(); /// <summary> /// Gets the singleton instance of this class. /// </summary> public static Comparer Instance { get { return Singleton; } } public int Compare(FieldInfoMember x, FieldInfoMember y) { return string.Compare(x.FieldInfo.Name, y.FieldInfo.Name, StringComparison.Ordinal); } } } } }
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.Resources; 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"); } if (!project.SupportsINuGetProjectSystem()) { 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 { if (!project.SupportsINuGetProjectSystem()) { 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 fullPath; IPackageFile scriptFile; if (package.FindCompatibleToolFiles(scriptFileName, targetFramework, out scriptFile)) { fullPath = Path.Combine(rootPath, scriptFile.Path); } else { return; } if (File.Exists(fullPath)) { if (project != null && scriptFile != null) { // targetFramework can be null for unknown project types string shortFramework = targetFramework == null ? string.Empty : VersionUtility.GetShortFrameworkName(targetFramework); WriteVerbose(String.Format(CultureInfo.CurrentCulture, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(), project.Name, shortFramework)); WriteVerbose(String.Format(CultureInfo.CurrentCulture, NuGetResources.Debug_TargetFrameworkInfo_PowershellScripts, Path.GetDirectoryName(scriptFile.Path), VersionUtility.GetTargetFrameworkLogString(scriptFile.TargetFramework))); } 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); } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Speech.Tts.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Android.Speech.Tts { /// <summary> /// <para>Synthesizes speech from text for immediate playback or to create a sound file. </para><para>A TextToSpeech instance can only be used to synthesize text once it has completed its initialization. Implement the TextToSpeech.OnInitListener to be notified of the completion of the initialization.<br></br> When you are done using the TextToSpeech instance, call the shutdown() method to release the native resources used by the TextToSpeech engine. </para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech", AccessFlags = 33)] public partial class TextToSpeech /* scope: __dot42__ */ { /// <summary> /// <para>Denotes a successful operation. </para> /// </summary> /// <java-name> /// SUCCESS /// </java-name> [Dot42.DexImport("SUCCESS", "I", AccessFlags = 25)] public const int SUCCESS = 0; /// <summary> /// <para>Denotes a generic operation failure. </para> /// </summary> /// <java-name> /// ERROR /// </java-name> [Dot42.DexImport("ERROR", "I", AccessFlags = 25)] public const int ERROR = -1; /// <summary> /// <para>Queue mode where all entries in the playback queue (media to be played and text to be synthesized) are dropped and replaced by the new entry. Queues are flushed with respect to a given calling app. Entries in the queue from other callees are not discarded. </para> /// </summary> /// <java-name> /// QUEUE_FLUSH /// </java-name> [Dot42.DexImport("QUEUE_FLUSH", "I", AccessFlags = 25)] public const int QUEUE_FLUSH = 0; /// <summary> /// <para>Queue mode where the new entry is added at the end of the playback queue. </para> /// </summary> /// <java-name> /// QUEUE_ADD /// </java-name> [Dot42.DexImport("QUEUE_ADD", "I", AccessFlags = 25)] public const int QUEUE_ADD = 1; /// <summary> /// <para>Denotes the language is available exactly as specified by the locale. </para> /// </summary> /// <java-name> /// LANG_COUNTRY_VAR_AVAILABLE /// </java-name> [Dot42.DexImport("LANG_COUNTRY_VAR_AVAILABLE", "I", AccessFlags = 25)] public const int LANG_COUNTRY_VAR_AVAILABLE = 2; /// <summary> /// <para>Denotes the language is available for the language and country specified by the locale, but not the variant. </para> /// </summary> /// <java-name> /// LANG_COUNTRY_AVAILABLE /// </java-name> [Dot42.DexImport("LANG_COUNTRY_AVAILABLE", "I", AccessFlags = 25)] public const int LANG_COUNTRY_AVAILABLE = 1; /// <summary> /// <para>Denotes the language is available for the language by the locale, but not the country and variant. </para> /// </summary> /// <java-name> /// LANG_AVAILABLE /// </java-name> [Dot42.DexImport("LANG_AVAILABLE", "I", AccessFlags = 25)] public const int LANG_AVAILABLE = 0; /// <summary> /// <para>Denotes the language data is missing. </para> /// </summary> /// <java-name> /// LANG_MISSING_DATA /// </java-name> [Dot42.DexImport("LANG_MISSING_DATA", "I", AccessFlags = 25)] public const int LANG_MISSING_DATA = -1; /// <summary> /// <para>Denotes the language is not supported. </para> /// </summary> /// <java-name> /// LANG_NOT_SUPPORTED /// </java-name> [Dot42.DexImport("LANG_NOT_SUPPORTED", "I", AccessFlags = 25)] public const int LANG_NOT_SUPPORTED = -2; /// <summary> /// <para>Broadcast Action: The TextToSpeech synthesizer has completed processing of all the text in the speech queue.</para><para>Note that this notifies callers when the <b>engine</b> has finished has processing text data. Audio playback might not have completed (or even started) at this point. If you wish to be notified when this happens, see OnUtteranceCompletedListener. </para> /// </summary> /// <java-name> /// ACTION_TTS_QUEUE_PROCESSING_COMPLETED /// </java-name> [Dot42.DexImport("ACTION_TTS_QUEUE_PROCESSING_COMPLETED", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_TTS_QUEUE_PROCESSING_COMPLETED = "android.speech.tts.TTS_QUEUE_PROCESSING_COMPLETED"; /// <summary> /// <para>The constructor for the TextToSpeech class, using the default TTS engine. This will also initialize the associated TextToSpeech engine if it isn't already running.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/content/Context;Landroid/speech/tts/TextToSpeech$OnInitListener;)V", AccessFlags = 1)] public TextToSpeech(global::Android.Content.Context context, global::Android.Speech.Tts.TextToSpeech.IOnInitListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Releases the resources used by the TextToSpeech engine. It is good practice for instance to call this method in the onDestroy() method of an Activity so the TextToSpeech engine can be cleanly stopped. </para> /// </summary> /// <java-name> /// shutdown /// </java-name> [Dot42.DexImport("shutdown", "()V", AccessFlags = 1)] public virtual void Shutdown() /* MethodBuilder.Create */ { } /// <summary> /// <para>Adds a mapping between a string of text and a sound resource in a package. After a call to this method, subsequent calls to speak(String, int, HashMap) will play the specified sound resource if it is available, or synthesize the text it is missing.</para><para><code>&lt;manifest xmlns:android="..." package="<b>com.google.marvin.compass</b>"&gt;</code> </para><para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addSpeech /// </java-name> [Dot42.DexImport("addSpeech", "(Ljava/lang/String;Ljava/lang/String;I)I", AccessFlags = 1)] public virtual int AddSpeech(string text, string packagename, int resourceId) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Adds a mapping between a string of text and a sound file. Using this, it is possible to add custom pronounciations for a string of text. After a call to this method, subsequent calls to speak(String, int, HashMap) will play the specified sound resource if it is available, or synthesize the text it is missing.</para><para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addSpeech /// </java-name> [Dot42.DexImport("addSpeech", "(Ljava/lang/String;Ljava/lang/String;)I", AccessFlags = 1)] public virtual int AddSpeech(string text, string filename) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Adds a mapping between a string of text and a sound resource in a package. Use this to add custom earcons.</para><para><para>#playEarcon(String, int, HashMap)</para><code>&lt;manifest xmlns:android="..." package="<b>com.google.marvin.compass</b>"&gt;</code> </para><para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addEarcon /// </java-name> [Dot42.DexImport("addEarcon", "(Ljava/lang/String;Ljava/lang/String;I)I", AccessFlags = 1)] public virtual int AddEarcon(string earcon, string packagename, int resourceId) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Adds a mapping between a string of text and a sound file. Use this to add custom earcons.</para><para><para>#playEarcon(String, int, HashMap)</para></para> /// </summary> /// <returns> /// <para>Code indicating success or failure. See ERROR and SUCCESS. </para> /// </returns> /// <java-name> /// addEarcon /// </java-name> [Dot42.DexImport("addEarcon", "(Ljava/lang/String;Ljava/lang/String;)I", AccessFlags = 1)] public virtual int AddEarcon(string earcon, string filename) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Speaks the string using the specified queuing strategy and speech parameters. This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the speak operation. </para> /// </returns> /// <java-name> /// speak /// </java-name> [Dot42.DexImport("speak", "(Ljava/lang/String;ILjava/util/HashMap;)I", AccessFlags = 1, Signature = "(Ljava/lang/String;ILjava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;)I")] public virtual int Speak(string text, int queueMode, global::Java.Util.HashMap<string, string> @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Plays the earcon using the specified queueing mode and parameters. The earcon must already have been added with addEarcon(String, String) or addEarcon(String, String, int). This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the playEarcon operation. </para> /// </returns> /// <java-name> /// playEarcon /// </java-name> [Dot42.DexImport("playEarcon", "(Ljava/lang/String;ILjava/util/HashMap;)I", AccessFlags = 1, Signature = "(Ljava/lang/String;ILjava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;)I")] public virtual int PlayEarcon(string earcon, int queueMode, global::Java.Util.HashMap<string, string> @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Plays silence for the specified amount of time using the specified queue mode. This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the playSilence operation. </para> /// </returns> /// <java-name> /// playSilence /// </java-name> [Dot42.DexImport("playSilence", "(JILjava/util/HashMap;)I", AccessFlags = 1, Signature = "(JILjava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;)I")] public virtual int PlaySilence(long durationInMs, int queueMode, global::Java.Util.HashMap<string, string> @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Checks whether the TTS engine is busy speaking. Note that a speech item is considered complete once it's audio data has been sent to the audio mixer, or written to a file. There might be a finite lag between this point, and when the audio hardware completes playback.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if the TTS engine is speaking. </para> /// </returns> /// <java-name> /// isSpeaking /// </java-name> [Dot42.DexImport("isSpeaking", "()Z", AccessFlags = 1)] public virtual bool IsSpeaking() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Interrupts the current utterance (whether played or rendered to file) and discards other utterances in the queue.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS. </para> /// </returns> /// <java-name> /// stop /// </java-name> [Dot42.DexImport("stop", "()I", AccessFlags = 1)] public virtual int Stop() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the speech rate.</para><para>This has no effect on any pre-recorded speech.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS. </para> /// </returns> /// <java-name> /// setSpeechRate /// </java-name> [Dot42.DexImport("setSpeechRate", "(F)I", AccessFlags = 1)] public virtual int SetSpeechRate(float speechRate) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the speech pitch for the TextToSpeech engine.</para><para>This has no effect on any pre-recorded speech.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS. </para> /// </returns> /// <java-name> /// setPitch /// </java-name> [Dot42.DexImport("setPitch", "(F)I", AccessFlags = 1)] public virtual int SetPitch(float pitch) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the text-to-speech language. The TTS engine will try to use the closest match to the specified language as represented by the Locale, but there is no guarantee that the exact same Locale will be used. Use isLanguageAvailable(Locale) to check the level of support before choosing the language to use for the next utterances.</para><para></para> /// </summary> /// <returns> /// <para>Code indicating the support status for the locale. See LANG_AVAILABLE, LANG_COUNTRY_AVAILABLE, LANG_COUNTRY_VAR_AVAILABLE, LANG_MISSING_DATA and LANG_NOT_SUPPORTED. </para> /// </returns> /// <java-name> /// setLanguage /// </java-name> [Dot42.DexImport("setLanguage", "(Ljava/util/Locale;)I", AccessFlags = 1)] public virtual int SetLanguage(global::Java.Util.Locale loc) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns a Locale instance describing the language currently being used for synthesis requests sent to the TextToSpeech engine.</para><para>In Android 4.2 and before (API &lt;= 17) this function returns the language that is currently being used by the TTS engine. That is the last language set by this or any other client by a TextToSpeech#setLanguage call to the same engine.</para><para>In Android versions after 4.2 this function returns the language that is currently being used for the synthesis requests sent from this client. That is the last language set by a TextToSpeech#setLanguage call on this instance.</para><para></para> /// </summary> /// <returns> /// <para>language, country (if any) and variant (if any) used by the client stored in a Locale instance, or <c> null </c> on error. </para> /// </returns> /// <java-name> /// getLanguage /// </java-name> [Dot42.DexImport("getLanguage", "()Ljava/util/Locale;", AccessFlags = 1)] public virtual global::Java.Util.Locale GetLanguage() /* MethodBuilder.Create */ { return default(global::Java.Util.Locale); } /// <summary> /// <para>Checks if the specified language as represented by the Locale is available and supported.</para><para></para> /// </summary> /// <returns> /// <para>Code indicating the support status for the locale. See LANG_AVAILABLE, LANG_COUNTRY_AVAILABLE, LANG_COUNTRY_VAR_AVAILABLE, LANG_MISSING_DATA and LANG_NOT_SUPPORTED. </para> /// </returns> /// <java-name> /// isLanguageAvailable /// </java-name> [Dot42.DexImport("isLanguageAvailable", "(Ljava/util/Locale;)I", AccessFlags = 1)] public virtual int IsLanguageAvailable(global::Java.Util.Locale loc) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Synthesizes the given text to a file using the specified parameters. This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns. In order to reliably detect errors during synthesis, we recommend setting an utterance progress listener (see setOnUtteranceProgressListener) and using the Engine#KEY_PARAM_UTTERANCE_ID parameter.</para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS of <b>queuing</b> the synthesizeToFile operation. </para> /// </returns> /// <java-name> /// synthesizeToFile /// </java-name> [Dot42.DexImport("synthesizeToFile", "(Ljava/lang/String;Ljava/util/HashMap;Ljava/lang/String;)I", AccessFlags = 1, Signature = "(Ljava/lang/String;Ljava/util/HashMap<Ljava/lang/String;Ljava/lang/String;>;Ljava" + "/lang/String;)I")] public virtual int SynthesizeToFile(string text, global::Java.Util.HashMap<string, string> @params, string filename) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the listener that will be notified when synthesis of an utterance completes.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use setOnUtteranceProgressListener(UtteranceProgressListener) instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS.</para> /// </returns> /// <java-name> /// setOnUtteranceCompletedListener /// </java-name> [Dot42.DexImport("setOnUtteranceCompletedListener", "(Landroid/speech/tts/TextToSpeech$OnUtteranceCompletedListener;)I", AccessFlags = 1)] public virtual int SetOnUtteranceCompletedListener(global::Android.Speech.Tts.TextToSpeech.IOnUtteranceCompletedListener listener) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the TTS engine to use.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>This doesn't inform callers when the TTS engine has been initialized. TextToSpeech(Context, OnInitListener, String) can be used with the appropriate engine name. Also, there is no guarantee that the engine specified will be loaded. If it isn't installed or disabled, the user / system wide defaults will apply.</para></xrefdescription></xrefsect></para><para></para> /// </summary> /// <returns> /// <para>ERROR or SUCCESS. </para> /// </returns> /// <java-name> /// setEngineByPackageName /// </java-name> [Dot42.DexImport("setEngineByPackageName", "(Ljava/lang/String;)I", AccessFlags = 1)] public virtual int SetEngineByPackageName(string enginePackageName) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Gets the package name of the default speech synthesis engine.</para><para></para> /// </summary> /// <returns> /// <para>Package name of the TTS engine that the user has chosen as their default. </para> /// </returns> /// <java-name> /// getDefaultEngine /// </java-name> [Dot42.DexImport("getDefaultEngine", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetDefaultEngine() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Checks whether the user's settings should override settings requested by the calling application. As of the Ice cream sandwich release, user settings never forcibly override the app's settings. </para> /// </summary> /// <java-name> /// areDefaultsEnforced /// </java-name> [Dot42.DexImport("areDefaultsEnforced", "()Z", AccessFlags = 1)] public virtual bool AreDefaultsEnforced() /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal TextToSpeech() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns a Locale instance describing the language currently being used for synthesis requests sent to the TextToSpeech engine.</para><para>In Android 4.2 and before (API &lt;= 17) this function returns the language that is currently being used by the TTS engine. That is the last language set by this or any other client by a TextToSpeech#setLanguage call to the same engine.</para><para>In Android versions after 4.2 this function returns the language that is currently being used for the synthesis requests sent from this client. That is the last language set by a TextToSpeech#setLanguage call on this instance.</para><para></para> /// </summary> /// <returns> /// <para>language, country (if any) and variant (if any) used by the client stored in a Locale instance, or <c> null </c> on error. </para> /// </returns> /// <java-name> /// getLanguage /// </java-name> public global::Java.Util.Locale Language { [Dot42.DexImport("getLanguage", "()Ljava/util/Locale;", AccessFlags = 1)] get{ return GetLanguage(); } } /// <summary> /// <para>Gets the package name of the default speech synthesis engine.</para><para></para> /// </summary> /// <returns> /// <para>Package name of the TTS engine that the user has chosen as their default. </para> /// </returns> /// <java-name> /// getDefaultEngine /// </java-name> public string DefaultEngine { [Dot42.DexImport("getDefaultEngine", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetDefaultEngine(); } } /// <summary> /// <para>Constants and parameter names for controlling text-to-speech. These include:</para><para><ul><li><para>Intents to ask engine to install data or check its data and extras for a TTS engine's check data activity. </para></li><li><para>Keys for the parameters passed with speak commands, e.g. Engine#KEY_PARAM_UTTERANCE_ID, Engine#KEY_PARAM_STREAM. </para></li><li><para>A list of feature strings that engines might support, e.g Engine#KEY_FEATURE_NETWORK_SYNTHESIS). These values may be passed in to TextToSpeech#speak and TextToSpeech#synthesizeToFile to modify engine behaviour. The engine can be queried for the set of features it supports through TextToSpeech#getFeatures(java.util.Locale). </para></li></ul></para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech$Engine /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech$Engine", AccessFlags = 1)] public partial class Engine /* scope: __dot42__ */ { /// <summary> /// <para>Default audio stream used when playing synthesized speech. </para> /// </summary> /// <java-name> /// DEFAULT_STREAM /// </java-name> [Dot42.DexImport("DEFAULT_STREAM", "I", AccessFlags = 25)] public const int DEFAULT_STREAM = 3; /// <summary> /// <para>Indicates success when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent. </para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_PASS /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_PASS", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_PASS = 1; /// <summary> /// <para>Indicates failure when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent. </para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_FAIL /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_FAIL", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_FAIL = 0; /// <summary> /// <para>Indicates erroneous data when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use CHECK_VOICE_DATA_FAIL instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_BAD_DATA /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_BAD_DATA", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_BAD_DATA = -1; /// <summary> /// <para>Indicates missing resources when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use CHECK_VOICE_DATA_FAIL instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_MISSING_DATA /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_MISSING_DATA", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_MISSING_DATA = -2; /// <summary> /// <para>Indicates missing storage volume when checking the installation status of the resources used by the TextToSpeech engine with the ACTION_CHECK_TTS_DATA intent.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use CHECK_VOICE_DATA_FAIL instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// CHECK_VOICE_DATA_MISSING_VOLUME /// </java-name> [Dot42.DexImport("CHECK_VOICE_DATA_MISSING_VOLUME", "I", AccessFlags = 25)] public const int CHECK_VOICE_DATA_MISSING_VOLUME = -3; /// <summary> /// <para>Activity Action: Triggers the platform TextToSpeech engine to start the activity that installs the resource files on the device that are required for TTS to be operational. Since the installation of the data can be interrupted or declined by the user, the application shouldn't expect successful installation upon return from that intent, and if need be, should check installation status with ACTION_CHECK_TTS_DATA. </para> /// </summary> /// <java-name> /// ACTION_INSTALL_TTS_DATA /// </java-name> [Dot42.DexImport("ACTION_INSTALL_TTS_DATA", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_INSTALL_TTS_DATA = "android.speech.tts.engine.INSTALL_TTS_DATA"; /// <summary> /// <para>Broadcast Action: broadcast to signal the change in the list of available languages or/and their features. </para> /// </summary> /// <java-name> /// ACTION_TTS_DATA_INSTALLED /// </java-name> [Dot42.DexImport("ACTION_TTS_DATA_INSTALLED", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_TTS_DATA_INSTALLED = "android.speech.tts.engine.TTS_DATA_INSTALLED"; /// <summary> /// <para>Activity Action: Starts the activity from the platform TextToSpeech engine to verify the proper installation and availability of the resource files on the system. Upon completion, the activity will return one of the following codes: CHECK_VOICE_DATA_PASS, CHECK_VOICE_DATA_FAIL, </para><para>Moreover, the data received in the activity result will contain the following fields: <ul><li><para>EXTRA_AVAILABLE_VOICES which contains an ArrayList&lt;String&gt; of all the available voices. The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). </para></li><li><para>EXTRA_UNAVAILABLE_VOICES which contains an ArrayList&lt;String&gt; of all the unavailable voices (ones that user can install). The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). </para></li></ul></para> /// </summary> /// <java-name> /// ACTION_CHECK_TTS_DATA /// </java-name> [Dot42.DexImport("ACTION_CHECK_TTS_DATA", "Ljava/lang/String;", AccessFlags = 25)] public const string ACTION_CHECK_TTS_DATA = "android.speech.tts.engine.CHECK_TTS_DATA"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine specifies the path to its resources.</para><para>It may be used by language packages to find out where to put their data.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>TTS engine implementation detail, this information has no use for text-to-speech API client. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_VOICE_DATA_ROOT_DIRECTORY /// </java-name> [Dot42.DexImport("EXTRA_VOICE_DATA_ROOT_DIRECTORY", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_VOICE_DATA_ROOT_DIRECTORY = "dataRoot"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine specifies the file names of its resources under the resource path.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>TTS engine implementation detail, this information has no use for text-to-speech API client. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_VOICE_DATA_FILES /// </java-name> [Dot42.DexImport("EXTRA_VOICE_DATA_FILES", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_VOICE_DATA_FILES = "dataFiles"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine specifies the locale associated with each resource file.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>TTS engine implementation detail, this information has no use for text-to-speech API client. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_VOICE_DATA_FILES_INFO /// </java-name> [Dot42.DexImport("EXTRA_VOICE_DATA_FILES_INFO", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_VOICE_DATA_FILES_INFO = "dataFilesInfo"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine returns an ArrayList&lt;String&gt; of all the available voices. The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). </para> /// </summary> /// <java-name> /// EXTRA_AVAILABLE_VOICES /// </java-name> [Dot42.DexImport("EXTRA_AVAILABLE_VOICES", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_AVAILABLE_VOICES = "availableVoices"; /// <summary> /// <para>Extra information received with the ACTION_CHECK_TTS_DATA intent result where the TextToSpeech engine returns an ArrayList&lt;String&gt; of all the unavailable voices. The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE"). </para> /// </summary> /// <java-name> /// EXTRA_UNAVAILABLE_VOICES /// </java-name> [Dot42.DexImport("EXTRA_UNAVAILABLE_VOICES", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_UNAVAILABLE_VOICES = "unavailableVoices"; /// <summary> /// <para>Extra information sent with the ACTION_CHECK_TTS_DATA intent where the caller indicates to the TextToSpeech engine which specific sets of voice data to check for by sending an ArrayList&lt;String&gt; of the voices that are of interest. The format of each voice is: lang-COUNTRY-variant where COUNTRY and variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Redundant functionality, checking for existence of specific sets of voice data can be done on client side. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_CHECK_VOICE_DATA_FOR /// </java-name> [Dot42.DexImport("EXTRA_CHECK_VOICE_DATA_FOR", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_CHECK_VOICE_DATA_FOR = "checkVoiceDataFor"; /// <summary> /// <para>Extra information received with the ACTION_TTS_DATA_INSTALLED intent result. It indicates whether the data files for the synthesis engine were successfully installed. The installation was initiated with the ACTION_INSTALL_TTS_DATA intent. The possible values for this extra are TextToSpeech#SUCCESS and TextToSpeech#ERROR.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>No longer in use. If client ise interested in information about what changed, is should send ACTION_CHECK_TTS_DATA intent to discover available voices. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// EXTRA_TTS_DATA_INSTALLED /// </java-name> [Dot42.DexImport("EXTRA_TTS_DATA_INSTALLED", "Ljava/lang/String;", AccessFlags = 25)] public const string EXTRA_TTS_DATA_INSTALLED = "dataInstalled"; /// <summary> /// <para>Parameter key to specify the audio stream type to be used when speaking text or playing back a file. The value should be one of the STREAM_ constants defined in AudioManager.</para><para><para>TextToSpeech::speak(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::playEarcon(String, int, HashMap) </para></para> /// </summary> /// <java-name> /// KEY_PARAM_STREAM /// </java-name> [Dot42.DexImport("KEY_PARAM_STREAM", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PARAM_STREAM = "streamType"; /// <summary> /// <para>Parameter key to identify an utterance in the TextToSpeech.OnUtteranceCompletedListener after text has been spoken, a file has been played back or a silence duration has elapsed.</para><para><para>TextToSpeech::speak(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::playEarcon(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::synthesizeToFile(String, HashMap, String) </para></para> /// </summary> /// <java-name> /// KEY_PARAM_UTTERANCE_ID /// </java-name> [Dot42.DexImport("KEY_PARAM_UTTERANCE_ID", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PARAM_UTTERANCE_ID = "utteranceId"; /// <summary> /// <para>Parameter key to specify the speech volume relative to the current stream type volume used when speaking text. Volume is specified as a float ranging from 0 to 1 where 0 is silence, and 1 is the maximum volume (the default behavior).</para><para><para>TextToSpeech::speak(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::playEarcon(String, int, HashMap) </para></para> /// </summary> /// <java-name> /// KEY_PARAM_VOLUME /// </java-name> [Dot42.DexImport("KEY_PARAM_VOLUME", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PARAM_VOLUME = "volume"; /// <summary> /// <para>Parameter key to specify how the speech is panned from left to right when speaking text. Pan is specified as a float ranging from -1 to +1 where -1 maps to a hard-left pan, 0 to center (the default behavior), and +1 to hard-right.</para><para><para>TextToSpeech::speak(String, int, HashMap) </para><simplesectsep></simplesectsep><para>TextToSpeech::playEarcon(String, int, HashMap) </para></para> /// </summary> /// <java-name> /// KEY_PARAM_PAN /// </java-name> [Dot42.DexImport("KEY_PARAM_PAN", "Ljava/lang/String;", AccessFlags = 25)] public const string KEY_PARAM_PAN = "pan"; /// <java-name> /// this$0 /// </java-name> [Dot42.DexImport("this$0", "Landroid/speech/tts/TextToSpeech;", AccessFlags = 4112)] internal readonly global::Android.Speech.Tts.TextToSpeech This_0; [Dot42.DexImport("<init>", "(Landroid/speech/tts/TextToSpeech;)V", AccessFlags = 1)] public Engine(global::Android.Speech.Tts.TextToSpeech textToSpeech) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Engine() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Listener that will be called when the TTS service has completed synthesizing an utterance. This is only called if the utterance has an utterance ID (see TextToSpeech.Engine#KEY_PARAM_UTTERANCE_ID).</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use UtteranceProgressListener instead. </para></xrefdescription></xrefsect></para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech$OnUtteranceCompletedListener /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech$OnUtteranceCompletedListener", AccessFlags = 1545)] public partial interface IOnUtteranceCompletedListener /* scope: __dot42__ */ { /// <summary> /// <para>Called when an utterance has been synthesized.</para><para></para> /// </summary> /// <java-name> /// onUtteranceCompleted /// </java-name> [Dot42.DexImport("onUtteranceCompleted", "(Ljava/lang/String;)V", AccessFlags = 1025)] void OnUtteranceCompleted(string utteranceId) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Interface definition of a callback to be invoked indicating the completion of the TextToSpeech engine initialization. </para> /// </summary> /// <java-name> /// android/speech/tts/TextToSpeech$OnInitListener /// </java-name> [Dot42.DexImport("android/speech/tts/TextToSpeech$OnInitListener", AccessFlags = 1545)] public partial interface IOnInitListener /* scope: __dot42__ */ { /// <summary> /// <para>Called to signal the completion of the TextToSpeech engine initialization.</para><para></para> /// </summary> /// <java-name> /// onInit /// </java-name> [Dot42.DexImport("onInit", "(I)V", AccessFlags = 1025)] void OnInit(int status) /* MethodBuilder.Create */ ; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Tools.ToolDialog // Description: The tool dialog to be used by tools. It get populated by DialogElements once it is created // // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is Toolbox.dll for the DotSpatial 4.6/6 ToolManager project // // The Initializeializeial Developer of this Original Code is Brian Marchionni. Created in Oct, 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using DotSpatial.Data; using DotSpatial.Modeling.Forms.Elements; using DotSpatial.Modeling.Forms.Parameters; namespace DotSpatial.Modeling.Forms { /// <summary> /// A generic form that works with the various dialog elements in order to create a fully working process. /// </summary> public partial class ToolDialog : Form { #region Constants and Fields private List<DataSetArray> _dataSets = new List<DataSetArray>(); private int _elementHeight = 3; private Extent _extent; private List<DialogElement> _listOfDialogElements = new List<DialogElement>(); private ITool _tool; private IContainer components = null; #endregion #region Constructors and Destructors /// <summary> /// The constructor for the ToolDialog /// </summary> /// <param name="tool">The ITool to create the dialog box for</param> /// <param name="dataSets">The list of available DataSets available</param> /// <param name="mapExtent">Creates a new instance of the tool dialog with map extent.</param> public ToolDialog(ITool tool, List<DataSetArray> dataSets, Extent mapExtent) { // Required by the designer InitializeComponent(); DataSets = dataSets; _extent = mapExtent; Initialize(tool); } /// <summary> /// The constructor for the ToolDialog /// </summary> /// <param name="tool">The ITool to create the dialog box for</param> /// <param name="modelElements">A list of all model elements</param> public ToolDialog(ITool tool, IEnumerable<ModelElement> modelElements) { // Required by the designer InitializeComponent(); // We store all the element names here and extract the datasets foreach (ModelElement me in modelElements) { if (me as DataElement != null) { bool addData = true; foreach (Parameter par in tool.OutputParameters) { if (par.ModelName == (me as DataElement).Parameter.ModelName) { addData = false; } break; } if (addData) { _dataSets.Add(new DataSetArray(me.Name, (me as DataElement).Parameter.Value as IDataSet)); } } } Initialize(tool); } #endregion #region Public Properties /// <summary> /// Returns a list of IDataSet that are available in the ToolDialog excluding any of its own outputs. /// </summary> public List<DataSetArray> DataSets { get { return _dataSets; } set { _dataSets = value; } } /// <summary> /// Gets the status of the tool /// </summary> public ToolStatus ToolStatus { get { foreach (DialogElement de in _listOfDialogElements) { if (de.Status != ToolStatus.Ok) { return ToolStatus.Error; } } return ToolStatus.Ok; } } #endregion #region Methods /// <summary> /// This adds the Elements to the form incrementally lower down /// </summary> /// <param name="element">The element to add</param> private void AddElement(DialogElement element) { _listOfDialogElements.Add(element); panelElementContainer.Controls.Add(element); element.Clicked += ElementClicked; element.Location = new Point(5, _elementHeight); _elementHeight = element.Height + _elementHeight; } /// <summary> /// When one of the DialogElements is clicked this event fires to populate the help /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ElementClicked(object sender, EventArgs e) { DialogElement element = sender as DialogElement; if (element == null) { PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage); } else if (element.Param == null) { PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage); } else if (element.Param.HelpText == string.Empty) { PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage); } else { PopulateHelp(element.Param.Name, element.Param.HelpText, element.Param.HelpImage); } } /// <summary> /// The constructor for the ToolDialog /// </summary> /// <param name="tool">The ITool to create the dialog box for</param> private void Initialize(ITool tool) { SuspendLayout(); // Generates the form based on what inputs the ITool has _tool = tool; Text = tool.Name; // Sets up the help link if (string.IsNullOrEmpty(tool.HelpUrl)) { helpHyperlink.Visible = false; } else { helpHyperlink.Links[0].LinkData = tool.HelpUrl; helpHyperlink.Links.Add(0, helpHyperlink.Text.Length, tool.HelpUrl); } // Sets-up the icon for the Dialog Icon = Images.HammerSmall; panelToolIcon.BackgroundImage = tool.Icon ?? Images.Hammer; DialogSpacerElement inputSpacer = new DialogSpacerElement(); inputSpacer.Text = ModelingMessageStrings.Input; AddElement(inputSpacer); // Populates the dialog with input elements PopulateInputElements(); DialogSpacerElement outputSpacer = new DialogSpacerElement(); outputSpacer.Text = ModelingMessageStrings.Output; AddElement(outputSpacer); // Populates the dialog with output elements PopulateOutputElements(); // Populate the help text PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage); ResumeLayout(); } /// <summary> /// Fires when a parameter is changed /// </summary> /// <param name="sender"></param> private void ParamValueChanged(Parameter sender) { _tool.ParameterChanged(sender); } /// <summary> /// This adds a Bitmap to the help section. /// </summary> /// <param name="title">The text to appear in the help box.</param> /// <param name="body">The title to appear in the help box.</param> /// <param name="image">The bitmap to appear at the bottom of the help box.</param> private void PopulateHelp(String title, String body, Image image) { rtbHelp.Text = string.Empty; rtbHelp.Size = new Size(0, 0); // Add the Title Font fBold = new Font("Tahoma", 14, FontStyle.Bold); rtbHelp.SelectionFont = fBold; rtbHelp.SelectionColor = Color.Black; rtbHelp.SelectedText = title + "\r\n\r\n"; // Add the text body fBold = new Font("Tahoma", 8, FontStyle.Bold); rtbHelp.SelectionFont = fBold; rtbHelp.SelectionColor = Color.Black; rtbHelp.SelectedText = body; rtbHelp.Size = new Size(rtbHelp.Width, rtbHelp.GetPositionFromCharIndex(rtbHelp.Text.Length).Y + 30); // Add the image to the bottom if (image != null) { pnlHelpImage.Visible = true; if (image.Size.Width > 250) { double height = image.Size.Height; double width = image.Size.Width; int newHeight = Convert.ToInt32(250 * (height / width)); pnlHelpImage.BackgroundImage = new Bitmap(image, new Size(250, newHeight)); pnlHelpImage.Size = new Size(250, newHeight); } else { pnlHelpImage.BackgroundImage = image; pnlHelpImage.Size = image.Size; } } else { pnlHelpImage.Visible = false; pnlHelpImage.BackgroundImage = null; pnlHelpImage.Size = new Size(0, 0); } } /// <summary> /// Adds Elements to the dialog based on what input Parameter the ITool contains /// </summary> private void PopulateInputElements() { // Loops through all the Parameter in the tool and generated their element foreach (Parameter param in _tool.InputParameters) { // We make sure that the input parameter is defined if (param == null) { continue; } // We add an event handler that fires if the parameter is changed param.ValueChanged += ParamValueChanged; ExtentParam p = param as ExtentParam; if (p != null && p.DefaultToMapExtent) { p.Value = _extent; } // Retrieve the dialog element from the parameter and add it to the dialog AddElement(param.InputDialogElement(DataSets)); } } /// <summary> /// Adds Elements to the dialog based on what output Parameter the ITool contains /// </summary> private void PopulateOutputElements() { if (_tool.OutputParameters == null) { return; } // Loops through all the Parameter in the tool and generated their element foreach (Parameter param in _tool.OutputParameters) { // We add an event handler that fires if the parameter is changed param.ValueChanged += ParamValueChanged; // Retrieve the dialog element from the parameter and add it to the dialog AddElement(param.OutputDialogElement(DataSets)); } } /// <summary> /// When the user clicks Cancel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; return; } /// <summary> /// When the user clicks OK /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOK_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } /// <summary> /// When the hyperlink is clicked this event fires. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void helpHyperlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Determine which link was clicked within the LinkLabel. helpHyperlink.Links[helpHyperlink.Links.IndexOf(e.Link)].Visited = true; // Display the appropriate link based on the value of the // LinkData property of the Link object. string target = e.Link.LinkData as string; Process.Start(target); } /// <summary> /// If the user clicks out side of one of the tool elements /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void otherElement_Click(object sender, EventArgs e) { PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage); } /// <summary> /// When the size of the help panel changes this event fires to move stuff around. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void panelHelp_SizeChanged(object sender, EventArgs e) { rtbHelp.Size = new Size(rtbHelp.Width, rtbHelp.GetPositionFromCharIndex(rtbHelp.Text.Length).Y + 30); } #endregion } }
using NUnit.Framework; using Rhino.Mocks; namespace Spring.Transaction.Support { [TestFixture] public class AbstractPlatformTransactionManagerTests { private MockTxnPlatformMgrAbstract _mockTxnMgr; [SetUp] public void Init() { _mockTxnMgr = new MockTxnPlatformMgrAbstract(); _mockTxnMgr.TransactionSynchronization = TransactionSynchronizationState.Always; if (TransactionSynchronizationManager.SynchronizationActive) { TransactionSynchronizationManager.ClearSynchronization(); } } [TearDown] public void Destroy() { _mockTxnMgr = null; if (TransactionSynchronizationManager.SynchronizationActive) { TransactionSynchronizationManager.Clear(); } } [Test] public void VanillaProperties() { Assert.AreEqual(TransactionSynchronizationState.Always, _mockTxnMgr.TransactionSynchronization); Assert.IsTrue(!_mockTxnMgr.NestedTransactionsAllowed); Assert.IsTrue(!_mockTxnMgr.RollbackOnCommitFailure); _mockTxnMgr.NestedTransactionsAllowed = true; _mockTxnMgr.RollbackOnCommitFailure = true; _mockTxnMgr.TransactionSynchronization = TransactionSynchronizationState.OnActualTransaction; Assert.AreEqual(TransactionSynchronizationState.OnActualTransaction, _mockTxnMgr.TransactionSynchronization); Assert.IsTrue(_mockTxnMgr.NestedTransactionsAllowed); Assert.IsTrue(_mockTxnMgr.RollbackOnCommitFailure); } [Test] [ExpectedException(typeof (InvalidTimeoutException), ExpectedMessage = "Invalid transaction timeout")] public void DefinitionInvalidTimeoutException() { MockTxnDefinition def = new MockTxnDefinition(); def.TransactionTimeout = -1000; _mockTxnMgr.GetTransaction(def); } [Test] [ExpectedException(typeof (IllegalTransactionStateException), ExpectedMessage = "Transaction propagation 'mandatory' but no existing transaction found")] public void DefinitionInvalidPropagationState() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Mandatory; _mockTxnMgr.GetTransaction(def); } [Test] [ExpectedException(typeof (IllegalTransactionStateException), ExpectedMessage = "Transaction propagation 'never' but existing transaction found.")] public void NeverPropagateState() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Never; SetGeneralGetTransactionExpectations(); _mockTxnMgr.GetTransaction(def); AssertVanillaGetTransactionExpectations(); } [Test] [ExpectedException(typeof (NestedTransactionNotSupportedException), ExpectedMessage = "Transaction manager does not allow nested transactions by default - specify 'NestedTransactionsAllowed' property with value 'true'")] public void NoNestedTransactionsAllowed() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Nested; SetGeneralGetTransactionExpectations(); _mockTxnMgr.GetTransaction(def); AssertVanillaGetTransactionExpectations(); } [Test] public void TransactionSuspendedSuccessfully() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.NotSupported; def.ReadOnly = false; SetGeneralGetTransactionExpectations(); DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(def); Assert.IsNull(status.Transaction); Assert.IsTrue(!status.IsNewTransaction); Assert.IsTrue(status.NewSynchronization); Assert.IsTrue(!status.ReadOnly); Assert.IsNotNull(status.SuspendedResources); AssertVanillaGetTransactionExpectations(); } [Test] public void TransactionCreatedSuccessfully() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.RequiresNew; def.ReadOnly = false; SetGeneralGetTransactionExpectations(); DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(def); Assert.AreEqual(_mockTxnMgr.Transaction, status.Transaction); Assert.IsTrue(status.IsNewTransaction); Assert.IsTrue(status.NewSynchronization); Assert.IsTrue(!status.ReadOnly); Assert.IsNotNull(status.SuspendedResources); AssertVanillaGetTransactionExpectations(); } [Test] public void NestedTransactionSuccessfully() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Nested; def.ReadOnly = false; SetGeneralGetTransactionExpectations(); _mockTxnMgr.Savepoints = false; _mockTxnMgr.NestedTransactionsAllowed = true; DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(def); Assert.AreEqual(_mockTxnMgr.Transaction, status.Transaction); Assert.IsTrue(status.IsNewTransaction); Assert.AreEqual(true, status.NewSynchronization); Assert.IsTrue(!status.ReadOnly); Assert.IsNull(status.SuspendedResources); AssertVanillaGetTransactionExpectations(); Assert.AreEqual(1, _mockTxnMgr.DoBeginCallCount); } [Test] public void NestedTransactionWithSavepoint() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Nested; def.ReadOnly = false; ISavepointManager saveMgr = MockRepository.GenerateMock<ISavepointManager>(); _mockTxnMgr.SetTransaction(saveMgr); _mockTxnMgr.Savepoints = true; _mockTxnMgr.NestedTransactionsAllowed = true; DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(def); Assert.AreEqual(_mockTxnMgr.Transaction, status.Transaction); Assert.IsFalse(status.IsNewTransaction); Assert.IsFalse(status.NewSynchronization); Assert.IsTrue(!status.ReadOnly); Assert.IsNull(status.SuspendedResources); AssertVanillaGetTransactionExpectations(); Assert.AreEqual(0, _mockTxnMgr.DoBeginCallCount); } [Test] public void DefaultPropagationBehavior() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Required; def.ReadOnly = true; SetGeneralGetTransactionExpectations(); DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(def); Assert.AreEqual(_mockTxnMgr.Transaction, status.Transaction); Assert.IsTrue(!status.IsNewTransaction); Assert.IsTrue(status.NewSynchronization); Assert.IsTrue(status.ReadOnly); Assert.IsNull(status.SuspendedResources); AssertVanillaGetTransactionExpectations(); } [Test] public void DefaultPropagationBehaviorWithNullDefinition() { SetGeneralGetTransactionExpectations(); DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(null); Assert.AreEqual(_mockTxnMgr.Transaction, status.Transaction); Assert.IsFalse(status.IsNewTransaction); Assert.IsTrue(status.NewSynchronization); Assert.IsFalse(status.ReadOnly); Assert.IsNull(status.SuspendedResources); AssertVanillaGetTransactionExpectations(); } [Test] public void DefaultNoExistingTransaction() { DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(null); Assert.IsNotNull(status.Transaction); Assert.IsTrue(status.IsNewTransaction); Assert.IsTrue(status.NewSynchronization); Assert.IsTrue(!status.ReadOnly); Assert.IsNull(status.SuspendedResources); Assert.AreEqual(1, _mockTxnMgr.DoBeginCallCount); AssertVanillaGetTransactionExpectations(); } [Test] public void DefaultBehaviorDefaultPropagationNoExistingTransaction() { MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Never; def.ReadOnly = true; DefaultTransactionStatus status = (DefaultTransactionStatus) _mockTxnMgr.GetTransaction(def); Assert.IsNull(status.Transaction); Assert.IsTrue(!status.IsNewTransaction); Assert.IsTrue(status.NewSynchronization); Assert.IsTrue(status.ReadOnly); Assert.IsNull(status.SuspendedResources); Assert.AreEqual(0, _mockTxnMgr.DoBeginCallCount); AssertVanillaGetTransactionExpectations(); } private void SetGeneralGetTransactionExpectations() { _mockTxnMgr.SetTransaction(new object()); } private void AssertVanillaGetTransactionExpectations() { Assert.AreEqual(1, _mockTxnMgr.DoGetTransactionCallCount); Assert.AreEqual(1, _mockTxnMgr.IsExistingTransactionCallCount); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Jasper.ErrorHandling; using Jasper.Logging; using Jasper.Persistence.Durability; using Jasper.Runtime.Handlers; using Jasper.Runtime.Routing; using Jasper.Runtime.Scheduled; using Jasper.Runtime.WorkerQueues; using Jasper.Serialization; using Jasper.Transports; using Jasper.Transports.Local; using Lamar; using LamarCodeGeneration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; namespace Jasper.Runtime { public class MessagingRoot : PooledObjectPolicy<ExecutionContext>, IMessagingRoot, IHostedService { private readonly IContainer _container; private readonly Lazy<IEnvelopePersistence> _persistence; private bool _hasStopped; public MessagingRoot(JasperOptions options, IMessageLogger messageLogger, IContainer container, ITransportLogger transportLogger) { Settings = options.Advanced; Options = options; Options.Serializers.Add(new NewtonsoftSerializer(Settings.JsonSerialization)); Handlers = options.HandlerGraph; TransportLogger = transportLogger; MessageLogger = messageLogger; var provider = container.GetInstance<ObjectPoolProvider>(); var pool = provider.Create(this); // TODO -- might make NoHandlerContinuation lazy! Pipeline = new HandlerPipeline(Handlers, MessageLogger, new NoHandlerContinuation(container.GetAllInstances<IMissingHandler>().ToArray(), this), this, pool); Runtime = new TransportRuntime(this); _persistence = new Lazy<IEnvelopePersistence>(container.GetInstance<IEnvelopePersistence>); Router = new EnvelopeRouter(this); Acknowledgements = new AcknowledgementSender(Router, this); _container = container; Cancellation = Settings.Cancellation; } public override ExecutionContext Create() { return new ExecutionContext(this); } public override bool Return(ExecutionContext context) { context.ClearState(); return true; } public DurabilityAgent Durability { get; private set; } public void Dispose() { if (_hasStopped) { StopAsync(Settings.Cancellation).GetAwaiter().GetResult(); } Settings.Cancel(); Runtime.Dispose(); ScheduledJobs.Dispose(); } public async Task StartAsync(CancellationToken cancellationToken) { try { await bootstrap(); } catch (Exception e) { MessageLogger.LogException(e, message: "Failed to start the Jasper messaging"); throw; } } public async Task StopAsync(CancellationToken cancellationToken) { if (_hasStopped) return; _hasStopped = true; // This is important! _container.As<Container>().DisposalLock = DisposalLock.Unlocked; if (Durability != null) await Durability.StopAsync(cancellationToken); Settings.Cancel(); } public IAcknowledgementSender Acknowledgements { get; } public ITransportRuntime Runtime { get; } public CancellationToken Cancellation { get; } public AdvancedSettings Settings { get; } public ITransportLogger TransportLogger { get; } public IScheduledJobProcessor ScheduledJobs { get; set; } public JasperOptions Options { get; } public IEnvelopeRouter Router { get; } public IHandlerPipeline Pipeline { get; } public IMessageLogger MessageLogger { get; } public IEnvelopePersistence Persistence => _persistence.Value; public IExecutionContext NewContext() { return new ExecutionContext(this); } public IExecutionContext ContextFor(Envelope envelope) { var context = new ExecutionContext(this); context.ReadEnvelope(envelope, InvocationCallback.Instance); return context; } public HandlerGraph Handlers { get; } private async Task bootstrap() { // Build up the message handlers await Handlers.Compiling; Handlers.Compile(Options.Advanced.CodeGeneration, _container); // If set, use pre-generated message handlers for quicker starts if (Options.Advanced.CodeGeneration.TypeLoadMode == TypeLoadMode.LoadFromPreBuiltAssembly) { await _container.GetInstance<DynamicCodeBuilder>().LoadPrebuiltTypes(); } // Start all the listeners and senders Runtime.As<TransportRuntime>().Initialize(); ScheduledJobs = new InMemoryScheduledJobProcessor((IWorkerQueue) Runtime.AgentForLocalQueue(TransportConstants.Replies)); // Bit of a hack, but it's necessary. Came up in compliance tests if (Persistence is NulloEnvelopePersistence p) p.ScheduledJobs = ScheduledJobs; switch (Settings.StorageProvisioning) { case StorageProvisioning.Rebuild: await Persistence.Admin.RebuildSchemaObjects(); break; case StorageProvisioning.Clear: await Persistence.Admin.ClearAllPersistedEnvelopes(); break; } await startDurabilityAgent(); } private async Task startDurabilityAgent() { // HOKEY, BUT IT WORKS if (_container.Model.DefaultTypeFor<IEnvelopePersistence>() != typeof(NulloEnvelopePersistence) && Options.Advanced.DurabilityAgentEnabled) { var durabilityLogger = _container.GetInstance<ILogger<DurabilityAgent>>(); // TODO -- use the worker queue for Retries? var worker = new DurableWorkerQueue(new LocalQueueSettings("scheduled"), Pipeline, Settings, Persistence, TransportLogger); Durability = new DurabilityAgent(TransportLogger, durabilityLogger, worker, Persistence, Runtime, Options.Advanced); await Durability.StartAsync(Options.Advanced.Cancellation); } } } }