context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Specialized; using System.Web; using System.Diagnostics.CodeAnalysis; namespace Scalider.Security.Otp { /// <summary> /// Provided the implementation to calculate HMAC-Based One-Time-Passwords (HOTP) from a secret key. /// </summary> /// <remarks> /// The specifications for this are found in RFC 4226 (http://tools.ietf.org/html/rfc4226) /// /// This implementation takes inspiration from OTPSharp /// (https://bitbucket.org/devinmartin/otp-sharp/src/default/) by Devin Martin /// </remarks> public sealed class HmacBasedOtpGenerator : OtpGenerator<long> { private const int kMinimumNumberOfDigits = 6; private const int kMaximumNumberOfDigits = 8; /// <summary> /// Initializes a new instance of the <see cref="HmacBasedOtpGenerator"/> class. /// </summary> /// <param name="secretKey">The secret key to use in OTP calculations.</param> /// <param name="hashMode">The hash mode to use when calculating and validating OTP.</param> /// <param name="numberOfDigits">The number of digits that the returning OTP should have. The default is 6.</param> public HmacBasedOtpGenerator([NotNull] byte[] secretKey, OtpHashMode hashMode = OtpHashMode.Sha1, int numberOfDigits = DefaultNumberOfDigits) : base(secretKey, OtpType.Hotp, hashMode, numberOfDigits) { if (numberOfDigits < 6 || numberOfDigits > 8) { // The given number of digits is not an allowed value for this OTP type throw new ArgumentOutOfRangeException( nameof(numberOfDigits), numberOfDigits, "Specified argument was out of the range of valid values." ); } } /// <summary> /// Generates a URI that can be used to link OTP generator to an application like Google Authenticator /// via directly linking it or by attaching it to a QRCode. /// </summary> /// <param name="counter">The current value of the counter.</param> /// <param name="accountName">The name of the account for the OTP URI.</param> /// <returns> /// The OTP URI. /// </returns> /// <remarks> /// https://github.com/google/google-authenticator/wiki/Key-Uri-Format /// </remarks> public string ToUri(long counter, string accountName) => ToUri(counter, accountName, default!); /// <summary> /// Generates a URI that can be used to link OTP generator to an application like Google Authenticator /// via directly linking it or by attaching it to a QRCode. /// </summary> /// <param name="counter">The current value of the counter.</param> /// <param name="accountName">The name of the account for the OTP URI.</param> /// <param name="issuer">The issuer for the OTP URI. This parameter is optional but it is /// strongly recommended.</param> /// <returns> /// The OTP URI. /// </returns> /// <remarks> /// https://github.com/google/google-authenticator/wiki/Key-Uri-Format /// </remarks> public string ToUri(long counter, [NotNull] string accountName, string issuer) => ToUri(accountName, issuer, new NameValueCollection {{"counter", counter.ToString()}}); #region TryParse /// <summary> /// Creates a new <see cref="HmacBasedOtpGenerator"/> using the provided <paramref name="uri"/>. /// </summary> /// <param name="uri">The string representing the OTP URI.</param> /// <param name="result">>When this method returns <c>true</c>, the created /// <see cref="HmacBasedOtpGenerator"/>; otherwise, <c>null</c>.</param> /// <returns> /// <c>true</c> if we were able to create the new <see cref="HmacBasedOtpGenerator"/> instance from /// the given <paramref name="uri"/>; otherwise, <c>false</c>. /// </returns> public static bool TryCreate([NotNull] string uri, [MaybeNullWhen(false)] out HmacBasedOtpGenerator result) => TryCreate(uri, out result, out _, out _, out _); /// <summary> /// Creates a new <see cref="HmacBasedOtpGenerator"/> using the provided <paramref name="uri"/>. /// </summary> /// <param name="uri">The string representing the OTP URI.</param> /// <param name="result">>When this method returns <c>true</c>, the created /// <see cref="HmacBasedOtpGenerator"/>; otherwise, <c>null</c>.</param> /// <param name="initialCounter">When this method returns <c>true</c> and the initial counter parameter /// is available, the value of the counter parameter; otherwise, <c>0</c>.</param> /// <param name="accountName">When this method returns <c>true</c>, the account name part of the label; /// otherwise, <c>null</c>.</param> /// <param name="issuer">When this method returns <c>true</c>, the issuer prefix of the label, or the /// issuer parameter, if the label doesn't have an issuer prefix; otherwise, <c>null</c></param> /// <returns> /// <c>true</c> if we were able to create the new <see cref="HmacBasedOtpGenerator"/> instance from /// the given <paramref name="uri"/>; otherwise, <c>false</c>. /// </returns> public static bool TryCreate(string uri, [MaybeNullWhen(false)] out HmacBasedOtpGenerator result, out long initialCounter, [MaybeNullWhen(false)] out string accountName, [MaybeNull] out string issuer) { result = null; initialCounter = 0; accountName = null; issuer = null; return !string.IsNullOrWhiteSpace(uri) && TryCreate(uri.AsSpan(), out result, out initialCounter, out accountName, out issuer); } /// <summary> /// Creates a new <see cref="HmacBasedOtpGenerator"/> using the provided <paramref name="uri"/>. /// </summary> /// <param name="uri">A span containing the string representing the OTP URI.</param> /// <param name="result">>When this method returns <c>true</c>, the created /// <see cref="HmacBasedOtpGenerator"/>; otherwise, <c>null</c>.</param> /// <returns> /// <c>true</c> if we were able to create the new <see cref="HmacBasedOtpGenerator"/> instance from /// the given <paramref name="uri"/>; otherwise, <c>false</c>. /// </returns> public static bool TryCreate(ReadOnlySpan<char> uri, [MaybeNullWhen(false)] out HmacBasedOtpGenerator result) => TryCreate(uri, out result, out _, out _, out _); /// <summary> /// Creates a new <see cref="HmacBasedOtpGenerator"/> using the provided <paramref name="uri"/>. /// </summary> /// <param name="uri">A span containing the string representing the OTP URI.</param> /// <param name="result">>When this method returns <c>true</c>, the created /// <see cref="HmacBasedOtpGenerator"/>; otherwise, <c>null</c>.</param> /// <param name="initialCounter">When this method returns <c>true</c> and the initial counter parameter /// is available, the value of the counter parameter; otherwise, <c>0</c>.</param> /// <param name="accountName">When this method returns <c>true</c>, the account name part of the label; /// otherwise, <c>null</c>.</param> /// <param name="issuer">When this method returns <c>true</c>, the issuer prefix of the label, or the /// issuer parameter, if the label doesn't have an issuer prefix; otherwise, <c>null</c></param> /// <returns> /// <c>true</c> if we were able to create the new <see cref="HmacBasedOtpGenerator"/> instance from /// the given <paramref name="uri"/>; otherwise, <c>false</c>. /// </returns> public static bool TryCreate(ReadOnlySpan<char> uri, [MaybeNullWhen(false)] out HmacBasedOtpGenerator result, out long initialCounter, [MaybeNullWhen(false)] out string accountName, [MaybeNull] out string issuer) { result = null; initialCounter = 0; accountName = null; issuer = null; if (!HasValidSchemeForType(uri, OtpType.Hotp, out var uriWithoutScheme)) return false; // An OTP URI have several parameters, including the secret key, as query string parameters, // as some of these values are mandatory, we need to determine whether the query string part // is present on the URI if (!TrySliceLabelAndParameters(uriWithoutScheme, out var labelAccountName, out var labelIssuer, out var parametersPart)) { // We were unable to successfully slice the OTP label and the query string from the given URI return false; } // Determine whether all the parameters were provided on the URI var parameters = HttpUtility.ParseQueryString(parametersPart.ToString()); var secretKeyStr = parameters["secret"]; if (string.IsNullOrWhiteSpace(secretKeyStr) || !Base32.TryFromBase32String(secretKeyStr, out var secretKey) || secretKey == null || secretKey.Length == 0) { // The URI doesn't have a valid secret key on the parameters return false; } // Determine whether the hash mode (the algorithm parameter) is present var hashMode = OtpHashMode.Sha1; var algorithmStr = parameters["algorithm"]; if (!string.IsNullOrWhiteSpace(algorithmStr)) { // We are only going to try to parse the OTP hash mode (the algorithm parameter) when it is present if (Enum.TryParse<OtpHashMode>(algorithmStr, true, out var algorithm)) { // And will only override the default hash mode when the provided value is a valid OtpHashMode hashMode = algorithm; } } // Determine whether the number of digits is present and is within the allowed range var numberOfDigits = DefaultNumberOfDigits; var digitsStr = parameters["digits"]; if (!string.IsNullOrWhiteSpace(digitsStr) && int.TryParse(digitsStr, out var digits)) { // Determine whether the given number of digits is in the allowed range if (digits < kMinimumNumberOfDigits || digits > kMaximumNumberOfDigits) { // The given number of digits isn't in the allowed range, we are going to // consider this an invalid URI return false; } numberOfDigits = digits; } // Determine whether the issuer was provided on the URI parameters if (!GetMostSuitableIssuer(labelIssuer, parameters, out issuer)) { // There seems to be an issue with the issuer on the OTP URI return false; } // Finally, we can try to retrieve the initial counter from the given URI var counterStr = parameters["counter"]; if (!string.IsNullOrWhiteSpace(counterStr) && long.TryParse(counterStr, out initialCounter)) { // The initial counter was present in the URI and we were able to parse it, lets // prevent it to be negative! if (initialCounter < 0) initialCounter = 0; } // Done result = new HmacBasedOtpGenerator(secretKey.ToArray(), hashMode, numberOfDigits); accountName = labelAccountName; return true; } #endregion /// <inheritdoc /> protected override long CalculateStep(long value) => value; } }
/* Copyright 2013 Esri Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; namespace ESRI.ArcGIS.SilverlightMapApp { /// <summary> /// Resizable and draggable custom window control /// </summary> [TemplatePart(Name = "btnClose", Type = typeof(Button))] //Close button [TemplatePart(Name = "TopBar", Type = typeof(UIElement))] //top bar / area used for dragging the window [TemplatePart(Name = "ResizeWidth", Type = typeof(UIElement))] //area used for resizing the window [TemplatePart(Name = "ResizeHeight", Type = typeof(UIElement))] // area used for resizing the window [TemplatePart(Name = "ResizeCorner", Type = typeof(UIElement))] //area used for resizing the window [TemplatePart(Name = "TitleText", Type = typeof(TextBlock))] [TemplatePart(Name = "ContentBorder", Type = typeof(Border))] [TemplateVisualState(GroupName = "CommonStates", Name = "Normal")] [TemplateVisualState(GroupName = "CommonStates", Name = "MouseOver")] [TemplateVisualState(GroupName = "CommonStates", Name = "Dragging")] [TemplateVisualState(GroupName = "CommonStates", Name = "Focus")] [ContentProperty("Content")] public class DraggableWindow : ContentControl { UIElement topbar; UIElement ResizeWidth; UIElement ResizeHeight; UIElement ResizeCorner; Border contentBorder; Point lastPoint; TextBlock titleText; Button btnClose; bool isMouseOver = false; bool isDragging = false; bool hasFocus = false; bool hideHeader = false; public DraggableWindow() { DefaultStyleKey = typeof(DraggableWindow); //this.MouseEnter += (s, e) => { this.isMouseOver = true; ChangeVisualState(true); }; //this.MouseLeave += (s, e) => { this.isMouseOver = false; ChangeVisualState(true); }; //this.GotFocus += (s, e) => { this.hasFocus = true; ChangeVisualState(true); }; //this.LostFocus += (s, e) => { this.hasFocus = false; ChangeVisualState(true); }; } /// <summary> /// When overridden in a derived class, is invoked whenever application code or /// internal processes (such as a rebuilding layout pass) call /// <see cref="M:System.Windows.Controls.Control.ApplyTemplate"/>. /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); contentBorder = GetTemplateChild("ContentBorder") as Border; if (contentBorder != null) contentBorder.Background = ContentBackground; btnClose = GetTemplateChild("btnClose") as Button; if (btnClose != null) { btnClose.Click += (s, e) => { this.IsOpen = false; }; showCloseButton(IsCloseButtonVisible); } topbar = GetTemplateChild("TopBar") as UIElement; if (topbar != null) { topbar.MouseLeftButtonDown += topbar_MouseLeftButtonDown; } this.RenderTransform = new TranslateTransform(); ResizeWidth = GetTemplateChild("ResizeWidth") as UIElement; ResizeHeight = GetTemplateChild("ResizeHeight") as UIElement; ResizeCorner = GetTemplateChild("ResizeCorner") as UIElement; if (ResizeWidth != null) { ResizeWidth.MouseLeftButtonDown += Resize_MouseLeftButtonDown; ResizeWidth.IsHitTestVisible = IsWidthResizeable; } if (ResizeHeight != null) { ResizeHeight.MouseLeftButtonDown += Resize_MouseLeftButtonDown; ResizeHeight.IsHitTestVisible = IsHeightResizeable; } if (ResizeCorner != null) { ResizeCorner.MouseLeftButtonDown += Resize_MouseLeftButtonDown; ResizeCorner.IsHitTestVisible = IsWidthResizeable && IsHeightResizeable; } titleText = GetTemplateChild("TitleText") as TextBlock; if (!IsHeaderVisible) { if (topbar != null) topbar.Visibility = Visibility.Collapsed; if (btnClose != null) btnClose.Visibility = Visibility.Collapsed; if (titleText != null) titleText.Visibility = Visibility.Collapsed; } ChangeVisualState(false); } bool resizingWidth; bool resizingBoth; public void showCloseButton(bool show) { if (btnClose != null) { btnClose.Visibility = show ? Visibility.Visible : Visibility.Collapsed; } } private void Resize_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { resizingBoth = (sender == ResizeCorner); resizingWidth = (sender == ResizeWidth); if (resizingBoth && double.IsNaN(this.Width) && double.IsNaN(this.Height)) return; else if (resizingWidth && double.IsNaN(this.Width)) return; //not supported/disabled else if (!resizingWidth && double.IsNaN(this.Height)) return; //not supported/disabled lastPoint = e.GetPosition(this.Parent as UIElement); Application.Current.RootVisual.MouseMove += Resize_MouseMove; Application.Current.RootVisual.MouseLeftButtonUp += Resize_MouseLeftButtonUp; Application.Current.RootVisual.MouseLeave += Resize_MouseLeave; e.Handled = true; } private void Resize_MouseMove(object sender, MouseEventArgs e) { Point p2 = e.GetPosition(this.Parent as UIElement); if (resizingBoth) { double d = p2.X - lastPoint.X; this.Width += d; if (this.HorizontalAlignment == HorizontalAlignment.Center) this.HorizontalOffset += d / 2; else if (this.HorizontalAlignment == HorizontalAlignment.Right) this.HorizontalOffset += d; d = p2.Y - lastPoint.Y; this.Height += d; if (this.VerticalAlignment == VerticalAlignment.Bottom) this.VerticalOffset += d; else if (this.VerticalAlignment == VerticalAlignment.Center) this.VerticalOffset += d / 2; } else if (resizingWidth) { double d = p2.X - lastPoint.X; this.Width += d; if (this.HorizontalAlignment == HorizontalAlignment.Center) this.HorizontalOffset += d / 2; else if (this.HorizontalAlignment == HorizontalAlignment.Right) this.HorizontalOffset += d; } else { double d = p2.Y - lastPoint.Y; this.Height += d; if (this.VerticalAlignment == VerticalAlignment.Bottom) this.VerticalOffset += d; else if (this.VerticalAlignment == VerticalAlignment.Center) this.VerticalOffset += d / 2; } lastPoint = p2; } private void Resize_MouseLeave(object sender, MouseEventArgs e) { StopResize(); } private void Resize_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { StopResize(); } private void StopResize() { Application.Current.RootVisual.MouseMove -= Resize_MouseMove; Application.Current.RootVisual.MouseLeftButtonUp -= Resize_MouseLeftButtonUp; Application.Current.RootVisual.MouseLeave -= Resize_MouseLeave; } /// <summary> /// Starts tragging window drag /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param> private void topbar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (!IsDraggable) return; lastPoint = e.GetPosition(this.Parent as UIElement); topbar.CaptureMouse(); topbar.MouseMove += RootVisual_MouseMove; topbar.MouseLeftButtonUp += RootVisual_MouseLeftButtonUp; topbar.LostMouseCapture += topbar_LostMouseCapture; //topbar.MouseLeave += RootVisual_MouseLeave; e.Handled = true; } void topbar_LostMouseCapture(object sender, MouseEventArgs e) { StopDrag(); } private void RootVisual_MouseLeave(object sender, MouseEventArgs e) { StopDrag(); } private void RootVisual_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { StopDrag(); } /// <summary> /// Stops tracking window drag. /// </summary> private void StopDrag() { isDragging = false; topbar.ReleaseMouseCapture(); topbar.MouseMove -= RootVisual_MouseMove; topbar.MouseLeftButtonUp -= RootVisual_MouseLeftButtonUp; topbar.LostMouseCapture -= topbar_LostMouseCapture; // Application.Current.RootVisual.MouseLeave -= RootVisual_MouseLeave; ChangeVisualState(true); } private void RootVisual_MouseMove(object sender, MouseEventArgs e) { isDragging = true; ChangeVisualState(true); TranslateTransform t = this.RenderTransform as TranslateTransform; Point p2 = e.GetPosition(this.Parent as UIElement); double dX = p2.X - lastPoint.X; double dY = p2.Y - lastPoint.Y; HorizontalOffset += dX; VerticalOffset += dY; lastPoint = p2; } private void ChangeVisualState(bool useTransitions) { if (isDragging) { GoToState(useTransitions, "Dragging"); } else if (hasFocus) { GoToState(useTransitions, "Focus"); } else if (isMouseOver) { GoToState(useTransitions, "MouseOver"); } else { GoToState(useTransitions, "Normal"); } } private bool GoToState(bool useTransitions, string stateName) { return VisualStateManager.GoToState(this, stateName, useTransitions); } #region Dependency Properties /// <summary> /// Identifies the <see cref="Title"/> dependency property. /// </summary> public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(DraggableWindow), null); /// <summary> /// Gets or sets Title. /// </summary> public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } /// <summary> /// Identifies the <see cref="IsOpen"/> dependency property. /// </summary> public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register("IsOpen", typeof(bool), typeof(DraggableWindow), new PropertyMetadata(true, OnIsOpenPropertyChanged)); /// <summary> /// Gets or sets IsOpen. /// </summary> public bool IsOpen { get { return (bool)GetValue(IsOpenProperty); } set { SetValue(IsOpenProperty, value); } } /// <summary> /// IsOpenProperty property changed handler. /// </summary> /// <param name="d">Window that changed its IsOpen.</param> /// <param name="e">DependencyPropertyChangedEventArgs.</param> private static void OnIsOpenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; bool isOpen = (bool)e.NewValue; dp.Visibility = isOpen ? Visibility.Visible : Visibility.Collapsed; if (isOpen) dp.OnOpened(); else dp.OnClosed(); } /// <summary> /// Identifies the <see cref="HorizontalOffset"/> dependency property. /// </summary> public static readonly DependencyProperty HorizontalOffsetProperty = DependencyProperty.Register("HorizontalOffset", typeof(double), typeof(DraggableWindow), new PropertyMetadata(0.0, OnHorizontalOffsetPropertyChanged)); /// <summary> /// Gets or sets HorisontalOffset. /// </summary> public double HorizontalOffset { get { return (double)GetValue(HorizontalOffsetProperty); } set { SetValue(HorizontalOffsetProperty, value); } } /// <summary> /// HorisontalOffsetProperty property changed handler. /// </summary> /// <param name="d">Window that changed its HorisontalOffset.</param> /// <param name="e">DependencyPropertyChangedEventArgs.</param> private static void OnHorizontalOffsetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.RenderTransform is TranslateTransform) (dp.RenderTransform as TranslateTransform).X = (double)e.NewValue; } /// <summary> /// Identifies the <see cref="VerticalOffset"/> dependency property. /// </summary> public static readonly DependencyProperty VerticalOffsetProperty = DependencyProperty.Register("VerticalOffset", typeof(double), typeof(DraggableWindow), new PropertyMetadata(0.0, OnVerticalOffsetPropertyChanged)); /// <summary> /// Gets or sets VerticalOffset. /// </summary> public double VerticalOffset { get { return (double)GetValue(VerticalOffsetProperty); } set { SetValue(VerticalOffsetProperty, value); } } /// <summary> /// VerticalOffsetProperty property changed handler. /// </summary> /// <param name="d">Window that changed its VerticalOffset.</param> /// <param name="e">DependencyPropertyChangedEventArgs.</param> private static void OnVerticalOffsetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.RenderTransform is TranslateTransform) (dp.RenderTransform as TranslateTransform).Y = (double)e.NewValue; } /// <summary> /// Identifies the <see cref="IsDraggable"/> dependency property. /// </summary> public static readonly DependencyProperty IsDraggableProperty = DependencyProperty.Register("IsDraggable", typeof(bool), typeof(DraggableWindow), new PropertyMetadata(true)); /// <summary> /// Gets or sets IsDraggable. /// </summary> public bool IsDraggable { get { return (bool)GetValue(IsDraggableProperty); } set { SetValue(IsDraggableProperty, value); } } /// <summary> /// Identifies the <see cref="IsWidthResizeable"/> dependency property. /// </summary> public static readonly DependencyProperty IsWidthResizeableProperty = DependencyProperty.Register("IsWidthResizeable", typeof(bool), typeof(DraggableWindow), new PropertyMetadata(true)); /// <summary> /// Gets or sets IsWidthResizeable. /// </summary> public bool IsWidthResizeable { get { return (bool)GetValue(IsWidthResizeableProperty); } set { SetValue(IsWidthResizeableProperty, value); } } /// <summary> /// IsWidthResizeableProperty property changed handler. /// </summary> /// <param name="d">Window that changed its IsWidthResizeable.</param> /// <param name="e">DependencyPropertyChangedEventArgs.</param> private static void OnIsWidthResizeablePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.ResizeWidth != null) { dp.ResizeWidth.IsHitTestVisible = (bool)e.NewValue; } } /// <summary> /// Identifies the <see cref="IsHeightResizeable"/> dependency property. /// </summary> public static readonly DependencyProperty IsHeightResizeableProperty = DependencyProperty.Register("IsHeightResizeable", typeof(bool), typeof(DraggableWindow), new PropertyMetadata(true, OnIsHeightResizeablePropertyChanged)); /// <summary> /// Gets or sets IsHeightResizeable. /// </summary> public bool IsHeightResizeable { get { return (bool)GetValue(IsHeightResizeableProperty); } set { SetValue(IsHeightResizeableProperty, value); } } /// <summary> /// IsHeightResizeableProperty property changed handler. /// </summary> /// <param name="d">Window that changed its VerticalOffset.</param> /// <param name="e">DependencyPropertyChangedEventArgs.</param> private static void OnIsHeightResizeablePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.ResizeHeight != null) { dp.ResizeHeight.IsHitTestVisible = (bool)e.NewValue; } } /// <summary> /// Identifies the <see cref="IsHeaderHidden"/> dependency property /// </summary> public static readonly DependencyProperty IsHeaderVisibleProperty = DependencyProperty.Register("IsHeaderHidden", typeof(bool), typeof(DraggableWindow), new PropertyMetadata(true, OnIsHeaderVisiblePropertyChanged)); /// <summary> /// Gets or sets IsHeaderVisible /// </summary> public bool IsHeaderVisible { get { return (bool)GetValue(IsHeaderVisibleProperty); } set { SetValue(IsHeaderVisibleProperty, value); } } private static void OnIsHeaderVisiblePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.topbar != null) { dp.topbar.Visibility = (bool)e.NewValue ? Visibility.Collapsed : Visibility.Visible; } } /// <summary> /// Identifies the <see cref="IsCloseButtonHidden"/> dependency property /// </summary> public static readonly DependencyProperty IsCloseButtonVisibleProperty = DependencyProperty.Register("IsCloseButtonHidden", typeof(bool), typeof(DraggableWindow), new PropertyMetadata(true, OnIsCloseButtonVisiblePropertyChanged)); /// <summary> /// Gets or sets IsCloseButtonVisible /// </summary> public bool IsCloseButtonVisible { get { return (bool)GetValue(IsCloseButtonVisibleProperty); } set { SetValue(IsCloseButtonVisibleProperty, value); } } private static void OnIsCloseButtonVisiblePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.btnClose != null) { dp.btnClose.Visibility = (bool)e.NewValue ? Visibility.Collapsed : Visibility.Visible; } } /// <summary> /// Identifies the <see cref="Title"/> dependency property. /// </summary> public static readonly DependencyProperty ContentBackgroundBorderProperty = DependencyProperty.Register("ContentBackground", typeof(Brush), typeof(DraggableWindow), new PropertyMetadata(new SolidColorBrush(Colors.Transparent), OnContentBackgroundPropertyChanged)); /// <summary> /// Gets or sets Title. /// </summary> public Brush ContentBackgroundBorder { get { return (Brush)GetValue(ContentBackgroundBorderProperty); } set { SetValue(ContentBackgroundBorderProperty, value); } } private static void OnContentBackgroundBorderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.contentBorder != null) { dp.contentBorder.BorderBrush = e.NewValue as Brush; } } /// <summary> /// Identifies the <see cref="Title"/> dependency property. /// </summary> public static readonly DependencyProperty ContentBackgroundProperty = DependencyProperty.Register("ContentBackground", typeof(Brush), typeof(DraggableWindow), new PropertyMetadata(new SolidColorBrush(Colors.Transparent), OnContentBackgroundPropertyChanged)); /// <summary> /// Gets or sets Title. /// </summary> public Brush ContentBackground { get { return (Brush)GetValue(ContentBackgroundProperty); } set { SetValue(ContentBackgroundProperty, value); } } private static void OnContentBackgroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DraggableWindow dp = d as DraggableWindow; if (dp.contentBorder != null) { dp.contentBorder.Background = e.NewValue as Brush; } } #endregion #region Events public event System.EventHandler Closed; public event System.EventHandler Opened; protected void OnClosed() { if (Closed != null) { Closed(this, new System.EventArgs()); } } protected void OnOpened() { if (Opened != null) { Opened(this, new System.EventArgs()); } } #endregion } }
// <copyright file="ResidualStopCriterionTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex32; using MathNet.Numerics.LinearAlgebra.Solvers; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Solvers.StopCriterion { using Numerics; /// <summary> /// Residual stop criterion tests. /// </summary> [TestFixture, Category("LASolver")] public sealed class ResidualStopCriterionTest { /// <summary> /// Create with negative maximum throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithNegativeMaximumThrowsArgumentOutOfRangeException() { Assert.That(() => new ResidualStopCriterion<Complex32>(-0.1f), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Create with illegal minimum iterations throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithIllegalMinimumIterationsThrowsArgumentOutOfRangeException() { Assert.That(() => new ResidualStopCriterion<Complex32>(-1), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create. /// </summary> [Test] public void Create() { var criterion = new ResidualStopCriterion<Complex32>(1e-6f, 50); Assert.AreEqual(1e-6f, criterion.Maximum, "Incorrect maximum"); Assert.AreEqual(50, criterion.MinimumIterationsBelowMaximum, "Incorrect iteration count"); } /// <summary> /// Determine status with illegal iteration number throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void DetermineStatusWithIllegalIterationNumberThrowsArgumentOutOfRangeException() { var criterion = new ResidualStopCriterion<Complex32>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( -1, Vector<Complex32>.Build.Dense(3, 4), Vector<Complex32>.Build.Dense(3, 5), Vector<Complex32>.Build.Dense(3, 6)), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Determine status with non-matching solution vector throws <c>ArgumentException</c>. /// </summary> [Test] public void DetermineStatusWithNonMatchingSolutionVectorThrowsArgumentException() { var criterion = new ResidualStopCriterion<Complex32>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( 1, Vector<Complex32>.Build.Dense(4, 4), Vector<Complex32>.Build.Dense(3, 4), Vector<Complex32>.Build.Dense(3, 4)), Throws.ArgumentException); } /// <summary> /// Determine status with non-matching source vector throws <c>ArgumentException</c>. /// </summary> [Test] public void DetermineStatusWithNonMatchingSourceVectorThrowsArgumentException() { var criterion = new ResidualStopCriterion<Complex32>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( 1, Vector<Complex32>.Build.Dense(3, 4), Vector<Complex32>.Build.Dense(4, 4), Vector<Complex32>.Build.Dense(3, 4)), Throws.ArgumentException); } /// <summary> /// Determine status with non-matching residual vector throws <c>ArgumentException</c>. /// </summary> [Test] public void DetermineStatusWithNonMatchingResidualVectorThrowsArgumentException() { var criterion = new ResidualStopCriterion<Complex32>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( 1, Vector<Complex32>.Build.Dense(3, 4), Vector<Complex32>.Build.Dense(3, 4), DenseVector.Create(4, 4)), Throws.ArgumentException); } /// <summary> /// Can determine status with source NaN. /// </summary> [Test] public void DetermineStatusWithSourceNaN() { var criterion = new ResidualStopCriterion<Complex32>(1e-3f, 10); var solution = new DenseVector(new[] {new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(2.0f, 1)}); var source = new DenseVector(new[] {new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(float.NaN, 1)}); var residual = new DenseVector(new[] {new Complex32(1000.0f, 1), new Complex32(1000.0f, 1), new Complex32(2001.0f, 1)}); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged"); } /// <summary> /// Can determine status with residual NaN. /// </summary> [Test] public void DetermineStatusWithResidualNaN() { var criterion = new ResidualStopCriterion<Complex32>(1e-3f, 10); var solution = new DenseVector(new[] {new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(2.0f, 1)}); var source = new DenseVector(new[] {new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(2.0f, 1)}); var residual = new DenseVector(new[] {new Complex32(1000.0f, 1), new Complex32(float.NaN, 1), new Complex32(2001.0f, 1)}); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged"); } /// <summary> /// Can determine status with convergence at first iteration. /// </summary> /// <remarks>Bugfix: The unit tests for the BiCgStab solver run with a super simple matrix equation /// which converges at the first iteration. The default settings for the /// residual stop criterion should be able to handle this. /// </remarks> [Test] public void DetermineStatusWithConvergenceAtFirstIteration() { var criterion = new ResidualStopCriterion<Complex32>(1e-6); var solution = new DenseVector(new[] {Complex32.One, Complex32.One, Complex32.One}); var source = new DenseVector(new[] {Complex32.One, Complex32.One, Complex32.One}); var residual = new DenseVector(new[] {Complex32.Zero, Complex32.Zero, Complex32.Zero}); var status = criterion.DetermineStatus(0, solution, source, residual); Assert.AreEqual(IterationStatus.Converged, status, "Should be done"); } /// <summary> /// Can determine status. /// </summary> [Test] public void DetermineStatus() { var criterion = new ResidualStopCriterion<Complex32>(1e-3f, 10); // the solution vector isn't actually being used so ... var solution = new DenseVector(new[] {new Complex32(float.NaN, float.NaN), new Complex32(float.NaN, float.NaN), new Complex32(float.NaN, float.NaN)}); // Set the source values var source = new DenseVector(new[] {new Complex32(1.000f, 1), new Complex32(1.000f, 1), new Complex32(2.001f, 1)}); // Set the residual values var residual = new DenseVector(new[] {new Complex32(0.001f, 0), new Complex32(0.001f, 0), new Complex32(0.002f, 0)}); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Continue, status, "Should still be running"); var status2 = criterion.DetermineStatus(16, solution, source, residual); Assert.AreEqual(IterationStatus.Converged, status2, "Should be done"); } /// <summary> /// Can reset calculation state. /// </summary> [Test] public void ResetCalculationState() { var criterion = new ResidualStopCriterion<Complex32>(1e-3f, 10); var solution = new DenseVector(new[] {new Complex32(0.001f, 1), new Complex32(0.001f, 1), new Complex32(0.002f, 1)}); var source = new DenseVector(new[] {new Complex32(0.001f, 1), new Complex32(0.001f, 1), new Complex32(0.002f, 1)}); var residual = new DenseVector(new[] {new Complex32(1.000f, 0), new Complex32(1.000f, 0), new Complex32(2.001f, 0)}); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Continue, status, "Should be running"); criterion.Reset(); Assert.AreEqual(IterationStatus.Continue, criterion.Status, "Should not have started"); } /// <summary> /// Can clone stop criterion. /// </summary> [Test] public void Clone() { var criterion = new ResidualStopCriterion<Complex32>(1e-3f, 10); var clone = criterion.Clone(); Assert.IsInstanceOf(typeof(ResidualStopCriterion<Complex32>), clone, "Wrong criterion type"); var clonedCriterion = clone as ResidualStopCriterion<Complex32>; Assert.IsNotNull(clonedCriterion); Assert.AreEqual(criterion.Maximum, clonedCriterion.Maximum, "Clone failed"); Assert.AreEqual(criterion.MinimumIterationsBelowMaximum, clonedCriterion.MinimumIterationsBelowMaximum, "Clone failed"); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Koffee.WebAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class OrderLine : IEquatable<OrderLine> { /// <summary> /// Initializes a new instance of the <see cref="OrderLine" /> class. /// Initializes a new instance of the <see cref="OrderLine" />class. /// </summary> /// <param name="ItemAccountCodeId">ItemAccountCodeId (required).</param> /// <param name="ItemLegacyLowStockContactId">ItemLegacyLowStockContactId (required).</param> /// <param name="ItemMajorGroupId">ItemMajorGroupId (required).</param> /// <param name="ItemSubGroupId">ItemSubGroupId (required).</param> /// <param name="ItemProductCodeId">ItemProductCodeId.</param> /// <param name="ItemSummaryCodeId">ItemSummaryCodeId (required).</param> /// <param name="CustomFields">CustomFields.</param> public OrderLine(int? ItemAccountCodeId = null, int? ItemLegacyLowStockContactId = null, int? ItemMajorGroupId = null, int? ItemSubGroupId = null, int? ItemProductCodeId = null, int? ItemSummaryCodeId = null, Dictionary<string, Object> CustomFields = null) { // to ensure "ItemAccountCodeId" is required (not null) if (ItemAccountCodeId == null) { throw new InvalidDataException("ItemAccountCodeId is a required property for OrderLine and cannot be null"); } else { this.ItemAccountCodeId = ItemAccountCodeId; } // to ensure "ItemLegacyLowStockContactId" is required (not null) if (ItemLegacyLowStockContactId == null) { throw new InvalidDataException("ItemLegacyLowStockContactId is a required property for OrderLine and cannot be null"); } else { this.ItemLegacyLowStockContactId = ItemLegacyLowStockContactId; } // to ensure "ItemMajorGroupId" is required (not null) if (ItemMajorGroupId == null) { throw new InvalidDataException("ItemMajorGroupId is a required property for OrderLine and cannot be null"); } else { this.ItemMajorGroupId = ItemMajorGroupId; } // to ensure "ItemSubGroupId" is required (not null) if (ItemSubGroupId == null) { throw new InvalidDataException("ItemSubGroupId is a required property for OrderLine and cannot be null"); } else { this.ItemSubGroupId = ItemSubGroupId; } // to ensure "ItemSummaryCodeId" is required (not null) if (ItemSummaryCodeId == null) { throw new InvalidDataException("ItemSummaryCodeId is a required property for OrderLine and cannot be null"); } else { this.ItemSummaryCodeId = ItemSummaryCodeId; } this.ItemProductCodeId = ItemProductCodeId; this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets OrderNo /// </summary> [DataMember(Name="orderNo", EmitDefaultValue=false)] public double? OrderNo { get; private set; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; private set; } /// <summary> /// Gets or Sets Sku /// </summary> [DataMember(Name="sku", EmitDefaultValue=false)] public string Sku { get; private set; } /// <summary> /// Gets or Sets PoNoId /// </summary> [DataMember(Name="poNoId", EmitDefaultValue=false)] public int? PoNoId { get; private set; } /// <summary> /// Gets or Sets OrderedQty /// </summary> [DataMember(Name="orderedQty", EmitDefaultValue=false)] public int? OrderedQty { get; private set; } /// <summary> /// Gets or Sets AllowedQty /// </summary> [DataMember(Name="allowedQty", EmitDefaultValue=false)] public int? AllowedQty { get; private set; } /// <summary> /// Gets or Sets ShippedQty /// </summary> [DataMember(Name="shippedQty", EmitDefaultValue=false)] public int? ShippedQty { get; private set; } /// <summary> /// Gets or Sets BackorderQty /// </summary> [DataMember(Name="backorderQty", EmitDefaultValue=false)] public int? BackorderQty { get; private set; } /// <summary> /// Gets or Sets RevDate /// </summary> [DataMember(Name="revDate", EmitDefaultValue=false)] public string RevDate { get; private set; } /// <summary> /// Gets or Sets ChargeCode /// </summary> [DataMember(Name="chargeCode", EmitDefaultValue=false)] public string ChargeCode { get; private set; } /// <summary> /// Gets or Sets DistributionCode /// </summary> [DataMember(Name="distributionCode", EmitDefaultValue=false)] public string DistributionCode { get; private set; } /// <summary> /// Gets or Sets Upc /// </summary> [DataMember(Name="upc", EmitDefaultValue=false)] public string Upc { get; private set; } /// <summary> /// Gets or Sets VendorSKU /// </summary> [DataMember(Name="vendorSKU", EmitDefaultValue=false)] public string VendorSKU { get; private set; } /// <summary> /// Gets or Sets OrderSourceSKU /// </summary> [DataMember(Name="orderSourceSKU", EmitDefaultValue=false)] public string OrderSourceSKU { get; private set; } /// <summary> /// Gets or Sets UnitCost /// </summary> [DataMember(Name="unitCost", EmitDefaultValue=false)] public double? UnitCost { get; private set; } /// <summary> /// Gets or Sets UnitSell /// </summary> [DataMember(Name="unitSell", EmitDefaultValue=false)] public double? UnitSell { get; private set; } /// <summary> /// Gets or Sets UnitDiscount /// </summary> [DataMember(Name="unitDiscount", EmitDefaultValue=false)] public double? UnitDiscount { get; private set; } /// <summary> /// Gets or Sets ExtendedCost /// </summary> [DataMember(Name="extendedCost", EmitDefaultValue=false)] public double? ExtendedCost { get; private set; } /// <summary> /// Gets or Sets ExtendedSell /// </summary> [DataMember(Name="extendedSell", EmitDefaultValue=false)] public double? ExtendedSell { get; private set; } /// <summary> /// Gets or Sets ExtendedDiscount /// </summary> [DataMember(Name="extendedDiscount", EmitDefaultValue=false)] public double? ExtendedDiscount { get; private set; } /// <summary> /// Gets or Sets NcExtendedSell /// </summary> [DataMember(Name="ncExtendedSell", EmitDefaultValue=false)] public double? NcExtendedSell { get; private set; } /// <summary> /// Gets or Sets ItemWeight /// </summary> [DataMember(Name="itemWeight", EmitDefaultValue=false)] public double? ItemWeight { get; private set; } /// <summary> /// Gets or Sets ProductionLot /// </summary> [DataMember(Name="productionLot", EmitDefaultValue=false)] public string ProductionLot { get; private set; } /// <summary> /// Gets or Sets WeightPerWrap /// </summary> [DataMember(Name="weightPerWrap", EmitDefaultValue=false)] public double? WeightPerWrap { get; private set; } /// <summary> /// Gets or Sets Sector /// </summary> [DataMember(Name="sector", EmitDefaultValue=false)] public string Sector { get; private set; } /// <summary> /// Gets or Sets ItemAccountCodeId /// </summary> [DataMember(Name="itemAccountCodeId", EmitDefaultValue=false)] public int? ItemAccountCodeId { get; set; } /// <summary> /// Gets or Sets ItemLegacyLowStockContactId /// </summary> [DataMember(Name="itemLegacyLowStockContactId", EmitDefaultValue=false)] public int? ItemLegacyLowStockContactId { get; set; } /// <summary> /// Gets or Sets ItemMajorGroupId /// </summary> [DataMember(Name="itemMajorGroupId", EmitDefaultValue=false)] public int? ItemMajorGroupId { get; set; } /// <summary> /// Gets or Sets ItemSubGroupId /// </summary> [DataMember(Name="itemSubGroupId", EmitDefaultValue=false)] public int? ItemSubGroupId { get; set; } /// <summary> /// Gets or Sets ItemProductCodeId /// </summary> [DataMember(Name="itemProductCodeId", EmitDefaultValue=false)] public int? ItemProductCodeId { get; set; } /// <summary> /// Gets or Sets ItemSummaryCodeId /// </summary> [DataMember(Name="itemSummaryCodeId", EmitDefaultValue=false)] public int? ItemSummaryCodeId { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderLine {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" OrderNo: ").Append(OrderNo).Append("\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" Sku: ").Append(Sku).Append("\n"); sb.Append(" PoNoId: ").Append(PoNoId).Append("\n"); sb.Append(" OrderedQty: ").Append(OrderedQty).Append("\n"); sb.Append(" AllowedQty: ").Append(AllowedQty).Append("\n"); sb.Append(" ShippedQty: ").Append(ShippedQty).Append("\n"); sb.Append(" BackorderQty: ").Append(BackorderQty).Append("\n"); sb.Append(" RevDate: ").Append(RevDate).Append("\n"); sb.Append(" ChargeCode: ").Append(ChargeCode).Append("\n"); sb.Append(" DistributionCode: ").Append(DistributionCode).Append("\n"); sb.Append(" Upc: ").Append(Upc).Append("\n"); sb.Append(" VendorSKU: ").Append(VendorSKU).Append("\n"); sb.Append(" OrderSourceSKU: ").Append(OrderSourceSKU).Append("\n"); sb.Append(" UnitCost: ").Append(UnitCost).Append("\n"); sb.Append(" UnitSell: ").Append(UnitSell).Append("\n"); sb.Append(" UnitDiscount: ").Append(UnitDiscount).Append("\n"); sb.Append(" ExtendedCost: ").Append(ExtendedCost).Append("\n"); sb.Append(" ExtendedSell: ").Append(ExtendedSell).Append("\n"); sb.Append(" ExtendedDiscount: ").Append(ExtendedDiscount).Append("\n"); sb.Append(" NcExtendedSell: ").Append(NcExtendedSell).Append("\n"); sb.Append(" ItemWeight: ").Append(ItemWeight).Append("\n"); sb.Append(" ProductionLot: ").Append(ProductionLot).Append("\n"); sb.Append(" WeightPerWrap: ").Append(WeightPerWrap).Append("\n"); sb.Append(" Sector: ").Append(Sector).Append("\n"); sb.Append(" ItemAccountCodeId: ").Append(ItemAccountCodeId).Append("\n"); sb.Append(" ItemLegacyLowStockContactId: ").Append(ItemLegacyLowStockContactId).Append("\n"); sb.Append(" ItemMajorGroupId: ").Append(ItemMajorGroupId).Append("\n"); sb.Append(" ItemSubGroupId: ").Append(ItemSubGroupId).Append("\n"); sb.Append(" ItemProductCodeId: ").Append(ItemProductCodeId).Append("\n"); sb.Append(" ItemSummaryCodeId: ").Append(ItemSummaryCodeId).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as OrderLine); } /// <summary> /// Returns true if OrderLine instances are equal /// </summary> /// <param name="other">Instance of OrderLine to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderLine other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.OrderNo == other.OrderNo || this.OrderNo != null && this.OrderNo.Equals(other.OrderNo) ) && ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.Sku == other.Sku || this.Sku != null && this.Sku.Equals(other.Sku) ) && ( this.PoNoId == other.PoNoId || this.PoNoId != null && this.PoNoId.Equals(other.PoNoId) ) && ( this.OrderedQty == other.OrderedQty || this.OrderedQty != null && this.OrderedQty.Equals(other.OrderedQty) ) && ( this.AllowedQty == other.AllowedQty || this.AllowedQty != null && this.AllowedQty.Equals(other.AllowedQty) ) && ( this.ShippedQty == other.ShippedQty || this.ShippedQty != null && this.ShippedQty.Equals(other.ShippedQty) ) && ( this.BackorderQty == other.BackorderQty || this.BackorderQty != null && this.BackorderQty.Equals(other.BackorderQty) ) && ( this.RevDate == other.RevDate || this.RevDate != null && this.RevDate.Equals(other.RevDate) ) && ( this.ChargeCode == other.ChargeCode || this.ChargeCode != null && this.ChargeCode.Equals(other.ChargeCode) ) && ( this.DistributionCode == other.DistributionCode || this.DistributionCode != null && this.DistributionCode.Equals(other.DistributionCode) ) && ( this.Upc == other.Upc || this.Upc != null && this.Upc.Equals(other.Upc) ) && ( this.VendorSKU == other.VendorSKU || this.VendorSKU != null && this.VendorSKU.Equals(other.VendorSKU) ) && ( this.OrderSourceSKU == other.OrderSourceSKU || this.OrderSourceSKU != null && this.OrderSourceSKU.Equals(other.OrderSourceSKU) ) && ( this.UnitCost == other.UnitCost || this.UnitCost != null && this.UnitCost.Equals(other.UnitCost) ) && ( this.UnitSell == other.UnitSell || this.UnitSell != null && this.UnitSell.Equals(other.UnitSell) ) && ( this.UnitDiscount == other.UnitDiscount || this.UnitDiscount != null && this.UnitDiscount.Equals(other.UnitDiscount) ) && ( this.ExtendedCost == other.ExtendedCost || this.ExtendedCost != null && this.ExtendedCost.Equals(other.ExtendedCost) ) && ( this.ExtendedSell == other.ExtendedSell || this.ExtendedSell != null && this.ExtendedSell.Equals(other.ExtendedSell) ) && ( this.ExtendedDiscount == other.ExtendedDiscount || this.ExtendedDiscount != null && this.ExtendedDiscount.Equals(other.ExtendedDiscount) ) && ( this.NcExtendedSell == other.NcExtendedSell || this.NcExtendedSell != null && this.NcExtendedSell.Equals(other.NcExtendedSell) ) && ( this.ItemWeight == other.ItemWeight || this.ItemWeight != null && this.ItemWeight.Equals(other.ItemWeight) ) && ( this.ProductionLot == other.ProductionLot || this.ProductionLot != null && this.ProductionLot.Equals(other.ProductionLot) ) && ( this.WeightPerWrap == other.WeightPerWrap || this.WeightPerWrap != null && this.WeightPerWrap.Equals(other.WeightPerWrap) ) && ( this.Sector == other.Sector || this.Sector != null && this.Sector.Equals(other.Sector) ) && ( this.ItemAccountCodeId == other.ItemAccountCodeId || this.ItemAccountCodeId != null && this.ItemAccountCodeId.Equals(other.ItemAccountCodeId) ) && ( this.ItemLegacyLowStockContactId == other.ItemLegacyLowStockContactId || this.ItemLegacyLowStockContactId != null && this.ItemLegacyLowStockContactId.Equals(other.ItemLegacyLowStockContactId) ) && ( this.ItemMajorGroupId == other.ItemMajorGroupId || this.ItemMajorGroupId != null && this.ItemMajorGroupId.Equals(other.ItemMajorGroupId) ) && ( this.ItemSubGroupId == other.ItemSubGroupId || this.ItemSubGroupId != null && this.ItemSubGroupId.Equals(other.ItemSubGroupId) ) && ( this.ItemProductCodeId == other.ItemProductCodeId || this.ItemProductCodeId != null && this.ItemProductCodeId.Equals(other.ItemProductCodeId) ) && ( this.ItemSummaryCodeId == other.ItemSummaryCodeId || this.ItemSummaryCodeId != null && this.ItemSummaryCodeId.Equals(other.ItemSummaryCodeId) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.OrderNo != null) hash = hash * 59 + this.OrderNo.GetHashCode(); if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.Sku != null) hash = hash * 59 + this.Sku.GetHashCode(); if (this.PoNoId != null) hash = hash * 59 + this.PoNoId.GetHashCode(); if (this.OrderedQty != null) hash = hash * 59 + this.OrderedQty.GetHashCode(); if (this.AllowedQty != null) hash = hash * 59 + this.AllowedQty.GetHashCode(); if (this.ShippedQty != null) hash = hash * 59 + this.ShippedQty.GetHashCode(); if (this.BackorderQty != null) hash = hash * 59 + this.BackorderQty.GetHashCode(); if (this.RevDate != null) hash = hash * 59 + this.RevDate.GetHashCode(); if (this.ChargeCode != null) hash = hash * 59 + this.ChargeCode.GetHashCode(); if (this.DistributionCode != null) hash = hash * 59 + this.DistributionCode.GetHashCode(); if (this.Upc != null) hash = hash * 59 + this.Upc.GetHashCode(); if (this.VendorSKU != null) hash = hash * 59 + this.VendorSKU.GetHashCode(); if (this.OrderSourceSKU != null) hash = hash * 59 + this.OrderSourceSKU.GetHashCode(); if (this.UnitCost != null) hash = hash * 59 + this.UnitCost.GetHashCode(); if (this.UnitSell != null) hash = hash * 59 + this.UnitSell.GetHashCode(); if (this.UnitDiscount != null) hash = hash * 59 + this.UnitDiscount.GetHashCode(); if (this.ExtendedCost != null) hash = hash * 59 + this.ExtendedCost.GetHashCode(); if (this.ExtendedSell != null) hash = hash * 59 + this.ExtendedSell.GetHashCode(); if (this.ExtendedDiscount != null) hash = hash * 59 + this.ExtendedDiscount.GetHashCode(); if (this.NcExtendedSell != null) hash = hash * 59 + this.NcExtendedSell.GetHashCode(); if (this.ItemWeight != null) hash = hash * 59 + this.ItemWeight.GetHashCode(); if (this.ProductionLot != null) hash = hash * 59 + this.ProductionLot.GetHashCode(); if (this.WeightPerWrap != null) hash = hash * 59 + this.WeightPerWrap.GetHashCode(); if (this.Sector != null) hash = hash * 59 + this.Sector.GetHashCode(); if (this.ItemAccountCodeId != null) hash = hash * 59 + this.ItemAccountCodeId.GetHashCode(); if (this.ItemLegacyLowStockContactId != null) hash = hash * 59 + this.ItemLegacyLowStockContactId.GetHashCode(); if (this.ItemMajorGroupId != null) hash = hash * 59 + this.ItemMajorGroupId.GetHashCode(); if (this.ItemSubGroupId != null) hash = hash * 59 + this.ItemSubGroupId.GetHashCode(); if (this.ItemProductCodeId != null) hash = hash * 59 + this.ItemProductCodeId.GetHashCode(); if (this.ItemSummaryCodeId != null) hash = hash * 59 + this.ItemSummaryCodeId.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Lucene.Net.Search { /* * 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 AtomicReader = Lucene.Net.Index.AtomicReader; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using DocsEnum = Lucene.Net.Index.DocsEnum; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using ReaderUtil = Lucene.Net.Index.ReaderUtil; using Similarity = Lucene.Net.Search.Similarities.Similarity; using SimScorer = Lucene.Net.Search.Similarities.Similarity.SimScorer; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// A <see cref="Query"/> that matches documents containing a term. /// this may be combined with other terms with a <see cref="BooleanQuery"/>. /// </summary> #if FEATURE_SERIALIZABLE [Serializable] #endif public class TermQuery : Query { private readonly Term term; private readonly int docFreq; private readonly TermContext perReaderTermState; internal sealed class TermWeight : Weight { private readonly TermQuery outerInstance; internal readonly Similarity similarity; internal readonly Similarity.SimWeight stats; internal readonly TermContext termStates; public TermWeight(TermQuery outerInstance, IndexSearcher searcher, TermContext termStates) { this.outerInstance = outerInstance; Debug.Assert(termStates != null, "TermContext must not be null"); this.termStates = termStates; this.similarity = searcher.Similarity; this.stats = similarity.ComputeWeight(outerInstance.Boost, searcher.CollectionStatistics(outerInstance.term.Field), searcher.TermStatistics(outerInstance.term, termStates)); } public override string ToString() { return "weight(" + outerInstance + ")"; } public override Query Query { get { return outerInstance; } } public override float GetValueForNormalization() { return stats.GetValueForNormalization(); } public override void Normalize(float queryNorm, float topLevelBoost) { stats.Normalize(queryNorm, topLevelBoost); } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { Debug.Assert(termStates.TopReaderContext == ReaderUtil.GetTopLevelContext(context), "The top-reader used to create Weight (" + termStates.TopReaderContext + ") is not the same as the current reader's top-reader (" + ReaderUtil.GetTopLevelContext(context)); TermsEnum termsEnum = GetTermsEnum(context); if (termsEnum == null) { return null; } DocsEnum docs = termsEnum.Docs(acceptDocs, null); Debug.Assert(docs != null); return new TermScorer(this, docs, similarity.GetSimScorer(stats, context)); } /// <summary> /// Returns a <see cref="TermsEnum"/> positioned at this weights <see cref="Index.Term"/> or <c>null</c> if /// the term does not exist in the given context. /// </summary> private TermsEnum GetTermsEnum(AtomicReaderContext context) { TermState state = termStates.Get(context.Ord); if (state == null) // term is not present in that reader { Debug.Assert(TermNotInReader(context.AtomicReader, outerInstance.term), "no termstate found but term exists in reader term=" + outerInstance.term); return null; } //System.out.println("LD=" + reader.getLiveDocs() + " set?=" + (reader.getLiveDocs() != null ? reader.getLiveDocs().get(0) : "null")); TermsEnum termsEnum = context.AtomicReader.GetTerms(outerInstance.term.Field).GetIterator(null); termsEnum.SeekExact(outerInstance.term.Bytes, state); return termsEnum; } private bool TermNotInReader(AtomicReader reader, Term term) { // only called from assert //System.out.println("TQ.termNotInReader reader=" + reader + " term=" + field + ":" + bytes.utf8ToString()); return reader.DocFreq(term) == 0; } public override Explanation Explain(AtomicReaderContext context, int doc) { Scorer scorer = GetScorer(context, context.AtomicReader.LiveDocs); if (scorer != null) { int newDoc = scorer.Advance(doc); if (newDoc == doc) { float freq = scorer.Freq; SimScorer docScorer = similarity.GetSimScorer(stats, context); ComplexExplanation result = new ComplexExplanation(); result.Description = "weight(" + Query + " in " + doc + ") [" + similarity.GetType().Name + "], result of:"; Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "termFreq=" + freq)); result.AddDetail(scoreExplanation); result.Value = scoreExplanation.Value; result.Match = true; return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } /// <summary> /// Constructs a query for the term <paramref name="t"/>. </summary> public TermQuery(Term t) : this(t, -1) { } /// <summary> /// Expert: constructs a <see cref="TermQuery"/> that will use the /// provided <paramref name="docFreq"/> instead of looking up the docFreq /// against the searcher. /// </summary> public TermQuery(Term t, int docFreq) { term = t; this.docFreq = docFreq; perReaderTermState = null; } /// <summary> /// Expert: constructs a <see cref="TermQuery"/> that will use the /// provided docFreq instead of looking up the docFreq /// against the searcher. /// </summary> public TermQuery(Term t, TermContext states) { Debug.Assert(states != null); term = t; docFreq = states.DocFreq; perReaderTermState = states; } /// <summary> /// Returns the term of this query. </summary> public virtual Term Term { get { return term; } } public override Weight CreateWeight(IndexSearcher searcher) { IndexReaderContext context = searcher.TopReaderContext; TermContext termState; if (perReaderTermState == null || perReaderTermState.TopReaderContext != context) { // make TermQuery single-pass if we don't have a PRTS or if the context differs! termState = TermContext.Build(context, term); } else { // PRTS was pre-build for this IS termState = this.perReaderTermState; } // we must not ignore the given docFreq - if set use the given value (lie) if (docFreq != -1) { termState.DocFreq = docFreq; } return new TermWeight(this, searcher, termState); } public override void ExtractTerms(ISet<Term> terms) { terms.Add(Term); } /// <summary> /// Prints a user-readable version of this query. </summary> public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); if (!term.Field.Equals(field, StringComparison.Ordinal)) { buffer.Append(term.Field); buffer.Append(":"); } buffer.Append(term.Text()); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } /// <summary> /// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary> public override bool Equals(object o) { if (!(o is TermQuery)) { return false; } TermQuery other = (TermQuery)o; return (this.Boost == other.Boost) && this.term.Equals(other.term); } /// <summary> /// Returns a hash code value for this object. </summary> public override int GetHashCode() { return Number.SingleToInt32Bits(Boost) ^ term.GetHashCode(); } } }
namespace KabMan.Forms { partial class CableManagerForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.CableNumberEdit = new DevExpress.XtraEditors.TextEdit(); this.SymbolSpinEdit = new DevExpress.XtraEditors.ComboBoxEdit(); this.CableTypeGroup = new DevExpress.XtraEditors.RadioGroup(); this.btnAddCables = new DevExpress.XtraEditors.SimpleButton(); this.CableModelLookUp = new KabMan.Controls.C_LookUpCableModel(); this.CableCategoryLookUp = new KabMan.Controls.C_LookUpCableCategory(); this.labelControl1 = new DevExpress.XtraEditors.LabelControl(); this.CablePropertiesGridControl = new DevExpress.XtraGrid.GridControl(); this.CablePropertiesGridView = new DevExpress.XtraGrid.Views.Grid.GridView(); this.CountSpinEdit = new DevExpress.XtraEditors.SpinEdit(); this.StartNoSpinEdit = new DevExpress.XtraEditors.SpinEdit(); this.CablesGridControl = new DevExpress.XtraGrid.GridControl(); this.CablesGridViewControl = new DevExpress.XtraGrid.Views.Grid.GridView(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem7 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem8 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem(); this.emptySpaceItem2 = new DevExpress.XtraLayout.EmptySpaceItem(); this.layoutControlItem10 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem11 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem9 = new DevExpress.XtraLayout.LayoutControlItem(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CableNumberEdit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SymbolSpinEdit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CableTypeGroup.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CableModelLookUp.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CableCategoryLookUp.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CablePropertiesGridControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CablePropertiesGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CountSpinEdit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.StartNoSpinEdit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CablesGridControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CablesGridViewControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).BeginInit(); this.SuspendLayout(); // // layoutControl1 // this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.CableNumberEdit); this.layoutControl1.Controls.Add(this.SymbolSpinEdit); this.layoutControl1.Controls.Add(this.CableTypeGroup); this.layoutControl1.Controls.Add(this.btnAddCables); this.layoutControl1.Controls.Add(this.CableModelLookUp); this.layoutControl1.Controls.Add(this.CableCategoryLookUp); this.layoutControl1.Controls.Add(this.labelControl1); this.layoutControl1.Controls.Add(this.CablePropertiesGridControl); this.layoutControl1.Controls.Add(this.CountSpinEdit); this.layoutControl1.Controls.Add(this.StartNoSpinEdit); this.layoutControl1.Controls.Add(this.CablesGridControl); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 0); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(691, 512); this.layoutControl1.TabIndex = 0; this.layoutControl1.Text = "layoutControl1"; // // CableNumberEdit // this.CableNumberEdit.Location = new System.Drawing.Point(87, 198); this.CableNumberEdit.Name = "CableNumberEdit"; this.CableNumberEdit.Properties.MaxLength = 5; this.CableNumberEdit.Size = new System.Drawing.Size(306, 20); this.CableNumberEdit.StyleController = this.layoutControl1; this.CableNumberEdit.TabIndex = 19; // // SymbolSpinEdit // this.SymbolSpinEdit.Location = new System.Drawing.Point(87, 167); this.SymbolSpinEdit.Name = "SymbolSpinEdit"; this.SymbolSpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.SymbolSpinEdit.Properties.Items.AddRange(new object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "Z"}); this.SymbolSpinEdit.Properties.NullText = "Select Cable Symbol!"; this.SymbolSpinEdit.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor; this.SymbolSpinEdit.Size = new System.Drawing.Size(306, 20); this.SymbolSpinEdit.StyleController = this.layoutControl1; this.SymbolSpinEdit.TabIndex = 18; // // CableTypeGroup // this.CableTypeGroup.EditValue = 2; this.CableTypeGroup.Location = new System.Drawing.Point(87, 7); this.CableTypeGroup.Margin = new System.Windows.Forms.Padding(0); this.CableTypeGroup.MaximumSize = new System.Drawing.Size(306, 25); this.CableTypeGroup.MinimumSize = new System.Drawing.Size(306, 25); this.CableTypeGroup.Name = "CableTypeGroup"; this.CableTypeGroup.Properties.Columns = 2; this.CableTypeGroup.Properties.Items.AddRange(new DevExpress.XtraEditors.Controls.RadioGroupItem[] { new DevExpress.XtraEditors.Controls.RadioGroupItem(1, "Single"), new DevExpress.XtraEditors.Controls.RadioGroupItem(2, "Multiple")}); this.CableTypeGroup.Size = new System.Drawing.Size(306, 25); this.CableTypeGroup.StyleController = this.layoutControl1; this.CableTypeGroup.TabIndex = 17; this.CableTypeGroup.SelectedIndexChanged += new System.EventHandler(this.CableTypeGroup_SelectedIndexChanged); // // btnAddCables // this.btnAddCables.Location = new System.Drawing.Point(313, 229); this.btnAddCables.Name = "btnAddCables"; this.btnAddCables.Size = new System.Drawing.Size(80, 22); this.btnAddCables.StyleController = this.layoutControl1; this.btnAddCables.TabIndex = 16; this.btnAddCables.Text = "Add Cables"; this.btnAddCables.Click += new System.EventHandler(this.btnAddCables_Click); // // CableModelLookUp // this.CableModelLookUp.Location = new System.Drawing.Point(87, 74); this.CableModelLookUp.Name = "CableModelLookUp"; this.CableModelLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CableModelLookUp.Properties.NullText = "Select Cable Model!"; this.CableModelLookUp.Size = new System.Drawing.Size(306, 20); this.CableModelLookUp.StyleController = this.layoutControl1; this.CableModelLookUp.TabIndex = 14; this.CableModelLookUp.TriggerLookUpEdit = this.CableCategoryLookUp; this.CableModelLookUp.EditValueChanged += new System.EventHandler(this.CableModelLookUp_EditValueChanged); // // CableCategoryLookUp // this.CableCategoryLookUp.AddButtonEnabled = true; this.CableCategoryLookUp.Location = new System.Drawing.Point(87, 43); this.CableCategoryLookUp.Name = "CableCategoryLookUp"; this.CableCategoryLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CableCategoryLookUp.Properties.DisplayMember = "Name"; this.CableCategoryLookUp.Properties.NullText = "Select Cable Category!"; this.CableCategoryLookUp.Properties.ValueMember = "ID"; this.CableCategoryLookUp.Size = new System.Drawing.Size(306, 20); this.CableCategoryLookUp.StyleController = this.layoutControl1; this.CableCategoryLookUp.TabIndex = 13; this.CableCategoryLookUp.EditValueChanged += new System.EventHandler(this.CableCategoryLookUp_EditValueChanged); // // labelControl1 // this.labelControl1.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None; this.labelControl1.Location = new System.Drawing.Point(404, 7); this.labelControl1.Name = "labelControl1"; this.labelControl1.Size = new System.Drawing.Size(281, 13); this.labelControl1.StyleController = this.layoutControl1; this.labelControl1.TabIndex = 12; this.labelControl1.Text = "Additional Properties"; // // CablePropertiesGridControl // this.CablePropertiesGridControl.Location = new System.Drawing.Point(404, 31); this.CablePropertiesGridControl.MainView = this.CablePropertiesGridView; this.CablePropertiesGridControl.Name = "CablePropertiesGridControl"; this.CablePropertiesGridControl.Size = new System.Drawing.Size(281, 220); this.CablePropertiesGridControl.TabIndex = 10; this.CablePropertiesGridControl.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.CablePropertiesGridView}); // // CablePropertiesGridView // this.CablePropertiesGridView.GridControl = this.CablePropertiesGridControl; this.CablePropertiesGridView.Name = "CablePropertiesGridView"; this.CablePropertiesGridView.OptionsBehavior.Editable = false; this.CablePropertiesGridView.OptionsView.ShowGroupPanel = false; this.CablePropertiesGridView.OptionsView.ShowIndicator = false; // // CountSpinEdit // this.CountSpinEdit.EditValue = new decimal(new int[] { 1, 0, 0, 0}); this.CountSpinEdit.Location = new System.Drawing.Point(87, 136); this.CountSpinEdit.Name = "CountSpinEdit"; this.CountSpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.CountSpinEdit.Properties.MaxValue = new decimal(new int[] { 99999, 0, 0, 0}); this.CountSpinEdit.Properties.MinValue = new decimal(new int[] { 1, 0, 0, 0}); this.CountSpinEdit.Size = new System.Drawing.Size(306, 20); this.CountSpinEdit.StyleController = this.layoutControl1; this.CountSpinEdit.TabIndex = 7; // // StartNoSpinEdit // this.StartNoSpinEdit.EditValue = new decimal(new int[] { 1, 0, 0, 0}); this.StartNoSpinEdit.Location = new System.Drawing.Point(87, 105); this.StartNoSpinEdit.Name = "StartNoSpinEdit"; this.StartNoSpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.StartNoSpinEdit.Properties.MaxValue = new decimal(new int[] { 99999, 0, 0, 0}); this.StartNoSpinEdit.Properties.MinValue = new decimal(new int[] { 1, 0, 0, 0}); this.StartNoSpinEdit.Size = new System.Drawing.Size(306, 20); this.StartNoSpinEdit.StyleController = this.layoutControl1; this.StartNoSpinEdit.TabIndex = 6; // // CablesGridControl // this.CablesGridControl.Location = new System.Drawing.Point(7, 262); this.CablesGridControl.MainView = this.CablesGridViewControl; this.CablesGridControl.Name = "CablesGridControl"; this.CablesGridControl.Size = new System.Drawing.Size(678, 244); this.CablesGridControl.TabIndex = 8; this.CablesGridControl.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.CablesGridViewControl}); // // CablesGridViewControl // this.CablesGridViewControl.GridControl = this.CablesGridControl; this.CablesGridViewControl.Name = "CablesGridViewControl"; this.CablesGridViewControl.OptionsBehavior.AllowIncrementalSearch = true; this.CablesGridViewControl.OptionsBehavior.Editable = false; this.CablesGridViewControl.OptionsCustomization.AllowFilter = false; this.CablesGridViewControl.OptionsView.EnableAppearanceEvenRow = true; this.CablesGridViewControl.OptionsView.EnableAppearanceOddRow = true; this.CablesGridViewControl.OptionsView.ShowGroupPanel = false; this.CablesGridViewControl.OptionsView.ShowIndicator = false; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem5, this.layoutControlItem3, this.layoutControlItem4, this.layoutControlItem7, this.layoutControlItem8, this.layoutControlItem1, this.layoutControlItem2, this.layoutControlItem6, this.emptySpaceItem2, this.layoutControlItem10, this.layoutControlItem11, this.layoutControlItem9}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(691, 512); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem5 // this.layoutControlItem5.Control = this.CablesGridControl; this.layoutControlItem5.CustomizationFormText = "layoutControlItem5"; this.layoutControlItem5.Location = new System.Drawing.Point(0, 255); this.layoutControlItem5.Name = "layoutControlItem5"; this.layoutControlItem5.Size = new System.Drawing.Size(689, 255); this.layoutControlItem5.Text = "layoutControlItem5"; this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem5.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem5.TextToControlDistance = 0; this.layoutControlItem5.TextVisible = false; // // layoutControlItem3 // this.layoutControlItem3.Control = this.StartNoSpinEdit; this.layoutControlItem3.CustomizationFormText = "Start No"; this.layoutControlItem3.Location = new System.Drawing.Point(0, 98); this.layoutControlItem3.MaxSize = new System.Drawing.Size(397, 31); this.layoutControlItem3.MinSize = new System.Drawing.Size(397, 31); this.layoutControlItem3.Name = "layoutControlItem3"; this.layoutControlItem3.Size = new System.Drawing.Size(397, 31); this.layoutControlItem3.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem3.Text = "Start No"; this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem3.TextSize = new System.Drawing.Size(75, 13); // // layoutControlItem4 // this.layoutControlItem4.Control = this.CountSpinEdit; this.layoutControlItem4.CustomizationFormText = "Count"; this.layoutControlItem4.Location = new System.Drawing.Point(0, 129); this.layoutControlItem4.MaxSize = new System.Drawing.Size(397, 31); this.layoutControlItem4.MinSize = new System.Drawing.Size(397, 31); this.layoutControlItem4.Name = "layoutControlItem4"; this.layoutControlItem4.Size = new System.Drawing.Size(397, 31); this.layoutControlItem4.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem4.Text = "Count"; this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem4.TextSize = new System.Drawing.Size(75, 13); // // layoutControlItem7 // this.layoutControlItem7.Control = this.CablePropertiesGridControl; this.layoutControlItem7.CustomizationFormText = "layoutControlItem7"; this.layoutControlItem7.Location = new System.Drawing.Point(397, 24); this.layoutControlItem7.Name = "layoutControlItem7"; this.layoutControlItem7.Size = new System.Drawing.Size(292, 231); this.layoutControlItem7.Text = "layoutControlItem7"; this.layoutControlItem7.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem7.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem7.TextToControlDistance = 0; this.layoutControlItem7.TextVisible = false; // // layoutControlItem8 // this.layoutControlItem8.Control = this.labelControl1; this.layoutControlItem8.CustomizationFormText = "layoutControlItem8"; this.layoutControlItem8.Location = new System.Drawing.Point(397, 0); this.layoutControlItem8.Name = "layoutControlItem8"; this.layoutControlItem8.Size = new System.Drawing.Size(292, 24); this.layoutControlItem8.Text = "layoutControlItem8"; this.layoutControlItem8.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem8.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem8.TextToControlDistance = 0; this.layoutControlItem8.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.CableCategoryLookUp; this.layoutControlItem1.CustomizationFormText = "Cable Category"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 36); this.layoutControlItem1.MaxSize = new System.Drawing.Size(397, 31); this.layoutControlItem1.MinSize = new System.Drawing.Size(397, 31); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(397, 31); this.layoutControlItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem1.Text = "Cable Category"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(75, 13); // // layoutControlItem2 // this.layoutControlItem2.Control = this.CableModelLookUp; this.layoutControlItem2.CustomizationFormText = "Cable Model"; this.layoutControlItem2.Location = new System.Drawing.Point(0, 67); this.layoutControlItem2.MaxSize = new System.Drawing.Size(397, 31); this.layoutControlItem2.MinSize = new System.Drawing.Size(397, 31); this.layoutControlItem2.Name = "layoutControlItem2"; this.layoutControlItem2.Size = new System.Drawing.Size(397, 31); this.layoutControlItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem2.Text = "Cable Model"; this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem2.TextSize = new System.Drawing.Size(75, 13); // // layoutControlItem6 // this.layoutControlItem6.Control = this.btnAddCables; this.layoutControlItem6.CustomizationFormText = "layoutControlItem6"; this.layoutControlItem6.Location = new System.Drawing.Point(306, 222); this.layoutControlItem6.MaxSize = new System.Drawing.Size(91, 33); this.layoutControlItem6.MinSize = new System.Drawing.Size(91, 33); this.layoutControlItem6.Name = "layoutControlItem6"; this.layoutControlItem6.Size = new System.Drawing.Size(91, 33); this.layoutControlItem6.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem6.Text = "layoutControlItem6"; this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem6.TextToControlDistance = 0; this.layoutControlItem6.TextVisible = false; // // emptySpaceItem2 // this.emptySpaceItem2.CustomizationFormText = "emptySpaceItem2"; this.emptySpaceItem2.Location = new System.Drawing.Point(0, 222); this.emptySpaceItem2.Name = "emptySpaceItem2"; this.emptySpaceItem2.Size = new System.Drawing.Size(306, 33); this.emptySpaceItem2.Text = "emptySpaceItem2"; this.emptySpaceItem2.TextSize = new System.Drawing.Size(0, 0); // // layoutControlItem10 // this.layoutControlItem10.Control = this.CableTypeGroup; this.layoutControlItem10.CustomizationFormText = "layoutControlItem10"; this.layoutControlItem10.Location = new System.Drawing.Point(0, 0); this.layoutControlItem10.Name = "layoutControlItem10"; this.layoutControlItem10.Size = new System.Drawing.Size(397, 36); this.layoutControlItem10.Text = "Type"; this.layoutControlItem10.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem10.TextSize = new System.Drawing.Size(75, 13); // // layoutControlItem11 // this.layoutControlItem11.Control = this.CableNumberEdit; this.layoutControlItem11.CustomizationFormText = "Number"; this.layoutControlItem11.Location = new System.Drawing.Point(0, 191); this.layoutControlItem11.Name = "layoutControlItem11"; this.layoutControlItem11.Size = new System.Drawing.Size(397, 31); this.layoutControlItem11.Text = "Number"; this.layoutControlItem11.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem11.TextSize = new System.Drawing.Size(75, 13); this.layoutControlItem11.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never; // // layoutControlItem9 // this.layoutControlItem9.Control = this.SymbolSpinEdit; this.layoutControlItem9.CustomizationFormText = "Symbol"; this.layoutControlItem9.Location = new System.Drawing.Point(0, 160); this.layoutControlItem9.Name = "layoutControlItem9"; this.layoutControlItem9.Size = new System.Drawing.Size(397, 31); this.layoutControlItem9.Text = "Symbol"; this.layoutControlItem9.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem9.TextSize = new System.Drawing.Size(75, 13); // // CableManagerForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(691, 512); this.Controls.Add(this.layoutControl1); this.Name = "CableManagerForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Cable Management"; this.Load += new System.EventHandler(this.CableManager_Load); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CableNumberEdit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SymbolSpinEdit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CableTypeGroup.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CableModelLookUp.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CableCategoryLookUp.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CablePropertiesGridControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CablePropertiesGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CountSpinEdit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.StartNoSpinEdit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CablesGridControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CablesGridViewControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraEditors.SpinEdit StartNoSpinEdit; private DevExpress.XtraEditors.SpinEdit CountSpinEdit; private DevExpress.XtraGrid.GridControl CablesGridControl; private DevExpress.XtraGrid.Views.Grid.GridView CablesGridViewControl; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5; private DevExpress.XtraGrid.GridControl CablePropertiesGridControl; private DevExpress.XtraGrid.Views.Grid.GridView CablePropertiesGridView; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem7; private DevExpress.XtraEditors.LabelControl labelControl1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem8; private KabMan.Controls.C_LookUpCableModel CableModelLookUp; private KabMan.Controls.C_LookUpCableCategory CableCategoryLookUp; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2; private DevExpress.XtraEditors.SimpleButton btnAddCables; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6; private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem2; private DevExpress.XtraEditors.RadioGroup CableTypeGroup; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem10; private DevExpress.XtraEditors.ComboBoxEdit SymbolSpinEdit; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem9; private DevExpress.XtraEditors.TextEdit CableNumberEdit; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem11; } }
using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob.Protocol; using Microsoft.WindowsAzure.Storage.Core; using Microsoft.WindowsAzure.Storage.Core.Executor; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.Storage.Blob { public class CloudPageBlob : CloudBlob, ICloudBlob, IListBlobItem { public int StreamWriteSizeInBytes { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public CloudPageBlob(Uri blobAbsoluteUri) : this(blobAbsoluteUri, (StorageCredentials) null) { throw new System.NotImplementedException(); } public CloudPageBlob(Uri blobAbsoluteUri, StorageCredentials credentials) : this(blobAbsoluteUri, new DateTimeOffset?(), credentials) { throw new System.NotImplementedException(); } public CloudPageBlob(Uri blobAbsoluteUri, DateTimeOffset? snapshotTime, StorageCredentials credentials) : this(new StorageUri(blobAbsoluteUri), snapshotTime, credentials) { throw new System.NotImplementedException(); } public CloudPageBlob(StorageUri blobAbsoluteUri, DateTimeOffset? snapshotTime, StorageCredentials credentials) : base(blobAbsoluteUri, snapshotTime, credentials) { throw new System.NotImplementedException(); } internal CloudPageBlob(string blobName, DateTimeOffset? snapshotTime, CloudBlobContainer container) : base(blobName, snapshotTime, container) { throw new System.NotImplementedException(); } internal CloudPageBlob(BlobAttributes attributes, CloudBlobClient serviceClient) : base(attributes, serviceClient) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudBlobStream> OpenWriteAsync(long? size) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudBlobStream> OpenWriteAsync(long? size, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudBlobStream> OpenWriteAsync(long? size, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, long length) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, long length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromStreamAsync(Stream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task UploadFromStreamAsync(Stream source, PremiumPageBlobTier? premiumBlobTier, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task UploadFromStreamAsync(Stream source, long length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task UploadFromStreamAsync(Stream source, long length, PremiumPageBlobTier? premiumBlobTier, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, PremiumPageBlobTier? premiumBlobTier, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task CreateAsync(long size) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync(long size, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync(long size, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task CreateAsync(long size, PremiumPageBlobTier? premiumBlobTier, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task ResizeAsync(long size) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ResizeAsync(long size, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ResizeAsync(long size, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetSequenceNumberAsync(SequenceNumberAction sequenceNumberAction, long? sequenceNumber) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetSequenceNumberAsync(SequenceNumberAction sequenceNumberAction, long? sequenceNumber, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetSequenceNumberAsync(SequenceNumberAction sequenceNumberAction, long? sequenceNumber, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<PageRange>> GetPageRangesAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<PageRange>> GetPageRangesAsync(long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<PageRange>> GetPageRangesAsync(long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<IEnumerable<PageDiffRange>> GetPageRangesDiffAsync(DateTimeOffset previousSnapshotTime) { throw new System.NotImplementedException(); } public virtual Task<IEnumerable<PageDiffRange>> GetPageRangesDiffAsync(DateTimeOffset previousSnapshotTime, long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<IEnumerable<PageDiffRange>> GetPageRangesDiffAsync(DateTimeOffset previousSnapshotTime, long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<CloudPageBlob> CreateSnapshotAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudPageBlob> CreateSnapshotAsync(IDictionary<string, string> metadata, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudPageBlob> CreateSnapshotAsync(IDictionary<string, string> metadata, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task WritePagesAsync(Stream pageData, long startOffset, string contentMD5) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task WritePagesAsync(Stream pageData, long startOffset, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task WritePagesAsync(Stream pageData, long startOffset, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ClearPagesAsync(long startOffset, long length) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ClearPagesAsync(long startOffset, long length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ClearPagesAsync(long startOffset, long length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<string> StartCopyAsync(CloudPageBlob source) { throw new System.NotImplementedException(); } public virtual Task<string> StartIncrementalCopyAsync(CloudPageBlob sourceSnapshot) { throw new System.NotImplementedException(); } public virtual Task<string> StartCopyAsync(CloudPageBlob source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<string> StartCopyAsync(CloudPageBlob source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<string> StartCopyAsync(CloudPageBlob source, PremiumPageBlobTier? premiumBlobTier, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<string> StartIncrementalCopyAsync(CloudPageBlob sourceSnapshot, AccessCondition destAccessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task SetPremiumBlobTierAsync(PremiumPageBlobTier premiumBlobTier) { throw new System.NotImplementedException(); } public virtual Task SetPremiumBlobTierAsync(PremiumPageBlobTier premiumBlobTier, BlobRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task SetPremiumBlobTierAsync(PremiumPageBlobTier premiumBlobTier, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } private RESTCommand<NullType> CreateImpl(long sizeInBytes, PremiumPageBlobTier? premiumBlobTier, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> ResizeImpl(long sizeInBytes, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> SetSequenceNumberImpl(SequenceNumberAction sequenceNumberAction, long? sequenceNumber, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<IEnumerable<PageRange>> GetPageRangesImpl(long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<IEnumerable<PageDiffRange>> GetPageRangesDiffImpl(DateTimeOffset previousSnapshotTime, long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> PutPageImpl(Stream pageData, long startOffset, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> ClearPageImpl(long startOffset, long length, AccessCondition accessCondition, BlobRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> SetBlobTierImpl(PremiumPageBlobTier premiumBlobTier, BlobRequestOptions options) { throw new System.NotImplementedException(); } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Reflection; using HLA40 = Net.Pkcs11Interop.HighLevelAPI40; using HLA41 = Net.Pkcs11Interop.HighLevelAPI41; using HLA80 = Net.Pkcs11Interop.HighLevelAPI80; using HLA81 = Net.Pkcs11Interop.HighLevelAPI81; using LLA40 = Net.Pkcs11Interop.LowLevelAPI40; using LLA41 = Net.Pkcs11Interop.LowLevelAPI41; using LLA80 = Net.Pkcs11Interop.LowLevelAPI80; using LLA81 = Net.Pkcs11Interop.LowLevelAPI81; namespace Net.Pkcs11Interop.Tests.HighLevelAPI { /// <summary> /// Object attributes tests. /// </summary> [TestClass] public class _13_ObjectAttributeTest { /// <summary> /// Attribute dispose test. /// </summary> [TestMethod] public void _01_DisposeAttributeTest() { // Unmanaged memory for attribute value stored in low level CK_ATTRIBUTE struct // is allocated by constructor of ObjectAttribute class. ObjectAttribute attr1 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); // Do something interesting with attribute // This unmanaged memory is freed by Dispose() method. attr1.Dispose(); // ObjectAttribute class can be used in using statement which defines a scope // at the end of which an object will be disposed (and unmanaged memory freed). using (ObjectAttribute attr2 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA)) { // Do something interesting with attribute } #pragma warning disable 0219 // Explicit calling of Dispose() method can also be ommitted. ObjectAttribute attr3 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); // Do something interesting with attribute // Dispose() method will be called (and unmanaged memory freed) by GC eventually // but we cannot be sure when will this occur. #pragma warning restore 0219 } /// <summary> /// Attribute with empty value test. /// </summary> [TestMethod] public void _02_EmptyAttributeTest() { // Create attribute without the value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS); Assert.IsTrue(attr.GetValueAsByteArray() == null); } } /// <summary> /// Attribute with ulong value test. /// </summary> [TestMethod] public void _03_UintAttributeTest() { ulong value = (ulong)CKO.CKO_DATA; // Create attribute with ulong value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS); Assert.IsTrue(attr.GetValueAsUlong() == value); } } /// <summary> /// Attribute with bool value test. /// </summary> [TestMethod] public void _04_BoolAttributeTest() { bool value = true; // Create attribute with bool value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_TOKEN, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_TOKEN); Assert.IsTrue(attr.GetValueAsBool() == value); } } /// <summary> /// Attribute with string value test. /// </summary> [TestMethod] public void _05_StringAttributeTest() { string value = "Hello world"; // Create attribute with string value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL); Assert.IsTrue(attr.GetValueAsString() == value); } value = null; // Create attribute with null string value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL); Assert.IsTrue(attr.GetValueAsString() == value); } } /// <summary> /// Attribute with byte array value test. /// </summary> [TestMethod] public void _06_ByteArrayAttributeTest() { byte[] value = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; // Create attribute with byte array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID); Assert.IsTrue(Convert.ToBase64String(attr.GetValueAsByteArray()) == Convert.ToBase64String(value)); } value = null; // Create attribute with null byte array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID); Assert.IsTrue(attr.GetValueAsByteArray() == value); } } /// <summary> /// Attribute with DateTime (CKA_DATE) value test. /// </summary> [TestMethod] public void _07_DateTimeAttributeTest() { DateTime value = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc); // Create attribute with DateTime value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_START_DATE, value)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_START_DATE); Assert.IsTrue(attr.GetValueAsDateTime() == value); } } /// <summary> /// Attribute with attribute array value test. /// </summary> [TestMethod] public void _08_AttributeArrayAttributeTest() { ObjectAttribute nestedAttribute1 = new ObjectAttribute(CKA.CKA_TOKEN, true); ObjectAttribute nestedAttribute2 = new ObjectAttribute(CKA.CKA_PRIVATE, true); List<ObjectAttribute> originalValue = new List<ObjectAttribute>(); originalValue.Add(nestedAttribute1); originalValue.Add(nestedAttribute2); // Create attribute with attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE); List<ObjectAttribute> recoveredValue = attr.GetValueAsObjectAttributeList(); Assert.IsTrue(recoveredValue.Count == 2); Assert.IsTrue(recoveredValue[0].Type == (ulong)CKA.CKA_TOKEN); Assert.IsTrue(recoveredValue[0].GetValueAsBool() == true); Assert.IsTrue(recoveredValue[1].Type == (ulong)CKA.CKA_PRIVATE); Assert.IsTrue(recoveredValue[1].GetValueAsBool() == true); } if (Platform.UnmanagedLongSize == 4) { if (Platform.StructPackingSize == 0) { // There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA40.ObjectAttribute objectAttribute40a = (HLA40.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1); LLA40.CK_ATTRIBUTE ckAttribute40a = (LLA40.CK_ATTRIBUTE)typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute40a); ckAttribute40a.value = IntPtr.Zero; ckAttribute40a.valueLen = 0; typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute40a, ckAttribute40a); // There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA40.ObjectAttribute objectAttribute40b = (HLA40.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2); LLA40.CK_ATTRIBUTE ckAttribute40b = (LLA40.CK_ATTRIBUTE)typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute40b); ckAttribute40b.value = IntPtr.Zero; ckAttribute40b.valueLen = 0; typeof(HLA40.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute40b, ckAttribute40b); } else { // There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA41.ObjectAttribute objectAttribute41a = (HLA41.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1); LLA41.CK_ATTRIBUTE ckAttribute41a = (LLA41.CK_ATTRIBUTE)typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute41a); ckAttribute41a.value = IntPtr.Zero; ckAttribute41a.valueLen = 0; typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute41a, ckAttribute41a); // There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA41.ObjectAttribute objectAttribute41b = (HLA41.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2); LLA41.CK_ATTRIBUTE ckAttribute41b = (LLA41.CK_ATTRIBUTE)typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute41b); ckAttribute41b.value = IntPtr.Zero; ckAttribute41b.valueLen = 0; typeof(HLA41.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute41b, ckAttribute41b); } } else { if (Platform.StructPackingSize == 0) { // There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA80.ObjectAttribute objectAttribute80a = (HLA80.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1); LLA80.CK_ATTRIBUTE ckAttribute80a = (LLA80.CK_ATTRIBUTE)typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute80a); ckAttribute80a.value = IntPtr.Zero; ckAttribute80a.valueLen = 0; typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute80a, ckAttribute80a); // There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA80.ObjectAttribute objectAttribute80b = (HLA80.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2); LLA80.CK_ATTRIBUTE ckAttribute80b = (LLA80.CK_ATTRIBUTE)typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute80b); ckAttribute80b.value = IntPtr.Zero; ckAttribute80b.valueLen = 0; typeof(HLA80.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute80b, ckAttribute80b); } else { // There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA81.ObjectAttribute objectAttribute81a = (HLA81.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1); LLA81.CK_ATTRIBUTE ckAttribute81a = (LLA81.CK_ATTRIBUTE)typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute81a); ckAttribute81a.value = IntPtr.Zero; ckAttribute81a.valueLen = 0; typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute81a, ckAttribute81a); // There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances // therefore private low level attribute structure needs to be modified to prevent double free. // This special handling is needed only in this synthetic test and should be avoided in real world application. HLA81.ObjectAttribute objectAttribute81b = (HLA81.ObjectAttribute)typeof(ObjectAttribute).GetField("_objectAttribute81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2); LLA81.CK_ATTRIBUTE ckAttribute81b = (LLA81.CK_ATTRIBUTE)typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectAttribute81b); ckAttribute81b.value = IntPtr.Zero; ckAttribute81b.valueLen = 0; typeof(HLA81.ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectAttribute81b, ckAttribute81b); } } originalValue = null; // Create attribute with null attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.GetValueAsObjectAttributeList() == originalValue); } originalValue = new List<ObjectAttribute>(); // Create attribute with empty attribute array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.GetValueAsObjectAttributeList() == null); } } /// <summary> /// Attribute with ulong array value test. /// </summary> [TestMethod] public void _09_UintArrayAttributeTest() { List<ulong> originalValue = new List<ulong>(); originalValue.Add(333333); originalValue.Add(666666); // Create attribute with ulong array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); List<ulong> recoveredValue = attr.GetValueAsUlongList(); for (int i = 0; i < recoveredValue.Count; i++) Assert.IsTrue(originalValue[i] == recoveredValue[i]); } originalValue = null; // Create attribute with null ulong array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsUlongList() == originalValue); } originalValue = new List<ulong>(); // Create attribute with empty ulong array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsUlongList() == null); } } /// <summary> /// Attribute with mechanism array value test. /// </summary> [TestMethod] public void _10_MechanismArrayAttributeTest() { List<CKM> originalValue = new List<CKM>(); originalValue.Add(CKM.CKM_RSA_PKCS); originalValue.Add(CKM.CKM_AES_CBC); // Create attribute with mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); List<CKM> recoveredValue = attr.GetValueAsCkmList(); for (int i = 0; i < recoveredValue.Count; i++) Assert.IsTrue(originalValue[i] == recoveredValue[i]); } originalValue = null; // Create attribute with null mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsCkmList() == originalValue); } originalValue = new List<CKM>(); // Create attribute with empty mechanism array value using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue)) { Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.GetValueAsCkmList() == null); } } } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Neo.IO; using Neo.SmartContract; using System; using System.Collections.Generic; using System.Linq; namespace Neo.Persistence { /// <summary> /// Represents a cache for the underlying storage of the NEO blockchain. /// </summary> public abstract class DataCache { /// <summary> /// Represents an entry in the cache. /// </summary> public class Trackable { /// <summary> /// The key of the entry. /// </summary> public StorageKey Key; /// <summary> /// The data of the entry. /// </summary> public StorageItem Item; /// <summary> /// The state of the entry. /// </summary> public TrackState State; } private readonly Dictionary<StorageKey, Trackable> dictionary = new(); private readonly HashSet<StorageKey> changeSet = new(); /// <summary> /// Reads a specified entry from the cache. If the entry is not in the cache, it will be automatically loaded from the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> /// <returns>The cached data.</returns> /// <exception cref="KeyNotFoundException">If the entry doesn't exist.</exception> public StorageItem this[StorageKey key] { get { lock (dictionary) { if (dictionary.TryGetValue(key, out Trackable trackable)) { if (trackable.State == TrackState.Deleted) throw new KeyNotFoundException(); } else { trackable = new Trackable { Key = key, Item = GetInternal(key), State = TrackState.None }; dictionary.Add(key, trackable); } return trackable.Item; } } } /// <summary> /// Adds a new entry to the cache. /// </summary> /// <param name="key">The key of the entry.</param> /// <param name="value">The data of the entry.</param> /// <exception cref="ArgumentException">The entry has already been cached.</exception> /// <remarks>Note: This method does not read the internal storage to check whether the record already exists.</remarks> public void Add(StorageKey key, StorageItem value) { lock (dictionary) { if (dictionary.TryGetValue(key, out Trackable trackable) && trackable.State != TrackState.Deleted) throw new ArgumentException(); dictionary[key] = new Trackable { Key = key, Item = value, State = trackable == null ? TrackState.Added : TrackState.Changed }; changeSet.Add(key); } } /// <summary> /// Adds a new entry to the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> /// <param name="value">The data of the entry.</param> protected abstract void AddInternal(StorageKey key, StorageItem value); /// <summary> /// Commits all changes in the cache to the underlying storage. /// </summary> public virtual void Commit() { LinkedList<StorageKey> deletedItem = new(); foreach (Trackable trackable in GetChangeSet()) switch (trackable.State) { case TrackState.Added: AddInternal(trackable.Key, trackable.Item); trackable.State = TrackState.None; break; case TrackState.Changed: UpdateInternal(trackable.Key, trackable.Item); trackable.State = TrackState.None; break; case TrackState.Deleted: DeleteInternal(trackable.Key); deletedItem.AddFirst(trackable.Key); break; } foreach (StorageKey key in deletedItem) { dictionary.Remove(key); } changeSet.Clear(); } /// <summary> /// Creates a snapshot, which uses this instance as the underlying storage. /// </summary> /// <returns>The snapshot of this instance.</returns> public DataCache CreateSnapshot() { return new ClonedCache(this); } /// <summary> /// Deletes an entry from the cache. /// </summary> /// <param name="key">The key of the entry.</param> public void Delete(StorageKey key) { lock (dictionary) { if (dictionary.TryGetValue(key, out Trackable trackable)) { if (trackable.State == TrackState.Added) { dictionary.Remove(key); changeSet.Remove(key); } else { trackable.State = TrackState.Deleted; changeSet.Add(key); } } else { StorageItem item = TryGetInternal(key); if (item == null) return; dictionary.Add(key, new Trackable { Key = key, Item = item, State = TrackState.Deleted }); changeSet.Add(key); } } } /// <summary> /// Deletes an entry from the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> protected abstract void DeleteInternal(StorageKey key); /// <summary> /// Finds the entries starting with the specified prefix. /// </summary> /// <param name="key_prefix">The prefix of the key.</param> /// <returns>The entries found with the desired prefix.</returns> public IEnumerable<(StorageKey Key, StorageItem Value)> Find(byte[] key_prefix = null) { foreach (var (key, value) in Seek(key_prefix, SeekDirection.Forward)) if (key.ToArray().AsSpan().StartsWith(key_prefix)) yield return (key, value); else yield break; } /// <summary> /// Finds the entries that between [start, end). /// </summary> /// <param name="start">The start key (inclusive).</param> /// <param name="end">The end key (exclusive).</param> /// <param name="direction">The search direction.</param> /// <returns>The entries found with the desired range.</returns> public IEnumerable<(StorageKey Key, StorageItem Value)> FindRange(byte[] start, byte[] end, SeekDirection direction = SeekDirection.Forward) { ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse; foreach (var (key, value) in Seek(start, direction)) if (comparer.Compare(key.ToArray(), end) < 0) yield return (key, value); else yield break; } /// <summary> /// Gets the change set in the cache. /// </summary> /// <returns>The change set.</returns> public IEnumerable<Trackable> GetChangeSet() { lock (dictionary) { foreach (StorageKey key in changeSet) yield return dictionary[key]; } } /// <summary> /// Determines whether the cache contains the specified entry. /// </summary> /// <param name="key">The key of the entry.</param> /// <returns><see langword="true"/> if the cache contains an entry with the specified key; otherwise, <see langword="false"/>.</returns> public bool Contains(StorageKey key) { lock (dictionary) { if (dictionary.TryGetValue(key, out Trackable trackable)) { if (trackable.State == TrackState.Deleted) return false; return true; } return ContainsInternal(key); } } /// <summary> /// Determines whether the underlying storage contains the specified entry. /// </summary> /// <param name="key">The key of the entry.</param> /// <returns><see langword="true"/> if the underlying storage contains an entry with the specified key; otherwise, <see langword="false"/>.</returns> protected abstract bool ContainsInternal(StorageKey key); /// <summary> /// Reads a specified entry from the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> /// <returns>The data of the entry. Or <see langword="null"/> if the entry doesn't exist.</returns> protected abstract StorageItem GetInternal(StorageKey key); /// <summary> /// Reads a specified entry from the cache, and mark it as <see cref="TrackState.Changed"/>. If the entry is not in the cache, it will be automatically loaded from the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> /// <param name="factory">A delegate used to create the entry if it doesn't exist. If the entry already exists, the factory will not be used.</param> /// <returns>The cached data. Or <see langword="null"/> if it doesn't exist and the <paramref name="factory"/> is not provided.</returns> public StorageItem GetAndChange(StorageKey key, Func<StorageItem> factory = null) { lock (dictionary) { if (dictionary.TryGetValue(key, out Trackable trackable)) { if (trackable.State == TrackState.Deleted) { if (factory == null) return null; trackable.Item = factory(); trackable.State = TrackState.Changed; } else if (trackable.State == TrackState.None) { trackable.State = TrackState.Changed; changeSet.Add(key); } } else { trackable = new Trackable { Key = key, Item = TryGetInternal(key) }; if (trackable.Item == null) { if (factory == null) return null; trackable.Item = factory(); trackable.State = TrackState.Added; } else { trackable.State = TrackState.Changed; } dictionary.Add(key, trackable); changeSet.Add(key); } return trackable.Item; } } /// <summary> /// Reads a specified entry from the cache. If the entry is not in the cache, it will be automatically loaded from the underlying storage. If the entry doesn't exist, the factory will be used to create a new one. /// </summary> /// <param name="key">The key of the entry.</param> /// <param name="factory">A delegate used to create the entry if it doesn't exist. If the entry already exists, the factory will not be used.</param> /// <returns>The cached data.</returns> public StorageItem GetOrAdd(StorageKey key, Func<StorageItem> factory) { lock (dictionary) { if (dictionary.TryGetValue(key, out Trackable trackable)) { if (trackable.State == TrackState.Deleted) { trackable.Item = factory(); trackable.State = TrackState.Changed; } } else { trackable = new Trackable { Key = key, Item = TryGetInternal(key) }; if (trackable.Item == null) { trackable.Item = factory(); trackable.State = TrackState.Added; changeSet.Add(key); } else { trackable.State = TrackState.None; } dictionary.Add(key, trackable); } return trackable.Item; } } /// <summary> /// Seeks to the entry with the specified key. /// </summary> /// <param name="keyOrPrefix">The key to be sought.</param> /// <param name="direction">The direction of seek.</param> /// <returns>An enumerator containing all the entries after seeking.</returns> public IEnumerable<(StorageKey Key, StorageItem Value)> Seek(byte[] keyOrPrefix = null, SeekDirection direction = SeekDirection.Forward) { IEnumerable<(byte[], StorageKey, StorageItem)> cached; HashSet<StorageKey> cachedKeySet; ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse; lock (dictionary) { cached = dictionary .Where(p => p.Value.State != TrackState.Deleted && (keyOrPrefix == null || comparer.Compare(p.Key.ToArray(), keyOrPrefix) >= 0)) .Select(p => ( KeyBytes: p.Key.ToArray(), p.Key, p.Value.Item )) .OrderBy(p => p.KeyBytes, comparer) .ToArray(); cachedKeySet = new HashSet<StorageKey>(dictionary.Keys); } var uncached = SeekInternal(keyOrPrefix ?? Array.Empty<byte>(), direction) .Where(p => !cachedKeySet.Contains(p.Key)) .Select(p => ( KeyBytes: p.Key.ToArray(), p.Key, p.Value )); using var e1 = cached.GetEnumerator(); using var e2 = uncached.GetEnumerator(); (byte[] KeyBytes, StorageKey Key, StorageItem Item) i1, i2; bool c1 = e1.MoveNext(); bool c2 = e2.MoveNext(); i1 = c1 ? e1.Current : default; i2 = c2 ? e2.Current : default; while (c1 || c2) { if (!c2 || (c1 && comparer.Compare(i1.KeyBytes, i2.KeyBytes) < 0)) { yield return (i1.Key, i1.Item); c1 = e1.MoveNext(); i1 = c1 ? e1.Current : default; } else { yield return (i2.Key, i2.Item); c2 = e2.MoveNext(); i2 = c2 ? e2.Current : default; } } } /// <summary> /// Seeks to the entry with the specified key in the underlying storage. /// </summary> /// <param name="keyOrPrefix">The key to be sought.</param> /// <param name="direction">The direction of seek.</param> /// <returns>An enumerator containing all the entries after seeking.</returns> protected abstract IEnumerable<(StorageKey Key, StorageItem Value)> SeekInternal(byte[] keyOrPrefix, SeekDirection direction); /// <summary> /// Reads a specified entry from the cache. If the entry is not in the cache, it will be automatically loaded from the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> /// <returns>The cached data. Or <see langword="null"/> if it is neither in the cache nor in the underlying storage.</returns> public StorageItem TryGet(StorageKey key) { lock (dictionary) { if (dictionary.TryGetValue(key, out Trackable trackable)) { if (trackable.State == TrackState.Deleted) return null; return trackable.Item; } StorageItem value = TryGetInternal(key); if (value == null) return null; dictionary.Add(key, new Trackable { Key = key, Item = value, State = TrackState.None }); return value; } } /// <summary> /// Reads a specified entry from the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> /// <returns>The data of the entry. Or <see langword="null"/> if it doesn't exist.</returns> protected abstract StorageItem TryGetInternal(StorageKey key); /// <summary> /// Updates an entry in the underlying storage. /// </summary> /// <param name="key">The key of the entry.</param> /// <param name="value">The data of the entry.</param> protected abstract void UpdateInternal(StorageKey key, StorageItem value); } }
/* * 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. */ // ReSharper disable UnusedAutoPropertyAccessor.Global namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests for compute. /// </summary> public partial class ComputeApiTest { /** Java binary class name. */ private const string JavaBinaryCls = "PlatformComputeJavaBinarizable"; /** */ public const string DefaultCacheName = "default"; /** First node. */ private IIgnite _grid1; /** Second node. */ private IIgnite _grid2; /** Third node. */ private IIgnite _grid3; /** Thin client. */ private IIgniteClient _igniteClient; /// <summary> /// Initialization routine. /// </summary> [TestFixtureSetUp] public void InitClient() { var configs = GetConfigs(); _grid1 = Ignition.Start(Configuration(configs.Item1)); _grid2 = Ignition.Start(Configuration(configs.Item2)); AffinityTopologyVersion waitingTop = new AffinityTopologyVersion(2, 1); Assert.True(_grid1.WaitTopology(waitingTop), "Failed to wait topology " + waitingTop); _grid3 = Ignition.Start(Configuration(configs.Item3)); // Start thin client. _igniteClient = Ignition.StartClient(GetThinClientConfiguration()); } /// <summary> /// Gets the configs. /// </summary> protected virtual Tuple<string, string, string> GetConfigs() { var path = Path.Combine("Config", "Compute", "compute-grid"); return Tuple.Create(path + "1.xml", path + "2.xml", path + "3.xml"); } /// <summary> /// Gets the thin client configuration. /// </summary> private static IgniteClientConfiguration GetThinClientConfiguration() { return new IgniteClientConfiguration { Endpoints = new List<string> { IPAddress.Loopback.ToString() }, SocketTimeout = TimeSpan.FromSeconds(15) }; } /// <summary> /// Gets the expected compact footers setting. /// </summary> protected virtual bool CompactFooter { get { return true; } } [TestFixtureTearDown] public void StopClient() { Ignition.StopAll(true); } [TearDown] public void AfterTest() { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3); } /// <summary> /// Test that it is possible to get projection from grid. /// </summary> [Test] public void TestProjection() { IClusterGroup prj = _grid1.GetCluster(); Assert.NotNull(prj); Assert.AreEqual(prj, prj.Ignite); // Check that default Compute projection excludes client nodes. CollectionAssert.AreEquivalent(prj.ForServers().GetNodes(), prj.GetCompute().ClusterGroup.GetNodes()); } /// <summary> /// Test non-existent cache. /// </summary> [Test] public void TestNonExistentCache() { Assert.Catch(typeof(ArgumentException), () => { _grid1.GetCache<int, int>("bad_name"); }); } /// <summary> /// Test node content. /// </summary> [Test] public void TestNodeContent() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); foreach (IClusterNode node in nodes) { Assert.NotNull(node.Addresses); Assert.IsTrue(node.Addresses.Count > 0); Assert.Throws<NotSupportedException>(() => node.Addresses.Add("addr")); Assert.NotNull(node.Attributes); Assert.IsTrue(node.Attributes.Count > 0); Assert.Throws<NotSupportedException>(() => node.Attributes.Add("key", "val")); #pragma warning disable 618 Assert.AreSame(node.Attributes, node.GetAttributes()); #pragma warning restore 618 Assert.NotNull(node.HostNames); Assert.Throws<NotSupportedException>(() => node.HostNames.Add("h")); Assert.IsTrue(node.Id != Guid.Empty); Assert.IsTrue(node.Order > 0); Assert.NotNull(node.GetMetrics()); } } /// <summary> /// Test cluster metrics. /// </summary> [Test] public void TestClusterMetrics() { var cluster = _grid1.GetCluster(); IClusterMetrics metrics = cluster.GetMetrics(); Assert.IsNotNull(metrics); Assert.AreEqual(cluster.GetNodes().Count, metrics.TotalNodes); Thread.Sleep(2000); IClusterMetrics newMetrics = cluster.GetMetrics(); Assert.IsFalse(metrics == newMetrics); Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime); } /// <summary> /// Test cluster metrics. /// </summary> [Test] public void TestNodeMetrics() { var node = _grid1.GetCluster().GetNode(); IClusterMetrics metrics = node.GetMetrics(); Assert.IsNotNull(metrics); Assert.IsTrue(metrics == node.GetMetrics()); Thread.Sleep(2000); IClusterMetrics newMetrics = node.GetMetrics(); Assert.IsFalse(metrics == newMetrics); Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime); } /// <summary> /// Test cluster metrics. /// </summary> [Test] public void TestResetMetrics() { var cluster = _grid1.GetCluster(); Thread.Sleep(2000); var metrics1 = cluster.GetMetrics(); cluster.ResetMetrics(); var metrics2 = cluster.GetMetrics(); Assert.IsNotNull(metrics1); Assert.IsNotNull(metrics2); } /// <summary> /// Test node ping. /// </summary> [Test] public void TestPingNode() { var cluster = _grid1.GetCluster(); Assert.IsTrue(cluster.GetNodes().Select(node => node.Id).All(cluster.PingNode)); Assert.IsFalse(cluster.PingNode(Guid.NewGuid())); } /// <summary> /// Tests the topology version. /// </summary> [Test] public void TestTopologyVersion() { var cluster = _grid1.GetCluster(); var topVer = cluster.TopologyVersion; Ignition.Stop(_grid3.Name, true); Assert.AreEqual(topVer + 1, _grid1.GetCluster().TopologyVersion); _grid3 = Ignition.Start(Configuration(GetConfigs().Item3)); Assert.AreEqual(topVer + 2, _grid1.GetCluster().TopologyVersion); } /// <summary> /// Tests the topology by version. /// </summary> [Test] public void TestTopology() { var cluster = _grid1.GetCluster(); Assert.AreEqual(1, cluster.GetTopology(1).Count); Assert.AreEqual(null, cluster.GetTopology(int.MaxValue)); // Check that Nodes and Topology return the same for current version var topVer = cluster.TopologyVersion; var top = cluster.GetTopology(topVer); var nodes = cluster.GetNodes(); Assert.AreEqual(top.Count, nodes.Count); Assert.IsTrue(top.All(nodes.Contains)); // Stop/start node to advance version and check that history is still correct Assert.IsTrue(Ignition.Stop(_grid2.Name, true)); try { top = cluster.GetTopology(topVer); Assert.AreEqual(top.Count, nodes.Count); Assert.IsTrue(top.All(nodes.Contains)); } finally { _grid2 = Ignition.Start(Configuration(GetConfigs().Item2)); } } /// <summary> /// Test nodes in full topology. /// </summary> [Test] public void TestNodes() { Assert.IsNotNull(_grid1.GetCluster().GetNode()); ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 3); // Check subsequent call on the same topology. nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 3); Assert.IsTrue(Ignition.Stop(_grid2.Name, true)); // Check subsequent calls on updating topologies. nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 2); nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 2); _grid2 = Ignition.Start(Configuration(GetConfigs().Item2)); nodes = _grid1.GetCluster().GetNodes(); Assert.IsTrue(nodes.Count == 3); } /// <summary> /// Test "ForNodes" and "ForNodeIds". /// </summary> [Test] public void TestForNodes() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterNode first = nodes.ElementAt(0); IClusterNode second = nodes.ElementAt(1); IClusterGroup singleNodePrj = _grid1.GetCluster().ForNodeIds(first.Id); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); singleNodePrj = _grid1.GetCluster().ForNodeIds(new List<Guid> { first.Id }); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); singleNodePrj = _grid1.GetCluster().ForNodes(first); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); singleNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first }); Assert.AreEqual(1, singleNodePrj.GetNodes().Count); Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id); IClusterGroup multiNodePrj = _grid1.GetCluster().ForNodeIds(first.Id, second.Id); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); multiNodePrj = _grid1.GetCluster().ForNodeIds(new[] {first, second}.Select(x => x.Id)); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); multiNodePrj = _grid1.GetCluster().ForNodes(first, second); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); multiNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first, second }); Assert.AreEqual(2, multiNodePrj.GetNodes().Count); Assert.IsTrue(multiNodePrj.GetNodes().Contains(first)); Assert.IsTrue(multiNodePrj.GetNodes().Contains(second)); } /// <summary> /// Test "ForNodes" and "ForNodeIds". Make sure lazy enumerables are enumerated only once. /// </summary> [Test] public void TestForNodesLaziness() { var nodes = _grid1.GetCluster().GetNodes().Take(2).ToArray(); var callCount = 0; Func<IClusterNode, IClusterNode> nodeSelector = node => { callCount++; return node; }; Func<IClusterNode, Guid> idSelector = node => { callCount++; return node.Id; }; var projection = _grid1.GetCluster().ForNodes(nodes.Select(nodeSelector)); Assert.AreEqual(2, projection.GetNodes().Count); Assert.AreEqual(2, callCount); projection = _grid1.GetCluster().ForNodeIds(nodes.Select(idSelector)); Assert.AreEqual(2, projection.GetNodes().Count); Assert.AreEqual(4, callCount); } /// <summary> /// Test for local node projection. /// </summary> [Test] public void TestForLocal() { IClusterGroup prj = _grid1.GetCluster().ForLocal(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.AreEqual(_grid1.GetCluster().GetLocalNode(), prj.GetNodes().First()); } /// <summary> /// Test for remote nodes projection. /// </summary> [Test] public void TestForRemotes() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForRemotes(); Assert.AreEqual(2, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0))); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1))); } /// <summary> /// Test for daemon nodes projection. /// </summary> [Test] public void TestForDaemons() { Assert.AreEqual(0, _grid1.GetCluster().ForDaemons().GetNodes().Count); using (var ignite = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = GetConfigs().Item1, IgniteInstanceName = "daemonGrid", IsDaemon = true }) ) { var prj = _grid1.GetCluster().ForDaemons(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.AreEqual(ignite.GetCluster().GetLocalNode().Id, prj.GetNode().Id); Assert.IsTrue(prj.GetNode().IsDaemon); Assert.IsTrue(ignite.GetCluster().GetLocalNode().IsDaemon); } } /// <summary> /// Test for host nodes projection. /// </summary> [Test] public void TestForHost() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForHost(nodes.First()); Assert.AreEqual(3, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0))); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1))); Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(2))); } /// <summary> /// Test for oldest, youngest and random projections. /// </summary> [Test] public void TestForOldestYoungestRandom() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForYoungest(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); prj = _grid1.GetCluster().ForOldest(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); prj = _grid1.GetCluster().ForRandom(); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); } /// <summary> /// Tests ForServers projection. /// </summary> [Test] public void TestForServers() { var cluster = _grid1.GetCluster(); var servers = cluster.ForServers().GetNodes(); Assert.AreEqual(2, servers.Count); Assert.IsTrue(servers.All(x => !x.IsClient)); var serverAndClient = cluster.ForNodeIds(new[] { _grid2, _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id)); Assert.AreEqual(1, serverAndClient.ForServers().GetNodes().Count); var client = cluster.ForNodeIds(new[] { _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id)); Assert.AreEqual(0, client.ForServers().GetNodes().Count); } /// <summary> /// Tests thin client ForServers projection. /// </summary> [Test] public void TestThinClientForServers() { var cluster = _igniteClient.GetCluster(); var servers = cluster.ForServers().GetNodes(); Assert.AreEqual(2, servers.Count); Assert.IsTrue(servers.All(x => !x.IsClient)); } /// <summary> /// Test for attribute projection. /// </summary> [Test] public void TestForAttribute() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); IClusterGroup prj = _grid1.GetCluster().ForAttribute("my_attr", "value1"); Assert.AreEqual(1, prj.GetNodes().Count); Assert.IsTrue(nodes.Contains(prj.GetNode())); Assert.AreEqual("value1", prj.GetNodes().First().GetAttribute<string>("my_attr")); } /// <summary> /// Test thin client for attribute projection. /// </summary> [Test] public void TestClientForAttribute() { IClientClusterGroup clientPrj = _igniteClient.GetCluster().ForAttribute("my_attr", "value1"); Assert.AreEqual(1,clientPrj.GetNodes().Count); var nodeId = _grid1.GetCluster().ForAttribute("my_attr", "value1").GetNodes().Single().Id; Assert.AreEqual(nodeId, clientPrj.GetNode().Id); } /// <summary> /// Test for cache/data/client projections. /// </summary> [Test] public void TestForCacheNodes() { ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes(); // Cache nodes. IClusterGroup prjCache = _grid1.GetCluster().ForCacheNodes("cache1"); Assert.AreEqual(2, prjCache.GetNodes().Count); Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(0))); Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(1))); // Data nodes. IClusterGroup prjData = _grid1.GetCluster().ForDataNodes("cache1"); Assert.AreEqual(2, prjData.GetNodes().Count); Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(0))); Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(1))); // Client nodes. IClusterGroup prjClient = _grid1.GetCluster().ForClientNodes("cache1"); Assert.AreEqual(0, prjClient.GetNodes().Count); } /// <summary> /// Test for cache predicate. /// </summary> [Test] public void TestForPredicate() { IClusterGroup prj1 = _grid1.GetCluster() .ForPredicate(new NotAttributePredicate<IClusterNode>("value1").Apply); Assert.AreEqual(2, prj1.GetNodes().Count); IClusterGroup prj2 = prj1 .ForPredicate(new NotAttributePredicate<IClusterNode>("value2").Apply); Assert.AreEqual(1, prj2.GetNodes().Count); string val; prj2.GetNodes().First().TryGetAttribute("my_attr", out val); Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2"))); } /// <summary> /// Test thin client for cache predicate. /// </summary> [Test] public void TestClientForPredicate() { var prj1 = _igniteClient.GetCluster() .ForPredicate(new NotAttributePredicate<IClientClusterNode>("value1").Apply); Assert.AreEqual(2, prj1.GetNodes().Count); var prj2 = prj1 .ForPredicate(new NotAttributePredicate<IClientClusterNode>("value2").Apply); Assert.AreEqual(1, prj2.GetNodes().Count); var val = (string) prj2.GetNodes().First().Attributes.FirstOrDefault(attr => attr.Key == "my_attr").Value; Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2"))); } /// <summary> /// Attribute predicate. /// </summary> private class NotAttributePredicate<T> where T: IBaselineNode { /** Required attribute value. */ private readonly string _attrVal; /// <summary> /// Constructor. /// </summary> /// <param name="attrVal">Required attribute value.</param> public NotAttributePredicate(string attrVal) { _attrVal = attrVal; } /** <inhreitDoc /> */ public bool Apply(T node) { object val; node.Attributes.TryGetValue("my_attr", out val); return val == null || !val.Equals(_attrVal); } } /// <summary> /// Tests the action broadcast. /// </summary> [Test] public void TestBroadcastAction() { var id = Guid.NewGuid(); _grid1.GetCompute().Broadcast(new ComputeAction(id)); Assert.AreEqual(2, ComputeAction.InvokeCount(id)); id = Guid.NewGuid(); _grid1.GetCompute().BroadcastAsync(new ComputeAction(id)).Wait(); Assert.AreEqual(2, ComputeAction.InvokeCount(id)); } /// <summary> /// Tests single action run. /// </summary> [Test] public void TestRunAction() { var id = Guid.NewGuid(); _grid1.GetCompute().Run(new ComputeAction(id)); Assert.AreEqual(1, ComputeAction.InvokeCount(id)); id = Guid.NewGuid(); _grid1.GetCompute().RunAsync(new ComputeAction(id)).Wait(); Assert.AreEqual(1, ComputeAction.InvokeCount(id)); } /// <summary> /// Tests single action run. /// </summary> [Test] public void TestRunActionAsyncCancel() { using (var cts = new CancellationTokenSource()) { // Cancel while executing var task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token); cts.Cancel(); Assert.IsTrue(task.IsCanceled); // Use cancelled token task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token); Assert.IsTrue(task.IsCanceled); } } /// <summary> /// Tests multiple actions run. /// </summary> [Test] public void TestRunActions() { var id = Guid.NewGuid(); _grid1.GetCompute().Run(Enumerable.Range(0, 10).Select(x => new ComputeAction(id))); Assert.AreEqual(10, ComputeAction.InvokeCount(id)); var id2 = Guid.NewGuid(); _grid1.GetCompute().RunAsync(Enumerable.Range(0, 10).Select(x => new ComputeAction(id2))).Wait(); Assert.AreEqual(10, ComputeAction.InvokeCount(id2)); } /// <summary> /// Tests affinity run. /// </summary> [Test] public void TestAffinityRun() { const string cacheName = DefaultCacheName; // Test keys for non-client nodes var nodes = new[] {_grid1, _grid2}.Select(x => x.GetCluster().GetLocalNode()); var aff = _grid1.GetAffinity(cacheName); foreach (var node in nodes) { var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node); var affinityKey = aff.GetAffinityKey<int, int>(primaryKey); var computeAction = new ComputeAction { ReservedPartition = aff.GetPartition(primaryKey), CacheNames = new[] {cacheName} }; _grid1.GetCompute().AffinityRun(cacheName, affinityKey, computeAction); Assert.AreEqual(node.Id, ComputeAction.LastNodeId); _grid1.GetCompute().AffinityRunAsync(cacheName, affinityKey, computeAction).Wait(); Assert.AreEqual(node.Id, ComputeAction.LastNodeId); } } /// <summary> /// Tests affinity call. /// </summary> [Test] public void TestAffinityCall() { const string cacheName = DefaultCacheName; // Test keys for non-client nodes var nodes = new[] { _grid1, _grid2 }.Select(x => x.GetCluster().GetLocalNode()); var aff = _grid1.GetAffinity(cacheName); foreach (var node in nodes) { var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node); var affinityKey = aff.GetAffinityKey<int, int>(primaryKey); var result = _grid1.GetCompute().AffinityCall(cacheName, affinityKey, new ComputeFunc()); Assert.AreEqual(result, ComputeFunc.InvokeCount); Assert.AreEqual(node.Id, ComputeFunc.LastNodeId); // Async. ComputeFunc.InvokeCount = 0; result = _grid1.GetCompute().AffinityCallAsync(cacheName, affinityKey, new ComputeFunc()).Result; Assert.AreEqual(result, ComputeFunc.InvokeCount); Assert.AreEqual(node.Id, ComputeFunc.LastNodeId); } } /// <summary> /// Tests affinity call with partition. /// </summary> [Test] public void TestAffinityCallWithPartition([Values(true, false)] bool async) { var cacheName = DefaultCacheName; var aff = _grid1.GetAffinity(cacheName); var localNode = _grid1.GetCluster().GetLocalNode(); var part = aff.GetPrimaryPartitions(localNode).First(); var compute = _grid1.GetCompute(); Func<IEnumerable<string>, int> action = names => async ? compute.AffinityCallAsync(names, part, new ComputeFunc()).Result : compute.AffinityCall(names, part, new ComputeFunc()); // One cache. var res = action(new[] {cacheName}); Assert.AreEqual(res, ComputeFunc.InvokeCount); Assert.AreEqual(localNode.Id, ComputeFunc.LastNodeId); // Two caches. var cache = _grid1.CreateCache<int, int>(TestUtils.TestName); res = action(new[] {cacheName, cache.Name}); Assert.AreEqual(res, ComputeFunc.InvokeCount); Assert.AreEqual(localNode.Id, ComputeFunc.LastNodeId); // Empty caches. var ex = Assert.Throws<ArgumentException>(() => action(new string[0])); StringAssert.StartsWith("cacheNames can not be empty", ex.Message); // Invalid cache name. Assert.Throws<AggregateException>(() => action(new[] {"bad"})); // Invalid partition. Assert.Throws<ArgumentException>(() => compute.AffinityCall(new[] {cacheName}, -1, new ComputeFunc())); } /// <summary> /// Tests affinity run with partition. /// </summary> [Test] public void TestAffinityRunWithPartition([Values(true, false)] bool local, [Values(true, false)] bool multiCache, [Values(true, false)] bool async) { var cacheNames = new List<string> {DefaultCacheName}; if (multiCache) { var cache2 = _grid1.CreateCache<int, int>(TestUtils.TestName); cacheNames.Add(cache2.Name); } var node = local ? _grid1.GetCluster().GetLocalNode() : _grid2.GetCluster().GetLocalNode(); var aff = _grid1.GetAffinity(cacheNames[0]); // Wait for some partitions to be assigned to the node. TestUtils.WaitForTrueCondition(() => aff.GetPrimaryPartitions(node).Any()); var part = aff.GetPrimaryPartitions(node).First(); var computeAction = new ComputeAction { ReservedPartition = part, CacheNames = cacheNames }; var action = async ? (Action) (() => _grid1.GetCompute().AffinityRunAsync(cacheNames, part, computeAction).Wait()) : () => _grid1.GetCompute().AffinityRun(cacheNames, part, computeAction); // Good case. action(); Assert.AreEqual(node.Id, ComputeAction.LastNodeId); // Exception in user code. computeAction.ShouldThrow = true; var aex = Assert.Throws<AggregateException>(() => action()); var ex = aex.GetBaseException(); StringAssert.StartsWith("Remote job threw user exception", ex.Message); Assert.AreEqual("Error in ComputeAction", ex.GetInnermostException().Message); } /// <summary> /// Tests affinity operations with cancellation. /// </summary> [Test] public void TestAffinityOpAsyncWithCancellation([Values(true, false)] bool callOrRun, [Values(true, false)] bool keyOrPart) { var compute = _grid1.GetCompute(); Action<CancellationToken> action = token => { if (callOrRun) { if (keyOrPart) { compute.AffinityCallAsync(DefaultCacheName, 1, new ComputeFunc(), token).Wait(); } else { compute.AffinityCallAsync(new[] {DefaultCacheName}, 1, new ComputeFunc(), token).Wait(); } } else { if (keyOrPart) { compute.AffinityRunAsync(DefaultCacheName, 1, new ComputeAction(), token).Wait(); } else { compute.AffinityRunAsync(new[] {DefaultCacheName}, 1, new ComputeAction(), token).Wait(); } } }; // Not cancelled. Assert.DoesNotThrow(() => action(CancellationToken.None)); // Cancelled. var ex = Assert.Throws<AggregateException>(() => action(new CancellationToken(true))); Assert.IsInstanceOf<TaskCanceledException>(ex.GetInnermostException()); } /// <summary> /// Test simple dotNet task execution. /// </summary> [Test] public void TestNetTaskSimple() { Assert.AreEqual(2, _grid1.GetCompute() .Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>( typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Res); Assert.AreEqual(2, _grid1.GetCompute() .ExecuteAsync<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>( typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Result.Res); Assert.AreEqual(4, _grid1.GetCompute().Execute(new NetSimpleTask(), new NetSimpleJobArgument(2)).Res); Assert.AreEqual(6, _grid1.GetCompute().ExecuteAsync(new NetSimpleTask(), new NetSimpleJobArgument(3)) .Result.Res); } /// <summary> /// Tests the exceptions. /// </summary> [Test] public void TestExceptions() { Assert.Throws<AggregateException>(() => _grid1.GetCompute().Broadcast(new InvalidComputeAction())); Assert.Throws<AggregateException>( () => _grid1.GetCompute().Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>( typeof (NetSimpleTask), new NetSimpleJobArgument(-1))); // Local. var ex = Assert.Throws<AggregateException>(() => _grid1.GetCluster().ForLocal().GetCompute().Broadcast(new ExceptionalComputeAction())); Assert.IsNotNull(ex.InnerException); Assert.AreEqual("Compute job has failed on local node, examine InnerException for details.", ex.InnerException.Message); Assert.IsNotNull(ex.InnerException.InnerException); Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message); // Remote. ex = Assert.Throws<AggregateException>(() => _grid1.GetCluster().ForRemotes().GetCompute().Broadcast(new ExceptionalComputeAction())); Assert.IsNotNull(ex.InnerException); Assert.AreEqual("Compute job has failed on remote node, examine InnerException for details.", ex.InnerException.Message); Assert.IsNotNull(ex.InnerException.InnerException); Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message); } /// <summary> /// Tests the footer setting. /// </summary> [Test] public void TestFooterSetting() { Assert.AreEqual(CompactFooter, ((Ignite) _grid1).Marshaller.CompactFooter); foreach (var g in new[] {_grid1, _grid2, _grid3}) Assert.AreEqual(CompactFooter, g.GetConfiguration().BinaryConfiguration.CompactFooter); } /// <summary> /// Create configuration. /// </summary> /// <param name="path">XML config path.</param> private static IgniteConfiguration Configuration(string path) { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof(PlatformComputeBinarizable)), new BinaryTypeConfiguration(typeof(PlatformComputeNetBinarizable)), new BinaryTypeConfiguration(JavaBinaryCls), new BinaryTypeConfiguration(typeof(PlatformComputeEnum)), new BinaryTypeConfiguration(typeof(InteropComputeEnumFieldTest)) }, NameMapper = new BinaryBasicNameMapper { IsSimpleName = true } }, SpringConfigUrl = path }; } } class PlatformComputeBinarizable { public int Field { get; set; } } class PlatformComputeNetBinarizable : PlatformComputeBinarizable { } [Serializable] class NetSimpleTask : IComputeTask<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult> { /** <inheritDoc /> */ public IDictionary<IComputeJob<NetSimpleJobResult>, IClusterNode> Map(IList<IClusterNode> subgrid, NetSimpleJobArgument arg) { var jobs = new Dictionary<IComputeJob<NetSimpleJobResult>, IClusterNode>(); for (int i = 0; i < subgrid.Count; i++) { var job = arg.Arg > 0 ? new NetSimpleJob {Arg = arg} : new InvalidNetSimpleJob(); jobs[job] = subgrid[i]; } return jobs; } /** <inheritDoc /> */ public ComputeJobResultPolicy OnResult(IComputeJobResult<NetSimpleJobResult> res, IList<IComputeJobResult<NetSimpleJobResult>> rcvd) { return ComputeJobResultPolicy.Wait; } /** <inheritDoc /> */ public NetSimpleTaskResult Reduce(IList<IComputeJobResult<NetSimpleJobResult>> results) { return new NetSimpleTaskResult(results.Sum(res => res.Data.Res)); } } [Serializable] class NetSimpleJob : IComputeJob<NetSimpleJobResult> { public NetSimpleJobArgument Arg; /** <inheritDoc /> */ public NetSimpleJobResult Execute() { return new NetSimpleJobResult(Arg.Arg); } /** <inheritDoc /> */ public void Cancel() { // No-op. } } class InvalidNetSimpleJob : NetSimpleJob, IBinarizable { public void WriteBinary(IBinaryWriter writer) { throw new BinaryObjectException("Expected"); } public void ReadBinary(IBinaryReader reader) { throw new BinaryObjectException("Expected"); } } [Serializable] class NetSimpleJobArgument { public int Arg; public NetSimpleJobArgument(int arg) { Arg = arg; } } [Serializable] class NetSimpleTaskResult { public int Res; public NetSimpleTaskResult(int res) { Res = res; } } [Serializable] class NetSimpleJobResult { public int Res; public NetSimpleJobResult(int res) { Res = res; } } [Serializable] class ComputeAction : IComputeAction { [InstanceResource] #pragma warning disable 649 // ReSharper disable once UnassignedField.Local private IIgnite _grid; public static ConcurrentBag<Guid> Invokes = new ConcurrentBag<Guid>(); public static Guid LastNodeId; public Guid Id { get; set; } public int? ReservedPartition { get; set; } public ICollection<string> CacheNames { get; set; } public bool ShouldThrow { get; set; } public ComputeAction() { // No-op. } public ComputeAction(Guid id) { Id = id; } public void Invoke() { Thread.Sleep(10); Invokes.Add(Id); LastNodeId = _grid.GetCluster().GetLocalNode().Id; if (ReservedPartition != null) { Assert.IsNotNull(CacheNames); foreach (var cacheName in CacheNames) { Assert.IsTrue(TestUtils.IsPartitionReserved(_grid, cacheName, ReservedPartition.Value)); } } if (ShouldThrow) { throw new Exception("Error in ComputeAction"); } } public static int InvokeCount(Guid id) { return Invokes.Count(x => x == id); } } class InvalidComputeAction : ComputeAction, IBinarizable { public void WriteBinary(IBinaryWriter writer) { throw new BinaryObjectException("Expected"); } public void ReadBinary(IBinaryReader reader) { throw new BinaryObjectException("Expected"); } } class ExceptionalComputeAction : IComputeAction { public const string ErrorText = "Expected user exception"; public void Invoke() { throw new OverflowException(ErrorText); } } interface IUserInterface<out T> { T Invoke(); } interface INestedComputeFunc : IComputeFunc<int> { } [Serializable] class ComputeFunc : INestedComputeFunc, IUserInterface<int> { [InstanceResource] // ReSharper disable once UnassignedField.Local private IIgnite _grid; public static int InvokeCount; public static Guid LastNodeId; int IComputeFunc<int>.Invoke() { Thread.Sleep(10); InvokeCount++; LastNodeId = _grid.GetCluster().GetLocalNode().Id; return InvokeCount; } int IUserInterface<int>.Invoke() { // Same signature as IComputeFunc<int>, but from different interface throw new Exception("Invalid method"); } public int Invoke() { // Same signature as IComputeFunc<int>, but due to explicit interface implementation this is a wrong method throw new Exception("Invalid method"); } } public enum PlatformComputeEnum : ushort { Foo, Bar, Baz } public class InteropComputeEnumFieldTest { public PlatformComputeEnum InteropEnum { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml; using Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.Contracts; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Listener.Configuration; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.WebApi; using Newtonsoft.Json; using Yaml = Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml; using YamlContracts = Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.Contracts; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Microsoft.VisualStudio.Services.Agent.Listener { [ServiceLocator(Default = typeof(LocalRunner))] public interface ILocalRunner : IAgentService { Task<int> LocalRunAsync(CommandSettings command, CancellationToken token); } public sealed class LocalRunner : AgentService, ILocalRunner { private string _gitPath; private ITaskStore _taskStore; private ITerminal _term; public sealed override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _taskStore = HostContext.GetService<ITaskStore>(); _term = hostContext.GetService<ITerminal>(); } public async Task<int> LocalRunAsync(CommandSettings command, CancellationToken token) { Trace.Info(nameof(LocalRunAsync)); // Warn preview. _term.WriteLine("This command is currently in preview. The interface and behavior will change in a future version."); if (!command.Unattended) { _term.WriteLine("Press Enter to continue."); _term.ReadLine(); } HostContext.RunMode = RunMode.Local; // Resolve the YAML file path. string ymlFile = command.GetYml(); if (string.IsNullOrEmpty(ymlFile)) { string[] ymlFiles = Directory.GetFiles(Directory.GetCurrentDirectory()) .Where((string filePath) => { return filePath.EndsWith(".yml", IOUtil.FilePathStringComparison); }) .ToArray(); if (ymlFiles.Length > 1) { throw new Exception($"More than one .yml file exists in the current directory. Specify which file to use via the --'{Constants.Agent.CommandLine.Args.Yml}' command line argument."); } ymlFile = ymlFiles.FirstOrDefault(); } if (string.IsNullOrEmpty(ymlFile)) { throw new Exception($"Unable to find a .yml file in the current directory. Specify which file to use via the --'{Constants.Agent.CommandLine.Args.Yml}' command line argument."); } // Load the YAML file. var parseOptions = new ParseOptions { MaxFiles = 10, MustacheEvaluationMaxResultLength = 512 * 1024, // 512k string length MustacheEvaluationTimeout = TimeSpan.FromSeconds(10), MustacheMaxDepth = 5, }; var pipelineParser = new PipelineParser(new PipelineTraceWriter(), new PipelineFileProvider(), parseOptions); if (command.WhatIf) { pipelineParser.DeserializeAndSerialize( defaultRoot: Directory.GetCurrentDirectory(), path: ymlFile, mustacheContext: null, cancellationToken: HostContext.AgentShutdownToken); return Constants.Agent.ReturnCode.Success; } YamlContracts.Process process = pipelineParser.LoadInternal( defaultRoot: Directory.GetCurrentDirectory(), path: ymlFile, mustacheContext: null, cancellationToken: HostContext.AgentShutdownToken); ArgUtil.NotNull(process, nameof(process)); // Verify the current directory is the root of a git repo. string repoDirectory = Directory.GetCurrentDirectory(); if (!Directory.Exists(Path.Combine(repoDirectory, ".git"))) { throw new Exception("Unable to run the build locally. The command must be executed from the root directory of a local git repository."); } // Verify at least one phase was found. if (process.Phases == null || process.Phases.Count == 0) { throw new Exception($"No phases or steps were discovered from the file: '{ymlFile}'"); } // Filter the phases. string phaseName = command.GetPhase(); if (!string.IsNullOrEmpty(phaseName)) { process.Phases = process.Phases .Cast<YamlContracts.Phase>() .Where(x => string.Equals(x.Name, phaseName, StringComparison.OrdinalIgnoreCase)) .Cast<YamlContracts.IPhase>() .ToList(); if (process.Phases.Count == 0) { throw new Exception($"Phase '{phaseName}' not found."); } } // Verify a phase was specified if more than one phase was found. if (process.Phases.Count > 1) { throw new Exception($"More than one phase was discovered. Use the --{Constants.Agent.CommandLine.Args.Phase} argument to specify a phase."); } // Get the matrix. var phase = process.Phases[0] as YamlContracts.Phase; var queueTarget = phase.Target as QueueTarget; // Filter to a specific matrix. string matrixName = command.GetMatrix(); if (!string.IsNullOrEmpty(matrixName)) { if (queueTarget?.Matrix != null) { queueTarget.Matrix = queueTarget.Matrix.Keys .Where(x => string.Equals(x, matrixName, StringComparison.OrdinalIgnoreCase)) .ToDictionary(keySelector: x => x, elementSelector: x => queueTarget.Matrix[x]); } if (queueTarget?.Matrix == null || queueTarget.Matrix.Count == 0) { throw new Exception($"Job configuration matrix '{matrixName}' not found."); } } // Verify a matrix was specified if more than one matrix was found. if (queueTarget?.Matrix != null && queueTarget.Matrix.Count > 1) { throw new Exception($"More than one job configuration matrix was discovered. Use the --{Constants.Agent.CommandLine.Args.Matrix} argument to specify a matrix."); } // Get the URL - required if missing tasks. string url = command.GetUrl(suppressPromptIfEmpty: true); if (string.IsNullOrEmpty(url)) { if (!TestAllTasksCached(process, token)) { url = command.GetUrl(suppressPromptIfEmpty: false); } } if (!string.IsNullOrEmpty(url)) { // Initialize and store the HTTP client. var credentialManager = HostContext.GetService<ICredentialManager>(); // Defaults to PAT authentication. string defaultAuthType = Constants.Configuration.PAT; string authType = command.GetAuth(defaultValue: defaultAuthType); ICredentialProvider provider = credentialManager.GetCredentialProvider(authType); provider.EnsureCredential(HostContext, command, url); _taskStore.HttpClient = new TaskAgentHttpClient(new Uri(url), provider.GetVssCredentials(HostContext)); } var configStore = HostContext.GetService<IConfigurationStore>(); AgentSettings settings = configStore.GetSettings(); // Create job message. JobInfo job = (await ConvertToJobMessagesAsync(process, repoDirectory, token)).Single(); IJobDispatcher jobDispatcher = null; try { jobDispatcher = HostContext.CreateService<IJobDispatcher>(); job.RequestMessage.Environment.Variables[Constants.Variables.Agent.RunMode] = RunMode.Local.ToString(); jobDispatcher.Run(Pipelines.AgentJobRequestMessageUtil.Convert(job.RequestMessage)); Task jobDispatch = jobDispatcher.WaitAsync(token); if (!Task.WaitAll(new[] { jobDispatch }, job.Timeout)) { jobDispatcher.Cancel(job.CancelMessage); // Finish waiting on the job dispatch task. The call to jobDispatcher.WaitAsync dequeues // the job dispatch task. In the cancel flow, we need to continue awaiting the task instance // (queue is now empty). await jobDispatch; } // Translate the job result to an agent return code. TaskResult jobResult = jobDispatcher.GetLocalRunJobResult(job.RequestMessage); switch (jobResult) { case TaskResult.Succeeded: case TaskResult.SucceededWithIssues: return Constants.Agent.ReturnCode.Success; default: return Constants.Agent.ReturnCode.TerminatedError; } } finally { if (jobDispatcher != null) { await jobDispatcher.ShutdownAsync(); } } } private async Task<List<JobInfo>> ConvertToJobMessagesAsync(YamlContracts.Process process, string repoDirectory, CancellationToken token) { // Collect info about the repo. string repoName = Path.GetFileName(repoDirectory); string userName = await GitAsync("config --get user.name", token); string userEmail = await GitAsync("config --get user.email", token); string branch = await GitAsync("symbolic-ref HEAD", token); string commit = await GitAsync("rev-parse HEAD", token); string commitAuthorName = await GitAsync("show --format=%an --no-patch HEAD", token); string commitSubject = await GitAsync("show --format=%s --no-patch HEAD", token); var jobs = new List<JobInfo>(); int requestId = 1; foreach (Phase phase in process.Phases ?? new List<IPhase>(0)) { IDictionary<string, IDictionary<string, string>> matrix; var queueTarget = phase.Target as QueueTarget; if (queueTarget?.Matrix != null && queueTarget.Matrix.Count > 0) { // Get the matrix. matrix = queueTarget.Matrix; } else { // Create the default matrix. matrix = new Dictionary<string, IDictionary<string, string>>(1); matrix[string.Empty] = new Dictionary<string, string>(0); } foreach (string jobName in matrix.Keys) { var builder = new StringBuilder(); builder.Append($@"{{ ""tasks"": ["); var steps = new List<ISimpleStep>(); foreach (IStep step in phase.Steps ?? new List<IStep>(0)) { if (step is ISimpleStep) { steps.Add(step as ISimpleStep); } else { var stepGroup = step as StepGroup; foreach (ISimpleStep nestedStep in stepGroup.Steps ?? new List<ISimpleStep>(0)) { steps.Add(nestedStep); } } } bool firstStep = true; foreach (ISimpleStep step in steps) { if (!(step is TaskStep)) { throw new Exception("Unable to run step type: " + step.GetType().FullName); } var task = step as TaskStep; if (!task.Enabled) { continue; } // Sanity check - the pipeline parser should have already validated version is an int. int taskVersion; if (!int.TryParse(task.Reference.Version, NumberStyles.None, CultureInfo.InvariantCulture, out taskVersion)) { throw new Exception($"Unexpected task version format. Expected an unsigned integer with no formatting. Actual: '{taskVersion}'"); } TaskDefinition definition = await _taskStore.GetTaskAsync( name: task.Reference.Name, version: taskVersion, token: token); await _taskStore.EnsureCachedAsync(definition, token); if (!firstStep) { builder.Append(","); } firstStep = false; builder.Append($@" {{ ""instanceId"": ""{Guid.NewGuid()}"", ""displayName"": {JsonConvert.ToString(!string.IsNullOrEmpty(task.Name) ? task.Name : definition.InstanceNameFormat)}, ""enabled"": true, ""continueOnError"": {task.ContinueOnError.ToString().ToLowerInvariant()}, ""condition"": {JsonConvert.ToString(task.Condition)}, ""alwaysRun"": false, ""timeoutInMinutes"": {task.TimeoutInMinutes.ToString(CultureInfo.InvariantCulture)}, ""id"": ""{definition.Id}"", ""name"": {JsonConvert.ToString(definition.Name)}, ""version"": {JsonConvert.ToString(definition.Version.ToString())}, ""inputs"": {{"); bool firstInput = true; foreach (KeyValuePair<string, string> input in task.Inputs ?? new Dictionary<string, string>(0)) { if (!firstInput) { builder.Append(","); } firstInput = false; builder.Append($@" {JsonConvert.ToString(input.Key)}: {JsonConvert.ToString(input.Value)}"); } builder.Append($@" }}, ""environment"": {{"); bool firstEnv = true; foreach (KeyValuePair<string, string> env in task.Environment ?? new Dictionary<string, string>(0)) { if (!firstEnv) { builder.Append(","); } firstEnv = false; builder.Append($@" {JsonConvert.ToString(env.Key)}: {JsonConvert.ToString(env.Value)}"); } builder.Append($@" }} }}"); } builder.Append($@" ], ""requestId"": {requestId++}, ""lockToken"": ""00000000-0000-0000-0000-000000000000"", ""lockedUntil"": ""0001-01-01T00:00:00"", ""messageType"": ""JobRequest"", ""plan"": {{ ""scopeIdentifier"": ""00000000-0000-0000-0000-000000000000"", ""planType"": ""Build"", ""version"": 8, ""planId"": ""00000000-0000-0000-0000-000000000000"", ""artifactUri"": ""vstfs:///Build/Build/1234"", ""artifactLocation"": null }}, ""timeline"": {{ ""id"": ""00000000-0000-0000-0000-000000000000"", ""changeId"": 1, ""location"": null }}, ""jobId"": ""{Guid.NewGuid()}"", ""jobName"": {JsonConvert.ToString(!string.IsNullOrEmpty(phase.Name) ? phase.Name : "Build")}, ""environment"": {{ ""endpoints"": [ {{ ""data"": {{ ""repositoryId"": ""00000000-0000-0000-0000-000000000000"", ""localDirectory"": {JsonConvert.ToString(repoDirectory)}, ""clean"": ""false"", ""checkoutSubmodules"": ""False"", ""onpremtfsgit"": ""False"", ""fetchDepth"": ""0"", ""gitLfsSupport"": ""false"", ""skipSyncSource"": ""false"", ""cleanOptions"": ""0"" }}, ""name"": {JsonConvert.ToString(repoName)}, ""type"": ""LocalRun"", ""url"": ""https://127.0.0.1/vsts-agent-local-runner?directory={Uri.EscapeDataString(repoDirectory)}"", ""authorization"": {{ ""parameters"": {{ ""AccessToken"": ""dummy-access-token"" }}, ""scheme"": ""OAuth"" }}, ""isReady"": false }} ], ""mask"": [ {{ ""type"": ""regex"", ""value"": ""dummy-access-token"" }} ], ""variables"": {{"); builder.Append($@" ""system"": ""build"", ""system.collectionId"": ""00000000-0000-0000-0000-000000000000"", ""system.culture"": ""en-US"", ""system.definitionId"": ""55"", ""system.isScheduled"": ""False"", ""system.hosttype"": ""build"", ""system.jobId"": ""00000000-0000-0000-0000-000000000000"", ""system.planId"": ""00000000-0000-0000-0000-000000000000"", ""system.timelineId"": ""00000000-0000-0000-0000-000000000000"", ""system.taskDefinitionsUri"": ""https://127.0.0.1/vsts-agent-local-runner"", ""system.teamFoundationCollectionUri"": ""https://127.0.0.1/vsts-agent-local-runner"", ""system.teamProject"": {JsonConvert.ToString(repoName)}, ""system.teamProjectId"": ""00000000-0000-0000-0000-000000000000"", ""build.buildId"": ""1863"", ""build.buildNumber"": ""1863"", ""build.buildUri"": ""vstfs:///Build/Build/1863"", ""build.clean"": """", ""build.definitionName"": ""My Build Definition Name"", ""build.definitionVersion"": ""1"", ""build.queuedBy"": {JsonConvert.ToString(userName)}, ""build.queuedById"": ""00000000-0000-0000-0000-000000000000"", ""build.requestedFor"": {JsonConvert.ToString(userName)}, ""build.requestedForEmail"": {JsonConvert.ToString(userEmail)}, ""build.requestedForId"": ""00000000-0000-0000-0000-000000000000"", ""build.repository.uri"": ""https://127.0.0.1/vsts-agent-local-runner/_git/{Uri.EscapeDataString(repoName)}"", ""build.sourceBranch"": {JsonConvert.ToString(branch)}, ""build.sourceBranchName"": {JsonConvert.ToString(branch.Split('/').Last())}, ""build.sourceVersion"": {JsonConvert.ToString(commit)}, ""build.sourceVersionAuthor"": {JsonConvert.ToString(commitAuthorName)}, ""build.sourceVersionMessage"": {JsonConvert.ToString(commitSubject)}, ""AZURE_HTTP_USER_AGENT"": ""VSTS_00000000-0000-0000-0000-000000000000_build_55_1863"", ""MSDEPLOY_HTTP_USER_AGENT"": ""VSTS_00000000-0000-0000-0000-000000000000_build_55_1863"""); foreach (Variable variable in phase.Variables ?? new List<IVariable>(0)) { builder.Append($@", {JsonConvert.ToString(variable.Name ?? string.Empty)}: {JsonConvert.ToString(variable.Value ?? string.Empty)}"); } foreach (KeyValuePair<string, string> variable in matrix[jobName]) { builder.Append($@", {JsonConvert.ToString(variable.Key ?? string.Empty)}: {JsonConvert.ToString(variable.Value ?? string.Empty)}"); } builder.Append($@" }}, ""systemConnection"": {{ ""data"": {{ ""ServerId"": ""00000000-0000-0000-0000-000000000000"", ""ServerName"": ""127.0.0.1"" }}, ""name"": ""SystemVssConnection"", ""url"": ""https://127.0.0.1/vsts-agent-local-runner"", ""authorization"": {{ ""parameters"": {{ ""AccessToken"": ""dummy-access-token"" }}, ""scheme"": ""OAuth"" }}, ""isReady"": false }} }} }}"); string message = builder.ToString(); try { jobs.Add(new JobInfo(phase, jobName, message)); } catch { Dump("Job message JSON", message); throw; } } } return jobs; } private async Task<string> GitAsync(string arguments, CancellationToken token) { // Resolve the location of git. if (_gitPath == null) { #if OS_WINDOWS _gitPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "git", "cmd", $"git{IOUtil.ExeExtension}"); ArgUtil.File(_gitPath, nameof(_gitPath)); #else _gitPath = WhichUtil.Which("git", require: true); #endif } // Prepare the environment variables to overlay. var overlayEnvironment = new Dictionary<string, string>(StringComparer.Ordinal); overlayEnvironment["GIT_TERMINAL_PROMPT"] = "0"; // Skip any GIT_TRACE variable since GIT_TRACE will affect ouput from every git command. // This will fail the parse logic for detect git version, remote url, etc. // Ex. // SET GIT_TRACE=true // git version // 11:39:58.295959 git.c:371 trace: built-in: git 'version' // git version 2.11.1.windows.1 IDictionary currentEnvironment = Environment.GetEnvironmentVariables(); foreach (DictionaryEntry entry in currentEnvironment) { string key = entry.Key as string ?? string.Empty; if (string.Equals(key, "GIT_TRACE", StringComparison.OrdinalIgnoreCase) || key.StartsWith("GIT_TRACE_", StringComparison.OrdinalIgnoreCase)) { overlayEnvironment[key] = string.Empty; } } // Run git and return the output from the streams. var output = new StringBuilder(); var processInvoker = HostContext.CreateService<IProcessInvoker>(); Console.WriteLine(); Console.WriteLine($"git {arguments}"); processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { output.AppendLine(message.Data); Console.WriteLine(message.Data); }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { output.AppendLine(message.Data); Console.WriteLine(message.Data); }; #if OS_WINDOWS Encoding encoding = Encoding.UTF8; #else Encoding encoding = null; #endif await processInvoker.ExecuteAsync( workingDirectory: Directory.GetCurrentDirectory(), fileName: _gitPath, arguments: arguments, environment: overlayEnvironment, requireExitCodeZero: true, outputEncoding: encoding, cancellationToken: token); string result = output.ToString().Trim(); ArgUtil.NotNullOrEmpty(result, nameof(result)); return result; } private bool TestAllTasksCached(Process process, CancellationToken token) { foreach (Phase phase in process.Phases ?? new List<IPhase>(0)) { var steps = new List<ISimpleStep>(); foreach (IStep step in phase.Steps ?? new List<IStep>(0)) { if (step is ISimpleStep) { if (!(step is CheckoutStep)) { steps.Add(step as ISimpleStep); } } else { var stepGroup = step as StepGroup; foreach (ISimpleStep nestedStep in stepGroup.Steps ?? new List<ISimpleStep>(0)) { steps.Add(nestedStep); } } } foreach (ISimpleStep step in steps) { if (!(step is TaskStep)) { throw new Exception("Unexpected step type: " + step.GetType().FullName); } var task = step as TaskStep; if (!task.Enabled) { continue; } // Sanity check - the pipeline parser should have already validated version is an int. int taskVersion; if (!int.TryParse(task.Reference.Version, NumberStyles.None, CultureInfo.InvariantCulture, out taskVersion)) { throw new Exception($"Unexpected task version format. Expected an unsigned integer with no formmatting. Actual: '{task.Reference.Version}'"); } if (!_taskStore.TestCached(name: task.Reference.Name, version: taskVersion, token: token)) { return false; } } } return true; } private static void Dump(string header, string value) { Console.WriteLine(); Console.WriteLine(String.Empty.PadRight(80, '*')); Console.WriteLine($"* {header}"); Console.WriteLine(String.Empty.PadRight(80, '*')); Console.WriteLine(); using (StringReader reader = new StringReader(value)) { int lineNumber = 1; string line = reader.ReadLine(); while (line != null) { Console.WriteLine($"{lineNumber.ToString().PadLeft(4)}: {line}"); line = reader.ReadLine(); lineNumber++; } } } [ServiceLocator(Default = typeof(TaskStore))] private interface ITaskStore : IAgentService { TaskAgentHttpClient HttpClient { get; set; } Task EnsureCachedAsync(TaskDefinition task, CancellationToken token); Task<TaskDefinition> GetTaskAsync(string name, int version, CancellationToken token); bool TestCached(string name, int version, CancellationToken token); } private sealed class TaskStore : AgentService, ITaskStore { private List<TaskDefinition> _localTasks; private List<TaskDefinition> _serverTasks; private ITerminal _term; public TaskAgentHttpClient HttpClient { get; set; } public sealed override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _term = hostContext.GetService<ITerminal>(); } public async Task EnsureCachedAsync(TaskDefinition task, CancellationToken token) { Trace.Entering(); ArgUtil.NotNull(task, nameof(task)); ArgUtil.NotNullOrEmpty(task.Version, nameof(task.Version)); // first check to see if we already have the task string destDirectory = GetTaskDirectory(task); Trace.Info($"Ensuring task exists: ID '{task.Id}', version '{task.Version}', name '{task.Name}', directory '{destDirectory}'."); if (File.Exists(destDirectory + ".completed")) { Trace.Info("Task already downloaded."); return; } // Invalidate the local cache. _localTasks = null; // delete existing task folder. Trace.Verbose("Deleting task destination folder: {0}", destDirectory); IOUtil.DeleteDirectory(destDirectory, CancellationToken.None); // Inform the user that a download is taking place. The download could take a while if // the task zip is large. It would be nice to print the localized name, but it is not // available from the reference included in the job message. _term.WriteLine(StringUtil.Loc("DownloadingTask0", task.Name)); string zipFile; var version = new TaskVersion(task.Version); //download and extract task in a temp folder and rename it on success string tempDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Tasks), "_temp_" + Guid.NewGuid()); try { Directory.CreateDirectory(tempDirectory); zipFile = Path.Combine(tempDirectory, string.Format("{0}.zip", Guid.NewGuid())); //open zip stream in async mode using (FileStream fs = new FileStream(zipFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { using (Stream result = await HttpClient.GetTaskContentZipAsync(task.Id, version, token)) { //81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k). await result.CopyToAsync(fs, 81920, token); await fs.FlushAsync(token); } } Directory.CreateDirectory(destDirectory); ZipFile.ExtractToDirectory(zipFile, destDirectory); Trace.Verbose("Create watermark file indicate task download succeed."); File.WriteAllText(destDirectory + ".completed", DateTime.UtcNow.ToString()); Trace.Info("Finished getting task."); } finally { try { //if the temp folder wasn't moved -> wipe it if (Directory.Exists(tempDirectory)) { Trace.Verbose("Deleting task temp folder: {0}", tempDirectory); IOUtil.DeleteDirectory(tempDirectory, CancellationToken.None); // Don't cancel this cleanup and should be pretty fast. } } catch (Exception ex) { //it is not critical if we fail to delete the temp folder Trace.Warning("Failed to delete temp folder '{0}'. Exception: {1}", tempDirectory, ex); Trace.Warning(StringUtil.Loc("FailedDeletingTempDirectory0Message1", tempDirectory, ex.Message)); } } } public async Task<TaskDefinition> GetTaskAsync(string name, int version, CancellationToken token) { if (HttpClient != null) { return (await GetServerTaskAsync(name, version, token)); } return GetLocalTask(name, version, require: true, token: token); } public bool TestCached(string name, int version, CancellationToken token) { TaskDefinition localTask = GetLocalTask(name, version, require: false, token: token); return localTask != null; } private TaskDefinition GetLocalTask(string name, int version, bool require, CancellationToken token) { if (_localTasks == null) { // Get tasks from the local cache. var tasks = new List<TaskDefinition>(); string tasksDirectory = HostContext.GetDirectory(WellKnownDirectory.Tasks); if (Directory.Exists(tasksDirectory)) { _term.WriteLine("Getting available tasks from the cache."); foreach (string taskDirectory in Directory.GetDirectories(tasksDirectory)) { foreach (string taskSubDirectory in Directory.GetDirectories(taskDirectory)) { string taskJsonPath = Path.Combine(taskSubDirectory, "task.json"); if (File.Exists(taskJsonPath) && File.Exists(taskSubDirectory + ".completed")) { token.ThrowIfCancellationRequested(); Trace.Info($"Loading: '{taskJsonPath}'"); TaskDefinition definition = IOUtil.LoadObject<TaskDefinition>(taskJsonPath); if (definition == null || string.IsNullOrEmpty(definition.Name) || definition.Version == null) { _term.WriteLine($"Task definition is invalid. The name property must not be empty and the version property must not be null. Task definition: {taskJsonPath}"); continue; } else if (!string.Equals(taskSubDirectory, GetTaskDirectory(definition), IOUtil.FilePathStringComparison)) { _term.WriteLine($"Task definition does not match the expected folder structure. Expected: '{GetTaskDirectory(definition)}'; actual: '{taskJsonPath}'"); continue; } tasks.Add(definition); } } } } _localTasks = FilterWithinMajorVersion(tasks); } return FilterByReference(_localTasks, name, version, require); } private async Task<TaskDefinition> GetServerTaskAsync(string name, int version, CancellationToken token) { ArgUtil.NotNull(HttpClient, nameof(HttpClient)); if (_serverTasks == null) { _term.WriteLine("Getting available task versions from server."); var tasks = await HttpClient.GetTaskDefinitionsAsync(cancellationToken: token); _term.WriteLine("Successfully retrieved task versions from server."); _serverTasks = FilterWithinMajorVersion(tasks); } return FilterByReference(_serverTasks, name, version, require: true); } private TaskDefinition FilterByReference(List<TaskDefinition> tasks, string name, int version, bool require) { // Filter by name. Guid id = default(Guid); if (Guid.TryParseExact(name, format: "D", result: out id)) // D = 32 digits separated by hyphens { // Filter by GUID. tasks = tasks.Where(x => x.Id == id).ToList(); } else { // Filter by name. tasks = tasks.Where(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)).ToList(); } // Validate name is not ambiguous. if (tasks.GroupBy(x => x.Id).Count() > 1) { throw new Exception($"Unable to resolve a task for the name '{name}'. The name is ambiguous."); } // Filter by version. tasks = tasks.Where(x => x.Version.Major == version).ToList(); // Validate a task was found. if (tasks.Count == 0) { if (require) { throw new Exception($"No tasks found matching: '{name}@{version}'"); } return null; } ArgUtil.Equal(1, tasks.Count, nameof(tasks.Count)); return tasks[0]; } private List<TaskDefinition> FilterWithinMajorVersion(List<TaskDefinition> tasks) { return tasks .GroupBy(x => new { Id = x.Id, MajorVersion = x.Version }) // Group by ID and major-version .Select(x => x.OrderByDescending(y => y.Version).First()) // Select the max version .ToList(); } private string GetTaskDirectory(TaskDefinition definition) { ArgUtil.NotEmpty(definition.Id, nameof(definition.Id)); ArgUtil.NotNull(definition.Name, nameof(definition.Name)); ArgUtil.NotNullOrEmpty(definition.Version, nameof(definition.Version)); return Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Tasks), $"{definition.Name}_{definition.Id}", definition.Version); } } private sealed class JobInfo { public JobInfo(Phase phase, string jobName, string requestMessage) { JobName = jobName ?? string.Empty; PhaseName = phase.Name ?? string.Empty; RequestMessage = JsonUtility.FromString<AgentJobRequestMessage>(requestMessage); string timeoutInMinutesString = (phase.Target as QueueTarget)?.TimeoutInMinutes ?? (phase.Target as DeploymentTarget)?.TimeoutInMinutes ?? "60"; Timeout = TimeSpan.FromMinutes(int.Parse(timeoutInMinutesString, NumberStyles.None)); } public JobCancelMessage CancelMessage => new JobCancelMessage(RequestMessage.JobId, TimeSpan.FromSeconds(60)); public string JobName { get; } public string PhaseName { get; } public AgentJobRequestMessage RequestMessage { get; } public TimeSpan Timeout { get; } } private sealed class PipelineTraceWriter : Yaml.ITraceWriter { public void Info(String format, params Object[] args) { Console.WriteLine(format, args); } public void Verbose(String format, params Object[] args) { Console.WriteLine(format, args); } } private sealed class PipelineFileProvider : Yaml.IFileProvider { public FileData GetFile(String path) { return new FileData { Name = Path.GetFileName(path), Directory = Path.GetDirectoryName(path), Content = File.ReadAllText(path), }; } public String ResolvePath(String defaultRoot, String path) { return Path.Combine(defaultRoot, path); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { [Flags] internal enum CompilationFlags { EmitExpressionStart = 0x0001, EmitNoExpressionStart = 0x0002, EmitAsDefaultType = 0x0010, EmitAsVoidType = 0x0020, EmitAsTail = 0x0100, // at the tail position of a lambda, tail call can be safely emitted EmitAsMiddle = 0x0200, // in the middle of a lambda, tail call can be emitted if it is in a return EmitAsNoTail = 0x0400, // neither at the tail or in a return, or tail call is not turned on, no tail call is emitted EmitExpressionStartMask = 0x000f, EmitAsTypeMask = 0x00f0, EmitAsTailCallMask = 0x0f00 } /// <summary> /// Update the flag with a new EmitAsTailCall flag /// </summary> private static CompilationFlags UpdateEmitAsTailCallFlag(CompilationFlags flags, CompilationFlags newValue) { Debug.Assert(newValue == CompilationFlags.EmitAsTail || newValue == CompilationFlags.EmitAsMiddle || newValue == CompilationFlags.EmitAsNoTail); CompilationFlags oldValue = flags & CompilationFlags.EmitAsTailCallMask; return flags ^ oldValue | newValue; } /// <summary> /// Update the flag with a new EmitExpressionStart flag /// </summary> private static CompilationFlags UpdateEmitExpressionStartFlag(CompilationFlags flags, CompilationFlags newValue) { Debug.Assert(newValue == CompilationFlags.EmitExpressionStart || newValue == CompilationFlags.EmitNoExpressionStart); CompilationFlags oldValue = flags & CompilationFlags.EmitExpressionStartMask; return flags ^ oldValue | newValue; } /// <summary> /// Update the flag with a new EmitAsType flag /// </summary> private static CompilationFlags UpdateEmitAsTypeFlag(CompilationFlags flags, CompilationFlags newValue) { Debug.Assert(newValue == CompilationFlags.EmitAsDefaultType || newValue == CompilationFlags.EmitAsVoidType); CompilationFlags oldValue = flags & CompilationFlags.EmitAsTypeMask; return flags ^ oldValue | newValue; } /// <summary> /// Generates code for this expression in a value position. /// This method will leave the value of the expression /// on the top of the stack typed as Type. /// </summary> internal void EmitExpression(Expression node) { EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart); } /// <summary> /// Emits an expression and discards the result. For some nodes this emits /// more optimal code then EmitExpression/Pop /// </summary> private void EmitExpressionAsVoid(Expression node) { EmitExpressionAsVoid(node, CompilationFlags.EmitAsNoTail); } private void EmitExpressionAsVoid(Expression node, CompilationFlags flags) { Debug.Assert(node != null); CompilationFlags startEmitted = EmitExpressionStart(node); switch (node.NodeType) { case ExpressionType.Assign: EmitAssign((AssignBinaryExpression)node, CompilationFlags.EmitAsVoidType); break; case ExpressionType.Block: Emit((BlockExpression)node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType)); break; case ExpressionType.Throw: EmitThrow((UnaryExpression)node, CompilationFlags.EmitAsVoidType); break; case ExpressionType.Goto: EmitGotoExpression(node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType)); break; case ExpressionType.Constant: case ExpressionType.Default: case ExpressionType.Parameter: // no-op break; default: if (node.Type == typeof(void)) { EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitNoExpressionStart)); } else { EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); _ilg.Emit(OpCodes.Pop); } break; } EmitExpressionEnd(startEmitted); } private void EmitExpressionAsType(Expression node, Type type, CompilationFlags flags) { if (type == typeof(void)) { EmitExpressionAsVoid(node, flags); } else { // if the node is emitted as a different type, CastClass IL is emitted at the end, // should not emit with tail calls. if (!TypeUtils.AreEquivalent(node.Type, type)) { EmitExpression(node); Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type)); _ilg.Emit(OpCodes.Castclass, type); } else { // emit the node with the flags and emit expression start EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart)); } } } #region label block tracking private CompilationFlags EmitExpressionStart(Expression node) { if (TryPushLabelBlock(node)) { return CompilationFlags.EmitExpressionStart; } return CompilationFlags.EmitNoExpressionStart; } private void EmitExpressionEnd(CompilationFlags flags) { if ((flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart) { PopLabelBlock(_labelBlock.Kind); } } #endregion #region InvocationExpression private void EmitInvocationExpression(Expression expr, CompilationFlags flags) { InvocationExpression node = (InvocationExpression)expr; // Optimization: inline code for literal lambda's directly // // This is worth it because otherwise we end up with a extra call // to DynamicMethod.CreateDelegate, which is expensive. // if (node.LambdaOperand != null) { EmitInlinedInvoke(node, flags); return; } expr = node.Expression; if (typeof(LambdaExpression).IsAssignableFrom(expr.Type)) { // if the invoke target is a lambda expression tree, first compile it into a delegate expr = Expression.Call(expr, expr.Type.GetMethod("Compile", Array.Empty<Type>())); } EmitMethodCall(expr, expr.Type.GetMethod("Invoke"), node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart); } private void EmitInlinedInvoke(InvocationExpression invoke, CompilationFlags flags) { LambdaExpression lambda = invoke.LambdaOperand; // This is tricky: we need to emit the arguments outside of the // scope, but set them inside the scope. Fortunately, using the IL // stack it is entirely doable. // 1. Emit invoke arguments List<WriteBack> wb = EmitArguments(lambda.Type.GetMethod("Invoke"), invoke); // 2. Create the nested LambdaCompiler var inner = new LambdaCompiler(this, lambda, invoke); // 3. Emit the body // if the inlined lambda is the last expression of the whole lambda, // tail call can be applied. if (wb != null) { Debug.Assert(wb.Count > 0); flags = UpdateEmitAsTailCallFlag(flags, CompilationFlags.EmitAsNoTail); } inner.EmitLambdaBody(_scope, true, flags); // 4. Emit write-backs if needed EmitWriteBack(wb); } #endregion #region IndexExpression private void EmitIndexExpression(Expression expr) { var node = (IndexExpression)expr; // Emit instance, if calling an instance method Type objectType = null; if (node.Object != null) { EmitInstance(node.Object, out objectType); } // Emit indexes. We don't allow byref args, so no need to worry // about write-backs or EmitAddress for (int i = 0, n = node.ArgumentCount; i < n; i++) { Expression arg = node.GetArgument(i); EmitExpression(arg); } EmitGetIndexCall(node, objectType); } private void EmitIndexAssignment(AssignBinaryExpression node, CompilationFlags flags) { Debug.Assert(!node.IsByRef); var index = (IndexExpression)node.Left; CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; // Emit instance, if calling an instance method Type objectType = null; if (index.Object != null) { EmitInstance(index.Object, out objectType); } // Emit indexes. We don't allow byref args, so no need to worry // about write-backs or EmitAddress for (int i = 0, n = index.ArgumentCount; i < n; i++) { Expression arg = index.GetArgument(i); EmitExpression(arg); } // Emit value EmitExpression(node.Right); // Save the expression value, if needed LocalBuilder temp = null; if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type)); } EmitSetIndexCall(index, objectType); // Restore the value if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Ldloc, temp); FreeLocal(temp); } } private void EmitGetIndexCall(IndexExpression node, Type objectType) { if (node.Indexer != null) { // For indexed properties, just call the getter MethodInfo method = node.Indexer.GetGetMethod(nonPublic: true); EmitCall(objectType, method); } else { EmitGetArrayElement(objectType); } } private void EmitGetArrayElement(Type arrayType) { if (!arrayType.IsVector()) { // Multidimensional arrays, call get _ilg.Emit(OpCodes.Call, arrayType.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance)); } else { // For one dimensional arrays, emit load _ilg.EmitLoadElement(arrayType.GetElementType()); } } private void EmitSetIndexCall(IndexExpression node, Type objectType) { if (node.Indexer != null) { // For indexed properties, just call the setter MethodInfo method = node.Indexer.GetSetMethod(nonPublic: true); EmitCall(objectType, method); } else { EmitSetArrayElement(objectType); } } private void EmitSetArrayElement(Type arrayType) { if (!arrayType.IsVector()) { // Multidimensional arrays, call set _ilg.Emit(OpCodes.Call, arrayType.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance)); } else { // For one dimensional arrays, emit store _ilg.EmitStoreElement(arrayType.GetElementType()); } } #endregion #region MethodCallExpression private void EmitMethodCallExpression(Expression expr, CompilationFlags flags) { MethodCallExpression node = (MethodCallExpression)expr; EmitMethodCall(node.Object, node.Method, node, flags); } private void EmitMethodCallExpression(Expression expr) { EmitMethodCallExpression(expr, CompilationFlags.EmitAsNoTail); } private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr) { EmitMethodCall(obj, method, methodCallExpr, CompilationFlags.EmitAsNoTail); } private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr, CompilationFlags flags) { // Emit instance, if calling an instance method Type objectType = null; if (!method.IsStatic) { Debug.Assert(obj != null); EmitInstance(obj, out objectType); } // if the obj has a value type, its address is passed to the method call so we cannot destroy the // stack by emitting a tail call if (obj != null && obj.Type.IsValueType) { EmitMethodCall(method, methodCallExpr, objectType); } else { EmitMethodCall(method, methodCallExpr, objectType, flags); } } // assumes 'object' of non-static call is already on stack private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType) { EmitMethodCall(mi, args, objectType, CompilationFlags.EmitAsNoTail); } // assumes 'object' of non-static call is already on stack private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType, CompilationFlags flags) { // Emit arguments List<WriteBack> wb = EmitArguments(mi, args); // Emit the actual call OpCode callOp = UseVirtual(mi) ? OpCodes.Callvirt : OpCodes.Call; if (callOp == OpCodes.Callvirt && objectType.IsValueType) { // This automatically boxes value types if necessary. _ilg.Emit(OpCodes.Constrained, objectType); } // The method call can be a tail call if // 1) the method call is the last instruction before Ret // 2) the method does not have any ByRef parameters, refer to ECMA-335 Partition III Section 2.4. // "Verification requires that no managed pointers are passed to the method being called, since // it does not track pointers into the current frame." if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail && !MethodHasByRefParameter(mi)) { _ilg.Emit(OpCodes.Tailcall); } if (mi.CallingConvention == CallingConventions.VarArgs) { int count = args.ArgumentCount; Type[] types = new Type[count]; for (int i = 0; i < count; i++) { types[i] = args.GetArgument(i).Type; } _ilg.EmitCall(callOp, mi, types); } else { _ilg.Emit(callOp, mi); } // Emit write-backs for properties passed as "ref" arguments EmitWriteBack(wb); } private static bool MethodHasByRefParameter(MethodInfo mi) { foreach (ParameterInfo pi in mi.GetParametersCached()) { if (pi.IsByRefParameter()) { return true; } } return false; } private void EmitCall(Type objectType, MethodInfo method) { if (method.CallingConvention == CallingConventions.VarArgs) { throw Error.UnexpectedVarArgsCall(method); } OpCode callOp = UseVirtual(method) ? OpCodes.Callvirt : OpCodes.Call; if (callOp == OpCodes.Callvirt && objectType.IsValueType) { _ilg.Emit(OpCodes.Constrained, objectType); } _ilg.Emit(callOp, method); } private static bool UseVirtual(MethodInfo mi) { // There are two factors: is the method static, virtual or non-virtual instance? // And is the object ref or value? // The cases are: // // static, ref: call // static, value: call // virtual, ref: callvirt // virtual, value: call -- e.g. double.ToString must be a non-virtual call to be verifiable. // instance, ref: callvirt -- this looks wrong, but is verifiable and gives us a free null check. // instance, value: call // // We never need to generate a non-virtual call to a virtual method on a reference type because // expression trees do not support "base.Foo()" style calling. // // We could do an optimization here for the case where we know that the object is a non-null // reference type and the method is a non-virtual instance method. For example, if we had // (new Foo()).Bar() for instance method Bar we don't need the null check so we could do a // call rather than a callvirt. However that seems like it would not be a very big win for // most dynamically generated code scenarios, so let's not do that for now. if (mi.IsStatic) { return false; } if (mi.DeclaringType.IsValueType) { return false; } return true; } /// <summary> /// Emits arguments to a call, and returns an array of write-backs that /// should happen after the call. /// </summary> private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args) { return EmitArguments(method, args, 0); } /// <summary> /// Emits arguments to a call, and returns an array of write-backs that /// should happen after the call. For emitting dynamic expressions, we /// need to skip the first parameter of the method (the call site). /// </summary> private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args, int skipParameters) { ParameterInfo[] pis = method.GetParametersCached(); Debug.Assert(args.ArgumentCount + skipParameters == pis.Length); List<WriteBack> writeBacks = null; for (int i = skipParameters, n = pis.Length; i < n; i++) { ParameterInfo parameter = pis[i]; Expression argument = args.GetArgument(i - skipParameters); Type type = parameter.ParameterType; if (type.IsByRef) { type = type.GetElementType(); WriteBack wb = EmitAddressWriteBack(argument, type); if (wb != null) { if (writeBacks == null) { writeBacks = new List<WriteBack>(); } writeBacks.Add(wb); } } else { EmitExpression(argument); } } return writeBacks; } private void EmitWriteBack(List<WriteBack> writeBacks) { if (writeBacks != null) { foreach (WriteBack wb in writeBacks) { wb(this); } } } #endregion private void EmitConstantExpression(Expression expr) { ConstantExpression node = (ConstantExpression)expr; EmitConstant(node.Value, node.Type); } private void EmitConstant(object value) { Debug.Assert(value != null); EmitConstant(value, value.GetType()); } private void EmitConstant(object value, Type type) { // Try to emit the constant directly into IL if (!_ilg.TryEmitConstant(value, type, this)) { _boundConstants.EmitConstant(this, value, type); } } private void EmitDynamicExpression(Expression expr) { #if FEATURE_COMPILE_TO_METHODBUILDER if (!(_method is DynamicMethod)) { throw Error.CannotCompileDynamic(); } #else Debug.Assert(_method is DynamicMethod); #endif var node = (IDynamicExpression)expr; object site = node.CreateCallSite(); Type siteType = site.GetType(); MethodInfo invoke = node.DelegateType.GetMethod("Invoke"); // site.Target.Invoke(site, args) EmitConstant(site, siteType); // Emit the temp as type CallSite so we get more reuse _ilg.Emit(OpCodes.Dup); LocalBuilder siteTemp = GetLocal(siteType); _ilg.Emit(OpCodes.Stloc, siteTemp); _ilg.Emit(OpCodes.Ldfld, siteType.GetField("Target")); _ilg.Emit(OpCodes.Ldloc, siteTemp); FreeLocal(siteTemp); List<WriteBack> wb = EmitArguments(invoke, node, 1); _ilg.Emit(OpCodes.Callvirt, invoke); EmitWriteBack(wb); } private void EmitNewExpression(Expression expr) { NewExpression node = (NewExpression)expr; if (node.Constructor != null) { if (node.Constructor.DeclaringType.IsAbstract) throw Error.NonAbstractConstructorRequired(); List<WriteBack> wb = EmitArguments(node.Constructor, node); _ilg.Emit(OpCodes.Newobj, node.Constructor); EmitWriteBack(wb); } else { Debug.Assert(node.ArgumentCount == 0, "Node with arguments must have a constructor."); Debug.Assert(node.Type.IsValueType, "Only value type may have constructor not set."); LocalBuilder temp = GetLocal(node.Type); _ilg.Emit(OpCodes.Ldloca, temp); _ilg.Emit(OpCodes.Initobj, node.Type); _ilg.Emit(OpCodes.Ldloc, temp); FreeLocal(temp); } } private void EmitTypeBinaryExpression(Expression expr) { TypeBinaryExpression node = (TypeBinaryExpression)expr; if (node.NodeType == ExpressionType.TypeEqual) { EmitExpression(node.ReduceTypeEqual()); return; } Type type = node.Expression.Type; // Try to determine the result statically AnalyzeTypeIsResult result = ConstantCheck.AnalyzeTypeIs(node); if (result == AnalyzeTypeIsResult.KnownTrue || result == AnalyzeTypeIsResult.KnownFalse) { // Result is known statically, so just emit the expression for // its side effects and return the result EmitExpressionAsVoid(node.Expression); _ilg.EmitPrimitive(result == AnalyzeTypeIsResult.KnownTrue); return; } if (result == AnalyzeTypeIsResult.KnownAssignable) { // We know the type can be assigned, but still need to check // for null at runtime if (type.IsNullableType()) { EmitAddress(node.Expression, type); _ilg.EmitHasValue(type); return; } Debug.Assert(!type.IsValueType); EmitExpression(node.Expression); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Cgt_Un); return; } Debug.Assert(result == AnalyzeTypeIsResult.Unknown); // Emit a full runtime "isinst" check EmitExpression(node.Expression); if (type.IsValueType) { _ilg.Emit(OpCodes.Box, type); } _ilg.Emit(OpCodes.Isinst, node.TypeOperand); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Cgt_Un); } private void EmitVariableAssignment(AssignBinaryExpression node, CompilationFlags flags) { var variable = (ParameterExpression)node.Left; CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; if (node.IsByRef) { EmitAddress(node.Right, node.Right.Type); } else { EmitExpression(node.Right); } if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Dup); } if (variable.IsByRef) { // Note: the stloc/ldloc pattern is a bit suboptimal, but it // saves us from having to spill stack when assigning to a // byref parameter. We already make this same trade-off for // hoisted variables, see ElementStorage.EmitStore LocalBuilder value = GetLocal(variable.Type); _ilg.Emit(OpCodes.Stloc, value); _scope.EmitGet(variable); _ilg.Emit(OpCodes.Ldloc, value); FreeLocal(value); _ilg.EmitStoreValueIndirect(variable.Type); } else { _scope.EmitSet(variable); } } private void EmitAssignBinaryExpression(Expression expr) { EmitAssign((AssignBinaryExpression)expr, CompilationFlags.EmitAsDefaultType); } private void EmitAssign(AssignBinaryExpression node, CompilationFlags emitAs) { switch (node.Left.NodeType) { case ExpressionType.Index: EmitIndexAssignment(node, emitAs); return; case ExpressionType.MemberAccess: EmitMemberAssignment(node, emitAs); return; case ExpressionType.Parameter: EmitVariableAssignment(node, emitAs); return; default: throw Error.InvalidLvalue(node.Left.NodeType); } } private void EmitParameterExpression(Expression expr) { ParameterExpression node = (ParameterExpression)expr; _scope.EmitGet(node); if (node.IsByRef) { _ilg.EmitLoadValueIndirect(node.Type); } } private void EmitLambdaExpression(Expression expr) { LambdaExpression node = (LambdaExpression)expr; EmitDelegateConstruction(node); } private void EmitRuntimeVariablesExpression(Expression expr) { RuntimeVariablesExpression node = (RuntimeVariablesExpression)expr; _scope.EmitVariableAccess(this, node.Variables); } private void EmitMemberAssignment(AssignBinaryExpression node, CompilationFlags flags) { Debug.Assert(!node.IsByRef); MemberExpression lvalue = (MemberExpression)node.Left; MemberInfo member = lvalue.Member; // emit "this", if any Type objectType = null; if (lvalue.Expression != null) { EmitInstance(lvalue.Expression, out objectType); } // emit value EmitExpression(node.Right); LocalBuilder temp = null; CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; if (emitAs != CompilationFlags.EmitAsVoidType) { // save the value so we can return it _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type)); } var fld = member as FieldInfo; if ((object)fld != null) { _ilg.EmitFieldSet((FieldInfo)member); } else { // MemberExpression.Member can only be a FieldInfo or a PropertyInfo Debug.Assert(member is PropertyInfo); var prop = (PropertyInfo)member; EmitCall(objectType, prop.GetSetMethod(nonPublic: true)); } if (emitAs != CompilationFlags.EmitAsVoidType) { _ilg.Emit(OpCodes.Ldloc, temp); FreeLocal(temp); } } private void EmitMemberExpression(Expression expr) { MemberExpression node = (MemberExpression)expr; // emit "this", if any Type instanceType = null; if (node.Expression != null) { EmitInstance(node.Expression, out instanceType); } EmitMemberGet(node.Member, instanceType); } // assumes instance is already on the stack private void EmitMemberGet(MemberInfo member, Type objectType) { var fi = member as FieldInfo; if ((object)fi != null) { if (fi.IsLiteral) { EmitConstant(fi.GetRawConstantValue(), fi.FieldType); } else { _ilg.EmitFieldGet(fi); } } else { // MemberExpression.Member or MemberBinding.Member can only be a FieldInfo or a PropertyInfo Debug.Assert(member is PropertyInfo); var prop = (PropertyInfo)member; EmitCall(objectType, prop.GetGetMethod(nonPublic: true)); } } private void EmitInstance(Expression instance, out Type type) { type = instance.Type; // NB: Instance can be a ByRef type due to stack spilling introducing ref locals for // accessing an instance of a value type. In that case, we don't have to take the // address of the instance anymore; we just load the ref local. if (type.IsByRef) { type = type.GetElementType(); Debug.Assert(instance.NodeType == ExpressionType.Parameter); Debug.Assert(type.IsValueType); EmitExpression(instance); } else if (type.IsValueType) { EmitAddress(instance, type); } else { EmitExpression(instance); } } private void EmitNewArrayExpression(Expression expr) { NewArrayExpression node = (NewArrayExpression)expr; ReadOnlyCollection<Expression> expressions = node.Expressions; int n = expressions.Count; if (node.NodeType == ExpressionType.NewArrayInit) { Type elementType = node.Type.GetElementType(); _ilg.EmitArray(elementType, n); for (int i = 0; i < n; i++) { _ilg.Emit(OpCodes.Dup); _ilg.EmitPrimitive(i); EmitExpression(expressions[i]); _ilg.EmitStoreElement(elementType); } } else { for (int i = 0; i < n; i++) { Expression x = expressions[i]; EmitExpression(x); _ilg.EmitConvertToType(x.Type, typeof(int), isChecked: true, locals: this); } _ilg.EmitArray(node.Type); } } private void EmitDebugInfoExpression(Expression expr) { return; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] private static void EmitExtensionExpression(Expression expr) { throw Error.ExtensionNotReduced(); } #region ListInit, MemberInit private void EmitListInitExpression(Expression expr) { EmitListInit((ListInitExpression)expr); } private void EmitMemberInitExpression(Expression expr) { EmitMemberInit((MemberInitExpression)expr); } private void EmitBinding(MemberBinding binding, Type objectType) { switch (binding.BindingType) { case MemberBindingType.Assignment: EmitMemberAssignment((MemberAssignment)binding, objectType); break; case MemberBindingType.ListBinding: EmitMemberListBinding((MemberListBinding)binding); break; case MemberBindingType.MemberBinding: EmitMemberMemberBinding((MemberMemberBinding)binding); break; default: throw Error.UnknownBindingType(); } } private void EmitMemberAssignment(MemberAssignment binding, Type objectType) { EmitExpression(binding.Expression); FieldInfo fi = binding.Member as FieldInfo; if (fi != null) { _ilg.Emit(OpCodes.Stfld, fi); } else { PropertyInfo pi = binding.Member as PropertyInfo; if (pi != null) { EmitCall(objectType, pi.GetSetMethod(nonPublic: true)); } else { throw Error.UnhandledBinding(); } } } private void EmitMemberMemberBinding(MemberMemberBinding binding) { Type type = GetMemberType(binding.Member); if (binding.Member is PropertyInfo && type.IsValueType) { throw Error.CannotAutoInitializeValueTypeMemberThroughProperty(binding.Member); } if (type.IsValueType) { EmitMemberAddress(binding.Member, binding.Member.DeclaringType); } else { EmitMemberGet(binding.Member, binding.Member.DeclaringType); } EmitMemberInit(binding.Bindings, false, type); } private void EmitMemberListBinding(MemberListBinding binding) { Type type = GetMemberType(binding.Member); if (binding.Member is PropertyInfo && type.IsValueType) { throw Error.CannotAutoInitializeValueTypeElementThroughProperty(binding.Member); } if (type.IsValueType) { EmitMemberAddress(binding.Member, binding.Member.DeclaringType); } else { EmitMemberGet(binding.Member, binding.Member.DeclaringType); } EmitListInit(binding.Initializers, false, type); } private void EmitMemberInit(MemberInitExpression init) { EmitExpression(init.NewExpression); LocalBuilder loc = null; if (init.NewExpression.Type.IsValueType && init.Bindings.Count > 0) { loc = GetLocal(init.NewExpression.Type); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); } EmitMemberInit(init.Bindings, loc == null, init.NewExpression.Type); if (loc != null) { _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); } } // This method assumes that the instance is on the stack and is expected, based on "keepOnStack" flag // to either leave the instance on the stack, or pop it. private void EmitMemberInit(ReadOnlyCollection<MemberBinding> bindings, bool keepOnStack, Type objectType) { int n = bindings.Count; if (n == 0) { // If there are no initializers and instance is not to be kept on the stack, we must pop explicitly. if (!keepOnStack) { _ilg.Emit(OpCodes.Pop); } } else { for (int i = 0; i < n; i++) { if (keepOnStack || i < n - 1) { _ilg.Emit(OpCodes.Dup); } EmitBinding(bindings[i], objectType); } } } private void EmitListInit(ListInitExpression init) { EmitExpression(init.NewExpression); LocalBuilder loc = null; if (init.NewExpression.Type.IsValueType) { loc = GetLocal(init.NewExpression.Type); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); } EmitListInit(init.Initializers, loc == null, init.NewExpression.Type); if (loc != null) { _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); } } // This method assumes that the list instance is on the stack and is expected, based on "keepOnStack" flag // to either leave the list instance on the stack, or pop it. private void EmitListInit(ReadOnlyCollection<ElementInit> initializers, bool keepOnStack, Type objectType) { int n = initializers.Count; if (n == 0) { // If there are no initializers and instance is not to be kept on the stack, we must pop explicitly. if (!keepOnStack) { _ilg.Emit(OpCodes.Pop); } } else { for (int i = 0; i < n; i++) { if (keepOnStack || i < n - 1) { _ilg.Emit(OpCodes.Dup); } EmitMethodCall(initializers[i].AddMethod, initializers[i], objectType); // Some add methods, ArrayList.Add for example, return non-void if (initializers[i].AddMethod.ReturnType != typeof(void)) { _ilg.Emit(OpCodes.Pop); } } } } private static Type GetMemberType(MemberInfo member) { FieldInfo fi = member as FieldInfo; if (fi != null) return fi.FieldType; PropertyInfo pi = member as PropertyInfo; if (pi != null) return pi.PropertyType; throw Error.MemberNotFieldOrProperty(member, nameof(member)); } #endregion #region Expression helpers internal static void ValidateLift(IReadOnlyList<ParameterExpression> variables, IReadOnlyList<Expression> arguments) { Debug.Assert(variables != null); Debug.Assert(arguments != null); if (variables.Count != arguments.Count) { throw Error.IncorrectNumberOfIndexes(); } for (int i = 0, n = variables.Count; i < n; i++) { if (!TypeUtils.AreReferenceAssignable(variables[i].Type, arguments[i].Type.GetNonNullableType())) { throw Error.ArgumentTypesMustMatch(); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private void EmitLift(ExpressionType nodeType, Type resultType, MethodCallExpression mc, ParameterExpression[] paramList, Expression[] argList) { Debug.Assert(TypeUtils.AreEquivalent(resultType.GetNonNullableType(), mc.Type.GetNonNullableType())); switch (nodeType) { default: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: { Label exit = _ilg.DefineLabel(); Label exitNull = _ilg.DefineLabel(); LocalBuilder anyNull = GetLocal(typeof(bool)); for (int i = 0, n = paramList.Length; i < n; i++) { ParameterExpression v = paramList[i]; Expression arg = argList[i]; if (arg.Type.IsNullableType()) { _scope.AddLocal(this, v); EmitAddress(arg, arg.Type); _ilg.Emit(OpCodes.Dup); _ilg.EmitHasValue(arg.Type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.EmitGetValueOrDefault(arg.Type); _scope.EmitSet(v); } else { _scope.AddLocal(this, v); EmitExpression(arg); if (!arg.Type.IsValueType) { _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Stloc, anyNull); } _scope.EmitSet(v); } _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Brtrue, exitNull); } EmitMethodCallExpression(mc); if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type)) { ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type }); _ilg.Emit(OpCodes.Newobj, ci); } _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(exitNull); if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType())) { if (resultType.IsValueType) { LocalBuilder result = GetLocal(resultType); _ilg.Emit(OpCodes.Ldloca, result); _ilg.Emit(OpCodes.Initobj, resultType); _ilg.Emit(OpCodes.Ldloc, result); FreeLocal(result); } else { _ilg.Emit(OpCodes.Ldnull); } } else { switch (nodeType) { case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: _ilg.Emit(OpCodes.Ldc_I4_0); break; default: throw Error.UnknownLiftType(nodeType); } } _ilg.MarkLabel(exit); FreeLocal(anyNull); return; } case ExpressionType.Equal: case ExpressionType.NotEqual: { if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType())) { goto default; } Label exit = _ilg.DefineLabel(); Label exitAllNull = _ilg.DefineLabel(); Label exitAnyNull = _ilg.DefineLabel(); LocalBuilder anyNull = GetLocal(typeof(bool)); LocalBuilder allNull = GetLocal(typeof(bool)); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Stloc, allNull); for (int i = 0, n = paramList.Length; i < n; i++) { ParameterExpression v = paramList[i]; Expression arg = argList[i]; _scope.AddLocal(this, v); if (arg.Type.IsNullableType()) { EmitAddress(arg, arg.Type); _ilg.Emit(OpCodes.Dup); _ilg.EmitHasValue(arg.Type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Or); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.Emit(OpCodes.Ldloc, allNull); _ilg.Emit(OpCodes.And); _ilg.Emit(OpCodes.Stloc, allNull); _ilg.EmitGetValueOrDefault(arg.Type); } else { EmitExpression(arg); if (!arg.Type.IsValueType) { _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Or); _ilg.Emit(OpCodes.Stloc, anyNull); _ilg.Emit(OpCodes.Ldloc, allNull); _ilg.Emit(OpCodes.And); _ilg.Emit(OpCodes.Stloc, allNull); } else { _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Stloc, allNull); } } _scope.EmitSet(v); } _ilg.Emit(OpCodes.Ldloc, allNull); _ilg.Emit(OpCodes.Brtrue, exitAllNull); _ilg.Emit(OpCodes.Ldloc, anyNull); _ilg.Emit(OpCodes.Brtrue, exitAnyNull); EmitMethodCallExpression(mc); if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type)) { ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type }); _ilg.Emit(OpCodes.Newobj, ci); } _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(exitAllNull); _ilg.EmitPrimitive(nodeType == ExpressionType.Equal); _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(exitAnyNull); _ilg.EmitPrimitive(nodeType == ExpressionType.NotEqual); _ilg.MarkLabel(exit); FreeLocal(anyNull); FreeLocal(allNull); return; } } } #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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; //using System.Globalization; using System.Runtime.CompilerServices; using System.Security; using System.Runtime.Serialization; namespace System.Collections.Generic { [Serializable] [TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Comparer<T> : IComparer, IComparer<T> { // To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small // as possible and define most of the creation logic in a non-generic class. public static Comparer<T> Default { get; } = (Comparer<T>)ComparerHelpers.CreateDefaultComparer(typeof(T)); public static Comparer<T> Create(Comparison<T> comparison) { Contract.Ensures(Contract.Result<Comparer<T>>() != null); if (comparison == null) throw new ArgumentNullException(nameof(comparison)); return new ComparisonComparer<T>(comparison); } public abstract int Compare(T x, T y); int IComparer.Compare(object x, object y) { if (x == null) return y == null ? 0 : -1; if (y == null) return 1; if (x is T && y is T) return Compare((T)x, (T)y); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return 0; } } // Note: although there is a lot of shared code in the following // comparers, we do not incorporate it into a base class for perf // reasons. Adding another base class (even one with no fields) // means another generic instantiation, which can be costly esp. // for value types. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T> { public override int Compare(T x, T y) { if (x != null) { if (y != null) return x.CompareTo(y); return 1; } if (y != null) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class NullableComparer<T> : Comparer<T?> where T : struct, IComparable<T> { public override int Compare(T? x, T? y) { if (x.HasValue) { if (y.HasValue) return x.value.CompareTo(y.value); return 1; } if (y.HasValue) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class ObjectComparer<T> : Comparer<T> { public override int Compare(T x, T y) { return System.Collections.Comparer.Default.Compare(x, y); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } internal sealed class ComparisonComparer<T> : Comparer<T> { private readonly Comparison<T> _comparison; public ComparisonComparer(Comparison<T> comparison) { _comparison = comparison; } public override int Compare(T x, T y) { return _comparison(x, y); } } // Enum comparers (specialized to avoid boxing) // NOTE: Each of these needs to implement ISerializable // and have a SerializationInfo/StreamingContext ctor, // since we want to serialize as ObjectComparer for // back-compat reasons (see below). [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class Int32EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public Int32EnumComparer() { Debug.Assert(typeof(T).IsEnum); } // Used by the serialization engine. private Int32EnumComparer(SerializationInfo info, StreamingContext context) { } public override int Compare(T x, T y) { int ix = JitHelpers.UnsafeEnumCast(x); int iy = JitHelpers.UnsafeEnumCast(y); return ix.CompareTo(iy); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); public void GetObjectData(SerializationInfo info, StreamingContext context) { // Previously Comparer<T> was not specialized for enums, // and instead fell back to ObjectComparer which uses boxing. // Set the type as ObjectComparer here so code that serializes // Comparer for enums will not break. info.SetType(typeof(ObjectComparer<T>)); } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class UInt32EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public UInt32EnumComparer() { Debug.Assert(typeof(T).IsEnum); } // Used by the serialization engine. private UInt32EnumComparer(SerializationInfo info, StreamingContext context) { } public override int Compare(T x, T y) { uint ix = (uint)JitHelpers.UnsafeEnumCast(x); uint iy = (uint)JitHelpers.UnsafeEnumCast(y); return ix.CompareTo(iy); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(ObjectComparer<T>)); } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class Int64EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public Int64EnumComparer() { Debug.Assert(typeof(T).IsEnum); } public override int Compare(T x, T y) { long lx = JitHelpers.UnsafeEnumCastLong(x); long ly = JitHelpers.UnsafeEnumCastLong(y); return lx.CompareTo(ly); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(ObjectComparer<T>)); } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class UInt64EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public UInt64EnumComparer() { Debug.Assert(typeof(T).IsEnum); } // Used by the serialization engine. private UInt64EnumComparer(SerializationInfo info, StreamingContext context) { } public override int Compare(T x, T y) { ulong lx = (ulong)JitHelpers.UnsafeEnumCastLong(x); ulong ly = (ulong)JitHelpers.UnsafeEnumCastLong(y); return lx.CompareTo(ly); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(ObjectComparer<T>)); } } }
using System; using System.Collections; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.web; using umbraco.editorControls.tinymce; using umbraco.editorControls.tinyMCE3.webcontrol; using umbraco.editorControls.wysiwyg; using umbraco.interfaces; using Umbraco.Core.IO; using umbraco.presentation; using umbraco.uicontrols; namespace umbraco.editorControls.tinyMCE3 { [Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")] public class TinyMCE : TinyMCEWebControl, IDataEditor, IMenuElement { private readonly string _activateButtons = ""; private readonly string _advancedUsers = ""; private readonly SortedList _buttons = new SortedList(); private readonly IData _data; private readonly string _disableButtons = "help,visualaid,"; private readonly string _editorButtons = ""; private readonly bool _enableContextMenu; private readonly bool _fullWidth; private readonly int _height; private readonly SortedList _mceButtons = new SortedList(); private readonly ArrayList _menuIcons = new ArrayList(); private readonly bool _showLabel; private readonly ArrayList _stylesheets = new ArrayList(); private readonly int _width; private readonly int m_maxImageWidth = 500; private bool _isInitialized; private string _plugins = ""; public TinyMCE(IData Data, string Configuration) { _data = Data; try { string[] configSettings = Configuration.Split("|".ToCharArray()); if (configSettings.Length > 0) { _editorButtons = configSettings[0]; if (configSettings.Length > 1) if (configSettings[1] == "1") _enableContextMenu = true; if (configSettings.Length > 2) _advancedUsers = configSettings[2]; if (configSettings.Length > 3) { if (configSettings[3] == "1") _fullWidth = true; else if (configSettings[4].Split(',').Length > 1) { _width = int.Parse(configSettings[4].Split(',')[0]); _height = int.Parse(configSettings[4].Split(',')[1]); } } // default width/height if (_width < 1) _width = 500; if (_height < 1) _height = 400; // add stylesheets if (configSettings.Length > 4) { foreach (string s in configSettings[5].Split(",".ToCharArray())) _stylesheets.Add(s); } if (configSettings.Length > 6 && configSettings[6] != "") _showLabel = bool.Parse(configSettings[6]); if (configSettings.Length > 7 && configSettings[7] != "") m_maxImageWidth = int.Parse(configSettings[7]); // sizing if (!_fullWidth) { config.Add("width", _width.ToString()); config.Add("height", _height.ToString()); } if (_enableContextMenu) _plugins += ",contextmenu"; // If the editor is used in umbraco, use umbraco's own toolbar bool onFront = false; if (GlobalSettings.RequestIsInUmbracoApplication(HttpContext.Current)) { config.Add("theme_umbraco_toolbar_location", "external"); config.Add("skin", "umbraco"); config.Add("inlinepopups_skin ", "umbraco"); } else { onFront = true; config.Add("theme_umbraco_toolbar_location", "top"); } // load plugins IDictionaryEnumerator pluginEnum = tinyMCEConfiguration.Plugins.GetEnumerator(); while (pluginEnum.MoveNext()) { var plugin = (tinyMCEPlugin)pluginEnum.Value; if (plugin.UseOnFrontend || (!onFront && !plugin.UseOnFrontend)) _plugins += "," + plugin.Name; } // add the umbraco overrides to the end // NB: It is !!REALLY IMPORTANT!! that these plugins are added at the end // as they make runtime modifications to default plugins, so require // those plugins to be loaded first. _plugins += ",umbracopaste,umbracolink,umbracocontextmenu"; if (_plugins.StartsWith(",")) _plugins = _plugins.Substring(1, _plugins.Length - 1); if (_plugins.EndsWith(",")) _plugins = _plugins.Substring(0, _plugins.Length - 1); config.Add("plugins", _plugins); // Check advanced settings if (UmbracoEnsuredPage.CurrentUser != null && ("," + _advancedUsers + ",").IndexOf("," + UmbracoEnsuredPage.CurrentUser.UserType.Id + ",") > -1) config.Add("umbraco_advancedMode", "true"); else config.Add("umbraco_advancedMode", "false"); // Check maximum image width config.Add("umbraco_maximumDefaultImageWidth", m_maxImageWidth.ToString()); // Styles string cssFiles = String.Empty; string styles = string.Empty; foreach (string styleSheetId in _stylesheets) { if (styleSheetId.Trim() != "") try { var s = StyleSheet.GetStyleSheet(int.Parse(styleSheetId), false, false); if (s.nodeObjectType == StyleSheet.ModuleObjectType) { cssFiles += IOHelper.ResolveUrl(SystemDirectories.Css + "/" + s.Text + ".css"); foreach (StylesheetProperty p in s.Properties) { if (styles != string.Empty) { styles += ";"; } if (p.Alias.StartsWith(".")) styles += p.Text + "=" + p.Alias; else styles += p.Text + "=" + p.Alias; } cssFiles += ","; } } catch (Exception ee) { LogHelper.Error<TinyMCE>("Error adding stylesheet to tinymce Id:" + styleSheetId, ee); } } // remove any ending comma (,) if (!string.IsNullOrEmpty(cssFiles)) { cssFiles = cssFiles.TrimEnd(','); } // language string userLang = (UmbracoEnsuredPage.CurrentUser != null) ? (User.GetCurrent().Language.Contains("-") ? User.GetCurrent().Language.Substring(0, User.GetCurrent().Language.IndexOf("-")) : User.GetCurrent().Language) : "en"; config.Add("language", userLang); config.Add("content_css", cssFiles); config.Add("theme_umbraco_styles", styles); // Add buttons IDictionaryEnumerator ide = tinyMCEConfiguration.Commands.GetEnumerator(); while (ide.MoveNext()) { var cmd = (tinyMCECommand)ide.Value; if (_editorButtons.IndexOf("," + cmd.Alias + ",") > -1) _activateButtons += cmd.Alias + ","; else _disableButtons += cmd.Alias + ","; } if (_activateButtons.Length > 0) _activateButtons = _activateButtons.Substring(0, _activateButtons.Length - 1); if (_disableButtons.Length > 0) _disableButtons = _disableButtons.Substring(0, _disableButtons.Length - 1); // Add buttons initButtons(); _activateButtons = ""; int separatorPriority = 0; ide = _mceButtons.GetEnumerator(); while (ide.MoveNext()) { string mceCommand = ide.Value.ToString(); var curPriority = (int)ide.Key; // Check priority if (separatorPriority > 0 && Math.Floor(decimal.Parse(curPriority.ToString()) / 10) > Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10)) _activateButtons += "separator,"; _activateButtons += mceCommand + ","; separatorPriority = curPriority; } config.Add("theme_umbraco_buttons1", _activateButtons); config.Add("theme_umbraco_buttons2", ""); config.Add("theme_umbraco_buttons3", ""); config.Add("theme_umbraco_toolbar_align", "left"); config.Add("theme_umbraco_disable", _disableButtons); config.Add("theme_umbraco_path ", "true"); config.Add("extended_valid_elements", "div[*]"); config.Add("document_base_url", "/"); config.Add("relative_urls", "false"); config.Add("remove_script_host", "true"); config.Add("event_elements", "div"); config.Add("paste_auto_cleanup_on_paste", "true"); config.Add("valid_elements", tinyMCEConfiguration.ValidElements.Substring(1, tinyMCEConfiguration.ValidElements.Length - 2)); config.Add("invalid_elements", tinyMCEConfiguration.InvalidElements); // custom commands if (tinyMCEConfiguration.ConfigOptions.Count > 0) { ide = tinyMCEConfiguration.ConfigOptions.GetEnumerator(); while (ide.MoveNext()) { config.Add(ide.Key.ToString(), ide.Value.ToString()); } } //if (HttpContext.Current.Request.Path.IndexOf(Umbraco.Core.IO.SystemDirectories.Umbraco) > -1) // config.Add("language", User.GetUser(BasePage.GetUserId(BasePage.umbracoUserContextID)).Language); //else // config.Add("language", System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName); if (_fullWidth) { config.Add("auto_resize", "true"); base.Columns = 30; base.Rows = 30; } else { base.Columns = 0; base.Rows = 0; } EnableViewState = false; } } catch (Exception ex) { throw new ArgumentException("Incorrect TinyMCE configuration.", "Configuration", ex); } } #region TreatAsRichTextEditor public virtual bool TreatAsRichTextEditor { get { return false; } } #endregion #region ShowLabel public virtual bool ShowLabel { get { return _showLabel; } } #endregion #region Editor public Control Editor { get { return this; } } #endregion #region Save() public virtual void Save() { string parsedString = base.Text.Trim(); string parsedStringForTinyMce = parsedString; if (parsedString != string.Empty) { parsedString = replaceMacroTags(parsedString).Trim(); // tidy html - refactored, see #30534 if (UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent) { // always wrap in a <div> - using <p> was a bad idea parsedString = "<div>" + parsedString + "</div>"; string tidyTxt = library.Tidy(parsedString, false); if (tidyTxt != "[error]") { parsedString = tidyTxt; // remove pesky \r\n, and other empty chars parsedString = parsedString.Trim(new char[] { '\r', '\n', '\t', ' ' }); // compensate for breaking macro tags by tidy (?) parsedString = parsedString.Replace("/?>", "/>"); // remove the wrapping <div> - safer to check that it is still here if (parsedString.StartsWith("<div>") && parsedString.EndsWith("</div>")) parsedString = parsedString.Substring("<div>".Length, parsedString.Length - "<div></div>".Length); } } // rescue umbraco tags parsedString = parsedString.Replace("|||?", "<?").Replace("/|||", "/>").Replace("|*|", "\""); // fix images parsedString = tinyMCEImageHelper.cleanImages(parsedString); // parse current domain and instances of slash before anchor (to fix anchor bug) // NH 31-08-2007 if (HttpContext.Current.Request.ServerVariables != null) { parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current) + "/#", "#"); parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current), ""); } // if a paragraph is empty, remove it if (parsedString.ToLower() == "<p></p>") parsedString = ""; // save string after all parsing is done, but before CDATA replacement - to put back into TinyMCE parsedStringForTinyMce = parsedString; //Allow CDATA nested into RTE without exceptions // GE 2012-01-18 parsedString = parsedString.Replace("<![CDATA[", "<!--CDATAOPENTAG-->").Replace("]]>", "<!--CDATACLOSETAG-->"); } _data.Value = parsedString; // update internal webcontrol value with parsed result base.Text = parsedStringForTinyMce; } #endregion public virtual string Plugins { get { return _plugins; } set { _plugins = value; } } public object[] MenuIcons { get { initButtons(); var tempIcons = new object[_menuIcons.Count]; for (int i = 0; i < _menuIcons.Count; i++) tempIcons[i] = _menuIcons[i]; return tempIcons; } } #region IMenuElement Members public string ElementName { get { return "div"; } } public string ElementIdPreFix { get { return "umbTinymceMenu"; } } public string ElementClass { get { return "tinymceMenuBar"; } } public int ExtraMenuWidth { get { initButtons(); return _buttons.Count * 40 + 300; } } #endregion protected override void OnLoad(EventArgs e) { try { // add current page info base.NodeId = ((cms.businesslogic.datatype.DefaultData)_data).NodeId; if (NodeId != 0) { base.VersionId = ((cms.businesslogic.datatype.DefaultData)_data).Version; config.Add("theme_umbraco_pageId", base.NodeId.ToString()); config.Add("theme_umbraco_versionId", base.VersionId.ToString()); // we'll need to make an extra check for the liveediting as that value is set after the constructor have initialized config.Add("umbraco_toolbar_id", ElementIdPreFix + ((cms.businesslogic.datatype.DefaultData)_data).PropertyId); } else { // this is for use when tinymce is used for non default Umbraco pages config.Add("umbraco_toolbar_id", ElementIdPreFix + "_" + this.ClientID); } } catch { // Empty catch as this is caused by the document doesn't exists yet, // like when using this on an autoform, partly replaced by the if/else check on nodeId above though } base.OnLoad(e); } protected override void OnInit(EventArgs e) { base.OnInit(e); //Allow CDATA nested into RTE without exceptions // GE 2012-01-18 if (_data != null && _data.Value != null) base.Text = _data.Value.ToString().Replace("<!--CDATAOPENTAG-->", "<![CDATA[").Replace("<!--CDATACLOSETAG-->", "]]>"); } private string replaceMacroTags(string text) { while (findStartTag(text) > -1) { string result = text.Substring(findStartTag(text), findEndTag(text) - findStartTag(text)); text = text.Replace(result, generateMacroTag(result)); } return text; } private string generateMacroTag(string macroContent) { string macroAttr = macroContent.Substring(5, macroContent.IndexOf(">") - 5); string macroTag = "|||?UMBRACO_MACRO "; Hashtable attributes = ReturnAttributes(macroAttr); IDictionaryEnumerator ide = attributes.GetEnumerator(); while (ide.MoveNext()) { if (ide.Key.ToString().IndexOf("umb_") != -1) { // Hack to compensate for Firefox adding all attributes as lowercase string orgKey = ide.Key.ToString(); if (orgKey == "umb_macroalias") orgKey = "umb_macroAlias"; macroTag += orgKey.Substring(4, orgKey.Length - 4) + "=|*|" + ide.Value.ToString().Replace("\\r\\n", Environment.NewLine) + "|*| "; } } macroTag += "/|||"; return macroTag; } [Obsolete("Has been superceded by Umbraco.Core.XmlHelper.GetAttributesFromElement")] public static Hashtable ReturnAttributes(String tag) { var h = new Hashtable(); foreach (var i in Umbraco.Core.XmlHelper.GetAttributesFromElement(tag)) { h.Add(i.Key, i.Value); } return h; } private int findStartTag(string text) { string temp = ""; text = text.ToLower(); if (text.IndexOf("ismacro=\"true\"") > -1) { temp = text.Substring(0, text.IndexOf("ismacro=\"true\"")); return temp.LastIndexOf("<"); } return -1; } private int findEndTag(string text) { string find = "<!-- endumbmacro -->"; int endMacroIndex = text.ToLower().IndexOf(find); string tempText = text.ToLower().Substring(endMacroIndex + find.Length, text.Length - endMacroIndex - find.Length); int finalEndPos = 0; while (tempText.Length > 5) if (tempText.Substring(finalEndPos, 6) == "</div>") break; else finalEndPos++; return endMacroIndex + find.Length + finalEndPos + 6; } private void initButtons() { if (!_isInitialized) { _isInitialized = true; // Add icons for the editor control: // Html // Preview // Style picker, showstyles // Bold, italic, Text Gen // Align: left, center, right // Lists: Bullet, Ordered, indent, undo indent // Link, Anchor // Insert: Image, macro, table, formular foreach (string button in _activateButtons.Split(',')) { if (button.Trim() != "") { try { var cmd = (tinyMCECommand)tinyMCEConfiguration.Commands[button]; string appendValue = ""; if (cmd.Value != "") appendValue = ", '" + cmd.Value + "'"; _mceButtons.Add(cmd.Priority, cmd.Command); _buttons.Add(cmd.Priority, new editorButton(cmd.Alias, ui.Text("buttons", cmd.Alias), cmd.Icon, "tinyMCE.execInstanceCommand('" + ClientID + "', '" + cmd.Command + "', " + cmd.UserInterface + appendValue + ")")); } catch (Exception ee) { LogHelper.Error<TinyMCE>(string.Format("TinyMCE: Error initializing button '{0}'", button), ee); } } } // add save icon int separatorPriority = 0; IDictionaryEnumerator ide = _buttons.GetEnumerator(); while (ide.MoveNext()) { object buttonObj = ide.Value; var curPriority = (int)ide.Key; // Check priority if (separatorPriority > 0 && Math.Floor(decimal.Parse(curPriority.ToString()) / 10) > Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10)) _menuIcons.Add("|"); try { var e = (editorButton)buttonObj; MenuIconI menuItem = new MenuIconClass(); menuItem.OnClickCommand = e.onClickCommand; menuItem.ImageURL = e.imageUrl; menuItem.AltText = e.alttag; menuItem.ID = e.id; _menuIcons.Add(menuItem); } catch { } separatorPriority = curPriority; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing.Internal #else namespace System.Diagnostics.Tracing.Internal #endif { #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; #endif using Microsoft.Reflection; using System.Reflection; internal static class Environment { public static readonly string NewLine = System.Environment.NewLine; public static int TickCount { get { return System.Environment.TickCount; } } public static string GetResourceString(string key, params object[] args) { string fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); string sargs = String.Empty; foreach(var arg in args) { if (sargs != String.Empty) sargs += ", "; sargs += arg.ToString(); } return key + " (" + sargs + ")"; } public static string GetRuntimeResourceString(string key, params object[] args) { return GetResourceString(key, args); } private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } } #if ES_BUILD_AGAINST_DOTNET_V35 namespace Microsoft.Diagnostics.Contracts.Internal { internal class Contract { public static void Assert(bool invariant) { Assert(invariant, string.Empty); } public static void Assert(bool invariant, string message) { if (!invariant) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); throw new Exception("Assertion failed: " + message); } } public static void EndContractBlock() { } } } namespace Microsoft.Internal { using System.Text; internal static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1> { private readonly T1 m_Item1; public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } int Size { get { return 1; } } } [Serializable] public class Tuple<T1, T2> { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } int Size { get { return 2; } } } } #endif namespace Microsoft.Reflection { using System.Reflection; #if ES_BUILD_PCL [Flags] public enum BindingFlags { DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search } public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } #endif static class ReflectionExtensions { #if (!ES_BUILD_PCL && !ES_BUILD_PN) // // Type extension methods // public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static Type BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; } #else // ES_BUILD_PCL // // Type extension methods // public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable<PropertyInfo> GetProperties(this Type type) { #if ES_BUILD_PN return type.GetProperties(); #else return type.GetRuntimeProperties(); #endif } public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0); Func<MethodInfo, bool> visFilter; Func<MethodInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = mi => false; break; case BindingFlags.Public: visFilter = mi => mi.IsPublic; break; case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break; default: visFilter = mi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = mi => false; break; case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break; case BindingFlags.Static: instFilter = mi => mi.IsStatic; break; default: instFilter = mi => true; break; } List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods) { if (visFilter(declaredMethod) && instFilter(declaredMethod)) methodInfos.Add(declaredMethod); } return methodInfos.ToArray(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0); Func<FieldInfo, bool> visFilter; Func<FieldInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = fi => false; break; case BindingFlags.Public: visFilter = fi => fi.IsPublic; break; case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break; default: visFilter = fi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = fi => false; break; case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break; case BindingFlags.Static: instFilter = fi => fi.IsStatic; break; default: instFilter = fi => true; break; } List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (var declaredField in type.GetTypeInfo().DeclaredFields) { if (visFilter(declaredField) && instFilter(declaredField)) fieldInfos.Add(declaredField); } return fieldInfos.ToArray(); } public static Type GetNestedType(this Type type, string nestedTypeName) { TypeInfo ti = null; foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) { ti = nt; break; } } return ti == null ? null : ti.AsType(); } public static TypeCode GetTypeCode(this Type type) { if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(string)) return TypeCode.String; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; else if (type == (typeof(Decimal))) return TypeCode.Decimal; else return TypeCode.Object; } // // FieldInfo extension methods // public static object GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // // Assembly extension methods // public static bool ReflectionOnly(this Assembly assm) { // In PCL we can't load in reflection-only context return false; } #endif } } // Defining some no-ops in PCL builds #if ES_BUILD_PCL namespace System.Security { class SuppressUnmanagedCodeSecurityAttribute : Attribute { } enum SecurityAction { Demand } } namespace System.Security.Permissions { class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } } class PermissionSetAttribute : Attribute { public PermissionSetAttribute(System.Security.SecurityAction action) { } public bool Unrestricted { get; set; } } } #endif #if ES_BUILD_PN namespace System { internal static class AppDomain { public static int GetCurrentThreadId() { return Internal.Runtime.Augments.RuntimeThread.CurrentThread.ManagedThreadId; } } } #endif
/* Copyright 2014 Google 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 System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using DriveProxy.API; using DriveProxy.Service; using DriveProxy.Utils; namespace DriveProxy.Forms { public partial class MainForm : Form { private LogForm _logForm; private bool _runTestCases; private ServicePipeServer _servicePipeServer; private System.Threading.Thread _servicePipeServerThread; private bool _servicePipeServer_Cancel = false; private StateForm _stateForm; public MainForm() { InitializeComponent(); ShowInTaskbar = false; Visible = false; Opacity = 0; StartPosition = System.Windows.Forms.FormStartPosition.Manual; Location = new Point(-1000, -1000); //Hide form from alt-tab FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; } private IntPtr Hwnd { get { return _stateForm.Hwnd; } set { _stateForm.Hwnd = value; } } //Hide form from alt-tab protected override CreateParams CreateParams { get { // Turn on WS_EX_TOOLWINDOW style bit CreateParams cp = base.CreateParams; cp.ExStyle |= 0x80; return cp; } } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); Visible = false; } private void FormMain_Load(object sender, EventArgs e) { try { ShowInTaskbar = false; Visible = false; Opacity = 0; StartPosition = System.Windows.Forms.FormStartPosition.Manual; Location = new Point(-1000, -1000); string notifyText = DriveService.Settings.Product + " " + DriveService.Settings.UserName + " on " + Environment.MachineName; if (notifyText.Length > 63) { notifyIcon1.Text = notifyText.Substring(0, 60) + "..."; } else { notifyIcon1.Text = notifyText; } foreach (MethodInfo methodInfo in DriveProxy.Service.Service.Methods) { methodInfo.OnReceivedHwnd += methodInfo_OnReceivedHwnd; } _stateForm = new StateForm(); _stateForm.Show(); _stateForm.Visible = false; _stateForm.Hide(); _logForm = new LogForm(); _logForm.FormClosed += LogForm_FormClosed; _logForm.Visible = false; _logForm.Hide(); StatusForm.Init(); FeedbackForm.Init(); if (_runTestCases) { if (System.Windows.Forms.MessageBox.Show(this, "Attempting to run test cases!", Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != System.Windows.Forms.DialogResult.OK) { _runTestCases = false; } } _servicePipeServerThread = new System.Threading.Thread(ServicePipeServer_Process); _servicePipeServerThread.Start(); Visible = false; } catch (Exception exception) { Log.Error(exception, false); } } private void LogForm_FormClosed(object sender, FormClosedEventArgs e) { try { _logForm = null; } catch (Exception exception) { Log.Error(exception, false); } } private void methodInfo_OnReceivedHwnd(IntPtr hwnd) { try { Hwnd = hwnd; } catch (Exception exception) { Log.Error(exception, false); } } private void ServicePipeServer_Process() { try { if (_runTestCases) { Test.Run(); return; } _servicePipeServer = new ServicePipeServer(); _servicePipeServer.Process(); } catch (Exception exception) { Log.Error(exception, false); } } private void logoutToolStripMenuItem_Click(object sender, EventArgs e) { try { if (_stateForm.IsProcessing) { _stateForm.ShowPopup(); MessageBox.Show(this, "Please wait until processing has completed.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ( MessageBox.Show(this, "Are you sure you want to sign in to another account?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes) { return; } _stateForm.ClosePopup(); DriveService.SignoutAndAuthenticate(true); } catch (Exception exception) { Log.Error(exception, false); } } private void showStatusWindowToolStripMenuItem_Click(object sender, EventArgs e) { try { _stateForm.ShowPopup(); } catch (Exception exception) { Log.Error(exception, false); } } private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { try { _logForm.AllowClose = true; _logForm.Close(); _stateForm.AllowClose = true; _stateForm.Close(); StatusForm.Close(); FeedbackForm.Close(); notifyIcon1.Visible = false; try { if (_servicePipeServerThread != null) { ServicePipeClient.CloseServer(); for (int i = 0; i < 1; i++) { if (_servicePipeServerThread == null) { break; } System.Threading.Thread.Sleep(100); } } } catch { } DriveService.StopBackgroundProcesses(true); } catch (Exception exception) { Log.Error(exception, false); } } private void toolStripMenuItemSignOut_Click(object sender, EventArgs e) { try { if (_stateForm.IsProcessing) { _stateForm.ShowPopup(); MessageBox.Show(this, "Please wait until processing has completed.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ( MessageBox.Show(this, "Are you sure you want to sign out?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes) { return; } _stateForm.ClosePopup(); DriveService.Signout(); } catch (Exception exception) { Log.Error(exception, false); } } private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { try { toolStripMenuItemSignOut.Enabled = DriveService.IsSignedIn; } catch (Exception exception) { Log.Error(exception, false); } } private void toolStripMenuItemSignIn_Click(object sender, EventArgs e) { try { DriveService.Authenticate(true); } catch (Exception exception) { Log.Error(exception, false); } } private void toolStripMenuItemSettings_Click(object sender, EventArgs e) { try { var settingsForm = new SettingsForm(); settingsForm.ShowDialog(this); } catch (Exception exception) { Log.Error(exception, false); } } private void toolStripMenuItemClearCache_Click(object sender, EventArgs e) { try { DialogResult dialogResult = MessageBox.Show(this, "This will delete any of the cached data about files listed in " + DriveService.Settings.Product + ".\r\n\r\nAre you sure you want to delete cached file data?", DriveService.Settings.Product, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialogResult != System.Windows.Forms.DialogResult.Yes) { return; } DriveService.ClearCache(); } catch (Exception exception) { Log.Error(exception, false); } } private void toolStripMenuItemCleanupFiles_Click(object sender, EventArgs e) { try { DialogResult dialogResult = MessageBox.Show(this, "This will remove any of the files on disk that were downloaded from " + DriveService.Settings.Product + ".\r\n\r\nAre you sure you want to remove any downloaded files?", DriveService.Settings.Product, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialogResult != System.Windows.Forms.DialogResult.Yes) { return; } DriveService.CleanupFiles(); } catch (Exception exception) { Log.Error(exception, false); } } private void toolStripMenuItemShowLog_Click(object sender, EventArgs e) { try { if (_logForm == null) { _logForm = new LogForm(); } _logForm.Visible = true; _logForm.Show(); } catch (Exception exception) { Log.Error(exception, false); } } private void toolStripMenuItemExit_Click(object sender, EventArgs e) { try { if (_stateForm.IsProcessing) { _stateForm.ShowPopup(); DialogResult dialogResult = MessageBox.Show(this, DriveService.Settings.Product + " is still processing and recommends waiting for completion.\r\n\r\nAre you sure you want to exit " + DriveService.Settings.Product + "...?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dialogResult != System.Windows.Forms.DialogResult.Yes) { return; } } else { if ( MessageBox.Show(this, "Are you sure you want to exit " + DriveService.Settings.Product + "?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes) { return; } } _stateForm.ClosePopup(); Close(); } catch (Exception exception) { Log.Error(exception, false); } } } }
// 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.Globalization; using Xunit; public static class Int16Tests { [Fact] public static void TestCtor() { Int16 i = new Int16(); Assert.True(i == 0); i = 41; Assert.True(i == 41); } [Fact] public static void TestMaxValue() { Int16 max = Int16.MaxValue; Assert.True(max == (Int16)0x7FFF); } [Fact] public static void TestMinValue() { Int16 min = Int16.MinValue; Assert.True(min == unchecked((Int16)0x8000)); } [Fact] public static void TestCompareToObject() { Int16 i = 234; IComparable comparable = i; Assert.Equal(1, comparable.CompareTo(null)); Assert.Equal(0, comparable.CompareTo((Int16)234)); Assert.True(comparable.CompareTo(Int16.MinValue) > 0); Assert.True(comparable.CompareTo((Int16)0) > 0); Assert.True(comparable.CompareTo((Int16)(-123)) > 0); Assert.True(comparable.CompareTo((Int16)123) > 0); Assert.True(comparable.CompareTo((Int16)456) < 0); Assert.True(comparable.CompareTo(Int16.MaxValue) < 0); Assert.Throws<ArgumentException>(() => comparable.CompareTo("a")); } [Fact] public static void TestCompareTo() { Int16 i = 234; Assert.Equal(0, i.CompareTo((Int16)234)); Assert.True(i.CompareTo(Int16.MinValue) > 0); Assert.True(i.CompareTo((Int16)0) > 0); Assert.True(i.CompareTo((Int16)(-123)) > 0); Assert.True(i.CompareTo((Int16)123) > 0); Assert.True(i.CompareTo((Int16)456) < 0); Assert.True(i.CompareTo(Int16.MaxValue) < 0); } [Fact] public static void TestEqualsObject() { Int16 i = 789; object obj1 = (Int16)789; Assert.True(i.Equals(obj1)); object obj2 = (Int16)(-789); Assert.True(!i.Equals(obj2)); object obj3 = (Int16)0; Assert.True(!i.Equals(obj3)); } [Fact] public static void TestEquals() { Int16 i = -911; Assert.True(i.Equals((Int16)(-911))); Assert.True(!i.Equals((Int16)911)); Assert.True(!i.Equals((Int16)0)); } [Fact] public static void TestGetHashCode() { Int16 i1 = 123; Int16 i2 = 654; Assert.NotEqual(0, i1.GetHashCode()); Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode()); } [Fact] public static void TestToString() { Int16 i1 = 6310; Assert.Equal("6310", i1.ToString()); Int16 i2 = -8249; Assert.Equal("-8249", i2.ToString()); } [Fact] public static void TestToStringFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); Int16 i1 = 6310; Assert.Equal("6310", i1.ToString(numberFormat)); Int16 i2 = -8249; Assert.Equal("-8249", i2.ToString(numberFormat)); Int16 i3 = -2468; // Changing the negative pattern doesn't do anything without also passing in a format string numberFormat.NumberNegativePattern = 0; Assert.Equal("-2468", i3.ToString(numberFormat)); } [Fact] public static void TestToStringFormat() { Int16 i1 = 6310; Assert.Equal("6310", i1.ToString("G")); Int16 i2 = -8249; Assert.Equal("-8249", i2.ToString("g")); Int16 i3 = -2468; Assert.Equal(string.Format("{0:N}", -2468.00), i3.ToString("N")); Int16 i4 = 0x248; Assert.Equal("248", i4.ToString("x")); } [Fact] public static void TestToStringFormatFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); Int16 i1 = 6310; Assert.Equal("6310", i1.ToString("G", numberFormat)); Int16 i2 = -8249; Assert.Equal("-8249", i2.ToString("g", numberFormat)); numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up numberFormat.NumberGroupSeparator = "*"; numberFormat.NumberNegativePattern = 0; Int16 i3 = -2468; Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat)); } [Fact] public static void TestParse() { Assert.Equal(123, Int16.Parse("123")); Assert.Equal(-123, Int16.Parse("-123")); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyle() { Assert.Equal(0x123, Int16.Parse("123", NumberStyles.HexNumber)); Assert.Equal(1000, Int16.Parse((1000).ToString("N0"), NumberStyles.AllowThousands)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal(123, Int16.Parse("123", nfi)); Assert.Equal(-123, Int16.Parse("-123", nfi)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyleFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal(0x123, Int16.Parse("123", NumberStyles.HexNumber, nfi)); nfi.CurrencySymbol = "$"; nfi.CurrencyGroupSeparator = ","; Assert.Equal(1000, Int16.Parse("$1,000", NumberStyles.Currency, nfi)); //TODO: Negative tests once we get better exception support } [Fact] public static void TestTryParse() { // Defaults NumberStyles.Integer = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign Int16 i; Assert.True(Int16.TryParse("123", out i)); // Simple Assert.Equal(123, i); Assert.True(Int16.TryParse("-385", out i)); // LeadingSign Assert.Equal(-385, i); Assert.True(Int16.TryParse(" 678 ", out i)); // Leading/Trailing whitespace Assert.Equal(678, i); var nfi = new NumberFormatInfo() { CurrencyGroupSeparator = "" }; Assert.False(Int16.TryParse((1000).ToString("C0", nfi), out i)); // Currency Assert.False(Int16.TryParse((1000).ToString("N0"), out i)); // Thousands Assert.False(Int16.TryParse("abc", out i)); // Hex digits Assert.False(Int16.TryParse((678.90).ToString("F2"), out i)); // Decimal Assert.False(Int16.TryParse("(135)", out i)); // Parentheses Assert.False(Int16.TryParse("1E23", out i)); // Exponent } [Fact] public static void TestTryParseNumberStyleFormatProvider() { Int16 i; var nfi = new NumberFormatInfo(); Assert.True(Int16.TryParse("123", NumberStyles.Any, nfi, out i)); // Simple positive Assert.Equal(123, i); Assert.True(Int16.TryParse("123", NumberStyles.HexNumber, nfi, out i)); // Simple Hex Assert.Equal(0x123, i); nfi.CurrencySymbol = "$"; Assert.True(Int16.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive Assert.Equal(1000, i); Assert.False(Int16.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative Assert.True(Int16.TryParse("abc", NumberStyles.HexNumber, nfi, out i)); // Hex Number positive Assert.Equal(0xabc, i); Assert.False(Int16.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal Assert.False(Int16.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative Assert.True(Int16.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese postive Assert.Equal(-135, i); } }
using System; using System.Collections.Generic; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class WindowSwitchingTest : DriverTestFixture { [Test] public void ShouldSwitchFocusToANewWindowWhenItIsOpenedAndNotStopFutureOperations() { driver.Url = xhtmlTestPage; String current = driver.CurrentWindowHandle; driver.FindElement(By.LinkText("Open new window")).Click(); Assert.AreEqual("XHTML Test Page", driver.Title); WaitFor(WindowCountToBe(2), "Window count was not 2"); WaitFor(WindowWithName("result"), "Could not find window with name 'result'"); WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); driver.Url = iframesPage; string handle = driver.CurrentWindowHandle; driver.FindElement(By.Id("iframe_page_heading")); driver.SwitchTo().Frame("iframe1"); Assert.AreEqual(driver.CurrentWindowHandle, handle); driver.SwitchTo().DefaultContent(); driver.Close(); driver.SwitchTo().Window(current); //Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] public void ShouldThrowNoSuchWindowException() { driver.Url = xhtmlTestPage; String current = driver.CurrentWindowHandle; try { driver.SwitchTo().Window("invalid name"); } catch (NoSuchWindowException) { // This is expected. } driver.SwitchTo().Window(current); } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle() { driver.Url = (xhtmlTestPage); String current = driver.CurrentWindowHandle; int currentWindowHandles = driver.WindowHandles.Count; driver.FindElement(By.LinkText("Open new window")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); Assert.AreEqual(2, driver.WindowHandles.Count); WaitFor(WindowWithName("result"), "Could not find window with name 'result'"); driver.SwitchTo().Window("result"); driver.Close(); try { string currentHandle = driver.CurrentWindowHandle; Assert.Fail("NoSuchWindowException expected"); } catch (NoSuchWindowException) { // Expected. } finally { driver.SwitchTo().Window(current); } } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldThrowNoSuchWindowExceptionOnAnyOperationIfAWindowIsClosed() { driver.Url = (xhtmlTestPage); String current = driver.CurrentWindowHandle; int currentWindowHandles = driver.WindowHandles.Count; driver.FindElement(By.LinkText("Open new window")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); Assert.AreEqual(2, driver.WindowHandles.Count); WaitFor(WindowWithName("result"), "Could not find window with name 'result'"); driver.SwitchTo().Window("result"); driver.Close(); try { try { string title = driver.Title; Assert.Fail("NoSuchWindowException expected"); } catch (NoSuchWindowException) { // Expected. } try { driver.FindElement(By.TagName("body")); Assert.Fail("NoSuchWindowException expected"); } catch (NoSuchWindowException) { // Expected. } } finally { driver.SwitchTo().Window(current); } } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldThrowNoSuchWindowExceptionOnAnyElementOperationIfAWindowIsClosed() { driver.Url = (xhtmlTestPage); String current = driver.CurrentWindowHandle; int currentWindowHandles = driver.WindowHandles.Count; driver.FindElement(By.LinkText("Open new window")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); Assert.AreEqual(2, driver.WindowHandles.Count); WaitFor(WindowWithName("result"), "Could not find window with name 'result'"); driver.SwitchTo().Window("result"); IWebElement body = driver.FindElement(By.TagName("body")); driver.Close(); try { string bodyText = body.Text; Assert.Fail("NoSuchWindowException expected"); } catch (NoSuchWindowException) { // Expected. } finally { driver.SwitchTo().Window(current); } } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] public void ShouldBeAbleToIterateOverAllOpenWindows() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("windowOne")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); driver.FindElement(By.Name("windowTwo")).Click(); WaitFor(WindowCountToBe(3), "Window count was not 3"); ReadOnlyCollection<string> allWindowHandles = driver.WindowHandles; // There should be three windows. We should also see each of the window titles at least once. List<string> seenHandles = new List<string>(); foreach (string handle in allWindowHandles) { Assert.That(seenHandles, Has.No.Member(handle)); driver.SwitchTo().Window(handle); seenHandles.Add(handle); } Assert.AreEqual(3, allWindowHandles.Count); } [Test] public void ClickingOnAButtonThatClosesAnOpenWindowDoesNotCauseTheBrowserToHang() { bool isIEDriver = TestUtilities.IsInternetExplorer(driver); bool isIE6 = TestUtilities.IsIE6(driver); driver.Url = xhtmlTestPage; String currentHandle = driver.CurrentWindowHandle; driver.FindElement(By.Name("windowThree")).Click(); driver.SwitchTo().Window("result"); try { IWebElement closeElement = WaitFor(() => { return driver.FindElement(By.Id("close")); }, "Could not find element with id 'close'"); closeElement.Click(); if (isIEDriver && !isIE6) { IAlert alert = WaitFor<IAlert>(AlertToBePresent(), "No alert found"); alert.Accept(); } // If we make it this far, we're all good. } finally { driver.SwitchTo().Window(currentHandle); driver.FindElement(By.Id("linkId")); } } [Test] public void CanCallGetWindowHandlesAfterClosingAWindow() { bool isIEDriver = TestUtilities.IsInternetExplorer(driver); bool isIE6 = TestUtilities.IsIE6(driver); driver.Url = xhtmlTestPage; String currentHandle = driver.CurrentWindowHandle; driver.FindElement(By.Name("windowThree")).Click(); driver.SwitchTo().Window("result"); try { IWebElement closeElement = WaitFor(() => { return driver.FindElement(By.Id("close")); }, "Could not find element with id 'close'"); closeElement.Click(); if (isIEDriver && !isIE6) { IAlert alert = WaitFor<IAlert>(AlertToBePresent(), "No alert found"); alert.Accept(); } ReadOnlyCollection<string> handles = driver.WindowHandles; // If we make it this far, we're all good. } finally { driver.SwitchTo().Window(currentHandle); } } [Test] public void CanObtainAWindowHandle() { driver.Url = xhtmlTestPage; String currentHandle = driver.CurrentWindowHandle; Assert.That(currentHandle, Is.Not.Null); } [Test] public void FailingToSwitchToAWindowLeavesTheCurrentWindowAsIs() { driver.Url = xhtmlTestPage; String current = driver.CurrentWindowHandle; try { driver.SwitchTo().Window("i will never exist"); Assert.Fail("Should not be ablt to change to a non-existant window"); } catch (NoSuchWindowException) { // expected } String newHandle = driver.CurrentWindowHandle; Assert.AreEqual(current, newHandle); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] public void CanCloseWindowWhenMultipleWindowsAreOpen() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("windowOne")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); ReadOnlyCollection<string> allWindowHandles = driver.WindowHandles; // There should be two windows. We should also see each of the window titles at least once. Assert.AreEqual(2, allWindowHandles.Count); string handle1 = allWindowHandles[1]; driver.SwitchTo().Window(handle1); driver.Close(); WaitFor(WindowCountToBe(1), "Window count was not 1"); allWindowHandles = driver.WindowHandles; Assert.AreEqual(1, allWindowHandles.Count); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] public void CanCloseWindowAndSwitchBackToMainWindow() { driver.Url = xhtmlTestPage; ReadOnlyCollection<string> currentWindowHandles = driver.WindowHandles; string mainHandle = driver.CurrentWindowHandle; driver.FindElement(By.Name("windowOne")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); ReadOnlyCollection<string> allWindowHandles = driver.WindowHandles; // There should be two windows. We should also see each of the window titles at least once. Assert.AreEqual(2, allWindowHandles.Count); foreach(string handle in allWindowHandles) { if (handle != mainHandle) { driver.SwitchTo().Window(handle); driver.Close(); } } driver.SwitchTo().Window(mainHandle); string newHandle = driver.CurrentWindowHandle; Assert.AreEqual(mainHandle, newHandle); Assert.AreEqual(1, driver.WindowHandles.Count); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] public void ClosingOnlyWindowShouldNotCauseTheBrowserToHang() { driver.Url = xhtmlTestPage; driver.Close(); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] [IgnoreBrowser(Browser.Firefox, "https://github.com/mozilla/geckodriver/issues/610")] public void ShouldFocusOnTheTopMostFrameAfterSwitchingToAWindow() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("window_switching_tests/page_with_frame.html"); ReadOnlyCollection<string> currentWindowHandles = driver.WindowHandles; string mainWindow = driver.CurrentWindowHandle; driver.FindElement(By.Id("a-link-that-opens-a-new-window")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); driver.SwitchTo().Frame("myframe"); driver.SwitchTo().Window("newWindow"); driver.Close(); driver.SwitchTo().Window(mainWindow); driver.FindElement(By.Name("myframe")); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] public void ShouldGetBrowserHandles() { driver.Url = xhtmlTestPage; driver.FindElement(By.LinkText("Open new window")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); string handle1, handle2; handle1 = driver.CurrentWindowHandle; System.Threading.Thread.Sleep(1000); driver.SwitchTo().Window("result"); handle2 = driver.CurrentWindowHandle; ReadOnlyCollection<string> handles = driver.WindowHandles; // At least the two handles we want should be there. Assert.Contains(handle1, handles, "Should have contained current handle"); Assert.Contains(handle2, handles, "Should have contained result handle"); // Some (semi-)clean up.. driver.SwitchTo().Window(handle2); driver.Close(); driver.SwitchTo().Window(handle1); driver.Url = macbethPage; } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void CloseShouldCloseCurrentHandleOnly() { driver.Url = xhtmlTestPage; driver.FindElement(By.LinkText("Open new window")).Click(); WaitFor(WindowCountToBe(2), "Window count was not 2"); string handle1, handle2; handle1 = driver.CurrentWindowHandle; driver.SwitchTo().Window("result"); handle2 = driver.CurrentWindowHandle; driver.Close(); SleepBecauseWindowsTakeTimeToOpen(); ReadOnlyCollection<string> handles = driver.WindowHandles; Assert.That(handles, Has.No.Member(handle2), "Invalid handle still in handle list"); Assert.That(handles, Contains.Item(handle1), "Valid handle not in handle list"); } [Test] [IgnoreBrowser(Browser.Chrome, "Driver does not yet support new window command")] [IgnoreBrowser(Browser.Edge, "Driver does not yet support new window command")] public void ShouldBeAbleToCreateANewWindow() { driver.Url = xhtmlTestPage; string originalHandle = driver.CurrentWindowHandle; driver.SwitchTo().NewWindow(WindowType.Tab); WaitFor(WindowCountToBe(2), "Window count was not 2"); string newWindowHandle = driver.CurrentWindowHandle; driver.Close(); driver.SwitchTo().Window(originalHandle); Assert.That(newWindowHandle, Is.Not.EqualTo(originalHandle)); } private void SleepBecauseWindowsTakeTimeToOpen() { try { System.Threading.Thread.Sleep(1000); } catch (Exception) { Assert.Fail("Interrupted"); } } private Func<bool> WindowCountToBe(int desiredCount) { return () => { return driver.WindowHandles.Count == desiredCount; }; } private Func<bool> WindowWithName(string name) { return () => { try { driver.SwitchTo().Window(name); return true; } catch (NoSuchWindowException) { } return false; }; } private Func<IAlert> AlertToBePresent() { return () => { IAlert alert = null; try { alert = driver.SwitchTo().Alert(); } catch (NoAlertPresentException) { } return alert; }; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using LibCSV.Dialects; using LibCSV.Exceptions; namespace LibCSV { /// <summary> /// CSVReader class is responsible for reading and parsing tabular data. /// Parsing is controlled by set of rules defined in Dialect. /// API exposes the following operations: /// Next() : reads and parses next record (returns true on success) /// Current : return current record as array of strings /// Headers : return headers as array of strings /// </summary> public class CSVReader : ICSVReader { internal const int DEFAULT_CAPACITY = 16; private TextReader _reader; private Dialect _dialect; private IList<string> _fields; private ParserState _state; private char[] _buffer; private int _capacity; private int _fieldLength; private long _index; private string[] _headers; private bool _ownsReader = false; public CSVReader(Dialect dialect, string filename, string encoding) { if (dialect == null) { throw new DialectIsNullException(); } _dialect = dialect; GrowBuffer(); if (_reader == null) { if (string.IsNullOrEmpty(filename) || filename.Trim().Length < 1) { throw new FileNameIsNullOrEmptyException(); } if (!File.Exists(filename)) { throw new CannotReadFromFileException(string.Format("Can't read from file: '{0}', file not exists!", filename)); } _ownsReader = true; try { _reader = new StreamReader(filename, Encoding.GetEncoding(encoding)); } catch(Exception exp) { throw new CannotReadFromFileException(string.Format("Can't read from file: '{0}'!", filename), exp); } } InitializeHeaders(); } public CSVReader(Dialect dialect, TextReader reader) { if (dialect == null) { throw new DialectIsNullException(); } _dialect = dialect; GrowBuffer(); if (reader == null) { throw new TextReaderIsNullException(); } _reader = reader; InitializeHeaders(); } public bool IsDisposed { get; private set; } protected void InitializeHeaders() { if (_dialect != null && _dialect.HasHeader) { Next(); if (_headers == null && _fields != null && _fields.Count > 0) { _headers = new string[_fields.Count]; _fields.CopyTo(_headers, 0); } } } protected void SaveField() { _fields.Add(new string(_buffer, 0, _fieldLength)); _fieldLength = 0; Array.Clear(_buffer, 0, _capacity); } protected void GrowBuffer() { if (_capacity == 0) { _capacity = DEFAULT_CAPACITY; _buffer = new char[_capacity]; } else { _capacity *= 2; Array.Resize(ref _buffer, _capacity); } } protected void AddChar(char character) { if (_fieldLength == _capacity) { GrowBuffer(); } _buffer[_fieldLength] = character; _fieldLength++; } private static bool IsNull(char character) { return (character == '\0'); } private static bool IsEndOfLine(char character) { return (character == '\n' || character == '\r'); } private static bool IsNullOrEndOfLine(char character) { return (IsNull(character) || IsEndOfLine(character)); } protected void ProcessChar(char currentCharacter) { switch (_state) { case ParserState.StartOfRecord: { //TODO: should we add ignore null byte attribute to dialect? // if (IsNull(currentCharacter)) // { // break; // } //TODO: can this be executed? // if (IsEndOfLine(currentCharacter)) // { // _state = ParserState.EndOfRecord; // break; // } _state = ParserState.StartOfField; goto case ParserState.StartOfField; } case ParserState.StartOfField: ProcessStartOfField(currentCharacter); break; case ParserState.EscapedCharacter: ProcessEscapedChar(currentCharacter); break; case ParserState.InField: ProcessInField(currentCharacter); break; case ParserState.InQuotedField: ProcessInQuotedField(currentCharacter); break; case ParserState.EscapeInQuotedField: ProcessEscapeInQuotedField(currentCharacter); break; case ParserState.QuoteInQuotedField: ProcessQuoteInQuotedField(currentCharacter); break; } } protected void ProcessQuoteInQuotedField(char currentCharacter) { if (_dialect.Quoting != QuoteStyle.QuoteNone && currentCharacter == _dialect.Quote) { AddChar(currentCharacter); _state = ParserState.InQuotedField; } else if (currentCharacter == _dialect.Delimiter) { SaveField(); _state = ParserState.StartOfField; } else if (IsNullOrEndOfLine(currentCharacter)) { SaveField(); _state = (IsNull(currentCharacter) ? ParserState.StartOfRecord : ParserState.EndOfRecord); } else if (!_dialect.Strict) { AddChar (currentCharacter); _state = ParserState.InField; } else { throw new BadFormatException ( string.Format ("Bad format: '{0}' expected after '{1}'", _dialect.Delimiter, _dialect.Quote)); } } protected void ProcessEscapeInQuotedField(char currentCharacter) { if (IsNull(currentCharacter) || currentCharacter == 'n') currentCharacter = '\n'; if (currentCharacter == 'r') currentCharacter = '\r'; if (currentCharacter == 't') currentCharacter = '\t'; AddChar(currentCharacter); _state = ParserState.InQuotedField; } protected void ProcessInQuotedField(char currentCharacter) { if (IsNull(currentCharacter)) { } else if (currentCharacter == _dialect.Escape) { _state = ParserState.EscapeInQuotedField; } else if (currentCharacter == _dialect.Quote && _dialect.Quoting != QuoteStyle.QuoteNone) { _state = _dialect.DoubleQuote ? ParserState.QuoteInQuotedField : ParserState.InField; } else { AddChar(currentCharacter); } } protected void ProcessInField(char currentCharacter) { if (IsNullOrEndOfLine(currentCharacter)) { SaveField(); _state = (IsNull(currentCharacter) ? ParserState.StartOfRecord : ParserState.EndOfRecord); } else if (currentCharacter == _dialect.Escape) { _state = ParserState.EscapedCharacter; } else if (currentCharacter == _dialect.Delimiter) { SaveField(); _state = ParserState.StartOfField; } else { AddChar(currentCharacter); } } protected void ProcessEscapedChar(char currentCharacter) { if (IsNull(currentCharacter)) currentCharacter = '\n'; AddChar(currentCharacter); _state = ParserState.InField; } protected void ProcessStartOfField(char currentCharacter) { if (IsNullOrEndOfLine(currentCharacter)) { SaveField(); _state = (IsNull(currentCharacter) ? ParserState.StartOfRecord : ParserState.EndOfRecord); } else if (currentCharacter == _dialect.Quote && _dialect.Quoting != QuoteStyle.QuoteNone) { _state = ParserState.InQuotedField; } else if (currentCharacter == _dialect.Escape) { _state = ParserState.EscapedCharacter; } else if (char.IsWhiteSpace(currentCharacter) && _dialect.SkipInitialSpace) { } else if (currentCharacter == _dialect.Delimiter) { SaveField(); } else { AddChar(currentCharacter); _state = ParserState.InField; } } protected void Reset() { _fields = new List<string>(); _fieldLength = 0; _state = ParserState.StartOfRecord; } /// <summary> /// Reads and parses next record. /// </summary> /// <returns>true on success otherwise false.</returns> public bool Next() { Reset(); var line = ReadLine(); if (string.IsNullOrEmpty(line) || line.Trim().Length < 1) { return false; } var length = line.Length; if (line != new string(_dialect.Delimiter, length)) { for (var i = 0; i < length; i++) { if (IsNull(line[i])) { throw new BadFormatException("Line contains NULL byte!"); } ProcessChar(line[i]); } SaveField(); } _index++; return true; } /// <summary> /// Returns the next line. /// </summary> public virtual String ReadLine() { StringBuilder sb = new StringBuilder(); bool inQuotes = false; while (true) { int ch = _reader.Read(); if (ch == -1) break; if (ch == _dialect.Quote) inQuotes = !inQuotes; if (!inQuotes && (ch == '\r' || ch == '\n')) { if (ch == '\r' && _reader.Peek() == '\n') _reader.Read(); return sb.ToString(); } sb.Append((char)ch); } if (sb.Length > 0) return sb.ToString(); return null; } /// <summary> /// Returns the headers as string array. /// </summary> public string[] Headers { get { return _headers; } } /// <summary> /// Returns the current record as string array. /// </summary> public string[] Current { get { string[] results = null; if (_fields != null) { results = new string[_fields.Count]; _fields.CopyTo(results, 0); } return results; } } protected virtual void Dispose(bool disposing) { if (!IsDisposed) { if (disposing) { if (_ownsReader && _reader != null) { _reader.Close(); _reader = null; } if (_reader != null) { _reader.Dispose(); } _reader = null; _dialect = null; _fields = null; _buffer = null; } IsDisposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~CSVReader() { Dispose(false); } } }
// $ANTLR 2.7.5 (20050128): "calc.g" -> "CalcL.cs"$ using antlr; // Generate header specific to lexer CSharp file using System; using Stream = System.IO.Stream; using TextReader = System.IO.TextReader; using Hashtable = System.Collections.Hashtable; using Comparer = System.Collections.Comparer; using TokenStreamException = antlr.TokenStreamException; using TokenStreamIOException = antlr.TokenStreamIOException; using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException; using CharStreamException = antlr.CharStreamException; using CharStreamIOException = antlr.CharStreamIOException; using ANTLRException = antlr.ANTLRException; using CharScanner = antlr.CharScanner; using InputBuffer = antlr.InputBuffer; using ByteBuffer = antlr.ByteBuffer; using CharBuffer = antlr.CharBuffer; using Token = antlr.Token; using IToken = antlr.IToken; using CommonToken = antlr.CommonToken; using SemanticException = antlr.SemanticException; using RecognitionException = antlr.RecognitionException; using NoViableAltForCharException = antlr.NoViableAltForCharException; using MismatchedCharException = antlr.MismatchedCharException; using TokenStream = antlr.TokenStream; using LexerSharedInputState = antlr.LexerSharedInputState; using BitSet = antlr.collections.impl.BitSet; public class CalcL : antlr.CharScanner , TokenStream { public const int EOF = 1; public const int NULL_TREE_LOOKAHEAD = 3; public const int NULL_NODE = 4; public const int PROG_LIST = 5; public const int FUNC = 6; public const int STRUCT = 7; public const int STRUCTLIST = 8; public const int GLOBA = 9; public const int GLOBD = 10; public const int DECLA = 11; public const int FUNC_HEAD = 12; public const int FUNC_APP = 13; public const int FORMAL_LIST = 14; public const int DECL = 15; public const int ARRAY_DEF = 16; public const int TYPE_DEF = 17; public const int VAR = 18; public const int VAL_INTEGER = 19; public const int ABS = 20; public const int SQRT = 21; public const int ROOT = 22; public const int LN = 23; public const int LOG = 24; public const int BLOCK = 25; public const int MATRIX = 26; public const int IDENT = 27; public const int LPAREN = 28; public const int RPAREN = 29; public const int LITERAL_abs = 30; public const int LITERAL_sqrt = 31; public const int LITERAL_ln = 32; public const int LITERAL_log = 33; public const int COMMA = 34; public const int LITERAL_root = 35; public const int LBRACKET = 36; // ";" = 37 public const int RBRACKET = 38; public const int MINUS = 39; public const int POWER = 40; public const int TIMES = 41; public const int DIVIDE = 42; public const int MOD = 43; public const int PLUS = 44; public const int LTHAN = 45; public const int GTHAN = 46; public const int GEQ = 47; public const int LEQ = 48; public const int EQ = 49; public const int NEQ = 50; public const int ICON = 51; public const int WS_ = 52; public const int ESC = 53; public const int CHCON = 54; public const int STCON = 55; public const int SEMICOLON = 56; public const int LCURL = 57; public const int RCURL = 58; public const int DOT = 59; public const int SHIFT_LEFT = 60; public const int SHIFT_RIGHT = 61; public CalcL(Stream ins) : this(new ByteBuffer(ins)) { } public CalcL(TextReader r) : this(new CharBuffer(r)) { } public CalcL(InputBuffer ib) : this(new LexerSharedInputState(ib)) { } public CalcL(LexerSharedInputState state) : base(state) { initialize(); } private void initialize() { caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(100, (float) 0.4, null, Comparer.Default); literals.Add("sqrt", 31); literals.Add("ln", 32); literals.Add("log", 33); literals.Add("abs", 30); literals.Add(";", 37); literals.Add("root", 35); } override public IToken nextToken() //throws TokenStreamException { IToken theRetToken = null; tryAgain: for (;;) { IToken _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try // for char stream error handling { try // for lexical error handling { switch ( cached_LA1 ) { case '\t': case '\n': case '\r': case ' ': { mWS_(true); theRetToken = returnToken_; break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { mIDENT(true); theRetToken = returnToken_; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { mICON(true); theRetToken = returnToken_; break; } case '\\': { mESC(true); theRetToken = returnToken_; break; } case '\'': { mCHCON(true); theRetToken = returnToken_; break; } case '"': { mSTCON(true); theRetToken = returnToken_; break; } case ',': { mCOMMA(true); theRetToken = returnToken_; break; } case ';': { mSEMICOLON(true); theRetToken = returnToken_; break; } case '(': { mLPAREN(true); theRetToken = returnToken_; break; } case '[': { mLBRACKET(true); theRetToken = returnToken_; break; } case ']': { mRBRACKET(true); theRetToken = returnToken_; break; } case ')': { mRPAREN(true); theRetToken = returnToken_; break; } case '{': { mLCURL(true); theRetToken = returnToken_; break; } case '}': { mRCURL(true); theRetToken = returnToken_; break; } case '+': { mPLUS(true); theRetToken = returnToken_; break; } case '-': { mMINUS(true); theRetToken = returnToken_; break; } case '*': { mTIMES(true); theRetToken = returnToken_; break; } case '.': { mDOT(true); theRetToken = returnToken_; break; } case '/': { mDIVIDE(true); theRetToken = returnToken_; break; } case '%': { mMOD(true); theRetToken = returnToken_; break; } case '^': { mPOWER(true); theRetToken = returnToken_; break; } case '=': { mEQ(true); theRetToken = returnToken_; break; } case '!': { mNEQ(true); theRetToken = returnToken_; break; } default: if ((cached_LA1=='<') && (cached_LA2=='=')) { mLEQ(true); theRetToken = returnToken_; } else if ((cached_LA1=='>') && (cached_LA2=='=')) { mGEQ(true); theRetToken = returnToken_; } else if ((cached_LA1=='<') && (cached_LA2=='<')) { mSHIFT_LEFT(true); theRetToken = returnToken_; } else if ((cached_LA1=='>') && (cached_LA2=='>')) { mSHIFT_RIGHT(true); theRetToken = returnToken_; } else if ((cached_LA1=='<') && (true)) { mLTHAN(true); theRetToken = returnToken_; } else if ((cached_LA1=='>') && (true)) { mGTHAN(true); theRetToken = returnToken_; } else { if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); } else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());} } break; } if ( null==returnToken_ ) goto tryAgain; // found SKIP token _ttype = returnToken_.Type; _ttype = testLiteralsTable(_ttype); returnToken_.Type = _ttype; return returnToken_; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse is CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.Message); } } } } public void mWS_(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = WS_; { switch ( cached_LA1 ) { case ' ': { match(' '); break; } case '\t': { match('\t'); break; } case '\n': { match('\n'); newline(); break; } case '\r': { match('\r'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } _ttype = Token.SKIP; if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mIDENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = IDENT; { switch ( cached_LA1 ) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } { // ( ... )* for (;;) { switch ( cached_LA1 ) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { { switch ( cached_LA1 ) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { { matchRange('0','9'); } break; } default: { goto _loop45_breakloop; } } } _loop45_breakloop: ; } // ( ... )* if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mICON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = ICON; matchRange('0','9'); { // ( ... )* for (;;) { if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) { matchRange('0','9'); } else { goto _loop48_breakloop; } } _loop48_breakloop: ; } // ( ... )* if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = ESC; match('\\'); { switch ( cached_LA1 ) { case 'n': { match('n'); break; } case 'r': { match('r'); break; } case 't': { match('t'); break; } case 'b': { match('b'); break; } case 'f': { match('f'); break; } case '"': { match('"'); break; } case '\'': { match('\''); break; } case '\\': { match('\\'); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mCHCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = CHCON; int _saveIndex = 0; _saveIndex = text.Length; match("'"); text.Length = _saveIndex; { switch ( cached_LA1 ) { case '\\': { mESC(false); break; } case '\u0000': case '\u0001': case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\u0007': case '\u0008': case '\t': case '\n': case '\u000b': case '\u000c': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': case '\u007f': { matchNot('\''); break; } default: { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); } } } _saveIndex = text.Length; match("'"); text.Length = _saveIndex; if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSTCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = STCON; match('"'); { // ( ... )* for (;;) { switch ( cached_LA1 ) { case '\\': { mESC(false); break; } case '\u0000': case '\u0001': case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\u0007': case '\u0008': case '\t': case '\n': case '\u000b': case '\u000c': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': case ' ': case '!': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': case '\u007f': { matchNot('"'); break; } default: { goto _loop55_breakloop; } } } _loop55_breakloop: ; } // ( ... )* match('"'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = COMMA; match(','); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSEMICOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = SEMICOLON; match(';'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LPAREN; match('('); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LBRACKET; match('['); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mRBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = RBRACKET; match(']'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mRPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = RPAREN; match(')'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LCURL; match('{'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mRCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = RCURL; match('}'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mPLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = PLUS; match('+'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mMINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = MINUS; match('-'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mTIMES(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = TIMES; match('*'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = DOT; match('.'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mDIVIDE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = DIVIDE; match('/'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mMOD(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = MOD; match('%'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mPOWER(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = POWER; match('^'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = EQ; match("="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mNEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = NEQ; match("!="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LTHAN; match('<'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mGTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = GTHAN; match('>'); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mLEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = LEQ; match("<="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mGEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = GEQ; match(">="); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSHIFT_LEFT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = SHIFT_LEFT; match("<<"); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } public void mSHIFT_RIGHT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; IToken _token=null; int _begin=text.Length; _ttype = SHIFT_RIGHT; match(">>"); if (_createToken && (null == _token) && (_ttype != Token.SKIP)) { _token = makeToken(_ttype); _token.setText(text.ToString(_begin, text.Length-_begin)); } returnToken_ = _token; } }
// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class drumstick : manipObject { public Transform masterObj; Transform glowTrans; Material mat; public Transform sticktip; List<drumpad> pads; List<Vector3> lastStickPos; public int ID = 1; Color glowColor = new Color(.25f, .5f, .25f); Vector3 origPos = Vector3.zero; Quaternion origRot = Quaternion.identity; GameObject highlight; Material highlightMat; public componentInterface _interface; public bool skinnable = true; public override void Awake() { base.Awake(); gameObject.layer = 10; //manipulator pads = new List<drumpad>(); lastStickPos = new List<Vector3>(); stickyGrip = true; if (masterObj == null) masterObj = transform.parent; glowTrans = transform.GetChild(0); mat = glowTrans.GetComponent<Renderer>().material; mat.SetColor("_TintColor", glowColor * .5f); mat.SetFloat("_EmissionGain", .5f); glowTrans.gameObject.SetActive(false); origPos = transform.localPosition; origRot = transform.localRotation; createHandleFeedback(); } GameObject skin; public void addSkin(GameObject g) { if (!skinnable) return; skin = Instantiate(g, transform) as GameObject; skin.transform.localPosition = Vector3.zero; skin.transform.localRotation = Quaternion.identity; skin.transform.localScale = Vector3.one; } public void removeSkin() { if (skin != null) Destroy(skin); } void OnCollisionEnter(Collision coll) { manipObject o = coll.transform.GetComponent<manipObject>(); if (o != null) o.onTouch(true, manipulatorObjScript); } void OnCollisionExit(Collision coll) { manipObject o = coll.transform.GetComponent<manipObject>(); if (o != null) o.onTouch(false, manipulatorObjScript); } void createHandleFeedback() { highlight = new GameObject("highlight"); MeshFilter m = highlight.AddComponent<MeshFilter>(); m.mesh = GetComponent<MeshFilter>().mesh; MeshRenderer r = highlight.AddComponent<MeshRenderer>(); r.material = Resources.Load("Materials/Highlight") as Material; highlightMat = r.material; highlight.transform.SetParent(transform, false); highlight.transform.localScale = new Vector3(1.6f, 1.6f, 1.02f); highlight.transform.localPosition = new Vector3(0, 0, -.003f); highlightMat.SetColor("_TintColor", glowColor); highlightMat.SetFloat("_EmissionGain", .3f); highlight.SetActive(false); } public override void grabUpdate(Transform t) { for (int i = 0; i < pads.Count; i++) { Vector3 pos = pads[i].transform.parent.InverseTransformPoint(sticktip.position); Vector2 posFlat = new Vector2(pos.x, pos.z); if (posFlat.magnitude < .175f) { if (lastStickPos[i].y > -.004f && pos.y <= -.004f) { pads[i].keyHit(true); if (manipulatorObjScript != null) manipulatorObjScript.bigHaptic(3999, .1f); } } lastStickPos[i] = pos; } } Coroutine returnRoutineID; IEnumerator returnRoutine() { Vector3 curPos = transform.localPosition; Quaternion curRot = transform.localRotation; float t = 0; float modT = 0; while (t < 1) { t = Mathf.Clamp01(t + Time.deltaTime * 2); modT = Mathf.Sin(t * Mathf.PI * 0.5f); transform.localPosition = Vector3.Lerp(curPos, origPos, modT); transform.localRotation = Quaternion.Lerp(curRot, origRot, modT); yield return null; } } bool revealing = false; Coroutine _revealSelfRoutine; public void revealSelf(bool on) { if (!gameObject.activeSelf) return; if (revealing == on) return; revealing = on; if (_revealSelfRoutine != null) StopCoroutine(_revealSelfRoutine); _revealSelfRoutine = StartCoroutine(revealSelfRoutine(on)); } float curRoutineTime = 0; IEnumerator revealSelfRoutine(bool on) { float a = -.05f; float b = .02f; Quaternion quatA = Quaternion.Euler(0, 145 * ID, 180); Quaternion quatB = Quaternion.Euler(0, 145 * ID, 0); if (on) { while (curRoutineTime < 1) { curRoutineTime = Mathf.Clamp01(curRoutineTime + Time.deltaTime * 2); Vector3 pos = origPos; pos.y = Mathf.SmoothStep(a, b, curRoutineTime); Quaternion rot = Quaternion.Lerp(quatA, quatB, curRoutineTime); updateRestingPosition(pos, rot); yield return null; } } else { while (curRoutineTime > 0) { curRoutineTime = Mathf.Clamp01(curRoutineTime - Time.deltaTime * 2); Vector3 pos = origPos; pos.y = Mathf.SmoothStep(a, b, curRoutineTime); Quaternion rot = Quaternion.Lerp(quatA, quatB, curRoutineTime); updateRestingPosition(pos, rot); yield return null; } } } public void updateRestingPosition(Vector3 v, Quaternion r) { origPos = v; origRot = r; if (curState != manipState.grabbed) { transform.localPosition = v; transform.localRotation = r; } } public override void setState(manipState state) { if (curState == state) return; if (curState == manipState.grabbed) { transform.parent = masterObj; glowTrans.gameObject.SetActive(false); returnRoutineID = StartCoroutine(returnRoutine()); if (_interface != null) _interface.onGrab(false, -1); } curState = state; if (curState == manipState.none) { highlight.SetActive(false); } else if (curState == manipState.selected) { highlight.SetActive(true); } else if (curState == manipState.grabbed) { if (_interface != null) _interface.onGrab(true, -1); if (returnRoutineID != null) StopCoroutine(returnRoutineID); highlight.SetActive(false); glowTrans.gameObject.SetActive(true); transform.parent = manipulatorObj.parent; transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; if (manipulatorObjScript != null) manipulatorObjScript.setVerticalPosition(transform); pads.Clear(); lastStickPos.Clear(); pads = FindObjectsOfType<drumpad>().ToList(); for (int i = 0; i < pads.Count; i++) lastStickPos.Add(pads[i].transform.parent.InverseTransformPoint(sticktip.position)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Sql.Fluent { using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Sql.Fluent.SqlSyncMember.Update; using Microsoft.Azure.Management.Sql.Fluent.SqlSyncMemberOperations.Definition; using Microsoft.Azure.Management.Sql.Fluent.SqlSyncMemberOperations.SqlSyncMemberOperationsDefinition; using Microsoft.Azure.Management.Sql.Fluent.Models; using System; /// <summary> /// Implementation for SqlSyncMember. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnNxbC5pbXBsZW1lbnRhdGlvbi5TcWxTeW5jTWVtYmVySW1wbA== internal partial class SqlSyncMemberImpl : ChildResource< Models.SyncMemberInner, Microsoft.Azure.Management.Sql.Fluent.SqlSyncGroupImpl, Microsoft.Azure.Management.Sql.Fluent.ISqlSyncGroup>, ISqlSyncMember, IUpdate, ISqlSyncMemberOperationsDefinition { private ISqlManager sqlServerManager; private string resourceGroupName; private string sqlServerName; private string sqlDatabaseName; private string sqlSyncGroupName; private string name; string IExternalChildResource<ISqlSyncMember, ISqlSyncGroup>.Id => this.Id(); string ICreatable<ISqlSyncMember>.Name => this.Name(); /// <summary> /// Creates an instance of external child resource in-memory. /// </summary> /// <param name="name">The name of this external child resource.</param> /// <param name="parent">Reference to the parent of this external child resource.</param> /// <param name="innerObject">Reference to the inner object representing this external child resource.</param> /// <param name="sqlServerManager">Reference to the SQL server manager that accesses DNS alias operations.</param> ///GENMHASH:CCE195E09193EDC4383029CD5CB1C628:2B6C79416FE1C7672196779693AE2D14 internal SqlSyncMemberImpl(string name, SqlSyncGroupImpl parent, SyncMemberInner innerObject, ISqlManager sqlServerManager) : base(innerObject, parent) { this.sqlServerManager = sqlServerManager; this.resourceGroupName = parent.ResourceGroupName(); this.sqlServerName = parent.SqlServerName(); this.sqlDatabaseName = parent.SqlDatabaseName(); this.sqlSyncGroupName = parent.Name(); } /// <summary> /// Creates an instance of external child resource in-memory. /// </summary> /// <param name="resourceGroupName">The resource group name.</param> /// <param name="sqlServerName">The parent SQL server name.</param> /// <param name="sqlDatabaseName">The parent SQL Database name.</param> /// <param name="sqlSyncGroupName">The parent SQL Sync Group name.</param> /// <param name="name">The name of this external child resource.</param> /// <param name="innerObject">Reference to the inner object representing this external child resource.</param> /// <param name="sqlServerManager">Reference to the SQL server manager that accesses DNS alias operations.</param> ///GENMHASH:8F51618C600342C2ED2950C13B0FBCBA:94FDB59ED889413CE8D45C337B683C50 internal SqlSyncMemberImpl(string resourceGroupName, string sqlServerName, string sqlDatabaseName, string sqlSyncGroupName, string name, SyncMemberInner innerObject, ISqlManager sqlServerManager) : base(innerObject, null) { this.sqlServerManager = sqlServerManager; this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; this.sqlDatabaseName = sqlDatabaseName; this.sqlSyncGroupName = sqlSyncGroupName; } /// <summary> /// Creates an instance of external child resource in-memory. /// </summary> /// <param name="name">The name of this external child resource.</param> /// <param name="innerObject">Reference to the inner object representing this external child resource.</param> /// <param name="sqlServerManager">Reference to the SQL server manager that accesses DNS alias operations.</param> ///GENMHASH:DE04C9A4A480ADDBCD794C715F4CCE5C:657722CF28579ADFAAA5E7E0CF6B5310 internal SqlSyncMemberImpl(string name, SyncMemberInner innerObject, ISqlManager sqlServerManager) : base(innerObject, null) { this.name = name; this.sqlServerManager = sqlServerManager; if (innerObject?.Id != null) { ResourceId resourceId = ResourceId.FromString(innerObject.Id); this.resourceGroupName = resourceId?.ResourceGroupName; this.sqlServerName = resourceId?.Parent?.Parent?.Parent?.Name; this.sqlDatabaseName = resourceId?.Parent?.Parent?.Name; this.sqlSyncGroupName = resourceId?.Parent?.Name; this.name = resourceId?.Name; } } public override string Name() { return this.name != null ? this.name : this.Inner?.Name; } ///GENMHASH:4406FF130E0497422AB31764F93B67AF:2CB2314804E457C9AD1B8E50E30A4F25 public string SqlServerDatabaseId() { return this.Inner.SqlServerDatabaseId?.ToString(); } ///GENMHASH:19BDEFC584B241587C4709ED25967CE0:42CA41F2097F28B6EEE58BD9D20EE6E0 public SqlSyncMemberImpl WithExistingSyncGroupName(string syncGroupName) { this.sqlSyncGroupName = syncGroupName; return this; } ///GENMHASH:3B89742D1355B6B50FE928002B887FA2:55F0618BF6BD745C131C2BBD910CE4A0 public string MemberServerName() { return this.Inner.ServerName; } ///GENMHASH:8085A7265EABA1790A728BA058BF34C6:BBC4EB2C23A13FF787D5322550E0EB4B public SqlSyncMemberImpl WithMemberDatabaseType(SyncMemberDbType databaseType) { this.Inner.DatabaseType = databaseType.Value; return this; } ///GENMHASH:6BCE517E09457FF033728269C8936E64:3322885CA35DEA7D7DD9EDDD0C44CF4C public IUpdate Update() { return this; } ///GENMHASH:25076928AAC27A4AEF5E24263CA3A83E:BB65DCC91137A34835DD213F6DE86BBC public async Task<IEnumerable<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncFullSchemaProperty>> ListMemberSchemasAsync(CancellationToken cancellationToken = default(CancellationToken)) { List<ISqlSyncFullSchemaProperty> syncFullSchemaProperties = new List<ISqlSyncFullSchemaProperty>(); var syncFullSchemaPropertiesInners = await this.sqlServerManager.Inner.SyncMembers .ListMemberSchemasAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.Name(), cancellationToken); if (syncFullSchemaPropertiesInners != null) { foreach(var syncFullSchemaPropertiesInner in syncFullSchemaPropertiesInners) { syncFullSchemaProperties.Add(new SqlSyncFullSchemaPropertyImpl(syncFullSchemaPropertiesInner)); } } return syncFullSchemaProperties.AsReadOnly(); } ///GENMHASH:875F3540BA3FFB0A7D4F8D040D5A538D:E7F94FDE664937F65EA0A83B5F814E68 public SqlSyncMemberImpl WithDatabaseType(SyncDirection syncDirection) { this.Inner.SyncDirection = syncDirection.Value; return this; } ///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:99137EC72E3EC025058CD00310C87AAC protected async Task<Models.SyncMemberInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await this.sqlServerManager.Inner.SyncMembers .GetAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.Name(), cancellationToken); } ///GENMHASH:65E6085BB9054A86F6A84772E3F5A9EC:AA95D6FDB4843CF4994807B6D0B0BDD1 public void Delete() { Extensions.Synchronize(() => this.DeleteAsync()); } ///GENMHASH:AD9CBE3ED55BCB7F75ECA04BEF92EF94:C6A660CBF70DBA9C3C4C09B0129FC86B public string SyncAgentId() { return this.Inner.SyncAgentId; } ///GENMHASH:8414FE72599249183B9C969B46AE2CDA:11C8814437754CFE63567E4BB352C26F public SqlSyncMemberImpl WithExistingDatabaseName(string databaseName) { this.sqlDatabaseName = databaseName; return this; } ///GENMHASH:FB979A042C59037777BE6C82A7D9F3D6:A1BBA0ABD8BFAFE0F17713B473FF93EE public SqlSyncMemberImpl WithExistingSyncGroup(ISqlSyncGroup sqlSyncGroup) { this.resourceGroupName = sqlSyncGroup.ResourceGroupName; this.sqlServerName = sqlSyncGroup.SqlServerName; this.sqlDatabaseName = sqlSyncGroup.SqlDatabaseName; this.sqlSyncGroupName = sqlSyncGroup.Name; return this; } ///GENMHASH:F22B4F7A39FEC67896EBC5CEC1D19089:DC262CD404279EC6A778CBAABE7F0797 public void RefreshMemberSchema() { Extensions.Synchronize(() => this.RefreshMemberSchemaAsync()); } ///GENMHASH:436F7850C246C7C576AE519E5EBB4FB9:E0FF69255451FAEFFAD90954D3EC0E83 public async Task RefreshMemberSchemaAsync(CancellationToken cancellationToken = default(CancellationToken)) { await this.sqlServerManager.Inner.SyncMembers .RefreshMemberSchemaAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.Name(), cancellationToken); } ///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC public string Id() { return this.Inner.Id; } ///GENMHASH:507A92D4DCD93CE9595A78198DEBDFCF:4C4C4336C86119672D7AD1E0D4BD29CB public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncMember> UpdateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await this.CreateResourceAsync(cancellationToken); } ///GENMHASH:5B9DE3DA00858077FEA3C153D30668E6:8892D33C89EB45AB71456048E4189668 public SqlSyncMemberImpl WithMemberPassword(string password) { this.Inner.Password = password; return this; } ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:275C0EFF6801962F56817CC44AF6A1E6 public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncMember> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { var syncMemberInner = await this.sqlServerManager.Inner.SyncMembers .CreateOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.Name(), this.Inner, cancellationToken); this.SetInner(syncMemberInner); return this; } ///GENMHASH:5B280DE182C5D2EEE8C64386C4189509:5410FC47FF345DF1DE37D0895E5DCAB0 public SqlSyncMemberImpl WithMemberUserName(string userName) { this.Inner.UserName = userName; return this; } ///GENMHASH:7BF54DCB43A8F83CAF5BA49CA6152E2D:56A31ED1F97C814F0A1E5485E213758D public SqlSyncMemberImpl WithMemberSqlServerName(string sqlServerName) { this.Inner.ServerName = sqlServerName; return this; } ///GENMHASH:D55C0BC6C1896D10050A2A45B9F1E6FC:2D29DF7CB31893427EBF0651FBEE3AD4 public SqlSyncMemberImpl WithMemberSqlDatabase(ISqlDatabase sqlDatabase) { this.Inner.ServerName = sqlDatabase.SqlServerName; this.Inner.DatabaseName = sqlDatabase.Name; return this; } ///GENMHASH:E9EDBD2E8DC2C547D1386A58778AA6B9:7EBD4102FEBFB0AD7091EA1ACBD84F8B public string ResourceGroupName() { return this.resourceGroupName; } ///GENMHASH:3A4DD77C2E8D817499C6F60417AB3596:44F5F71CD9996FE437F3FF8F3E8E46F9 public string MemberDatabaseName() { return this.Inner.DatabaseName; } ///GENMHASH:61F5809AB3B985C61AC40B98B1FBC47E:998832D58C98F6DCF3637916D2CC70B9 public string SqlServerName() { return this.sqlServerName; } ///GENMHASH:0BA2C0DAE27266D79653208FF06A9B80:99EDD7AD8CCAED9BC095807A7E85DE17 public SqlSyncMemberImpl WithExistingSqlServer(string resourceGroupName, string sqlServerName) { this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; return this; } ///GENMHASH:74CC786A12BD16E99274FDA4312C231B:8CBE6D07DEC2431D8F827589DF59CAAD public SyncMemberState SyncState() { return Models.SyncMemberState.Parse(this.Inner.SyncState); } ///GENMHASH:0FEDA307DAD2022B36843E8905D26EAD:95BA1017B6D636BB0934427C9B74AB8D public async Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken)) { await this.DeleteResourceAsync(cancellationToken); } ///GENMHASH:A3379C409FDEA374F81BA23D717740E8:1911A6A619CB13C7EE098F82118AC819 public string UserName() { return this.Inner.UserName; } ///GENMHASH:7A0398C4BB6EBF42CC817EE638D40E9C:2DC6B3BEB4C8A428A0339820143BFEB3 public string ParentId() { var resourceId = ResourceId.FromString(this.Id()); return resourceId?.Parent?.Id; } ///GENMHASH:AF40DAB933F8B3F7B0F9B5DF8CA667F7:BDB25FFB52E063698BA7165F98332656 public SqlSyncMemberImpl WithMemberSqlDatabaseName(string sqlDatabaseName) { this.Inner.DatabaseName = sqlDatabaseName; return this; } ///GENMHASH:34645F7AAC85BDB9B4B2319A8E8A5AD6:DEB5F8EF5229ECF71C1EE408DFDD3674 public SyncMemberDbType DatabaseType() { return Models.SyncMemberDbType.Parse(this.Inner.DatabaseType); } ///GENMHASH:0A8C95E7BCF012420BB9CA8540401D0F:BD7BB32481D5B7E613BD35E4E7DB5CBF public SyncDirection SyncDirection() { return Models.SyncDirection.Parse(this.Inner.SyncDirection); } ///GENMHASH:6059E1A9D3915C813F3878D0DB9E0819:31BC00949A75A3F86A2BE328DDB25175 public IEnumerable<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncFullSchemaProperty> ListMemberSchemas() { return Extensions.Synchronize(() => this.ListMemberSchemasAsync()); } ///GENMHASH:E24A9768E91CD60E963E43F00AA1FDFE:5F4B36E6AB2C7F6F3128E769FD2DE126 public async Task DeleteResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { await this.sqlServerManager.Inner.SyncMembers .DeleteAsync(this.resourceGroupName, this.sqlServerName, this.sqlDatabaseName, this.sqlSyncGroupName, this.Name(), cancellationToken); } ///GENMHASH:D6F2CA9FCB582F6890064D6BF0DD0F7D:9C4EE3FA82BE9069D73452E4AE656294 public string SqlSyncGroupName() { return this.sqlSyncGroupName; } ///GENMHASH:975CFB2E2076677C0B3809B900A8B22E:81D4625030F31F3802DFC9934445ECD0 public string SqlDatabaseName() { return this.sqlDatabaseName; } public ISqlSyncMember Refresh() { return Extensions.Synchronize(() => this.RefreshAsync()); } public async Task<ISqlSyncMember> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken)) { this.SetInner(await this.GetInnerAsync(cancellationToken)); return this; } public ISqlSyncMember Apply() { return Extensions.Synchronize(() => this.ApplyAsync()); } public async Task<ISqlSyncMember> ApplyAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true) { return await this.UpdateResourceAsync(cancellationToken); } public ISqlSyncMember Create() { return Extensions.Synchronize(() => this.CreateAsync()); } public async Task<ISqlSyncMember> CreateAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true) { return await this.CreateResourceAsync(cancellationToken); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ProjectWithSecurity.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Diagnostics; using System.Text; using i64 = System.Int64; using u8 = System.Byte; using u32 = System.UInt32; using Pgno = System.UInt32; namespace System.Data.SQLite { using sqlite3_int64 = System.Int64; public partial class Sqlite3 { /* ** 2008 December 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This module implements an object we call a "RowSet". ** ** The RowSet object is a collection of rowids. Rowids ** are inserted into the RowSet in an arbitrary order. Inserts ** can be intermixed with tests to see if a given rowid has been ** previously inserted into the RowSet. ** ** After all inserts are finished, it is possible to extract the ** elements of the RowSet in sorted order. Once this extraction ** process has started, no new elements may be inserted. ** ** Hence, the primitive operations for a RowSet are: ** ** CREATE ** INSERT ** TEST ** SMALLEST ** DESTROY ** ** The CREATE and DESTROY primitives are the constructor and destructor, ** obviously. The INSERT primitive adds a new element to the RowSet. ** TEST checks to see if an element is already in the RowSet. SMALLEST ** extracts the least value from the RowSet. ** ** The INSERT primitive might allocate additional memory. Memory is ** allocated in chunks so most INSERTs do no allocation. There is an ** upper bound on the size of allocated memory. No memory is freed ** until DESTROY. ** ** The TEST primitive includes a "batch" number. The TEST primitive ** will only see elements that were inserted before the last change ** in the batch number. In other words, if an INSERT occurs between ** two TESTs where the TESTs have the same batch nubmer, then the ** value added by the INSERT will not be visible to the second TEST. ** The initial batch number is zero, so if the very first TEST contains ** a non-zero batch number, it will see all prior INSERTs. ** ** No INSERTs may occurs after a SMALLEST. An assertion will fail if ** that is attempted. ** ** The cost of an INSERT is roughly constant. (Sometime new memory ** has to be allocated on an INSERT.) The cost of a TEST with a new ** batch number is O(NlogN) where N is the number of elements in the RowSet. ** The cost of a TEST using the same batch number is O(logN). The cost ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST ** primitives are constant time. The cost of DESTROY is O(N). ** ** There is an added cost of O(N) when switching between TEST and ** SMALLEST primitives. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" /* ** Target size for allocation chunks. */ //#define ROWSET_ALLOCATION_SIZE 1024 const int ROWSET_ALLOCATION_SIZE = 1024; /* ** The number of rowset entries per allocation chunk. */ //#define ROWSET_ENTRY_PER_CHUNK \ // ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) const int ROWSET_ENTRY_PER_CHUNK = 63; /* ** Each entry in a RowSet is an instance of the following object. */ public class RowSetEntry { public i64 v; /* ROWID value for this entry */ public RowSetEntry pRight; /* Right subtree (larger entries) or list */ public RowSetEntry pLeft; /* Left subtree (smaller entries) */ }; /* ** Index entries are allocated in large chunks (instances of the ** following structure) to reduce memory allocation overhead. The ** chunks are kept on a linked list so that they can be deallocated ** when the RowSet is destroyed. */ public class RowSetChunk { public RowSetChunk pNextChunk; /* Next chunk on list of them all */ public RowSetEntry[] aEntry = new RowSetEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ }; /* ** A RowSet in an instance of the following structure. ** ** A typedef of this structure if found in sqliteInt.h. */ public class RowSet { public RowSetChunk pChunk; /* List of all chunk allocations */ public sqlite3 db; /* The database connection */ public RowSetEntry pEntry; /* /* List of entries using pRight */ public RowSetEntry pLast; /* Last entry on the pEntry list */ public RowSetEntry[] pFresh; /* Source of new entry objects */ public RowSetEntry pTree; /* Binary tree of entries */ public int nFresh; /* Number of objects on pFresh */ public bool isSorted; /* True if pEntry is sorted */ public u8 iBatch; /* Current insert batch */ public RowSet(sqlite3 db, int N) { this.pChunk = null; this.db = db; this.pEntry = null; this.pLast = null; this.pFresh = new RowSetEntry[N]; this.pTree = null; this.nFresh = N; this.isSorted = true; this.iBatch = 0; } }; /* ** Turn bulk memory into a RowSet object. N bytes of memory ** are available at pSpace. The db pointer is used as a memory context ** for any subsequent allocations that need to occur. ** Return a pointer to the new RowSet object. ** ** It must be the case that N is sufficient to make a Rowset. If not ** an assertion fault occurs. ** ** If N is larger than the minimum, use the surplus as an initial ** allocation of entries available to be filled. */ static RowSet sqlite3RowSetInit(sqlite3 db, object pSpace, u32 N) { RowSet p = new RowSet(db, (int)N); //Debug.Assert(N >= ROUND8(sizeof(*p)) ); // p = pSpace; // p.pChunk = 0; // p.db = db; // p.pEntry = 0; // p.pLast = 0; // p.pTree = 0; // p.pFresh =(struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); // p.nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); // p.isSorted = 1; // p.iBatch = 0; return p; } /* ** Deallocate all chunks from a RowSet. This frees all memory that ** the RowSet has allocated over its lifetime. This routine is ** the destructor for the RowSet. */ static void sqlite3RowSetClear(RowSet p) { RowSetChunk pChunk, pNextChunk; for (pChunk = p.pChunk; pChunk != null; pChunk = pNextChunk) { pNextChunk = pChunk.pNextChunk; sqlite3DbFree(p.db, ref pChunk); } p.pChunk = null; p.nFresh = 0; p.pEntry = null; p.pLast = null; p.pTree = null; p.isSorted = true; } /* ** Insert a new value into a RowSet. ** ** The mallocFailed flag of the database connection is set if a ** memory allocation fails. */ static void sqlite3RowSetInsert(RowSet p, i64 rowid) { RowSetEntry pEntry; /* The new entry */ RowSetEntry pLast; /* The last prior entry */ Debug.Assert(p != null); if (p.nFresh == 0) { RowSetChunk pNew; pNew = new RowSetChunk();//sqlite3DbMallocRaw(p.db, sizeof(*pNew)); if (pNew == null) { return; } pNew.pNextChunk = p.pChunk; p.pChunk = pNew; p.pFresh = pNew.aEntry; p.nFresh = ROWSET_ENTRY_PER_CHUNK; } p.pFresh[p.pFresh.Length - p.nFresh] = new RowSetEntry(); pEntry = p.pFresh[p.pFresh.Length - p.nFresh]; p.nFresh--; pEntry.v = rowid; pEntry.pRight = null; pLast = p.pLast; if (pLast != null) { if (p.isSorted && rowid <= pLast.v) { p.isSorted = false; } pLast.pRight = pEntry; } else { Debug.Assert(p.pEntry == null);/* Fires if INSERT after SMALLEST */ p.pEntry = pEntry; } p.pLast = pEntry; } /* ** Merge two lists of RowSetEntry objects. Remove duplicates. ** ** The input lists are connected via pRight pointers and are ** assumed to each already be in sorted order. */ static RowSetEntry rowSetMerge( RowSetEntry pA, /* First sorted list to be merged */ RowSetEntry pB /* Second sorted list to be merged */ ) { RowSetEntry head = new RowSetEntry(); RowSetEntry pTail; pTail = head; while (pA != null && pB != null) { Debug.Assert(pA.pRight == null || pA.v <= pA.pRight.v); Debug.Assert(pB.pRight == null || pB.v <= pB.pRight.v); if (pA.v < pB.v) { pTail.pRight = pA; pA = pA.pRight; pTail = pTail.pRight; } else if (pB.v < pA.v) { pTail.pRight = pB; pB = pB.pRight; pTail = pTail.pRight; } else { pA = pA.pRight; } } if (pA != null) { Debug.Assert(pA.pRight == null || pA.v <= pA.pRight.v); pTail.pRight = pA; } else { Debug.Assert(pB == null || pB.pRight == null || pB.v <= pB.pRight.v); pTail.pRight = pB; } return head.pRight; } /* ** Sort all elements on the pEntry list of the RowSet into ascending order. */ static void rowSetSort(RowSet p) { u32 i; RowSetEntry pEntry; RowSetEntry[] aBucket = new RowSetEntry[40]; Debug.Assert(p.isSorted == false); //memset(aBucket, 0, sizeof(aBucket)); while (p.pEntry != null) { pEntry = p.pEntry; p.pEntry = pEntry.pRight; pEntry.pRight = null; for (i = 0; aBucket[i] != null; i++) { pEntry = rowSetMerge(aBucket[i], pEntry); aBucket[i] = null; } aBucket[i] = pEntry; } pEntry = null; for (i = 0; i < aBucket.Length; i++)//sizeof(aBucket)/sizeof(aBucket[0]) { pEntry = rowSetMerge(pEntry, aBucket[i]); } p.pEntry = pEntry; p.pLast = null; p.isSorted = true; } /* ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects. ** Convert this tree into a linked list connected by the pRight pointers ** and return pointers to the first and last elements of the new list. */ static void rowSetTreeToList( RowSetEntry pIn, /* Root of the input tree */ ref RowSetEntry ppFirst, /* Write head of the output list here */ ref RowSetEntry ppLast /* Write tail of the output list here */ ) { Debug.Assert(pIn != null); if (pIn.pLeft != null) { RowSetEntry p = new RowSetEntry(); rowSetTreeToList(pIn.pLeft, ref ppFirst, ref p); p.pRight = pIn; } else { ppFirst = pIn; } if (pIn.pRight != null) { rowSetTreeToList(pIn.pRight, ref pIn.pRight, ref ppLast); } else { ppLast = pIn; } Debug.Assert((ppLast).pRight == null); } /* ** Convert a sorted list of elements (connected by pRight) into a binary ** tree with depth of iDepth. A depth of 1 means the tree contains a single ** node taken from the head of *ppList. A depth of 2 means a tree with ** three nodes. And so forth. ** ** Use as many entries from the input list as required and update the ** *ppList to point to the unused elements of the list. If the input ** list contains too few elements, then construct an incomplete tree ** and leave *ppList set to NULL. ** ** Return a pointer to the root of the constructed binary tree. */ static RowSetEntry rowSetNDeepTree( ref RowSetEntry ppList, int iDepth ) { RowSetEntry p; /* Root of the new tree */ RowSetEntry pLeft; /* Left subtree */ if (ppList == null) { return null; } if (iDepth == 1) { p = ppList; ppList = p.pRight; p.pLeft = p.pRight = null; return p; } pLeft = rowSetNDeepTree(ref ppList, iDepth - 1); p = ppList; if (p == null) { return pLeft; } p.pLeft = pLeft; ppList = p.pRight; p.pRight = rowSetNDeepTree(ref ppList, iDepth - 1); return p; } /* ** Convert a sorted list of elements into a binary tree. Make the tree ** as deep as it needs to be in order to contain the entire list. */ static RowSetEntry rowSetListToTree(RowSetEntry pList) { int iDepth; /* Depth of the tree so far */ RowSetEntry p; /* Current tree root */ RowSetEntry pLeft; /* Left subtree */ Debug.Assert(pList != null); p = pList; pList = p.pRight; p.pLeft = p.pRight = null; for (iDepth = 1; pList != null; iDepth++) { pLeft = p; p = pList; pList = p.pRight; p.pLeft = pLeft; p.pRight = rowSetNDeepTree(ref pList, iDepth); } return p; } /* ** Convert the list in p.pEntry into a sorted list if it is not ** sorted already. If there is a binary tree on p.pTree, then ** convert it into a list too and merge it into the p.pEntry list. */ static void rowSetToList(RowSet p) { if (!p.isSorted) { rowSetSort(p); } if (p.pTree != null) { RowSetEntry pHead = new RowSetEntry(); RowSetEntry pTail = new RowSetEntry(); rowSetTreeToList(p.pTree, ref pHead, ref pTail); p.pTree = null; p.pEntry = rowSetMerge(p.pEntry, pHead); } } /* ** Extract the smallest element from the RowSet. ** Write the element into *pRowid. Return 1 on success. Return ** 0 if the RowSet is already empty. ** ** After this routine has been called, the sqlite3RowSetInsert() ** routine may not be called again. */ static int sqlite3RowSetNext(RowSet p, ref i64 pRowid) { rowSetToList(p); if (p.pEntry != null) { pRowid = p.pEntry.v; p.pEntry = p.pEntry.pRight; if (p.pEntry == null) { sqlite3RowSetClear(p); } return 1; } else { return 0; } } /* ** Check to see if element iRowid was inserted into the the rowset as ** part of any insert batch prior to iBatch. Return 1 or 0. */ static int sqlite3RowSetTest(RowSet pRowSet, u8 iBatch, sqlite3_int64 iRowid) { RowSetEntry p; if (iBatch != pRowSet.iBatch) { if (pRowSet.pEntry != null) { rowSetToList(pRowSet); pRowSet.pTree = rowSetListToTree(pRowSet.pEntry); pRowSet.pEntry = null; pRowSet.pLast = null; } pRowSet.iBatch = iBatch; } p = pRowSet.pTree; while (p != null) { if (p.v < iRowid) { p = p.pRight; } else if (p.v > iRowid) { p = p.pLeft; } else { return 1; } } return 0; } } }
namespace WinFormsGraphicsDevice { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; //public MapArea mapArea1 = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.panel1 = new System.Windows.Forms.Panel(); this.resourceList = new System.Windows.Forms.ImageList(this.components); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menu_FileNew = new System.Windows.Forms.ToolStripMenuItem(); this.fileLoadMenu = new System.Windows.Forms.ToolStripMenuItem(); this.fileSaveMenu = new System.Windows.Forms.ToolStripMenuItem(); this.fileExitMenu = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menu_EditClear = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.clearPlatformsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearEnemiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearPoweToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearStartGoalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.helpMenu = new System.Windows.Forms.ToolStripMenuItem(); this.helpAboutMenu = new System.Windows.Forms.ToolStripMenuItem(); this.insertAssetButton = new System.Windows.Forms.Button(); this.dlgOpen = new System.Windows.Forms.OpenFileDialog(); this.dlgSave = new System.Windows.Forms.OpenFileDialog(); this.tabControl = new System.Windows.Forms.TabControl(); this.Platforms = new System.Windows.Forms.TabPage(); this.resourceListView = new System.Windows.Forms.ListView(); this.Enemies = new System.Windows.Forms.TabPage(); this.enemyResourceListView = new System.Windows.Forms.ListView(); this.enemyResourceList = new System.Windows.Forms.ImageList(this.components); this.Powerups = new System.Windows.Forms.TabPage(); this.powerupsResourceListView = new System.Windows.Forms.ListView(); this.powerupsResourceList = new System.Windows.Forms.ImageList(this.components); this.StartGoal = new System.Windows.Forms.TabPage(); this.startgoalResourceListView = new System.Windows.Forms.ListView(); this.startgoalResourceList = new System.Windows.Forms.ImageList(this.components); this.invisibleResourceList = new System.Windows.Forms.ImageList(this.components); this.breakableResourceList = new System.Windows.Forms.ImageList(this.components); this.Invisible = new System.Windows.Forms.TabPage(); this.Breakable = new System.Windows.Forms.TabPage(); this.invisibleResourceListView = new System.Windows.Forms.ListView(); this.breakableResourceListView = new System.Windows.Forms.ListView(); this.clearInvisibleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearBreakableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.tabControl.SuspendLayout(); this.Platforms.SuspendLayout(); this.Enemies.SuspendLayout(); this.Powerups.SuspendLayout(); this.StartGoal.SuspendLayout(); this.Invisible.SuspendLayout(); this.Breakable.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.AutoScroll = true; this.panel1.BackColor = System.Drawing.SystemColors.AppWorkspace; this.panel1.Location = new System.Drawing.Point(8, 32); this.panel1.Margin = new System.Windows.Forms.Padding(2); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(556, 558); this.panel1.TabIndex = 0; // // resourceList // this.resourceList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.resourceList.ImageSize = new System.Drawing.Size(16, 16); this.resourceList.TransparentColor = System.Drawing.Color.Transparent; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.helpMenu}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Padding = new System.Windows.Forms.Padding(4, 1, 0, 1); this.menuStrip1.Size = new System.Drawing.Size(796, 24); this.menuStrip1.TabIndex = 2; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menu_FileNew, this.fileLoadMenu, this.fileSaveMenu, this.fileExitMenu}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 22); this.fileToolStripMenuItem.Text = "&File"; // // menu_FileNew // this.menu_FileNew.Name = "menu_FileNew"; this.menu_FileNew.Size = new System.Drawing.Size(107, 22); this.menu_FileNew.Text = "&New..."; this.menu_FileNew.Click += new System.EventHandler(this.menu_FileNew_Click); // // fileLoadMenu // this.fileLoadMenu.Name = "fileLoadMenu"; this.fileLoadMenu.Size = new System.Drawing.Size(107, 22); this.fileLoadMenu.Text = "&Load"; this.fileLoadMenu.Click += new System.EventHandler(this.fileLoadMenu_Click); // // fileSaveMenu // this.fileSaveMenu.Name = "fileSaveMenu"; this.fileSaveMenu.Size = new System.Drawing.Size(107, 22); this.fileSaveMenu.Text = "&Save"; this.fileSaveMenu.Click += new System.EventHandler(this.fileSaveMenu_Click); // // fileExitMenu // this.fileExitMenu.Name = "fileExitMenu"; this.fileExitMenu.Size = new System.Drawing.Size(107, 22); this.fileExitMenu.Text = "&Exit"; this.fileExitMenu.Click += new System.EventHandler(this.fileExitMenu_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menu_EditClear, this.toolStripSeparator2, this.clearPlatformsToolStripMenuItem, this.clearEnemiesToolStripMenuItem, this.clearPoweToolStripMenuItem, this.clearStartGoalToolStripMenuItem, this.toolStripSeparator1, this.clearInvisibleToolStripMenuItem, this.clearBreakableToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 22); this.editToolStripMenuItem.Text = "&Edit"; // // menu_EditClear // this.menu_EditClear.Name = "menu_EditClear"; this.menu_EditClear.Size = new System.Drawing.Size(157, 22); this.menu_EditClear.Text = "Clear &All"; this.menu_EditClear.Click += new System.EventHandler(this.menu_EditClear_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(154, 6); // // clearPlatformsToolStripMenuItem // this.clearPlatformsToolStripMenuItem.Name = "clearPlatformsToolStripMenuItem"; this.clearPlatformsToolStripMenuItem.Size = new System.Drawing.Size(157, 22); this.clearPlatformsToolStripMenuItem.Text = "Clear &Platforms"; this.clearPlatformsToolStripMenuItem.Click += new System.EventHandler(this.clearPlatformsToolStripMenuItem_Click); // // clearEnemiesToolStripMenuItem // this.clearEnemiesToolStripMenuItem.Name = "clearEnemiesToolStripMenuItem"; this.clearEnemiesToolStripMenuItem.Size = new System.Drawing.Size(157, 22); this.clearEnemiesToolStripMenuItem.Text = "Clear &Enemies"; this.clearEnemiesToolStripMenuItem.Click += new System.EventHandler(this.clearEnemiesToolStripMenuItem_Click); // // clearPoweToolStripMenuItem // this.clearPoweToolStripMenuItem.Name = "clearPoweToolStripMenuItem"; this.clearPoweToolStripMenuItem.Size = new System.Drawing.Size(157, 22); this.clearPoweToolStripMenuItem.Text = "Clear Po&werups"; this.clearPoweToolStripMenuItem.Click += new System.EventHandler(this.clearPoweToolStripMenuItem_Click); // // clearStartGoalToolStripMenuItem // this.clearStartGoalToolStripMenuItem.Name = "clearStartGoalToolStripMenuItem"; this.clearStartGoalToolStripMenuItem.Size = new System.Drawing.Size(157, 22); this.clearStartGoalToolStripMenuItem.Text = "Clear &Start/Goal"; this.clearStartGoalToolStripMenuItem.Click += new System.EventHandler(this.clearStartGoalToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(154, 6); // // helpMenu // this.helpMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.helpAboutMenu}); this.helpMenu.Name = "helpMenu"; this.helpMenu.Size = new System.Drawing.Size(44, 22); this.helpMenu.Text = "&Help"; // // helpAboutMenu // this.helpAboutMenu.Name = "helpAboutMenu"; this.helpAboutMenu.Size = new System.Drawing.Size(107, 22); this.helpAboutMenu.Text = "&About"; this.helpAboutMenu.Click += new System.EventHandler(this.helpAboutMenu_Click); // // insertAssetButton // this.insertAssetButton.Location = new System.Drawing.Point(568, 560); this.insertAssetButton.Margin = new System.Windows.Forms.Padding(2); this.insertAssetButton.Name = "insertAssetButton"; this.insertAssetButton.Size = new System.Drawing.Size(75, 21); this.insertAssetButton.TabIndex = 3; this.insertAssetButton.Text = "Insert Asset"; this.insertAssetButton.UseVisualStyleBackColor = true; this.insertAssetButton.Click += new System.EventHandler(this.button1_Click); // // dlgOpen // this.dlgOpen.FileName = "openFileDialog1"; // // dlgSave // this.dlgSave.FileName = "openFileDialog1"; // // tabControl // this.tabControl.Controls.Add(this.Platforms); this.tabControl.Controls.Add(this.Enemies); this.tabControl.Controls.Add(this.Powerups); this.tabControl.Controls.Add(this.StartGoal); this.tabControl.Controls.Add(this.Invisible); this.tabControl.Controls.Add(this.Breakable); this.tabControl.Location = new System.Drawing.Point(568, 32); this.tabControl.Margin = new System.Windows.Forms.Padding(2); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size(216, 525); this.tabControl.TabIndex = 0; // // Platforms // this.Platforms.Controls.Add(this.resourceListView); this.Platforms.Location = new System.Drawing.Point(4, 22); this.Platforms.Margin = new System.Windows.Forms.Padding(2); this.Platforms.Name = "Platforms"; this.Platforms.Padding = new System.Windows.Forms.Padding(2); this.Platforms.Size = new System.Drawing.Size(208, 499); this.Platforms.TabIndex = 0; this.Platforms.Text = "Platforms"; this.Platforms.UseVisualStyleBackColor = true; // // resourceListView // this.resourceListView.BorderStyle = System.Windows.Forms.BorderStyle.None; this.resourceListView.HideSelection = false; this.resourceListView.LargeImageList = this.resourceList; this.resourceListView.Location = new System.Drawing.Point(2, 2); this.resourceListView.Margin = new System.Windows.Forms.Padding(2); this.resourceListView.MaximumSize = new System.Drawing.Size(300, 499); this.resourceListView.MultiSelect = false; this.resourceListView.Name = "resourceListView"; this.resourceListView.Size = new System.Drawing.Size(207, 499); this.resourceListView.TabIndex = 0; this.resourceListView.UseCompatibleStateImageBehavior = false; // // Enemies // this.Enemies.Controls.Add(this.enemyResourceListView); this.Enemies.Location = new System.Drawing.Point(4, 22); this.Enemies.Margin = new System.Windows.Forms.Padding(2); this.Enemies.Name = "Enemies"; this.Enemies.Padding = new System.Windows.Forms.Padding(2); this.Enemies.Size = new System.Drawing.Size(208, 499); this.Enemies.TabIndex = 1; this.Enemies.Text = "Enemies"; this.Enemies.UseVisualStyleBackColor = true; // // enemyResourceListView // this.enemyResourceListView.HideSelection = false; this.enemyResourceListView.LargeImageList = this.enemyResourceList; this.enemyResourceListView.Location = new System.Drawing.Point(5, 3); this.enemyResourceListView.Margin = new System.Windows.Forms.Padding(2); this.enemyResourceListView.MultiSelect = false; this.enemyResourceListView.Name = "enemyResourceListView"; this.enemyResourceListView.Size = new System.Drawing.Size(203, 498); this.enemyResourceListView.TabIndex = 0; this.enemyResourceListView.UseCompatibleStateImageBehavior = false; // // enemyResourceList // this.enemyResourceList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.enemyResourceList.ImageSize = new System.Drawing.Size(16, 16); this.enemyResourceList.TransparentColor = System.Drawing.Color.Transparent; // // Powerups // this.Powerups.Controls.Add(this.powerupsResourceListView); this.Powerups.Location = new System.Drawing.Point(4, 22); this.Powerups.Margin = new System.Windows.Forms.Padding(2); this.Powerups.Name = "Powerups"; this.Powerups.Padding = new System.Windows.Forms.Padding(2); this.Powerups.Size = new System.Drawing.Size(208, 499); this.Powerups.TabIndex = 2; this.Powerups.Text = "Powerups"; this.Powerups.UseVisualStyleBackColor = true; // // powerupsResourceListView // this.powerupsResourceListView.HideSelection = false; this.powerupsResourceListView.LargeImageList = this.powerupsResourceList; this.powerupsResourceListView.Location = new System.Drawing.Point(5, 5); this.powerupsResourceListView.Margin = new System.Windows.Forms.Padding(2); this.powerupsResourceListView.MultiSelect = false; this.powerupsResourceListView.Name = "powerupsResourceListView"; this.powerupsResourceListView.Size = new System.Drawing.Size(203, 496); this.powerupsResourceListView.TabIndex = 0; this.powerupsResourceListView.UseCompatibleStateImageBehavior = false; // // powerupsResourceList // this.powerupsResourceList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.powerupsResourceList.ImageSize = new System.Drawing.Size(16, 16); this.powerupsResourceList.TransparentColor = System.Drawing.Color.Transparent; // // StartGoal // this.StartGoal.Controls.Add(this.startgoalResourceListView); this.StartGoal.Location = new System.Drawing.Point(4, 22); this.StartGoal.Margin = new System.Windows.Forms.Padding(2); this.StartGoal.Name = "StartGoal"; this.StartGoal.Size = new System.Drawing.Size(208, 499); this.StartGoal.TabIndex = 3; this.StartGoal.Text = "Start/Finish"; this.StartGoal.UseVisualStyleBackColor = true; // // startgoalResourceListView // this.startgoalResourceListView.HideSelection = false; this.startgoalResourceListView.LargeImageList = this.startgoalResourceList; this.startgoalResourceListView.Location = new System.Drawing.Point(3, 3); this.startgoalResourceListView.Margin = new System.Windows.Forms.Padding(2); this.startgoalResourceListView.MultiSelect = false; this.startgoalResourceListView.Name = "startgoalResourceListView"; this.startgoalResourceListView.Size = new System.Drawing.Size(207, 500); this.startgoalResourceListView.TabIndex = 0; this.startgoalResourceListView.UseCompatibleStateImageBehavior = false; // // startgoalResourceList // this.startgoalResourceList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.startgoalResourceList.ImageSize = new System.Drawing.Size(16, 16); this.startgoalResourceList.TransparentColor = System.Drawing.Color.Transparent; // // invisibleResourceList // this.invisibleResourceList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.invisibleResourceList.ImageSize = new System.Drawing.Size(16, 16); this.invisibleResourceList.TransparentColor = System.Drawing.Color.Transparent; // // breakableResourceList // this.breakableResourceList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.breakableResourceList.ImageSize = new System.Drawing.Size(16, 16); this.breakableResourceList.TransparentColor = System.Drawing.Color.Transparent; // // Invisible // this.Invisible.Controls.Add(this.invisibleResourceListView); this.Invisible.Location = new System.Drawing.Point(4, 22); this.Invisible.Name = "Invisible"; this.Invisible.Size = new System.Drawing.Size(208, 499); this.Invisible.TabIndex = 4; this.Invisible.Text = "Invisible"; this.Invisible.UseVisualStyleBackColor = true; // // Breakable // this.Breakable.Controls.Add(this.breakableResourceListView); this.Breakable.Location = new System.Drawing.Point(4, 22); this.Breakable.Name = "Breakable"; this.Breakable.Size = new System.Drawing.Size(208, 499); this.Breakable.TabIndex = 5; this.Breakable.Text = "Breakable"; this.Breakable.UseVisualStyleBackColor = true; // // invisibleResourceListView // this.invisibleResourceListView.HideSelection = false; this.invisibleResourceListView.LargeImageList = this.invisibleResourceList; this.invisibleResourceListView.Location = new System.Drawing.Point(3, 3); this.invisibleResourceListView.MultiSelect = false; this.invisibleResourceListView.Name = "invisibleResourceListView"; this.invisibleResourceListView.Size = new System.Drawing.Size(202, 493); this.invisibleResourceListView.TabIndex = 0; this.invisibleResourceListView.UseCompatibleStateImageBehavior = false; // // breakableResourceListView // this.breakableResourceListView.HideSelection = false; this.breakableResourceListView.LargeImageList = this.breakableResourceList; this.breakableResourceListView.Location = new System.Drawing.Point(4, 4); this.breakableResourceListView.MultiSelect = false; this.breakableResourceListView.Name = "breakableResourceListView"; this.breakableResourceListView.Size = new System.Drawing.Size(201, 492); this.breakableResourceListView.TabIndex = 0; this.breakableResourceListView.UseCompatibleStateImageBehavior = false; // // clearInvisibleToolStripMenuItem // this.clearInvisibleToolStripMenuItem.Name = "clearInvisibleToolStripMenuItem"; this.clearInvisibleToolStripMenuItem.Size = new System.Drawing.Size(157, 22); this.clearInvisibleToolStripMenuItem.Text = "Clear &Invisible"; this.clearInvisibleToolStripMenuItem.Click += new System.EventHandler(this.clearInvisibleToolStripMenuItem_Click); // // clearBreakableToolStripMenuItem // this.clearBreakableToolStripMenuItem.Name = "clearBreakableToolStripMenuItem"; this.clearBreakableToolStripMenuItem.Size = new System.Drawing.Size(157, 22); this.clearBreakableToolStripMenuItem.Text = "Clear &Breakable"; this.clearBreakableToolStripMenuItem.Click += new System.EventHandler(this.clearBreakableToolStripMenuItem_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Highlight; this.ClientSize = new System.Drawing.Size(796, 590); this.Controls.Add(this.tabControl); this.Controls.Add(this.insertAssetButton); this.Controls.Add(this.panel1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "MainForm"; this.Text = "Level Editor"; this.Load += new System.EventHandler(this.MainForm_Load); this.Resize += new System.EventHandler(this.MainForm_Resize); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.tabControl.ResumeLayout(false); this.Platforms.ResumeLayout(false); this.Enemies.ResumeLayout(false); this.Powerups.ResumeLayout(false); this.StartGoal.ResumeLayout(false); this.Invisible.ResumeLayout(false); this.Breakable.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ImageList resourceList; private System.Windows.Forms.Button insertAssetButton; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem menu_FileNew; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem menu_EditClear; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem helpMenu; private System.Windows.Forms.ToolStripMenuItem helpAboutMenu; private System.Windows.Forms.ToolStripMenuItem fileLoadMenu; private System.Windows.Forms.ToolStripMenuItem fileSaveMenu; private System.Windows.Forms.OpenFileDialog dlgOpen; private System.Windows.Forms.ToolStripMenuItem fileExitMenu; private System.Windows.Forms.OpenFileDialog dlgSave; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage Platforms; private System.Windows.Forms.ListView resourceListView; private System.Windows.Forms.TabPage Enemies; private System.Windows.Forms.TabPage Powerups; private System.Windows.Forms.ImageList enemyResourceList; private System.Windows.Forms.ListView enemyResourceListView; private System.Windows.Forms.ListView powerupsResourceListView; private System.Windows.Forms.TabPage StartGoal; private System.Windows.Forms.ImageList powerupsResourceList; private System.Windows.Forms.ImageList startgoalResourceList; private System.Windows.Forms.ListView startgoalResourceListView; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem clearPlatformsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearEnemiesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearPoweToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearStartGoalToolStripMenuItem; private System.Windows.Forms.ImageList invisibleResourceList; private System.Windows.Forms.ImageList breakableResourceList; private System.Windows.Forms.TabPage Invisible; private System.Windows.Forms.TabPage Breakable; private System.Windows.Forms.ListView invisibleResourceListView; private System.Windows.Forms.ListView breakableResourceListView; private System.Windows.Forms.ToolStripMenuItem clearInvisibleToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearBreakableToolStripMenuItem; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for RouteFiltersOperations. /// </summary> public static partial class RouteFiltersOperationsExtensions { /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> public static void Delete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName) { operations.DeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='expand'> /// Expands referenced express route bgp peering resources. /// </param> public static RouteFilter Get(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string)) { return operations.GetAsync(resourceGroupName, routeFilterName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='expand'> /// Expands referenced express route bgp peering resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> GetAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeFilterName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> public static RouteFilter CreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> CreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> public static RouteFilter Update(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters) { return operations.UpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> UpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<RouteFilter> ListByResourceGroup(this IRouteFiltersOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilter>> ListByResourceGroupAsync(this IRouteFiltersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<RouteFilter> List(this IRouteFiltersOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilter>> ListAsync(this IRouteFiltersOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> public static void BeginDelete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName) { operations.BeginDeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> public static RouteFilter BeginCreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> BeginCreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> public static RouteFilter BeginUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters) { return operations.BeginUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilter> BeginUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a resource group. /// </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<RouteFilter> ListByResourceGroupNext(this IRouteFiltersOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a resource group. /// </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<RouteFilter>> ListByResourceGroupNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route filters in a subscription. /// </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<RouteFilter> ListNext(this IRouteFiltersOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all route filters in a subscription. /// </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<RouteFilter>> ListNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A stadium. /// </summary> public class StadiumOrArena_Core : TypeCore, ICivicStructure { public StadiumOrArena_Core() { this._TypeId = 250; this._Id = "StadiumOrArena"; this._Schema_Org_Url = "http://schema.org/StadiumOrArena"; string label = ""; GetLabel(out label, "StadiumOrArena", typeof(StadiumOrArena_Core)); this._Label = label; this._Ancestors = new int[]{266,206,62}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{62,246}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using numl.Utils; using numl.Model; using System.Data; using System.Linq; using System.Dynamic; using numl.Tests.Data; using NUnit.Framework; using System.Collections.Generic; namespace numl.Tests.DataTests { [TestFixture, Category("Data")] public class SimpleConversionTests { public static IEnumerable<string> ShortStrings { get { yield return "OnE!"; yield return "TWo2"; yield return "t#hrE^e"; yield return "T%hrE@e"; } } public static IEnumerable<string> WordStrings { get { yield return "TH@e QUi#CK bRow!N fox 12"; yield return "s@upeR B#roWN BEaR"; yield return "1829! UGlY FoX"; yield return "ThE QuICk beAr"; } } [Test][Explicit][Category("Explicit")] public void Test_Univariate_Conversions() { // boolean Assert.AreEqual(1, Ject.Convert(true)); Assert.AreEqual(-1, Ject.Convert(false)); // numeric types Assert.AreEqual(1d, Ject.Convert((Byte)1)); // byte Assert.AreEqual(1d, Ject.Convert((SByte)1)); // sbyte Assert.AreEqual(0.4d, Ject.Convert((Decimal)0.4m)); // decimal Assert.AreEqual(0.1d, Ject.Convert((Double)0.1d)); // double Assert.AreEqual(300d, Ject.Convert((Single)300f)); // single Assert.AreEqual(1d, Ject.Convert((Int16)1)); // int16 Assert.AreEqual(2d, Ject.Convert((UInt16)2)); // uint16 Assert.AreEqual(2323432, Ject.Convert((Int32)2323432)); // int32 Assert.AreEqual(2323432d, Ject.Convert((UInt32)2323432)); // uint32 Assert.AreEqual(1232323434345d, Ject.Convert((Int64)1232323434345)); // int64 Assert.AreEqual(1232323434345d, Ject.Convert((UInt64)1232323434345)); // uint64 Assert.AreEqual(1232323434345d, Ject.Convert((long)1232323434345)); // long // enum Assert.AreEqual(0d, Ject.Convert(FakeEnum.Item0)); Assert.AreEqual(1d, Ject.Convert(FakeEnum.Item1)); Assert.AreEqual(2d, Ject.Convert(FakeEnum.Item2)); Assert.AreEqual(3d, Ject.Convert(FakeEnum.Item3)); Assert.AreEqual(4d, Ject.Convert(FakeEnum.Item4)); Assert.AreEqual(5d, Ject.Convert(FakeEnum.Item5)); Assert.AreEqual(6d, Ject.Convert(FakeEnum.Item6)); Assert.AreEqual(7d, Ject.Convert(FakeEnum.Item7)); Assert.AreEqual(8d, Ject.Convert(FakeEnum.Item8)); Assert.AreEqual(9d, Ject.Convert(FakeEnum.Item9)); // char Assert.AreEqual(65d, Ject.Convert('A')); // timespan Assert.AreEqual(300d, Ject.Convert(TimeSpan.FromSeconds(300))); } [Test][Explicit][Category("Explicit")] public void Test_Univariate_Back_Conversions() { // boolean Assert.AreEqual(true, Ject.Convert(1, typeof(bool))); Assert.AreEqual(false, Ject.Convert(-1, typeof(bool))); // numeric types Assert.AreEqual((Byte)1, Ject.Convert(1d, typeof(Byte))); // byte Assert.AreEqual((SByte)1, Ject.Convert(1d, typeof(SByte))); // sbyte Assert.AreEqual((Decimal)0.4m, Ject.Convert(0.4d, typeof(Decimal))); // decimal Assert.AreEqual((Double)0.1d, Ject.Convert(0.1d, typeof(Double))); // double Assert.AreEqual((Single)300f, Ject.Convert(300d, typeof(Single))); // single Assert.AreEqual((Int16)1, Ject.Convert(1d, typeof(Int16))); // int16 Assert.AreEqual((UInt16)2, Ject.Convert(2d, typeof(UInt16))); // uint16 Assert.AreEqual((Int32)2323432, Ject.Convert(2323432, typeof(Int32))); // int32 Assert.AreEqual((UInt32)2323432, Ject.Convert(2323432d, typeof(UInt32))); // uint32 Assert.AreEqual((Int64)1232323434345, Ject.Convert(1232323434345d, typeof(Int64))); // int64 Assert.AreEqual((UInt64)1232323434345, Ject.Convert(1232323434345d, typeof(UInt64))); // uint64 Assert.AreEqual((long)1232323434345, Ject.Convert(1232323434345d, typeof(long))); // long // enum Assert.AreEqual(FakeEnum.Item0, Ject.Convert(0d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item1, Ject.Convert(1d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item2, Ject.Convert(2d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item3, Ject.Convert(3d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item4, Ject.Convert(4d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item5, Ject.Convert(5d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item6, Ject.Convert(6d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item7, Ject.Convert(7d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item8, Ject.Convert(8d, typeof(FakeEnum))); Assert.AreEqual(FakeEnum.Item9, Ject.Convert(9d, typeof(FakeEnum))); // char Assert.AreEqual('A', Ject.Convert(65d, typeof(char))); // timespan Assert.AreEqual(TimeSpan.FromSeconds(300), Ject.Convert(300d, typeof(TimeSpan))); } [Test][Explicit][Category("Explicit")] public void Test_Char_Dictionary_Gen() { var d = StringHelpers.BuildCharDictionary(ShortStrings); // should have the following: // O(2), N(1), E(5), #SYM#(5), T(3), W(1), #NUM#(1), H(2), R(2) var dict = new Dictionary<string, double> { { "O", 2 }, { "N", 1 }, { "E", 5 }, { "#SYM#", 5 }, { "T", 3 }, { "W", 1 }, { "#NUM#", 1 }, { "H", 2 }, { "R", 2 }, }; Assert.AreEqual(dict, d); } [Test][Explicit][Category("Explicit")] public void Test_Enum_Dictionary_Gen() { var d = StringHelpers.BuildEnumDictionary(ShortStrings); // should have the following: // ONE(1), TWO2(1), THREE(2) var dict = new Dictionary<string, double> { { "ONE", 1 }, { "TWO2", 1 }, { "THREE", 2 }, }; Assert.AreEqual(dict, d); } [Test][Explicit][Category("Explicit")] public void Test_Word_Dictionary_Gen() { var d = StringHelpers.BuildWordDictionary(WordStrings); // should have the following: var dict = new Dictionary<string, double> { { "THE", 2 }, { "QUICK", 2 }, { "BROWN", 2 }, { "FOX", 2 }, { "#NUM#", 2 }, { "SUPER", 1 }, { "BEAR", 2 }, { "UGLY", 1 }, }; Assert.AreEqual(dict, d); } [Test][Explicit][Category("Explicit")] public void Test_Fast_Reflection_Get_Standard() { var o = new Student { Age = 23, Friends = 12, GPA = 3.2, Grade = Grade.A, Name = "Jordan Spears", Tall = true, Nice = false }; var age = Ject.Get(o, "Age"); Assert.AreEqual(23, (int)age); var friends = Ject.Get(o, "Friends"); Assert.AreEqual(12, (int)friends); var gpa = Ject.Get(o, "GPA"); Assert.AreEqual(3.2, (double)gpa); var grade = Ject.Get(o, "Grade"); Assert.AreEqual(Grade.A, (Grade)grade); var name = Ject.Get(o, "Name"); Assert.AreEqual("Jordan Spears", (string)name); var tall = Ject.Get(o, "Tall"); Assert.AreEqual(true, (bool)tall); var nice = Ject.Get(o, "Nice"); Assert.AreEqual(false, (bool)nice); } [Test][Explicit][Category("Explicit")] public void Test_Fast_Reflection_Set_Standard() { var o = new Student { Age = 23, Friends = 12, GPA = 3.2, Grade = Grade.A, Name = "Jordan Spears", Tall = true, Nice = false }; Ject.Set(o, "Age", 25); Assert.AreEqual(25, o.Age); Ject.Set(o, "Friends", 1); Assert.AreEqual(1, o.Friends); Ject.Set(o, "GPA", 1.2); Assert.AreEqual(1.2, o.GPA); Ject.Set(o, "Grade", Grade.C); Assert.AreEqual(Grade.C, o.Grade); Ject.Set(o, "Name", "Seth Juarez"); Assert.AreEqual("Seth Juarez", o.Name); Ject.Set(o, "Tall", false); Assert.AreEqual(false, o.Tall); Ject.Set(o, "Nice", true); Assert.AreEqual(true, o.Nice); } [Test][Explicit][Category("Explicit")] public void Test_Fast_Reflection_Get_Dictionary() { var o = new Dictionary<string, object>(); o["Age"] = 23; o["Friends"] = 12; o["GPA"] = 3.2; o["Grade"] = Grade.A; o["Name"] = "Jordan Spears"; o["Tall"] = true; o["Nice"] = false; var age = Ject.Get(o, "Age"); Assert.AreEqual(23, (int)age); var friends = Ject.Get(o, "Friends"); Assert.AreEqual(12, (int)friends); var gpa = Ject.Get(o, "GPA"); Assert.AreEqual(3.2, (double)gpa); var grade = Ject.Get(o, "Grade"); Assert.AreEqual(Grade.A, (Grade)grade); var name = Ject.Get(o, "Name"); Assert.AreEqual("Jordan Spears", (string)name); var tall = Ject.Get(o, "Tall"); Assert.AreEqual(true, (bool)tall); var nice = Ject.Get(o, "Nice"); Assert.AreEqual(false, (bool)nice); } [Test][Explicit][Category("Explicit")] public void Test_Fast_Reflection_Set_Dictionary() { var o = new Dictionary<string, object>(); o["Age"] = 23; o["Friends"] = 12; o["GPA"] = 3.2; o["Grade"] = Grade.A; o["Name"] = "Jordan Spears"; o["Tall"] = true; o["Nice"] = false; Ject.Set(o, "Age", 25); Assert.AreEqual(25, o["Age"]); Ject.Set(o, "Friends", 1); Assert.AreEqual(1, o["Friends"]); Ject.Set(o, "GPA", 1.2); Assert.AreEqual(1.2, o["GPA"]); Ject.Set(o, "Grade", Grade.C); Assert.AreEqual(Grade.C, o["Grade"]); Ject.Set(o, "Name", "Seth Juarez"); Assert.AreEqual("Seth Juarez", o["Name"]); Ject.Set(o, "Tall", false); Assert.AreEqual(false, o["Tall"]); Ject.Set(o, "Nice", true); Assert.AreEqual(true, o["Nice"]); } [Test][Explicit][Category("Explicit")] public void Test_Vector_Conversion_Simple_Numbers() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age", Type = typeof(int) }, new Property { Name = "Height", Type=typeof(double) }, new Property { Name = "Weight", Type = typeof(decimal) }, new Property { Name = "Good", Type=typeof(bool) }, }; var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false }; var truths = new double[] { 23, 6.21, 220, -1 }; var actual = d.Convert(o); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Vector_DataRow_Conversion_Simple_Numbers() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age", }, new Property { Name = "Height", }, new Property { Name = "Weight", }, new Property { Name = "Good", }, }; DataTable table = new DataTable("student"); var age = table.Columns.Add("Age", typeof(int)); var height = table.Columns.Add("Height", typeof(double)); var weight = table.Columns.Add("Weight", typeof(decimal)); var good = table.Columns.Add("Good", typeof(bool)); DataRow row = table.NewRow(); row[age] = 23; row[height] = 6.21; row[weight] = 220m; row[good] = false; var truths = new double[] { 23, 6.21, 220, -1 }; var actual = d.Convert(row); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Vector_Dictionary_Conversion_Simple_Numbers() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age", }, new Property { Name = "Height", }, new Property { Name = "Weight", }, new Property { Name = "Good", }, }; Dictionary<string, object> item = new Dictionary<string, object>(); item["Age"] = 23; item["Height"] = 6.21; item["Weight"] = 220m; item["Good"] = false; var truths = new double[] { 23, 6.21, 220, -1 }; var actual = d.Convert(item); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Vector_Expando_Conversion_Simple_Numbers() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age", }, new Property { Name = "Height", }, new Property { Name = "Weight", }, new Property { Name = "Good", }, }; dynamic item = new ExpandoObject(); item.Age = 23; item.Height = 6.21; item.Weight = 220m; item.Good = false; var truths = new double[] { 23, 6.21, 220, -1 }; var actual = d.Convert(item); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Vector_Conversion_Simple_Numbers_And_Strings() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildWordDictionary(WordStrings) .Select(k => k.Key) .ToArray(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Words", Dictionary = dictionary }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // [THE, QUICK, BROWN, FOX, #NUM#, SUPER, BEAR, UGLY] // [ 1, 0, 1, 0, 1, 0, 0, 0] var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "the brown 432" }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN TEXT */ 1, 0, 1, 0, 1, 0, 0, 0, /* END TEXT */ 220, -1 }; var actual = d.Convert(o); Assert.AreEqual(truths, actual); // offset test Assert.AreEqual(10, d.Features[3].Start); Assert.AreEqual(11, d.Features[4].Start); } [Test][Explicit][Category("Explicit")] public void Test_Vector_Conversion_Simple_Numbers_And_Strings_As_Enum() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildWordDictionary(WordStrings) .Select(k => k.Key) .ToArray(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Words", Dictionary = dictionary, AsEnum = true }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // [THE, QUICK, BROWN, FOX, #NUM#, SUPER, BEAR, UGLY] // [ 0, 1, 2, 3, 4, 5, 6, 7] var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "QUICK" }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN TEXT */ 1, /* END TEXT */ 220, -1 }; var actual = d.Convert(o); Assert.AreEqual(truths, actual); o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "sUpEr" }; // array generated by descriptor ordering truths = new double[] { 23, 6.21, /* BEGIN TEXT */ 5, /* END TEXT */ 220, -1 }; actual = d.Convert(o); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Vector_Conversion_Simple_Numbers_And_Chars() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildCharDictionary(ShortStrings) .Select(k => k.Key) .ToArray(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Chars", Dictionary = dictionary, SplitType = StringSplitType.Character }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // ["O", "N", "E", "#SYM#", "T", "W", "#NUM#", "H", "R"] // [ 2, 1, 0, 1, 0, 0, 1, 0, 3] var o = new { Age = 23, Height = 6.21d, Chars = "oon!3RrR", Weight = 220m, Good = false, }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN CHARS */ 2, 1, 0, 1, 0, 0, 1, 0, 3, /* END CHARS */ 220, -1 }; var actual = d.Convert(o); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Vector_Conversion_Simple_Numbers_And_Chars_As_Enum() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildCharDictionary(ShortStrings) .Select(k => k.Key) .ToArray(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Chars", Dictionary = dictionary, SplitType = StringSplitType.Character, AsEnum = true }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // ["O", "N", "E", "#SYM#", "T", "W", "#NUM#", "H", "R"] // [ 2, 1, 0, 1, 0, 0, 1, 0, 3] var o = new { Age = 23, Height = 6.21d, Chars = "N", Weight = 220m, Good = false, }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN CHARS */ 1, /* END CHARS */ 220, -1 }; var actual = d.Convert(o); Assert.AreEqual(truths, actual); o = new { Age = 23, Height = 6.21d, Chars = "!", Weight = 220m, Good = false, }; // array generated by descriptor ordering truths = new double[] { 23, 6.21, /* BEGIN CHARS */ 3, /* END CHARS */ 220, -1 }; actual = d.Convert(o); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Matrix_Conversion_Simple() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; var o = new[] { new { Age = 23, Height = 6.21d, Weight = 220m, Good = false }, new { Age = 12, Height = 4.2d, Weight = 120m, Good = true }, new { Age = 9, Height = 6.0d, Weight = 340m, Good = true }, new { Age = 87, Height = 3.7d, Weight = 79m, Good = false } }; // array generated by descriptor ordering // (returns IEnumerable, but should pass) var truths = new double[][] { new double[] { 23, 6.21, 220, -1 }, new double[] { 12, 4.2, 120, 1 }, new double[] { 9, 6.0, 340, 1 }, new double[] { 87, 3.7, 79, -1 } }; var actual = d.Convert(o); Assert.AreEqual(truths, actual); } [Test][Explicit][Category("Explicit")] public void Test_Matrix_Conversion_With_Label() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; d.Label = new Property { Name = "Nice" }; var o = new[] { new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Nice = true }, new { Age = 12, Height = 4.2d, Weight = 120m, Good = true, Nice = false }, new { Age = 9, Height = 6.0d, Weight = 340m, Good = true, Nice = true }, new { Age = 87, Height = 3.7d, Weight = 79m, Good = false, Nice = false } }; // array generated by descriptor ordering // (returns IEnumerable, but should pass) var truths = new double[][] { new double[] { 23, 6.21, 220, -1, 1 }, new double[] { 12, 4.2, 120, 1, -1 }, new double[] { 9, 6.0, 340, 1, 1 }, new double[] { 87, 3.7, 79, -1, -1 } }; var actual = d.Convert(o); Assert.AreEqual(truths, actual); } } }
// // HomeView.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Linq; using Mono.Unix; using Gtk; using Hyena.Collections; using Hyena.Data.Sqlite; using Hyena.Data; using Hyena.Data.Gui; using Hyena.Widgets; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.Database; using Banshee.Gui; using Banshee.Library; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Playlist; using Banshee.Preferences; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Widgets; using IA=InternetArchive; namespace Banshee.InternetArchive { public class HomeView : Gtk.HBox, Banshee.Sources.Gui.ISourceContents { private HomeSource source; public HomeView (HomeSource source) { this.source = source; //var sw = new Gtk.ScrolledWindow (); //sw.BorderWidth = 4; //sw.AddWithViewport (Build ()); var frame = new Hyena.Widgets.RoundedFrame (); frame.Child = Build (); PackStart (frame, true, true, 0); ShowAll (); } private Widget Build () { var hbox = new HBox () { Spacing = 8, BorderWidth = 4 }; hbox.PackStart (BuildTiles (), false, false, 0); hbox.PackStart (BuildCenter (), true, true, 0); return hbox; } private Widget BuildCenter () { var vbox = new VBox () { Spacing = 2 }; // Search entry/button var search_box = new HBox () { Spacing = 6, BorderWidth = 4 }; var entry = new Banshee.Widgets.SearchEntry () { Visible = true, EmptyMessage = String.Format (Catalog.GetString ("Search...")) }; // Make the search entry text nice and big var font = entry.InnerEntry.Style.FontDescription.Copy (); font.Size = (int) (font.Size * Pango.Scale.XLarge); entry.InnerEntry.ModifyFont (font); var button = new Hyena.Widgets.ImageButton (Catalog.GetString ("_Go"), Stock.Find); entry.Activated += (o, a) => { button.Activate (); }; button.Clicked += (o, a) => source.SetSearch (new SearchDescription (null, entry.Query, IA.Sort.DownloadsDesc, null)); search_box.PackStart (entry, true, true, 0); search_box.PackStart (button, false, false, 0); var example_searches = new SearchDescription [] { new SearchDescription (Catalog.GetString ("Staff Picks"), "pick:1", IA.Sort.WeekDesc, null), new SearchDescription (Catalog.GetString ("Creative Commons"), "license:creativecommons", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("History"), "subject:history", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("Classic Cartoons"), "", IA.Sort.DateCreatedAsc, IA.MediaType.Get ("animationandcartoons")), new SearchDescription (Catalog.GetString ("Speeches"), "subject:speeches OR title:speech", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("For Children"), "subject:children", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("Poetry"), "subject:poetry", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("Creator is United States"), "creator:\"United States\"", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("Old Movies"), "", IA.Sort.DateCreatedAsc, IA.MediaType.Get ("moviesandfilms")), new SearchDescription (Catalog.GetString ("New From LibriVox"), "publisher:LibriVox", IA.Sort.DateAddedDesc, IA.MediaType.Get ("audio")), new SearchDescription (Catalog.GetString ("Old Texts"), "", IA.Sort.DateCreatedAsc, IA.MediaType.Get ("texts")), new SearchDescription (Catalog.GetString ("Charlie Chaplin"), "\"Charlie Chaplin\"", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("NASA"), "NASA", IA.Sort.DownloadsDesc, null), new SearchDescription (Catalog.GetString ("Library of Congress"), "creator:\"Library of Congress\"", IA.Sort.DownloadsDesc, null) }; var examples = new FlowBox () { Spacing = 0 }; examples.Add (PaddingBox (new Label () { Markup = "Examples:" })); foreach (var search in example_searches) { var this_search = search; var link = CreateLink (search.Name, search.Query); link.TooltipText = search.Query; link.Clicked += (o, a) => source.SetSearch (this_search); examples.Add (link); } // Intro text and visit button var intro_label = new Hyena.Widgets.WrapLabel () { Markup = Catalog.GetString ("The Internet Archive, a 501(c)(3) non-profit, is building a digital library of Internet sites and other cultural artifacts in digital form. Like a paper library, we provide free access to researchers, historians, scholars, and the general public.") }; var visit_button = new LinkButton ("http://archive.org/", Catalog.GetString ("Visit the Internet Archive online at archive.org")); visit_button.Clicked += (o, a) => Banshee.Web.Browser.Open ("http://archive.org/"); visit_button.Xalign = 0f; var visit_box = new HBox (); visit_box.PackStart (visit_button, false, false, 0); visit_box.PackStart (new Label () { Visible = true }, true, true, 0); // Packing vbox.PackStart (search_box, false, false, 0); vbox.PackStart (examples, false, false, 0); vbox.PackStart (PaddingBox (new HSeparator ()), false, false, 6); vbox.PackStart (PaddingBox (intro_label), false, false, 0); vbox.PackStart (visit_box, false, false, 0); return vbox; } private Widget PaddingBox (Widget child) { var box = new HBox () { BorderWidth = 4 }; box.PackStart (child, true, true, 0); child.Show (); box.Show (); return box; } public class FlowBox : VBox { private List<HBox> rows = new List<HBox> (); private List<Widget> children = new List<Widget> (); private int hspacing; public int HSpacing { get { return hspacing; } set { hspacing = value; foreach (var box in rows) { box.Spacing = hspacing; } } } public FlowBox () { HSpacing = 2; Spacing = 2; bool updating_layout = false; SizeAllocated += (o, a) => { if (!updating_layout) { updating_layout = true; UpdateLayout (); updating_layout = false; } }; } public new void Add (Widget widget) { children.Add (widget); UpdateLayout (); } private void UpdateLayout () { if (Allocation.Width < 2) return; int width = Allocation.Width; int y = 0; int x = 0; int j = 0; foreach (var widget in children) { x += widget.Allocation.Width + hspacing; if (x > width) { y++; j = 0; x = widget.Allocation.Width; } Reparent (widget, GetRow (y), j); j++; } for (int i = y + 1; i < rows.Count; i++) { var row = GetRow (i); rows.Remove (row); Remove (row); } } private void Reparent (Widget widget, HBox box, int index) { if (widget.Parent == box) { return; } if (widget.Parent == null) { box.PackStart (widget, false, false, 0); } else { widget.Reparent (box); box.SetChildPacking (widget, false, false, 0, PackType.Start); } box.ReorderChild (widget, index); widget.Show (); } private HBox GetRow (int i) { if (i < rows.Count) { return rows[i]; } else { var box = new HBox () { Spacing = HSpacing }; rows.Add (box); PackStart (box, false, false, 0); box.Show (); return box; } } } private Button CreateLink (string title, string url) { var button = new LinkButton (url, "") { Relief = ReliefStyle.None, }; var label = button.Child as Label; if (label != null) { label.Markup = title;//"<small>" + title + "</small>"; } return button; } private class Category : SearchDescription { public long Count { get; private set; } public string IconName { get; private set; } public Category (string media_type, string name, int count, string icon_name) : this (media_type, name, null, count, icon_name) {} public Category (string media_type, string name, string query, int count, string icon_name) : base (name, query, IA.Sort.DownloadsDesc, IA.MediaType.Get (media_type)) { Count = count; IconName = icon_name; } } private Widget BuildTiles () { var vbox = new VBox () { Spacing = 12, BorderWidth = 4 }; var categories = new Category [] { new Category ("audio_bookspoetry", Catalog.GetString ("Audiobooks"), 4300, "audio-x-generic"), new Category ("movies", Catalog.GetString ("Movies"), 200000, "video-x-generic"), new Category (null, Catalog.GetString ("Lectures"), "subject:ocw OR creator:university OR mediatype:education OR publisher:University", 1290, "x-office-presentation"), new Category ("etree", Catalog.GetString ("Concerts"), 69000, "audio-x-generic"), new Category ("texts", Catalog.GetString ("Books"), 1600000, "x-office-document") }; foreach (var cat in categories.OrderBy (c => c.Name)) { var this_cat = cat; var tile = new ImageButton (cat.Name, cat.IconName) { InnerPadding = 4 }; tile.LabelWidget.Xalign = 0; tile.Clicked += (o, a) => source.SetSearch (this_cat); vbox.PackStart (tile, false, false, 0); } return vbox; } #region ISourceContents public bool SetSource (ISource source) { this.source = source as HomeSource; return this.source != null; } public void ResetSource () { source = null; } public ISource Source { get { return source; } } public Widget Widget { get { return this; } } #endregion } }
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Diagnostics; using Microsoft.Research.DryadLinq.Internal; namespace Microsoft.Research.DryadLinq { // The information we know about the dataset at each stage of the // computation. For each operator, we try to compute this from the // DataSetInfo of its input datasets and the semantics of the operator. [Serializable] internal class DataSetInfo { internal static PartitionInfo OnePartition = new RandomPartition(1); internal static OrderByInfo NoOrderBy = new OrderByInfo(); internal static DistinctInfo NoDistinct = new DistinctInfo(); internal PartitionInfo partitionInfo; internal OrderByInfo orderByInfo; internal DistinctInfo distinctInfo; internal DataSetInfo() { this.partitionInfo = OnePartition; this.orderByInfo = NoOrderBy; this.distinctInfo = NoDistinct; } internal DataSetInfo(PartitionInfo pinfo, OrderByInfo oinfo, DistinctInfo dinfo) { this.partitionInfo = pinfo; this.orderByInfo = oinfo; this.distinctInfo = dinfo; } internal DataSetInfo(DataSetInfo info) { this.partitionInfo = info.partitionInfo; this.orderByInfo = info.orderByInfo; this.distinctInfo = info.distinctInfo; } // Return true iff the entire dataset is ordered. internal bool IsOrderedBy(LambdaExpression keySel, object comparer) { return (this.partitionInfo.ParType == PartitionType.Range && this.partitionInfo.IsPartitionedBy(keySel, comparer) && this.orderByInfo.IsOrderedBy(keySel, comparer) && this.orderByInfo.IsSameMonotoncity(this.partitionInfo)); } internal static DataSetInfo Read(Stream fstream) { BinaryFormatter bfm = new BinaryFormatter(); return (DataSetInfo)bfm.Deserialize(fstream); } internal static void Write(DataSetInfo dsInfo, Stream fstream) { BinaryFormatter bfm = new BinaryFormatter(); bfm.Serialize(fstream, dsInfo); } } internal enum PartitionType { Random = 0x0000, Hash = 0x0001, Range = 0x0002, HashOrRange = 0x0003 } internal abstract class PartitionInfo { private PartitionType m_partitionType; protected PartitionInfo(PartitionType parType) { this.m_partitionType = parType; } internal PartitionType ParType { get { return this.m_partitionType; } } internal virtual bool IsDescending { get { throw new InvalidOperationException(); } } internal virtual bool HasKeys { get { throw new InvalidOperationException(); } } internal virtual PartitionInfo Concat(PartitionInfo p) { return new RandomPartition(this.Count + p.Count); } internal abstract int Count { get; set; } internal abstract bool IsPartitionedBy(LambdaExpression keySel); internal abstract bool IsPartitionedBy(LambdaExpression keySel, object comparer); internal abstract bool IsPartitionedBy(LambdaExpression keySel, object comparer, bool isDescending); internal abstract bool IsSamePartition(PartitionInfo p); internal abstract DLinqQueryNode CreatePartitionNode(LambdaExpression keySelector, DLinqQueryNode child); internal abstract PartitionInfo Create(LambdaExpression keySel); internal abstract PartitionInfo Rewrite(LambdaExpression keySel, ParameterExpression param); internal static PartitionInfo CreateHash(LambdaExpression keySel, int count, object comparer, Type keyType) { Type hashType = typeof(HashPartition<>).MakeGenericType(keyType); object[] args = new object[] { keySel, count, comparer }; return (PartitionInfo)Activator.CreateInstance(hashType, BindingFlags.NonPublic | BindingFlags.Instance, null ,args, null); } internal static PartitionInfo CreateRange(LambdaExpression keySel, object keys, object comparer, bool? isDescending, Int32 parCnt, Type keyType) { Type parType = typeof(RangePartition<>).MakeGenericType(keyType); object[] args = new object[] { keySel, keys, comparer, isDescending, parCnt }; try { return (PartitionInfo)Activator.CreateInstance(parType, BindingFlags.NonPublic | BindingFlags.Instance, null, args, null); } catch (TargetInvocationException tie) { // The ctor for RangePartition<> can throw.. we trap and rethrow the useful exception here. if (tie.InnerException != null) throw tie.InnerException; else throw; } } internal virtual Pair<MethodInfo, Expression[]> GetOperator() { throw new InvalidOperationException(); } } internal class RandomPartition : PartitionInfo { private int m_count; internal RandomPartition(int count) : base(PartitionType.Random) { this.m_count = count; } internal override int Count { get { return this.m_count; } set { this.m_count = value; } } internal override bool IsPartitionedBy(LambdaExpression keySel) { return false; } internal override bool IsPartitionedBy(LambdaExpression keySel, object comparer) { return false; } internal override bool IsPartitionedBy(LambdaExpression keySel, object comparer, bool isDescending) { return false; } internal override bool IsSamePartition(PartitionInfo p) { return false; } internal override DLinqQueryNode CreatePartitionNode(LambdaExpression keySel, DLinqQueryNode child) { throw new DryadLinqException(DryadLinqErrorCode.CannotCreatePartitionNodeRandom, SR.CannotCreatePartitionNodeRandom); } internal override PartitionInfo Create(LambdaExpression keySel) { return this; } internal override PartitionInfo Rewrite(LambdaExpression resultSel, ParameterExpression param) { return this; } } internal class RangePartition<TKey> : PartitionInfo { private int m_count; private LambdaExpression m_keySelector; private TKey[] m_partitionKeys; private IComparer<TKey> m_comparer; private bool m_isDescending; internal RangePartition(LambdaExpression keySelector, TKey[] partitionKeys, IComparer<TKey> comparer) : this(keySelector, partitionKeys, comparer, null, 1) { } internal RangePartition(LambdaExpression keySelector, TKey[] partitionKeys, IComparer<TKey> comparer, bool? isDescending, Int32 parCnt) : base(PartitionType.Range) { this.m_count = (partitionKeys == null) ? parCnt : (partitionKeys.Length + 1); this.m_keySelector = keySelector; this.m_partitionKeys = partitionKeys; this.m_comparer = TypeSystem.GetComparer<TKey>(comparer); if (isDescending == null) { if (partitionKeys == null) { throw new DryadLinqException(DryadLinqErrorCode.PartitionKeysNotProvided, SR.PartitionKeysNotProvided); } bool? detectedIsDescending; if (!DryadLinqUtil.ComputeIsDescending(partitionKeys, m_comparer, out detectedIsDescending)) { throw new DryadLinqException(DryadLinqErrorCode.PartitionKeysAreNotConsistentlyOrdered, SR.PartitionKeysAreNotConsistentlyOrdered); } this.m_isDescending = detectedIsDescending ?? false; } else { this.m_isDescending = isDescending.GetValueOrDefault(); if (partitionKeys != null && !DryadLinqUtil.IsOrdered(partitionKeys, this.m_comparer, this.m_isDescending)) { throw new DryadLinqException(DryadLinqErrorCode.IsDescendingIsInconsistent, SR.IsDescendingIsInconsistent); } } } internal RangePartition(LambdaExpression keySelector, IComparer<TKey> comparer, bool isDescending, Int32 parCnt) : base(PartitionType.Range) { this.m_count = parCnt; this.m_keySelector = keySelector; this.m_partitionKeys = null; this.m_comparer = TypeSystem.GetComparer<TKey>(comparer); } internal TKey[] Keys { get { return this.m_partitionKeys; } } internal Expression KeysExpression { get { return Expression.Constant(this.m_partitionKeys); } } internal Expression KeySelector { get { return this.m_keySelector; } } internal IComparer<TKey> Comparer { get { return this.m_comparer; } } internal override bool IsDescending { get { return this.m_isDescending; } } internal override bool HasKeys { get { return this.m_partitionKeys != null; } } internal override int Count { get { return this.m_count; } set { this.m_count = value; } } internal override bool IsPartitionedBy(LambdaExpression keySel) { // Match the key selector functions: if (this.m_keySelector == null) { return (keySel == null); } if (keySel == null) return false; return ExpressionMatcher.Match(this.m_keySelector, keySel); } internal override bool IsPartitionedBy(LambdaExpression keySel, object comp) { // Match the key selector functions: if (!this.IsPartitionedBy(keySel)) { return false; } // Check the comparers: IComparer<TKey> comp1 = TypeSystem.GetComparer<TKey>(comp); if (comp1 == null) return false; return this.m_comparer.Equals(comp1); } internal override bool IsPartitionedBy(LambdaExpression keySel, object comp, bool isDescending) { // Match the key selector functions: if (!this.IsPartitionedBy(keySel)) { return false; } // Check the comparers: IComparer<TKey> comp1 = TypeSystem.GetComparer<TKey>(comp); if (comp1 == null) return false; if (this.m_isDescending != isDescending) { comp1 = new MinusComparer<TKey>(comp1); } return this.m_comparer.Equals(comp1); } internal override bool IsSamePartition(PartitionInfo p) { RangePartition<TKey> p1 = p as RangePartition<TKey>; if (p1 == null) return false; // Check the keys: if (this.Keys == null || p1.Keys == null || this.Keys.Length != p1.Keys.Length) { return false; } IComparer<TKey> comp1 = TypeSystem.GetComparer<TKey>(p1.m_comparer); if (comp1 == null) return false; if (this.IsDescending != p1.IsDescending) { comp1 = new MinusComparer<TKey>(comp1); } for (int i = 0; i < this.Keys.Length; i++) { if (this.m_comparer.Compare(this.Keys[i], p1.Keys[i]) != 0) { return false; } } // Check the comparers: return this.m_comparer.Equals(p1.m_comparer); } internal override DLinqQueryNode CreatePartitionNode(LambdaExpression keySel, DLinqQueryNode child) { Expression keysExpr = Expression.Constant(this.m_partitionKeys); Expression comparerExpr = Expression.Constant(this.m_comparer, typeof(IComparer<TKey>)); Expression isDescendingExpr = Expression.Constant(this.m_isDescending); return new DLinqRangePartitionNode(keySel, null, keysExpr, comparerExpr, isDescendingExpr, null, child.QueryExpression, child); } internal override PartitionInfo Create(LambdaExpression keySel) { Type keyType = keySel.Body.Type; return PartitionInfo.CreateRange(keySel, this.Keys, this.m_comparer, this.m_isDescending, this.Count, keyType); } internal override PartitionInfo Rewrite(LambdaExpression resultSel, ParameterExpression param) { ParameterExpression a = this.m_keySelector.Parameters[0]; Substitution pSubst = Substitution.Empty.Cons(a, param); LambdaExpression newKeySel = DryadLinqExpression.Rewrite(this.m_keySelector, resultSel, pSubst); if (newKeySel == null) { return new RandomPartition(this.m_count); } return this.Create(newKeySel); } internal override Pair<MethodInfo, Expression[]> GetOperator() { Type sourceType = this.m_keySelector.Parameters[0].Type; MethodInfo operation = TypeSystem.FindStaticMethod( typeof(Microsoft.Research.DryadLinq.DryadLinqQueryable), "RangePartition", new Type[] { typeof(IQueryable<>).MakeGenericType(sourceType), m_keySelector.GetType(), m_partitionKeys.GetType(), m_comparer.GetType(), typeof(bool) }, new Type[] { sourceType, typeof(TKey) }); Expression[] arguments = new Expression[] { this.m_keySelector, Expression.Constant(this.m_partitionKeys), Expression.Constant(this.m_comparer, typeof(IComparer<TKey>)), Expression.Constant(this.m_isDescending) }; return new Pair<MethodInfo, Expression[]>(operation, arguments); } } internal class HashPartition<TKey> : PartitionInfo { private int m_count; private LambdaExpression m_keySelector; private IEqualityComparer<TKey> m_comparer; internal HashPartition(LambdaExpression keySelector, int count) : this(keySelector, count, null) { } internal HashPartition(LambdaExpression keySelector, int count, IEqualityComparer<TKey> eqComparer) : base(PartitionType.Hash) { this.m_count = count; this.m_keySelector = keySelector; this.m_comparer = (eqComparer == null) ? EqualityComparer<TKey>.Default : eqComparer; } internal Expression KeySelector { get { return this.m_keySelector; } } internal IEqualityComparer<TKey> EqualityComparer { get { return this.m_comparer; } } internal override int Count { get { return this.m_count; } set { this.m_count = value; } } internal override bool IsPartitionedBy(LambdaExpression keySel) { // Match the key selector functions: if (this.m_keySelector == null) { return (keySel == null); } if (keySel == null) return false; return ExpressionMatcher.Match(this.m_keySelector, keySel); } internal override bool IsPartitionedBy(LambdaExpression keySel, object comp) { // Match the key selector functions: if (!this.IsPartitionedBy(keySel)) { return false; } // Check the comparers: IEqualityComparer<TKey> comp1 = TypeSystem.GetEqualityComparer<TKey>(comp); if (comp1 == null) return false; return this.m_comparer.Equals(comp1); } internal override bool IsPartitionedBy(LambdaExpression keySel, object comparer, bool isDescending) { return this.IsPartitionedBy(keySel, comparer); } internal override bool IsSamePartition(PartitionInfo p) { HashPartition<TKey> p1 = p as HashPartition<TKey>; if (p1 == null || this.Count != p1.Count) { return false; } // Check the comparers: return this.m_comparer.Equals(p1.m_comparer); } internal override DLinqQueryNode CreatePartitionNode(LambdaExpression keySel, DLinqQueryNode child) { Expression comparerExpr = Expression.Constant(this.m_comparer, typeof(IEqualityComparer<TKey>)); return new DLinqHashPartitionNode(keySel, comparerExpr, this.Count, child.QueryExpression, child); } internal override PartitionInfo Create(LambdaExpression keySel) { Type keyType = keySel.Body.Type; return PartitionInfo.CreateHash(keySel, this.Count, this.m_comparer, keyType); } internal override PartitionInfo Rewrite(LambdaExpression resultSel, ParameterExpression param) { ParameterExpression a = this.m_keySelector.Parameters[0]; Substitution pSubst = Substitution.Empty.Cons(a, param); LambdaExpression newKeySel = DryadLinqExpression.Rewrite(this.m_keySelector, resultSel, pSubst); if (newKeySel == null) { return new RandomPartition(this.m_count); } return this.Create(newKeySel); } internal override Pair<MethodInfo, Expression[]> GetOperator() { Type sourceType = this.m_keySelector.Parameters[0].Type; MethodInfo operation = TypeSystem.FindStaticMethod( typeof(Microsoft.Research.DryadLinq.DryadLinqQueryable), "HashPartition", new Type[] { typeof(IQueryable<>).MakeGenericType(sourceType), m_keySelector.GetType(), m_comparer.GetType(), typeof(int) }, new Type[] { sourceType, typeof(TKey) }); Expression[] arguments = new Expression[] { m_keySelector, Expression.Constant(this.m_comparer, typeof(IEqualityComparer<TKey>)), Expression.Constant(this.Count) }; return new Pair<MethodInfo, Expression[]>(operation, arguments); } } internal class OrderByInfo { internal virtual bool IsOrdered { get { return false; } } internal virtual LambdaExpression KeySelector { get { return null; } } internal virtual Expression Comparer { get { return null; } } internal virtual bool IsDescending { get { return false; } } internal virtual bool IsOrderedBy(LambdaExpression keySel) { return false; } internal virtual bool IsOrderedBy(LambdaExpression keySel, object comparer) { return false; } internal virtual bool IsOrderedBy(LambdaExpression keySel, object comparer, bool isDescending) { return false; } internal virtual bool IsSameMonotoncity(PartitionInfo pinfo) { return false; } internal static OrderByInfo Create(Expression keySel, object comparer, bool isDescending, Type keyType) { Type infoType = typeof(OrderByInfo<>).MakeGenericType(keyType); object[] args = new object[] { keySel, comparer, isDescending }; return (OrderByInfo)Activator.CreateInstance(infoType, BindingFlags.NonPublic | BindingFlags.Instance, null, args, null); } internal virtual OrderByInfo Create(LambdaExpression keySel) { return DataSetInfo.NoOrderBy; } internal virtual OrderByInfo Rewrite(LambdaExpression resultSel, ParameterExpression param) { return DataSetInfo.NoOrderBy; } } internal class OrderByInfo<TKey> : OrderByInfo { private LambdaExpression m_keySelector; private IComparer<TKey> m_comparer; private bool m_isDescending; internal OrderByInfo(LambdaExpression keySelector, IComparer<TKey> comparer, bool isDescending) { this.m_keySelector = keySelector; this.m_comparer = TypeSystem.GetComparer<TKey>(comparer); this.m_isDescending = isDescending; } internal override LambdaExpression KeySelector { get { return this.m_keySelector; } } internal override Expression Comparer { get { return Expression.Constant(this.m_comparer, typeof(IComparer<TKey>)); } } internal override bool IsDescending { get { return this.m_isDescending; } } internal override bool IsOrdered { get { return true; } } internal override bool IsOrderedBy(LambdaExpression keySel) { if (this.m_keySelector == null) { return (keySel == null); } if (keySel == null) return false; return ExpressionMatcher.Match(this.m_keySelector, keySel); } internal override bool IsOrderedBy(LambdaExpression keySel, object comp) { // Match the key selector functions: if (!this.IsOrderedBy(keySel)) { return false; } // Check the comparers: IComparer<TKey> comp1 = TypeSystem.GetComparer<TKey>(comp); if (comp1 == null) return false; return this.m_comparer.Equals(comp1); } internal override bool IsOrderedBy(LambdaExpression keySel, object comp, bool isDescending) { // Match the key selector functions: if (!this.IsOrderedBy(keySel)) { return false; } // Check the comparers: IComparer<TKey> comp1 = TypeSystem.GetComparer<TKey>(comp); if (comp1 == null) return false; if (this.IsDescending != isDescending) { comp1 = new MinusComparer<TKey>(comp1); } return this.m_comparer.Equals(comp1); } internal override bool IsSameMonotoncity(PartitionInfo pinfo) { RangePartition<TKey> pinfo1 = pinfo as RangePartition<TKey>; if (pinfo1 == null) return false; IComparer<TKey> comp1 = pinfo1.Comparer; if (this.m_isDescending != pinfo1.IsDescending) { comp1 = new MinusComparer<TKey>(comp1); } return this.m_comparer.Equals(comp1); } internal override OrderByInfo Create(LambdaExpression keySel) { Type keyType = keySel.Body.Type; return OrderByInfo.Create(keySel, this.m_comparer, this.m_isDescending, keyType); } internal override OrderByInfo Rewrite(LambdaExpression resultSel, ParameterExpression param) { ParameterExpression a = this.m_keySelector.Parameters[0]; Substitution pSubst = Substitution.Empty.Cons(a, param); LambdaExpression newKeySel = DryadLinqExpression.Rewrite(this.m_keySelector, resultSel, pSubst); if (newKeySel == null) { return DataSetInfo.NoOrderBy; } return this.Create(newKeySel); } } internal class DistinctInfo { internal virtual bool IsDistinct() { return false; } internal virtual bool IsDistinct(object comp) { return false; } internal virtual bool IsSameDistinct(DistinctInfo dist) { return false; } internal static DistinctInfo Create(object comparer, Type type) { Type infoType = typeof(DistinctInfo<>).MakeGenericType(type); object[] args = new object[] { comparer }; return (DistinctInfo)Activator.CreateInstance(infoType, BindingFlags.NonPublic | BindingFlags.Instance, null ,args, null); } } internal class DistinctInfo<TKey> : DistinctInfo { private IEqualityComparer<TKey> m_comparer; internal Expression Comparer { get { return Expression.Constant(this.m_comparer, typeof(IEqualityComparer<TKey>)); } } internal DistinctInfo(IEqualityComparer<TKey> comparer) { this.m_comparer = (comparer == null) ? EqualityComparer<TKey>.Default : comparer; } internal override bool IsDistinct() { return true; } internal override bool IsDistinct(object comp) { IEqualityComparer<TKey> comp1 = TypeSystem.GetEqualityComparer<TKey>(comp); if (comp1 == null) return false; return this.m_comparer.Equals(comp1); } internal override bool IsSameDistinct(DistinctInfo dist) { DistinctInfo<TKey> info = dist as DistinctInfo<TKey>; if (info == null) return false; else return IsDistinct(info.Comparer); } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadROSoftDelete.DataAccess; using SelfLoadROSoftDelete.DataAccess.ERLevel; namespace SelfLoadROSoftDelete.Business.ERLevel { /// <summary> /// G02_Continent (read only object).<br/> /// This is a generated base class of <see cref="G02_Continent"/> business object. /// This class is a root object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="G03_SubContinentObjects"/> of type <see cref="G03_SubContinentColl"/> (1:M relation to <see cref="G04_SubContinent"/>) /// </remarks> [Serializable] public partial class G02_Continent : ReadOnlyBase<G02_Continent> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID", -1); /// <summary> /// Gets the Continents ID. /// </summary> /// <value>The Continents ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name"); /// <summary> /// Gets the Continents Name. /// </summary> /// <value>The Continents Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } } /// <summary> /// Maintains metadata about child <see cref="G03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<G03_Continent_Child> G03_Continent_SingleObjectProperty = RegisterProperty<G03_Continent_Child>(p => p.G03_Continent_SingleObject, "G03 Continent Single Object"); /// <summary> /// Gets the G03 Continent Single Object ("self load" child property). /// </summary> /// <value>The G03 Continent Single Object.</value> public G03_Continent_Child G03_Continent_SingleObject { get { return GetProperty(G03_Continent_SingleObjectProperty); } private set { LoadProperty(G03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<G03_Continent_ReChild> G03_Continent_ASingleObjectProperty = RegisterProperty<G03_Continent_ReChild>(p => p.G03_Continent_ASingleObject, "G03 Continent ASingle Object"); /// <summary> /// Gets the G03 Continent ASingle Object ("self load" child property). /// </summary> /// <value>The G03 Continent ASingle Object.</value> public G03_Continent_ReChild G03_Continent_ASingleObject { get { return GetProperty(G03_Continent_ASingleObjectProperty); } private set { LoadProperty(G03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<G03_SubContinentColl> G03_SubContinentObjectsProperty = RegisterProperty<G03_SubContinentColl>(p => p.G03_SubContinentObjects, "G03 SubContinent Objects"); /// <summary> /// Gets the G03 Sub Continent Objects ("self load" child property). /// </summary> /// <value>The G03 Sub Continent Objects.</value> public G03_SubContinentColl G03_SubContinentObjects { get { return GetProperty(G03_SubContinentObjectsProperty); } private set { LoadProperty(G03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="G02_Continent"/> object, based on given parameters. /// </summary> /// <param name="continent_ID">The Continent_ID parameter of the G02_Continent to fetch.</param> /// <returns>A reference to the fetched <see cref="G02_Continent"/> object.</returns> public static G02_Continent GetG02_Continent(int continent_ID) { return DataPortal.Fetch<G02_Continent>(continent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G02_Continent() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="G02_Continent"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID">The Continent ID.</param> protected void DataPortal_Fetch(int continent_ID) { var args = new DataPortalHookArgs(continent_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadROSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IG02_ContinentDal>(); var data = dal.Fetch(continent_ID); Fetch(data); } OnFetchPost(args); FetchChildren(); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> private void FetchChildren() { LoadProperty(G03_Continent_SingleObjectProperty, G03_Continent_Child.GetG03_Continent_Child(Continent_ID)); LoadProperty(G03_Continent_ASingleObjectProperty, G03_Continent_ReChild.GetG03_Continent_ReChild(Continent_ID)); LoadProperty(G03_SubContinentObjectsProperty, G03_SubContinentColl.GetG03_SubContinentColl(Continent_ID)); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
// Copyright 2020 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 gax = Google.Api.Gax; using sys = System; namespace Google.Cloud.Workflows.Common.V1 { /// <summary>Resource name for the <c>Workflow</c> resource.</summary> public sealed partial class WorkflowName : gax::IResourceName, sys::IEquatable<WorkflowName> { /// <summary>The possible contents of <see cref="WorkflowName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/workflows/{workflow}</c>. /// </summary> ProjectLocationWorkflow = 1, } private static gax::PathTemplate s_projectLocationWorkflow = new gax::PathTemplate("projects/{project}/locations/{location}/workflows/{workflow}"); /// <summary>Creates a <see cref="WorkflowName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="WorkflowName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static WorkflowName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new WorkflowName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="WorkflowName"/> with the pattern /// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="WorkflowName"/> constructed from the provided ids.</returns> public static WorkflowName FromProjectLocationWorkflow(string projectId, string locationId, string workflowId) => new WorkflowName(ResourceNameType.ProjectLocationWorkflow, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workflowId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="WorkflowName"/> with pattern /// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="WorkflowName"/> with pattern /// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>. /// </returns> public static string Format(string projectId, string locationId, string workflowId) => FormatProjectLocationWorkflow(projectId, locationId, workflowId); /// <summary> /// Formats the IDs into the string representation of this <see cref="WorkflowName"/> with pattern /// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="WorkflowName"/> with pattern /// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>. /// </returns> public static string FormatProjectLocationWorkflow(string projectId, string locationId, string workflowId) => s_projectLocationWorkflow.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId))); /// <summary>Parses the given resource name string into a new <see cref="WorkflowName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item> /// </list> /// </remarks> /// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="WorkflowName"/> if successful.</returns> public static WorkflowName Parse(string workflowName) => Parse(workflowName, false); /// <summary> /// Parses the given resource name string into a new <see cref="WorkflowName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="WorkflowName"/> if successful.</returns> public static WorkflowName Parse(string workflowName, bool allowUnparsed) => TryParse(workflowName, allowUnparsed, out WorkflowName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="WorkflowName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item> /// </list> /// </remarks> /// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="WorkflowName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string workflowName, out WorkflowName result) => TryParse(workflowName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="WorkflowName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="WorkflowName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string workflowName, bool allowUnparsed, out WorkflowName result) { gax::GaxPreconditions.CheckNotNull(workflowName, nameof(workflowName)); gax::TemplatedResourceName resourceName; if (s_projectLocationWorkflow.TryParseName(workflowName, out resourceName)) { result = FromProjectLocationWorkflow(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(workflowName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private WorkflowName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string workflowId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; WorkflowId = workflowId; } /// <summary> /// Constructs a new instance of a <see cref="WorkflowName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/workflows/{workflow}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param> public WorkflowName(string projectId, string locationId, string workflowId) : this(ResourceNameType.ProjectLocationWorkflow, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workflowId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Workflow</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string WorkflowId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationWorkflow: return s_projectLocationWorkflow.Expand(ProjectId, LocationId, WorkflowId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as WorkflowName); /// <inheritdoc/> public bool Equals(WorkflowName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(WorkflowName a, WorkflowName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(WorkflowName a, WorkflowName b) => !(a == b); } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Glx { /// <summary> /// [GLX] Value of GLX_GPU_VENDOR_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_VENDOR_AMD = 0x1F00; /// <summary> /// [GLX] Value of GLX_GPU_RENDERER_STRING_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_RENDERER_STRING_AMD = 0x1F01; /// <summary> /// [GLX] Value of GLX_GPU_OPENGL_VERSION_STRING_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_OPENGL_VERSION_STRING_AMD = 0x1F02; /// <summary> /// [GLX] Value of GLX_GPU_FASTEST_TARGET_GPUS_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_FASTEST_TARGET_GPUS_AMD = 0x21A2; /// <summary> /// [GLX] Value of GLX_GPU_RAM_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_RAM_AMD = 0x21A3; /// <summary> /// [GLX] Value of GLX_GPU_CLOCK_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_CLOCK_AMD = 0x21A4; /// <summary> /// [GLX] Value of GLX_GPU_NUM_PIPES_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_NUM_PIPES_AMD = 0x21A5; /// <summary> /// [GLX] Value of GLX_GPU_NUM_SIMD_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_NUM_SIMD_AMD = 0x21A6; /// <summary> /// [GLX] Value of GLX_GPU_NUM_RB_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_NUM_RB_AMD = 0x21A7; /// <summary> /// [GLX] Value of GLX_GPU_NUM_SPI_AMD symbol. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public const int GPU_NUM_SPI_AMD = 0x21A8; /// <summary> /// [GLX] glXGetGPUIDsAMD: Binding for glXGetGPUIDsAMD. /// </summary> /// <param name="maxCount"> /// A <see cref="T:uint"/>. /// </param> /// <param name="ids"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static uint GetAMD(uint maxCount, [Out] uint[] ids) { uint retValue; unsafe { fixed (uint* p_ids = ids) { Debug.Assert(Delegates.pglXGetGPUIDsAMD != null, "pglXGetGPUIDsAMD not implemented"); retValue = Delegates.pglXGetGPUIDsAMD(maxCount, p_ids); LogCommand("glXGetGPUIDsAMD", retValue, maxCount, ids ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXGetGPUInfoAMD: Binding for glXGetGPUInfoAMD. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="property"> /// A <see cref="T:int"/>. /// </param> /// <param name="dataType"> /// A <see cref="T:int"/>. /// </param> /// <param name="size"> /// A <see cref="T:uint"/>. /// </param> /// <param name="data"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static int GetGPUInfoAMD(uint id, int property, int dataType, uint size, IntPtr data) { int retValue; Debug.Assert(Delegates.pglXGetGPUInfoAMD != null, "pglXGetGPUInfoAMD not implemented"); retValue = Delegates.pglXGetGPUInfoAMD(id, property, dataType, size, data); LogCommand("glXGetGPUInfoAMD", retValue, id, property, dataType, size, data ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXGetContextGPUIDAMD: Binding for glXGetContextGPUIDAMD. /// </summary> /// <param name="ctx"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static uint GetContextAMD(IntPtr ctx) { uint retValue; Debug.Assert(Delegates.pglXGetContextGPUIDAMD != null, "pglXGetContextGPUIDAMD not implemented"); retValue = Delegates.pglXGetContextGPUIDAMD(ctx); LogCommand("glXGetContextGPUIDAMD", retValue, ctx ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXCreateAssociatedContextAMD: Binding for glXCreateAssociatedContextAMD. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="share_list"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static IntPtr CreateAssociatedContextAMD(uint id, IntPtr share_list) { IntPtr retValue; Debug.Assert(Delegates.pglXCreateAssociatedContextAMD != null, "pglXCreateAssociatedContextAMD not implemented"); retValue = Delegates.pglXCreateAssociatedContextAMD(id, share_list); LogCommand("glXCreateAssociatedContextAMD", retValue, id, share_list ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXCreateAssociatedContextAttribsAMD: Binding for glXCreateAssociatedContextAttribsAMD. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="share_context"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="attribList"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static IntPtr CreateAssociatedContextAttribsAMD(uint id, IntPtr share_context, int[] attribList) { IntPtr retValue; unsafe { fixed (int* p_attribList = attribList) { Debug.Assert(Delegates.pglXCreateAssociatedContextAttribsAMD != null, "pglXCreateAssociatedContextAttribsAMD not implemented"); retValue = Delegates.pglXCreateAssociatedContextAttribsAMD(id, share_context, p_attribList); LogCommand("glXCreateAssociatedContextAttribsAMD", retValue, id, share_context, attribList ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXDeleteAssociatedContextAMD: Binding for glXDeleteAssociatedContextAMD. /// </summary> /// <param name="ctx"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static bool DeleteAssociatedContextAMD(IntPtr ctx) { bool retValue; Debug.Assert(Delegates.pglXDeleteAssociatedContextAMD != null, "pglXDeleteAssociatedContextAMD not implemented"); retValue = Delegates.pglXDeleteAssociatedContextAMD(ctx); LogCommand("glXDeleteAssociatedContextAMD", retValue, ctx ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXMakeAssociatedContextCurrentAMD: Binding for glXMakeAssociatedContextCurrentAMD. /// </summary> /// <param name="ctx"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static bool MakeAssociatedContextCurrentAMD(IntPtr ctx) { bool retValue; Debug.Assert(Delegates.pglXMakeAssociatedContextCurrentAMD != null, "pglXMakeAssociatedContextCurrentAMD not implemented"); retValue = Delegates.pglXMakeAssociatedContextCurrentAMD(ctx); LogCommand("glXMakeAssociatedContextCurrentAMD", retValue, ctx ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXGetCurrentAssociatedContextAMD: Binding for glXGetCurrentAssociatedContextAMD. /// </summary> [RequiredByFeature("GLX_AMD_gpu_association")] public static IntPtr GetCurrentAssociatedContextAMD() { IntPtr retValue; Debug.Assert(Delegates.pglXGetCurrentAssociatedContextAMD != null, "pglXGetCurrentAssociatedContextAMD not implemented"); retValue = Delegates.pglXGetCurrentAssociatedContextAMD(); LogCommand("glXGetCurrentAssociatedContextAMD", retValue ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXBlitContextFramebufferAMD: Binding for glXBlitContextFramebufferAMD. /// </summary> /// <param name="dstCtx"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="srcX0"> /// A <see cref="T:int"/>. /// </param> /// <param name="srcY0"> /// A <see cref="T:int"/>. /// </param> /// <param name="srcX1"> /// A <see cref="T:int"/>. /// </param> /// <param name="srcY1"> /// A <see cref="T:int"/>. /// </param> /// <param name="dstX0"> /// A <see cref="T:int"/>. /// </param> /// <param name="dstY0"> /// A <see cref="T:int"/>. /// </param> /// <param name="dstX1"> /// A <see cref="T:int"/>. /// </param> /// <param name="dstY1"> /// A <see cref="T:int"/>. /// </param> /// <param name="mask"> /// A <see cref="T:uint"/>. /// </param> /// <param name="filter"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GLX_AMD_gpu_association")] public static void BlitContextFramebufferAMD(IntPtr dstCtx, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, uint mask, int filter) { Debug.Assert(Delegates.pglXBlitContextFramebufferAMD != null, "pglXBlitContextFramebufferAMD not implemented"); Delegates.pglXBlitContextFramebufferAMD(dstCtx, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); LogCommand("glXBlitContextFramebufferAMD", null, dstCtx, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter ); DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate uint glXGetGPUIDsAMD(uint maxCount, uint* ids); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXGetGPUIDsAMD pglXGetGPUIDsAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate int glXGetGPUInfoAMD(uint id, int property, int dataType, uint size, IntPtr data); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXGetGPUInfoAMD pglXGetGPUInfoAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate uint glXGetContextGPUIDAMD(IntPtr ctx); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXGetContextGPUIDAMD pglXGetContextGPUIDAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr glXCreateAssociatedContextAMD(uint id, IntPtr share_list); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXCreateAssociatedContextAMD pglXCreateAssociatedContextAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr glXCreateAssociatedContextAttribsAMD(uint id, IntPtr share_context, int* attribList); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXCreateAssociatedContextAttribsAMD pglXCreateAssociatedContextAttribsAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate bool glXDeleteAssociatedContextAMD(IntPtr ctx); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXDeleteAssociatedContextAMD pglXDeleteAssociatedContextAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate bool glXMakeAssociatedContextCurrentAMD(IntPtr ctx); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXMakeAssociatedContextCurrentAMD pglXMakeAssociatedContextCurrentAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr glXGetCurrentAssociatedContextAMD(); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXGetCurrentAssociatedContextAMD pglXGetCurrentAssociatedContextAMD; [RequiredByFeature("GLX_AMD_gpu_association")] [SuppressUnmanagedCodeSecurity] internal delegate void glXBlitContextFramebufferAMD(IntPtr dstCtx, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, uint mask, int filter); [RequiredByFeature("GLX_AMD_gpu_association")] internal static glXBlitContextFramebufferAMD pglXBlitContextFramebufferAMD; } } }
// // PlayQueueSource.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Alexander Kojevnikov <alexander@kojevnikov.com> // // Copyright (C) 2008 Novell, Inc. // Copyright (C) 2009 Alexander Kojevnikov // // 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.Linq; using Mono.Unix; using Hyena; using Hyena.Collections; using Hyena.Data.Sqlite; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.Database; using Banshee.Gui; using Banshee.Library; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Playlist; using Banshee.Preferences; using Banshee.ServiceStack; using Banshee.Sources; namespace Banshee.PlayQueue { public class PlayQueueSource : PlaylistSource, IBasicPlaybackController, IPlayQueue, IDBusExportable, IDisposable { private static string special_playlist_name = Catalog.GetString ("Play Queue"); private ITrackModelSource prior_playback_source; private DatabaseTrackInfo current_track; private Shuffler shuffler; private long offset = -1; private TrackInfo prior_playback_track; private PlayQueueActions actions; private bool was_playing = false; protected DateTime source_set_at = DateTime.MinValue; private HeaderWidget header_widget; private SourcePage pref_page; private Section pref_section; private string populate_shuffle_mode = PopulateModeSchema.Get (); private string populate_from_name = PopulateFromSchema.Get (); private DatabaseSource populate_from = null; private int played_songs_number = PlayedSongsNumberSchema.Get (); private int upcoming_songs_number = UpcomingSongsNumberSchema.Get (); public PlayQueueSource () : base (Catalog.GetString ("Play Queue"), null) { BindToDatabase (); TypeUniqueId = DbId.ToString (); Initialize (); AfterInitialized (); Order = 20; Properties.SetString ("Icon.Name", "source-playlist"); Properties.SetString ("RemoveSelectedTracksActionLabel", Catalog.GetString ("Remove From Play Queue")); Properties.SetString ("RemovePlayingTrackActionLabel", Catalog.GetString ("Remove From Library")); DatabaseTrackModel.ForcedSortQuery = "CorePlaylistEntries.ViewOrder ASC, CorePlaylistEntries.EntryID ASC"; DatabaseTrackModel.CanReorder = true; ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent); ServiceManager.PlaybackController.TrackStarted += OnTrackStarted; actions = new PlayQueueActions (this); Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml"); Properties.SetString ("GtkActionPath", "/PlayQueueContextMenu"); // TODO listen to all primary sources, and handle transient primary sources ServiceManager.SourceManager.MusicLibrary.TracksChanged += HandleTracksChanged; ServiceManager.SourceManager.MusicLibrary.TracksDeleted += HandleTracksDeleted; populate_from = ServiceManager.SourceManager.Sources.FirstOrDefault ( source => source.Name == populate_from_name) as DatabaseSource; if (populate_from != null) { populate_from.Reload (); } TrackModel.Reloaded += HandleReloaded; int saved_offset = DatabaseConfigurationClient.Client.Get (CurrentOffsetSchema, CurrentOffsetSchema.Get ()); Offset = Math.Min ( saved_offset, ServiceManager.DbConnection.Query<long> (@" SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId)); ServiceManager.SourceManager.AddSource (this); } protected override void Initialize () { base.Initialize (); shuffler = new Shuffler (UniqueId); InstallPreferences (); header_widget = CreateHeaderWidget (); header_widget.ShowAll (); Properties.Set<Gtk.Widget> ("Nereid.SourceContents.HeaderWidget", header_widget); } public HeaderWidget CreateHeaderWidget () { var header_widget = new HeaderWidget (shuffler, populate_shuffle_mode, populate_from_name); header_widget.ModeChanged += delegate (object sender, EventArgs<RandomBy> e) { populate_shuffle_mode = e.Value.Id; PopulateModeSchema.Set (populate_shuffle_mode); UpdatePlayQueue (); OnUpdated (); }; populate_shuffle_mode = header_widget.ShuffleModeId; header_widget.SourceChanged += delegate (object sender, EventArgs<DatabaseSource> e) { populate_from = e.Value; if (populate_from == null) { populate_from_name = String.Empty; PopulateFromSchema.Set (String.Empty); return; } populate_from_name = e.Value.Name; PopulateFromSchema.Set (e.Value.Name); source_set_at = DateTime.Now; populate_from.Reload (); Refresh (); }; return header_widget; } // Randomizes the ViewOrder of all the enabled, unplayed/playing songs public void Shuffle () { if (!Populate) { if (current_track == null) return; int shuffle_count = EnabledCount; int first_view_order = (int)CurrentTrackViewOrder; // If the current track is playing, don't shuffle it if (ServiceManager.PlayerEngine.IsPlaying (current_track)) { first_view_order++; shuffle_count--; } // Nothing to do if less than 2 tracks if (shuffle_count < 2) { return; } // Save the current_track index, so we can update the current track // to be whatever one is at that position after we shuffle them -- assuming // the current_track isn't already playing. int current_index = TrackModel.IndexOf (current_track); // Setup a function that will return a random ViewOrder in the range we want var rand = new Random (); var func_id = "play-queue-shuffle-order-" + rand.NextDouble ().ToString (); var view_orders = Enumerable.Range (first_view_order, shuffle_count) .OrderBy (a => rand.NextDouble ()) .ToList (); int i = 0; BinaryFunction.Add (func_id, (f, b) => view_orders[i++]); ServiceManager.DbConnection.Execute ( "UPDATE CorePlaylistEntries SET ViewOrder = HYENA_BINARY_FUNCTION (?, NULL, NULL) WHERE PlaylistID = ? AND ViewOrder >= ?", func_id, DbId, first_view_order ); BinaryFunction.Remove (func_id); Reload (); // Update the current track unless it was playing (and therefore wasn't moved) if (!ServiceManager.PlayerEngine.IsPlaying (current_track)) { SetCurrentTrack (TrackModel[current_index] as DatabaseTrackInfo); } } } #region IPlayQueue, IDBusExportable public void EnqueueUri (string uri) { EnqueueUri (uri, false); } public void EnqueueUri (string uri, bool prepend) { EnqueueId (DatabaseTrackInfo.GetTrackIdForUri (uri), prepend, false); } public void EnqueueTrack (TrackInfo track, bool prepend) { DatabaseTrackInfo db_track = track as DatabaseTrackInfo; if (db_track != null) { EnqueueId (db_track.TrackId, prepend, false); } else { EnqueueUri (track.Uri.AbsoluteUri, prepend); } } private void EnqueueId (long trackId, bool prepend, bool generated) { if (trackId <= 0) { return; } long view_order; if (prepend && current_track != null) { // We are going to prepend the track to the play queue, which means // adding it after the current_track. view_order = CurrentTrackViewOrder; if (ServiceManager.PlayerEngine.IsPlaying (current_track)) { view_order++; } } else { if (generated) { // view_order will point after the last track in the queue. view_order = MaxViewOrder; } else { // view_order will point after the last non-generated track in the queue. view_order = ServiceManager.DbConnection.Query<long> (@" SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ? AND Generated = 0", DbId ); } } // Increment the order of all tracks after view_order ServiceManager.DbConnection.Execute (@" UPDATE CorePlaylistEntries SET ViewOrder = ViewOrder + 1 WHERE PlaylistID = ? AND ViewOrder >= ?", DbId, view_order ); // Add the track to the queue using the view order calculated above. ServiceManager.DbConnection.Execute (@" INSERT INTO CorePlaylistEntries (PlaylistID, TrackID, ViewOrder, Generated) VALUES (?, ?, ?, ?)", DbId, trackId, view_order, generated ? 1 : 0 ); if (!generated) { shuffler.RecordShuffleModification (trackId, ShuffleModificationType.Insertion); } OnTracksAdded (); NotifyUser (); } IDBusExportable IDBusExportable.Parent { get { return ServiceManager.SourceManager; } } string IService.ServiceName { get { return "PlayQueue"; } } private long CurrentTrackViewOrder { get { // Get the ViewOrder of the current_track return current_track == null ? ServiceManager.DbConnection.Query<long> (@" SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId) : ServiceManager.DbConnection.Query<long> (@" SELECT ViewOrder FROM CorePlaylistEntries WHERE PlaylistID = ? AND EntryID = ?", DbId, Convert.ToInt64 (current_track.CacheEntryId)); } } #endregion public override bool AddSelectedTracks (Source source, Selection selection) { return AddSelectedTracks (source, selection, QueueMode.Normal); } public bool AddSelectedTracks (Source source, QueueMode mode) { return AddSelectedTracks (source, null, mode); } public bool AddSelectedTracks (Source source, Selection selection, QueueMode mode) { if ((Parent == null || source == Parent || source.Parent == Parent) && AcceptsInputFromSource (source)) { DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel; if (model == null) { return false; } selection = selection ?? model.Selection; long view_order = CalculateViewOrder (mode); long max_view_order = MaxViewOrder; long current_view_order = CurrentTrackViewOrder; // If the current_track is not playing, insert before it. int index = -1; if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) { current_view_order--; index = TrackModel.IndexOf (current_track); } WithTrackSelection (model, selection, shuffler.RecordInsertions); // Add the tracks to the end of the queue. WithTrackSelection (model, selection, AddTrackRange); if (mode != QueueMode.Normal) { ShiftForAddedAfter (view_order, max_view_order); } ShiftGeneratedTracks (view_order); OnTracksAdded (); OnUserNotifyUpdated (); // If the current_track was not playing, and there were no non-generated tracks, // mark the first added track as current. if (index != -1 && view_order == current_view_order) { SetCurrentTrack (TrackModel[index] as DatabaseTrackInfo); SetAsPlaybackSourceUnlessPlaying (); } return true; } return false; } private long CalculateViewOrder (QueueMode mode) { long view_order = 0; long current_view_order = CurrentTrackViewOrder; switch (mode) { case QueueMode.AfterCurrentTrack: // view_order will point to the currently playing track, or if we're playing from // somewhere besides the play queue it will point to the very top of the queue. // We want to insert tracks after this one. view_order = ServiceManager.PlaybackController.Source is PlayQueueSource ? current_view_order : current_view_order - 1; break; case QueueMode.AfterCurrentAlbum: // view order will point to the last track of the currently // playing album. IterateTrackModelUntilEndMatch (out view_order, true); break; case QueueMode.AfterCurrentArtist: // view order will point to the last track of the currently // playing artist. IterateTrackModelUntilEndMatch (out view_order, false); break; case QueueMode.Normal: // view_order will point to the last pending non-generated track in the queue // or to the current_track if all tracks are generated. We want to insert tracks after it. view_order = Math.Max(current_view_order, ServiceManager.DbConnection.Query<long> (@" SELECT MAX(ViewOrder) FROM CorePlaylistEntries WHERE PlaylistID = ? AND ViewOrder > ? AND Generated = 0", DbId, current_view_order )); break; default: throw new ArgumentException ("Handling for that QueueMode has not been defined"); } return view_order; } private void IterateTrackModelUntilEndMatch (out long viewOrder, bool checkAlbum) { var t = TrackModel; bool in_match = false; long current_view_order = CurrentTrackViewOrder; int index = Math.Max (0, TrackModel.IndexOf (current_track)); string current_album = ServiceManager.PlayerEngine.CurrentTrack.AlbumTitle; string current_artist = ServiceManager.PlayerEngine.CurrentTrack.AlbumArtist; // view order will point to the last track that has the same album and artist of the // currently playing track. viewOrder = current_view_order; for (int i = index; i < t.Count; i++) { var track = t[i]; if (current_artist == track.AlbumArtist && (!checkAlbum || current_album == track.AlbumTitle)) { in_match = true; viewOrder++; } else if (!in_match) { continue; } else { viewOrder--; break; } } } private void ShiftForAddedAfter (long viewOrder, long maxViewOrder) { ServiceManager.DbConnection.Execute (@" UPDATE CorePlaylistEntries SET ViewOrder = ViewOrder - ? + ? WHERE PlaylistID = ? AND ViewOrder > ? AND ViewOrder < ?", viewOrder, MaxViewOrder, DbId, viewOrder, maxViewOrder ); } private void ShiftGeneratedTracks (long viewOrder) { // Shift generated tracks to the end of the queue. ServiceManager.DbConnection.Execute (@" UPDATE CorePlaylistEntries SET ViewOrder = ViewOrder - ? + ? WHERE PlaylistID = ? AND ViewOrder > ? AND Generated = 1", viewOrder, MaxViewOrder, DbId, viewOrder ); } private void SetAsPlaybackSourceUnlessPlaying () { if (current_track != null && ServiceManager.PlaybackController.Source != this) { bool set_source = !ServiceManager.PlayerEngine.IsPlaying (); if (!set_source) { long view_order = ServiceManager.DbConnection.Query<long> (@" SELECT ViewOrder FROM CorePlaylistEntries WHERE PlaylistID = ? AND EntryID = ?", DbId, Convert.ToInt64 (current_track.CacheEntryId)); long nongenerated = ServiceManager.DbConnection.Query<long> (@" SELECT COUNT(*) FROM CorePlaylistEntries WHERE PlaylistID = ? AND ViewOrder >= ? AND Generated = 0", DbId, view_order); set_source = nongenerated > 0; } if (set_source) { PriorSource = ServiceManager.PlaybackController.Source; ServiceManager.PlaybackController.NextSource = this; } } } public void Clear () { Clear (false); } private void Clear (bool disposing) { if (Populate) { if (disposing) { PopulateModeSchema.Set ("off"); } else { header_widget.SetManual (); } } ServiceManager.DbConnection.Execute (@" DELETE FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId ); offset = 0; SetCurrentTrack (null); if (disposing) { return; } if (this == ServiceManager.PlaybackController.Source && ServiceManager.PlayerEngine.IsPlaying ()) { ServiceManager.PlayerEngine.Close(); } Reload (); } public void Dispose () { int track_index = current_track == null ? Count : Math.Max (0, TrackModel.IndexOf (current_track)); DatabaseConfigurationClient.Client.Set (CurrentTrackSchema, track_index); ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); ServiceManager.PlaybackController.TrackStarted -= OnTrackStarted; if (actions != null) { actions.Dispose (); } UninstallPreferences (); Properties.Remove ("Nereid.SourceContents.HeaderWidget"); if (header_widget != null) { header_widget.Destroy (); header_widget = null; } if (ClearOnQuitSchema.Get ()) { Clear (true); } } private void BindToDatabase () { long result = ServiceManager.DbConnection.Query<long> ( "SELECT PlaylistID FROM CorePlaylists WHERE Special = 1 AND Name = ? LIMIT 1", special_playlist_name ); if (result != 0) { DbId = result; } else { DbId = ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@" INSERT INTO CorePlaylists (PlaylistID, Name, SortColumn, SortType, Special) VALUES (NULL, ?, -1, 0, 1) ", special_playlist_name)); } } protected override void OnTracksAdded () { int old_count = Count; base.OnTracksAdded (); if (current_track == null && old_count < Count) { SetCurrentTrack (TrackModel[old_count] as DatabaseTrackInfo); } SetAsPlaybackSourceUnlessPlaying (); } protected override void OnTracksRemoved () { base.OnTracksRemoved (); if (this == ServiceManager.PlaybackController.Source && ServiceManager.PlayerEngine.IsPlaying () && TrackModel.IndexOf (ServiceManager.PlayerEngine.CurrentTrack) == -1) { if (ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused || current_track == null) { ServiceManager.PlayerEngine.Close(); } else { ServiceManager.PlayerEngine.OpenPlay (current_track); } } UpdatePlayQueue (); } protected override void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range) { shuffler.RecordShuffleModifications (model, range, ShuffleModificationType.Discard); base.RemoveTrackRange (model, range); model.Selection.UnselectRange (range.Start, range.End); int index = TrackModel.IndexOf (current_track); if (range.Start <= index && index <= range.End) { SetCurrentTrack (range.End + 1 < Count ? TrackModel[range.End + 1] as DatabaseTrackInfo : null); } } private void HandleReloaded(object sender, EventArgs e) { int track_index = DatabaseConfigurationClient.Client.Get (CurrentTrackSchema, CurrentTrackSchema.Get ()); if (track_index < Count) { SetCurrentTrack (TrackModel[track_index] as DatabaseTrackInfo); } SetAsPlaybackSourceUnlessPlaying (); TrackModel.Reloaded -= HandleReloaded; } public override void ReorderSelectedTracks (int drop_row) { // If the current_track is not playing, dropping tracks may change it. // If the selection is dropped above the current_track, the first pending // of the dropped tracks (if any) will become the new current_track. // If the tracks are dropped below the curren_track, // the first pending track not in the selection will become current. if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) { int current_index = TrackModel.IndexOf (current_track); bool above = drop_row <= current_index; int new_index = -1; for (int index = current_index; index < TrackModel.Count; index++) { if (above == TrackModel.Selection.Contains (index)) { new_index = index; break; } } if (new_index != current_index && new_index >= 0) { SetCurrentTrack (TrackModel[new_index] as DatabaseTrackInfo); } } base.ReorderSelectedTracks (drop_row); } private void OnPlayerEvent (PlayerEventArgs args) { if (args.Event == PlayerEvent.EndOfStream) { // If EoS is for the last track in the play queue if (this == ServiceManager.PlaybackController.Source && TrackModel.IndexOf (current_track) == Count - 1) { SetCurrentTrack (null); UpdatePlayQueue (); if (was_playing) { ServiceManager.PlaybackController.PriorTrack = prior_playback_track; } else { // Stop playback; nothing was playing before the play queue, so it doesn't // make sense to continue playback. ServiceManager.PlaybackController.StopWhenFinished = true; } } if (ServiceManager.PlaybackController.StopWhenFinished) { if (current_track != null && this == ServiceManager.PlaybackController.Source) { int index = TrackModel.IndexOf (current_track) + 1; SetCurrentTrack (index < Count ? TrackModel[index] as DatabaseTrackInfo : null); } } } else if (args.Event == PlayerEvent.StartOfStream) { if (TrackModel.IndexOf (ServiceManager.PlayerEngine.CurrentTrack) != -1) { SetCurrentTrack (ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo); SetAsPlaybackSourceUnlessPlaying (); UpdatePlayQueue (); } else { prior_playback_track = ServiceManager.PlayerEngine.CurrentTrack; } } } public override void Reload () { enabled_cache.Clear (); base.Reload (); if (current_track == null) { if (this == ServiceManager.PlaybackController.Source || this == ServiceManager.PlaybackController.NextSource) { ServiceManager.PlaybackController.NextSource = PriorSource; } } } protected override DatabaseTrackListModel CreateTrackModelFor (DatabaseSource src) { return new PlayQueueTrackListModel (ServiceManager.DbConnection, DatabaseTrackInfo.Provider, (PlayQueueSource) src); } bool IBasicPlaybackController.First () { return ((IBasicPlaybackController)this).Next (false, true); } bool IBasicPlaybackController.Next (bool restart, bool changeImmediately) { if (current_track != null && ServiceManager.PlayerEngine.CurrentTrack == current_track) { int index = TrackModel.IndexOf (current_track) + 1; SetCurrentTrack (index < Count ? TrackModel[index] as DatabaseTrackInfo : null); } if (current_track == null) { UpdatePlayQueue (); ServiceManager.PlaybackController.Source = PriorSource; if (was_playing) { ServiceManager.PlaybackController.PriorTrack = prior_playback_track; ServiceManager.PlaybackController.Next (restart, changeImmediately); } else { if (!changeImmediately) { ServiceManager.PlayerEngine.SetNextTrack ((TrackInfo)null); } ServiceManager.PlayerEngine.Close (); } return true; } if (changeImmediately) { ServiceManager.PlayerEngine.OpenPlay (current_track); } else { ServiceManager.PlayerEngine.SetNextTrack (current_track); } return true; } bool IBasicPlaybackController.Previous (bool restart) { if (current_track != null && ServiceManager.PlayerEngine.CurrentTrack == current_track) { int index = TrackModel.IndexOf (current_track); if (index > 0) { SetCurrentTrack (TrackModel[index - 1] as DatabaseTrackInfo); } ServiceManager.PlayerEngine.OpenPlay (current_track); } return true; } private void UpdatePlayQueue () { // Find the ViewOrder of the current_track. long view_order; if (current_track == null) { view_order = ServiceManager.DbConnection.Query<long> (@" SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId ); } else { view_order = ServiceManager.DbConnection.Query<long> (@" SELECT ViewOrder FROM CorePlaylistEntries WHERE PlaylistID = ? AND EntryID = ?", DbId, Convert.ToInt64 (current_track.CacheEntryId) ); } // Offset the model so that no more than played_songs_number tracks are shown before the current_track. Offset = played_songs_number == 0 ? view_order : ServiceManager.DbConnection.Query<long> (@" SELECT MIN(ViewOrder) FROM ( SELECT ViewOrder FROM CorePlaylistEntries WHERE PlaylistID = ? AND ViewOrder < ? ORDER BY ViewOrder DESC LIMIT ? )", DbId, view_order, played_songs_number ); // Check if we need to add more tracks. int tracks_to_add = upcoming_songs_number - (current_track == null ? 0 : Count - TrackModel.IndexOf (current_track) - 1); // If the current track is not playing count it as well. if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) { tracks_to_add--; } if (tracks_to_add > 0 && Populate && populate_from != null) { // Add songs from the selected source, skip if all tracks need to be populated. bool skip = tracks_to_add == upcoming_songs_number; for (int i = 0; i < tracks_to_add; i++) { var track = populate_from.DatabaseTrackModel.GetRandom ( source_set_at, populate_shuffle_mode, false, skip && i == 0, shuffler) as DatabaseTrackInfo; if (track != null) { EnqueueId (track.TrackId, false, true); } } OnTracksAdded (); if (current_track == null && Count > 0) { // If the queue was empty, make the first added track the current one. SetCurrentTrack (TrackModel[0] as DatabaseTrackInfo); ServiceManager.PlayerEngine.OpenPlay (current_track); } } } private readonly Dictionary<int, bool> enabled_cache = new Dictionary<int, bool> (); public bool IsTrackEnabled (int index) { if (!enabled_cache.ContainsKey (index)) { int current_index = current_track == null ? Count : TrackModel.IndexOf (current_track); enabled_cache.Add (index, index >= current_index); } return enabled_cache[index]; } private void SetCurrentTrack (DatabaseTrackInfo track) { enabled_cache.Clear (); current_track = track; } public void Refresh () { int index = current_track == null ? Count : TrackModel.IndexOf (current_track); // If the current track is not playing refresh it too. if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) { index--; } if (index + 1 < Count) { // Get the ViewOrder of the current_track long current_view_order = CurrentTrackViewOrder; // Get the list of generated tracks. var generated = new HashSet<long> (); foreach (long trackID in ServiceManager.DbConnection.QueryEnumerable<long> ( @" SELECT TrackID FROM CorePlaylistEntries WHERE PlaylistID = ? AND Generated = 1 AND ViewOrder >= ?", DbId, current_view_order)) { generated.Add (trackID); } // Collect the indices of all generated tracks. var ranges = new RangeCollection (); for (int i = index + 1; i < Count; i++) { if (generated.Contains (((DatabaseTrackInfo)TrackModel[i]).TrackId)) { ranges.Add (i); } } bool removed = false; foreach (var range in ranges.Ranges) { RemoveTrackRange (DatabaseTrackModel, range); removed = true; } if (removed) { OnTracksRemoved (); } } else if (Count == 0 || current_track == null) { UpdatePlayQueue (); } } public void AddMoreRandomTracks () { int current_fill = current_track == null ? 0 : Count - TrackModel.IndexOf (current_track) - 1; upcoming_songs_number += current_fill; UpdatePlayQueue (); upcoming_songs_number -= current_fill; } private void OnTrackStarted(object sender, EventArgs e) { SetAsPlaybackSourceUnlessPlaying (); } private bool enable_population = true; public bool Populate { get { return enable_population && populate_shuffle_mode != "off"; } set { enable_population = value; } } private ITrackModelSource PriorSource { get { if (prior_playback_source == null || prior_playback_source == this) { return (ITrackModelSource)ServiceManager.SourceManager.DefaultSource; } return prior_playback_source; } set { if (value == null || value == this) { return; } prior_playback_source = value; was_playing = ServiceManager.PlayerEngine.IsPlaying (); } } public long Offset { get { return offset; } protected set { if (value != offset) { offset = value; DatabaseConfigurationClient.Client.Set (CurrentOffsetSchema, (int)offset); Reload (); } } } public override int EnabledCount { get { return current_track == null ? 0 : Count - TrackModel.IndexOf (current_track); } } public override int FilteredCount { get { return EnabledCount; } } public override bool CanRename { get { return false; } } public override bool CanSearch { get { return false; } } public override bool ShowBrowser { get { return false; } } protected override bool HasArtistAlbum { get { return false; } } public override bool ConfirmRemoveTracks { get { return false; } } public override bool CanRepeat { get { return false; } } public override bool CanShuffle { get { return false; } } public override bool CanUnmap { get { return false; } } public override string PreferencesPageId { get { return "play-queue"; } } private void InstallPreferences () { pref_page = new Banshee.Preferences.SourcePage (PreferencesPageId, Name, "source-playlist", 500); pref_section = pref_page.Add (new Section ()); pref_section.ShowLabel = false; pref_section.Add (new SchemaPreference<int> (PlayedSongsNumberSchema, Catalog.GetString ("Number of _played songs to show"), null, delegate { played_songs_number = PlayedSongsNumberSchema.Get (); UpdatePlayQueue (); } )); pref_section.Add (new SchemaPreference<int> (UpcomingSongsNumberSchema, Catalog.GetString ("Number of _upcoming songs to show"), null, delegate { upcoming_songs_number = UpcomingSongsNumberSchema.Get (); UpdatePlayQueue (); } )); } private void UninstallPreferences () { pref_page.Dispose (); pref_page = null; pref_section = null; } public static readonly SchemaEntry<bool> ClearOnQuitSchema = new SchemaEntry<bool> ( "plugins.play_queue", "clear_on_quit", false, "Clear on Quit", "Clear the play queue when quitting" ); // TODO: By 1.8 next two schemas can be removed. They are kept only to ease // the migration from GConfConfigurationClient to DatabaseConfigurationClient. private static readonly SchemaEntry<int> CurrentTrackSchema = new SchemaEntry<int> ( "plugins.play_queue", "current_track", 0, "Current Track", "Current track in the Play Queue" ); private static readonly SchemaEntry<int> CurrentOffsetSchema = new SchemaEntry<int> ( "plugins.play_queue", "current_offset", 0, "Current Offset", "Current offset of the Play Queue" ); public static readonly SchemaEntry<string> PopulateModeSchema = new SchemaEntry<string> ( "plugins.play_queue", "populate_shuffle_mode", "off", "Play Queue population mode", "How (and if) the Play Queue should be randomly populated" ); public static readonly SchemaEntry<string> PopulateFromSchema = new SchemaEntry<string> ( "plugins.play_queue", "populate_from", MusicLibrarySource.SourceName, "Source to poplulate from", "Name of the source to populate the the Play Queue from" ); public static readonly SchemaEntry<int> PlayedSongsNumberSchema = new SchemaEntry<int> ( "plugins.play_queue", "played_songs_number", 10, 0, 100, "Played Songs Number", "Number of played songs to show in the Play Queue" ); public static readonly SchemaEntry<int> UpcomingSongsNumberSchema = new SchemaEntry<int> ( "plugins.play_queue", "upcoming_songs_number", 10, 1, 100, "Upcoming Songs Number", "Number of upcoming songs to show in the Play Queue" ); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using System.Xml.Schema; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Globalization; using System.Runtime.Serialization; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Xml { internal static class XmlConverter { public const int MaxDateTimeChars = 64; public const int MaxInt32Chars = 16; public const int MaxInt64Chars = 32; public const int MaxBoolChars = 5; public const int MaxFloatChars = 16; public const int MaxDoubleChars = 32; public const int MaxDecimalChars = 40; public const int MaxUInt64Chars = 32; public const int MaxPrimitiveChars = MaxDateTimeChars; private static UTF8Encoding s_utf8Encoding; private static UnicodeEncoding s_unicodeEncoding; private static Base64Encoding s_base64Encoding; static public Base64Encoding Base64Encoding { get { if (s_base64Encoding == null) s_base64Encoding = new Base64Encoding(); return s_base64Encoding; } } private static UTF8Encoding UTF8Encoding { get { if (s_utf8Encoding == null) s_utf8Encoding = new UTF8Encoding(false, true); return s_utf8Encoding; } } private static UnicodeEncoding UnicodeEncoding { get { if (s_unicodeEncoding == null) s_unicodeEncoding = new UnicodeEncoding(false, false, true); return s_unicodeEncoding; } } static public bool ToBoolean(string value) { try { return XmlConvert.ToBoolean(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Boolean", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Boolean", exception)); } } static public bool ToBoolean(byte[] buffer, int offset, int count) { if (count == 1) { byte ch = buffer[offset]; if (ch == (byte)'1') return true; else if (ch == (byte)'0') return false; } return ToBoolean(ToString(buffer, offset, count)); } static public int ToInt32(string value) { try { return XmlConvert.ToInt32(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception)); } } static public int ToInt32(byte[] buffer, int offset, int count) { int value; if (TryParseInt32(buffer, offset, count, out value)) return value; return ToInt32(ToString(buffer, offset, count)); } static public Int64 ToInt64(string value) { try { return XmlConvert.ToInt64(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception)); } } static public Int64 ToInt64(byte[] buffer, int offset, int count) { long value; if (TryParseInt64(buffer, offset, count, out value)) return value; return ToInt64(ToString(buffer, offset, count)); } static public float ToSingle(string value) { try { return XmlConvert.ToSingle(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception)); } } static public float ToSingle(byte[] buffer, int offset, int count) { float value; if (TryParseSingle(buffer, offset, count, out value)) return value; return ToSingle(ToString(buffer, offset, count)); } static public double ToDouble(string value) { try { return XmlConvert.ToDouble(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception)); } } static public double ToDouble(byte[] buffer, int offset, int count) { double value; if (TryParseDouble(buffer, offset, count, out value)) return value; return ToDouble(ToString(buffer, offset, count)); } static public decimal ToDecimal(string value) { try { return XmlConvert.ToDecimal(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception)); } } static public decimal ToDecimal(byte[] buffer, int offset, int count) { return ToDecimal(ToString(buffer, offset, count)); } static public DateTime ToDateTime(Int64 value) { try { return DateTime.FromBinary(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ToString(value), "DateTime", exception)); } } static public DateTime ToDateTime(string value) { try { return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "DateTime", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "DateTime", exception)); } } static public DateTime ToDateTime(byte[] buffer, int offset, int count) { DateTime value; if (TryParseDateTime(buffer, offset, count, out value)) return value; return ToDateTime(ToString(buffer, offset, count)); } static public UniqueId ToUniqueId(string value) { try { return new UniqueId(Trim(value)); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UniqueId", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UniqueId", exception)); } } static public UniqueId ToUniqueId(byte[] buffer, int offset, int count) { return ToUniqueId(ToString(buffer, offset, count)); } static public TimeSpan ToTimeSpan(string value) { try { return XmlConvert.ToTimeSpan(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception)); } } static public TimeSpan ToTimeSpan(byte[] buffer, int offset, int count) { return ToTimeSpan(ToString(buffer, offset, count)); } static public Guid ToGuid(string value) { try { return new Guid(Trim(value)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception)); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception)); } } static public Guid ToGuid(byte[] buffer, int offset, int count) { return ToGuid(ToString(buffer, offset, count)); } static public UInt64 ToUInt64(string value) { try { return ulong.Parse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception)); } } static public UInt64 ToUInt64(byte[] buffer, int offset, int count) { return ToUInt64(ToString(buffer, offset, count)); } static public string ToString(byte[] buffer, int offset, int count) { try { return UTF8Encoding.GetString(buffer, offset, count); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception)); } } static public string ToStringUnicode(byte[] buffer, int offset, int count) { try { return UnicodeEncoding.GetString(buffer, offset, count); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception)); } } static public byte[] ToBytes(string value) { try { return UTF8Encoding.GetBytes(value); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(value, exception)); } } static public int ToChars(byte[] buffer, int offset, int count, char[] chars, int charOffset) { try { return UTF8Encoding.GetChars(buffer, offset, count, chars, charOffset); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception)); } } static public string ToString(bool value) { return value ? "true" : "false"; } static public string ToString(int value) { return XmlConvert.ToString(value); } static public string ToString(Int64 value) { return XmlConvert.ToString(value); } static public string ToString(float value) { return XmlConvert.ToString(value); } static public string ToString(double value) { return XmlConvert.ToString(value); } static public string ToString(decimal value) { return XmlConvert.ToString(value); } static public string ToString(TimeSpan value) { return XmlConvert.ToString(value); } static public string ToString(UniqueId value) { return value.ToString(); } static public string ToString(Guid value) { return value.ToString(); } static public string ToString(UInt64 value) { return value.ToString(NumberFormatInfo.InvariantInfo); } static public string ToString(DateTime value) { byte[] dateChars = new byte[MaxDateTimeChars]; int count = ToChars(value, dateChars, 0); return ToString(dateChars, 0, count); } private static string ToString(object value) { if (value is int) return ToString((int)value); else if (value is Int64) return ToString((Int64)value); else if (value is float) return ToString((float)value); else if (value is double) return ToString((double)value); else if (value is decimal) return ToString((decimal)value); else if (value is TimeSpan) return ToString((TimeSpan)value); else if (value is UniqueId) return ToString((UniqueId)value); else if (value is Guid) return ToString((Guid)value); else if (value is UInt64) return ToString((UInt64)value); else if (value is DateTime) return ToString((DateTime)value); else if (value is bool) return ToString((bool)value); else return value.ToString(); } static public string ToString(object[] objects) { if (objects.Length == 0) return string.Empty; string value = ToString(objects[0]); if (objects.Length > 1) { StringBuilder sb = new StringBuilder(value); for (int i = 1; i < objects.Length; i++) { sb.Append(' '); sb.Append(ToString(objects[i])); } value = sb.ToString(); } return value; } static public void ToQualifiedName(string qname, out string prefix, out string localName) { int index = qname.IndexOf(':'); if (index < 0) { prefix = string.Empty; localName = Trim(qname); } else { if (index == qname.Length - 1) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlInvalidQualifiedName, qname))); prefix = Trim(qname.Substring(0, index)); localName = Trim(qname.Substring(index + 1)); } } private static bool TryParseInt32(byte[] chars, int offset, int count, out int result) { result = 0; if (count == 0) return false; int value = 0; int offsetMax = offset + count; if (chars[offset] == '-') { if (count == 1) return false; for (int i = offset + 1; i < offsetMax; i++) { int digit = (chars[i] - '0'); if ((uint)digit > 9) return false; if (value < int.MinValue / 10) return false; value *= 10; if (value < int.MinValue + digit) return false; value -= digit; } } else { for (int i = offset; i < offsetMax; i++) { int digit = (chars[i] - '0'); if ((uint)digit > 9) return false; if (value > int.MaxValue / 10) return false; value *= 10; if (value > int.MaxValue - digit) return false; value += digit; } } result = value; return true; } private static bool TryParseInt64(byte[] chars, int offset, int count, out long result) { result = 0; if (count < 11) { int value; if (!TryParseInt32(chars, offset, count, out value)) return false; result = value; return true; } else { long value = 0; int offsetMax = offset + count; if (chars[offset] == '-') { if (count == 1) return false; for (int i = offset + 1; i < offsetMax; i++) { int digit = (chars[i] - '0'); if ((uint)digit > 9) return false; if (value < long.MinValue / 10) return false; value *= 10; if (value < long.MinValue + digit) return false; value -= digit; } } else { for (int i = offset; i < offsetMax; i++) { int digit = (chars[i] - '0'); if ((uint)digit > 9) return false; if (value > long.MaxValue / 10) return false; value *= 10; if (value > long.MaxValue - digit) return false; value += digit; } } result = value; return true; } } private static bool TryParseSingle(byte[] chars, int offset, int count, out float result) { result = 0; int offsetMax = offset + count; bool negative = false; if (offset < offsetMax && chars[offset] == '-') { negative = true; offset++; count--; } if (count < 1 || count > 10) return false; int value = 0; int ch; while (offset < offsetMax) { ch = (chars[offset] - '0'); if (ch == ('.' - '0')) { offset++; int pow10 = 1; while (offset < offsetMax) { ch = chars[offset] - '0'; if (((uint)ch) >= 10) return false; pow10 *= 10; value = value * 10 + ch; offset++; } // More than 8 characters (7 sig figs and a decimal) and int -> float conversion is lossy, so use double if (count > 8) { result = (float)((double)value / (double)pow10); } else { result = (float)value / (float)pow10; } if (negative) result = -result; return true; } else if (((uint)ch) >= 10) return false; value = value * 10 + ch; offset++; } // Ten digits w/out a decimal point might have overflowed the int if (count == 10) return false; if (negative) result = -value; else result = value; return true; } private static bool TryParseDouble(byte[] chars, int offset, int count, out double result) { result = 0; int offsetMax = offset + count; bool negative = false; if (offset < offsetMax && chars[offset] == '-') { negative = true; offset++; count--; } if (count < 1 || count > 10) return false; int value = 0; int ch; while (offset < offsetMax) { ch = (chars[offset] - '0'); if (ch == ('.' - '0')) { offset++; int pow10 = 1; while (offset < offsetMax) { ch = chars[offset] - '0'; if (((uint)ch) >= 10) return false; pow10 *= 10; value = value * 10 + ch; offset++; } if (negative) result = -(double)value / pow10; else result = (double)value / pow10; return true; } else if (((uint)ch) >= 10) return false; value = value * 10 + ch; offset++; } // Ten digits w/out a decimal point might have overflowed the int if (count == 10) return false; if (negative) result = -value; else result = value; return true; } static public int ToChars(int value, byte[] chars, int offset) { int count = ToCharsR(value, chars, offset + MaxInt32Chars); Buffer.BlockCopy(chars, offset + MaxInt32Chars - count, chars, offset, count); return count; } static public int ToChars(long value, byte[] chars, int offset) { int count = ToCharsR(value, chars, offset + MaxInt64Chars); Buffer.BlockCopy(chars, offset + MaxInt64Chars - count, chars, offset, count); return count; } static public int ToCharsR(long value, byte[] chars, int offset) { int count = 0; if (value >= 0) { while (value > int.MaxValue) { long valueDiv10 = value / 10; count++; chars[--offset] = (byte)('0' + (int)(value - valueDiv10 * 10)); value = valueDiv10; } } else { while (value < int.MinValue) { long valueDiv10 = value / 10; count++; chars[--offset] = (byte)('0' - (int)(value - valueDiv10 * 10)); value = valueDiv10; } } Fx.Assert(value >= int.MinValue && value <= int.MaxValue, ""); return count + ToCharsR((int)value, chars, offset); } [SecuritySafeCritical] private static unsafe bool IsNegativeZero(float value) { // Simple equals function will report that -0 is equal to +0, so compare bits instead float negativeZero = -0e0F; return (*(Int32*)&value == *(Int32*)&negativeZero); } [SecuritySafeCritical] private static unsafe bool IsNegativeZero(double value) { // Simple equals function will report that -0 is equal to +0, so compare bits instead double negativeZero = -0e0; return (*(Int64*)&value == *(Int64*)&negativeZero); } private static int ToInfinity(bool isNegative, byte[] buffer, int offset) { if (isNegative) { buffer[offset + 0] = (byte)'-'; buffer[offset + 1] = (byte)'I'; buffer[offset + 2] = (byte)'N'; buffer[offset + 3] = (byte)'F'; return 4; } else { buffer[offset + 0] = (byte)'I'; buffer[offset + 1] = (byte)'N'; buffer[offset + 2] = (byte)'F'; return 3; } } private static int ToZero(bool isNegative, byte[] buffer, int offset) { if (isNegative) { buffer[offset + 0] = (byte)'-'; buffer[offset + 1] = (byte)'0'; return 2; } else { buffer[offset] = (byte)'0'; return 1; } } static public int ToChars(double value, byte[] buffer, int offset) { if (double.IsInfinity(value)) return ToInfinity(double.IsNegativeInfinity(value), buffer, offset); if (value == 0.0) return ToZero(IsNegativeZero(value), buffer, offset); return ToAsciiChars(value.ToString("R", NumberFormatInfo.InvariantInfo), buffer, offset); } static public int ToChars(float value, byte[] buffer, int offset) { if (float.IsInfinity(value)) return ToInfinity(float.IsNegativeInfinity(value), buffer, offset); if (value == 0.0) return ToZero(IsNegativeZero(value), buffer, offset); return ToAsciiChars(value.ToString("R", NumberFormatInfo.InvariantInfo), buffer, offset); } static public int ToChars(decimal value, byte[] buffer, int offset) { return ToAsciiChars(value.ToString(null, NumberFormatInfo.InvariantInfo), buffer, offset); } static public int ToChars(UInt64 value, byte[] buffer, int offset) { return ToAsciiChars(value.ToString(null, NumberFormatInfo.InvariantInfo), buffer, offset); } private static int ToAsciiChars(string s, byte[] buffer, int offset) { for (int i = 0; i < s.Length; i++) { Fx.Assert(s[i] < 128, ""); buffer[offset++] = (byte)s[i]; } return s.Length; } static public int ToChars(bool value, byte[] buffer, int offset) { if (value) { buffer[offset + 0] = (byte)'t'; buffer[offset + 1] = (byte)'r'; buffer[offset + 2] = (byte)'u'; buffer[offset + 3] = (byte)'e'; return 4; } else { buffer[offset + 0] = (byte)'f'; buffer[offset + 1] = (byte)'a'; buffer[offset + 2] = (byte)'l'; buffer[offset + 3] = (byte)'s'; buffer[offset + 4] = (byte)'e'; return 5; } } private static int ToInt32D2(byte[] chars, int offset) { byte ch1 = (byte)(chars[offset + 0] - '0'); byte ch2 = (byte)(chars[offset + 1] - '0'); if (ch1 > 9 || ch2 > 9) return -1; return 10 * ch1 + ch2; } private static int ToInt32D4(byte[] chars, int offset, int count) { return ToInt32D7(chars, offset, count); } private static int ToInt32D7(byte[] chars, int offset, int count) { int value = 0; for (int i = 0; i < count; i++) { byte ch = (byte)(chars[offset + i] - '0'); if (ch > 9) return -1; value = value * 10 + ch; } return value; } private static bool TryParseDateTime(byte[] chars, int offset, int count, out DateTime result) { int offsetMax = offset + count; result = DateTime.MaxValue; if (count < 19) return false; // 1 2 3 // 012345678901234567890123456789012 // "yyyy-MM-ddTHH:mm:ss" // "yyyy-MM-ddTHH:mm:ss.fffffff" // "yyyy-MM-ddTHH:mm:ss.fffffffZ" // "yyyy-MM-ddTHH:mm:ss.fffffff+xx:yy" // "yyyy-MM-ddTHH:mm:ss.fffffff-xx:yy" if (chars[offset + 4] != '-' || chars[offset + 7] != '-' || chars[offset + 10] != 'T' || chars[offset + 13] != ':' || chars[offset + 16] != ':') return false; int year = ToInt32D4(chars, offset + 0, 4); int month = ToInt32D2(chars, offset + 5); int day = ToInt32D2(chars, offset + 8); int hour = ToInt32D2(chars, offset + 11); int minute = ToInt32D2(chars, offset + 14); int second = ToInt32D2(chars, offset + 17); if ((year | month | day | hour | minute | second) < 0) return false; DateTimeKind kind = DateTimeKind.Unspecified; offset += 19; int ticks = 0; if (offset < offsetMax && chars[offset] == '.') { offset++; int digitOffset = offset; while (offset < offsetMax) { byte ch = chars[offset]; if (ch < '0' || ch > '9') break; offset++; } int digitCount = offset - digitOffset; if (digitCount < 1 || digitCount > 7) return false; ticks = ToInt32D7(chars, digitOffset, digitCount); if (ticks < 0) return false; for (int i = digitCount; i < 7; ++i) ticks *= 10; } bool isLocal = false; int hourDelta = 0; int minuteDelta = 0; if (offset < offsetMax) { byte ch = chars[offset]; if (ch == 'Z') { offset++; kind = DateTimeKind.Utc; } else if (ch == '+' || ch == '-') { offset++; if (offset + 5 > offsetMax || chars[offset + 2] != ':') return false; kind = DateTimeKind.Utc; isLocal = true; hourDelta = ToInt32D2(chars, offset); minuteDelta = ToInt32D2(chars, offset + 3); if ((hourDelta | minuteDelta) < 0) return false; if (ch == '+') { hourDelta = -hourDelta; minuteDelta = -minuteDelta; } offset += 5; } } if (offset < offsetMax) return false; DateTime value; try { value = new DateTime(year, month, day, hour, minute, second, kind); } catch (ArgumentException) { return false; } if (ticks > 0) { value = value.AddTicks(ticks); } if (isLocal) { try { TimeSpan ts = new TimeSpan(hourDelta, minuteDelta, 0); if (hourDelta >= 0 && (value < DateTime.MaxValue - ts) || hourDelta < 0 && (value > DateTime.MinValue - ts)) { value = value.Add(ts).ToLocalTime(); } else { value = value.ToLocalTime().Add(ts); } } catch (ArgumentOutOfRangeException) // Overflow { return false; } } result = value; return true; } // Works left from offset static public int ToCharsR(int value, byte[] chars, int offset) { int count = 0; if (value >= 0) { while (value >= 10) { int valueDiv10 = value / 10; count++; chars[--offset] = (byte)('0' + (value - valueDiv10 * 10)); value = valueDiv10; } chars[--offset] = (byte)('0' + value); count++; } else { while (value <= -10) { int valueDiv10 = value / 10; count++; chars[--offset] = (byte)('0' - (value - valueDiv10 * 10)); value = valueDiv10; } chars[--offset] = (byte)('0' - value); chars[--offset] = (byte)'-'; count += 2; } return count; } private static int ToCharsD2(int value, byte[] chars, int offset) { DiagnosticUtility.DebugAssert(value >= 0 && value < 100, ""); if (value < 10) { chars[offset + 0] = (byte)'0'; chars[offset + 1] = (byte)('0' + value); } else { int valueDiv10 = value / 10; chars[offset + 0] = (byte)('0' + valueDiv10); chars[offset + 1] = (byte)('0' + value - valueDiv10 * 10); } return 2; } private static int ToCharsD4(int value, byte[] chars, int offset) { DiagnosticUtility.DebugAssert(value >= 0 && value < 10000, ""); ToCharsD2(value / 100, chars, offset + 0); ToCharsD2(value % 100, chars, offset + 2); return 4; } private static int ToCharsD7(int value, byte[] chars, int offset) { DiagnosticUtility.DebugAssert(value >= 0 && value < 10000000, ""); int zeroCount = 7 - ToCharsR(value, chars, offset + 7); for (int i = 0; i < zeroCount; i++) chars[offset + i] = (byte)'0'; int count = 7; while (count > 0 && chars[offset + count - 1] == '0') count--; return count; } static public int ToChars(DateTime value, byte[] chars, int offset) { const long TicksPerMillisecond = 10000; const long TicksPerSecond = TicksPerMillisecond * 1000; int offsetMin = offset; // "yyyy-MM-ddTHH:mm:ss.fffffff"; offset += ToCharsD4(value.Year, chars, offset); chars[offset++] = (byte)'-'; offset += ToCharsD2(value.Month, chars, offset); chars[offset++] = (byte)'-'; offset += ToCharsD2(value.Day, chars, offset); chars[offset++] = (byte)'T'; offset += ToCharsD2(value.Hour, chars, offset); chars[offset++] = (byte)':'; offset += ToCharsD2(value.Minute, chars, offset); chars[offset++] = (byte)':'; offset += ToCharsD2(value.Second, chars, offset); int ms = (int)(value.Ticks % TicksPerSecond); if (ms != 0) { chars[offset++] = (byte)'.'; offset += ToCharsD7(ms, chars, offset); } switch (value.Kind) { case DateTimeKind.Unspecified: break; case DateTimeKind.Local: // +"zzzzzz"; TimeSpan ts = TimeZoneInfo.Local.GetUtcOffset(value); if (ts.Ticks < 0) chars[offset++] = (byte)'-'; else chars[offset++] = (byte)'+'; offset += ToCharsD2(Math.Abs(ts.Hours), chars, offset); chars[offset++] = (byte)':'; offset += ToCharsD2(Math.Abs(ts.Minutes), chars, offset); break; case DateTimeKind.Utc: // +"Z" chars[offset++] = (byte)'Z'; break; default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } return offset - offsetMin; } static public bool IsWhitespace(string s) { for (int i = 0; i < s.Length; i++) { if (!IsWhitespace(s[i])) return false; } return true; } static public bool IsWhitespace(char ch) { return (ch <= ' ' && (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')); } static public string StripWhitespace(string s) { int count = s.Length; for (int i = 0; i < s.Length; i++) { if (IsWhitespace(s[i])) { count--; } } if (count == s.Length) return s; char[] chars = new char[count]; count = 0; for (int i = 0; i < s.Length; i++) { char ch = s[i]; if (!IsWhitespace(ch)) { chars[count++] = ch; } } return new string(chars); } private static string Trim(string s) { int i; for (i = 0; i < s.Length && IsWhitespace(s[i]); i++) ; int j; for (j = s.Length; j > 0 && IsWhitespace(s[j - 1]); j--) ; if (i == 0 && j == s.Length) return s; else if (j == 0) return string.Empty; else return s.Substring(i, j - i); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics; using System.Collections.Generic; namespace System.Xml { public class XmlNamespaceManager : IXmlNamespaceResolver, IEnumerable { private struct NamespaceDeclaration { public string prefix; public string uri; public int scopeId; public int previousNsIndex; public void Set(string prefix, string uri, int scopeId, int previousNsIndex) { this.prefix = prefix; this.uri = uri; this.scopeId = scopeId; this.previousNsIndex = previousNsIndex; } } // array with namespace declarations private NamespaceDeclaration[] _nsdecls; // index of last declaration private int _lastDecl = 0; // name table private XmlNameTable _nameTable; // ID (depth) of the current scope private int _scopeId; // hash table for faster lookup when there is lots of namespaces private Dictionary<string, int> _hashTable; private bool _useHashtable; // atomized prefixes for "xml" and "xmlns" private string _xml; private string _xmlNs; // Constants private const int MinDeclsCountForHashtable = 16; internal XmlNamespaceManager() { } public XmlNamespaceManager(XmlNameTable nameTable) { _nameTable = nameTable; _xml = nameTable.Add("xml"); _xmlNs = nameTable.Add("xmlns"); _nsdecls = new NamespaceDeclaration[8]; string emptyStr = nameTable.Add(string.Empty); _nsdecls[0].Set(emptyStr, emptyStr, -1, -1); _nsdecls[1].Set(_xmlNs, nameTable.Add(XmlReservedNs.NsXmlNs), -1, -1); _nsdecls[2].Set(_xml, nameTable.Add(XmlReservedNs.NsXml), 0, -1); _lastDecl = 2; _scopeId = 1; } public virtual XmlNameTable NameTable { get { return _nameTable; } } public virtual string DefaultNamespace { get { string defaultNs = LookupNamespace(string.Empty); return (defaultNs == null) ? string.Empty : defaultNs; } } public virtual void PushScope() { _scopeId++; } public virtual bool PopScope() { int decl = _lastDecl; if (_scopeId == 1) { return false; } while (_nsdecls[decl].scopeId == _scopeId) { if (_useHashtable) { _hashTable[_nsdecls[decl].prefix] = _nsdecls[decl].previousNsIndex; } decl--; Debug.Assert(decl >= 2); } _lastDecl = decl; _scopeId--; return true; } public virtual void AddNamespace(string prefix, string uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); if (prefix == null) throw new ArgumentNullException(nameof(prefix)); prefix = _nameTable.Add(prefix); uri = _nameTable.Add(uri); if ((Ref.Equal(_xml, prefix) && !uri.Equals(XmlReservedNs.NsXml))) { throw new ArgumentException(SR.Xml_XmlPrefix); } if (Ref.Equal(_xmlNs, prefix)) { throw new ArgumentException(SR.Xml_XmlnsPrefix); } int declIndex = LookupNamespaceDecl(prefix); int previousDeclIndex = -1; if (declIndex != -1) { if (_nsdecls[declIndex].scopeId == _scopeId) { // redefine if in the same scope _nsdecls[declIndex].uri = uri; return; } else { // otherwise link previousDeclIndex = declIndex; } } // set new namespace declaration if (_lastDecl == _nsdecls.Length - 1) { NamespaceDeclaration[] newNsdecls = new NamespaceDeclaration[_nsdecls.Length * 2]; Array.Copy(_nsdecls, 0, newNsdecls, 0, _nsdecls.Length); _nsdecls = newNsdecls; } _nsdecls[++_lastDecl].Set(prefix, uri, _scopeId, previousDeclIndex); // add to hashTable if (_useHashtable) { _hashTable[prefix] = _lastDecl; } // or create a new hashTable if the threshold has been reached else if (_lastDecl >= MinDeclsCountForHashtable) { // add all to hash table Debug.Assert(_hashTable == null); _hashTable = new Dictionary<string, int>(_lastDecl); for (int i = 0; i <= _lastDecl; i++) { _hashTable[_nsdecls[i].prefix] = i; } _useHashtable = true; } } public virtual void RemoveNamespace(string prefix, string uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } int declIndex = LookupNamespaceDecl(prefix); while (declIndex != -1) { if (string.Equals(_nsdecls[declIndex].uri, uri) && _nsdecls[declIndex].scopeId == _scopeId) { _nsdecls[declIndex].uri = null; } declIndex = _nsdecls[declIndex].previousNsIndex; } } public virtual IEnumerator GetEnumerator() { Dictionary<string, string> prefixes = new Dictionary<string, string>(_lastDecl + 1); for (int thisDecl = 0; thisDecl <= _lastDecl; thisDecl++) { if (_nsdecls[thisDecl].uri != null) { prefixes[_nsdecls[thisDecl].prefix] = _nsdecls[thisDecl].prefix; } } return prefixes.Keys.GetEnumerator(); } // This pragma disables a warning that the return type is not CLS-compliant, but generics are part of CLS in Whidbey. #pragma warning disable 3002 public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { #pragma warning restore 3002 int i = 0; switch (scope) { case XmlNamespaceScope.All: i = 2; break; case XmlNamespaceScope.ExcludeXml: i = 3; break; case XmlNamespaceScope.Local: i = _lastDecl; while (_nsdecls[i].scopeId == _scopeId) { i--; Debug.Assert(i >= 2); } i++; break; } Dictionary<string, string> dict = new Dictionary<string, string>(_lastDecl - i + 1); for (; i <= _lastDecl; i++) { string prefix = _nsdecls[i].prefix; string uri = _nsdecls[i].uri; Debug.Assert(prefix != null); if (uri != null) { if (uri.Length > 0 || prefix.Length > 0 || scope == XmlNamespaceScope.Local) { dict[prefix] = uri; } else { // default namespace redeclared to "" -> remove from list for all scopes other than local dict.Remove(prefix); } } } return dict; } public virtual string LookupNamespace(string prefix) { int declIndex = LookupNamespaceDecl(prefix); return (declIndex == -1) ? null : _nsdecls[declIndex].uri; } private int LookupNamespaceDecl(string prefix) { if (_useHashtable) { int declIndex; if (_hashTable.TryGetValue(prefix, out declIndex)) { while (declIndex != -1 && _nsdecls[declIndex].uri == null) { declIndex = _nsdecls[declIndex].previousNsIndex; } return declIndex; } return -1; } else { // First assume that prefix is atomized for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--) { if ((object)_nsdecls[thisDecl].prefix == (object)prefix && _nsdecls[thisDecl].uri != null) { return thisDecl; } } // Non-atomized lookup for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--) { if (string.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null) { return thisDecl; } } } return -1; } public virtual string LookupPrefix(string uri) { // Don't assume that prefix is atomized for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--) { if (string.Equals(_nsdecls[thisDecl].uri, uri)) { string prefix = _nsdecls[thisDecl].prefix; if (string.Equals(LookupNamespace(prefix), uri)) { return prefix; } } } return null; } public virtual bool HasNamespace(string prefix) { // Don't assume that prefix is atomized for (int thisDecl = _lastDecl; _nsdecls[thisDecl].scopeId == _scopeId; thisDecl--) { if (string.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null) { if (prefix.Length > 0 || _nsdecls[thisDecl].uri.Length > 0) { return true; } return false; } } return false; } internal bool GetNamespaceDeclaration(int idx, out string prefix, out string uri) { idx = _lastDecl - idx; if (idx < 0) { prefix = uri = null; return false; } prefix = _nsdecls[idx].prefix; uri = _nsdecls[idx].uri; return true; } } //XmlNamespaceManager }
namespace EmpMan.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class initial : DbMigration { public override void Up() { CreateTable( "dbo.AppRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(), Description = c.String(), Discriminator = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AppUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), AppUser_Id = c.String(maxLength: 128), IdentityRole_Id = c.String(maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AppUsers", t => t.AppUser_Id) .ForeignKey("dbo.AppRoles", t => t.IdentityRole_Id) .Index(t => t.AppUser_Id) .Index(t => t.IdentityRole_Id); CreateTable( "dbo.Colors", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(maxLength: 250), Code = c.String(maxLength: 250), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.ContactDetails", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 250), Phone = c.String(maxLength: 50), Email = c.String(maxLength: 250), Website = c.String(maxLength: 250), Address = c.String(maxLength: 250), Other = c.String(), Lat = c.Double(), Lng = c.Double(), Status = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Errors", c => new { ID = c.Int(nullable: false, identity: true), Message = c.String(), StackTrace = c.String(), CreatedDate = c.DateTime(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Feedbacks", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 250), Email = c.String(maxLength: 250), Message = c.String(maxLength: 500), CreatedDate = c.DateTime(nullable: false), Status = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Footers", c => new { ID = c.String(nullable: false, maxLength: 50), Content = c.String(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Functions", c => new { ID = c.String(nullable: false, maxLength: 50, unicode: false), Name = c.String(nullable: false, maxLength: 50), URL = c.String(nullable: false, maxLength: 256), DisplayOrder = c.Int(nullable: false), ParentId = c.String(maxLength: 50, unicode: false), Status = c.Boolean(nullable: false), IconCss = c.String(), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.Functions", t => t.ParentId) .Index(t => t.ParentId); CreateTable( "dbo.OrderDetails", c => new { OrderID = c.Int(nullable: false), ProductID = c.Int(nullable: false), Quantity = c.Int(nullable: false), Price = c.Decimal(nullable: false, precision: 18, scale: 2), }) .PrimaryKey(t => new { t.OrderID, t.ProductID }) .ForeignKey("dbo.Orders", t => t.OrderID, cascadeDelete: true) .ForeignKey("dbo.Products", t => t.ProductID, cascadeDelete: true) .Index(t => t.OrderID) .Index(t => t.ProductID); CreateTable( "dbo.Orders", c => new { ID = c.Int(nullable: false, identity: true), CustomerName = c.String(nullable: false, maxLength: 256), CustomerAddress = c.String(nullable: false, maxLength: 256), CustomerEmail = c.String(nullable: false, maxLength: 256), CustomerMobile = c.String(nullable: false, maxLength: 50), CustomerMessage = c.String(nullable: false, maxLength: 256), PaymentMethod = c.String(maxLength: 256), CreatedDate = c.DateTime(), CreatedBy = c.String(), PaymentStatus = c.String(), Status = c.Boolean(nullable: false), CustomerId = c.String(maxLength: 128), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.AppUsers", t => t.CustomerId) .Index(t => t.CustomerId); CreateTable( "dbo.AppUsers", c => new { Id = c.String(nullable: false, maxLength: 128), FullName = c.String(maxLength: 256), Address = c.String(maxLength: 256), Avatar = c.String(), BirthDay = c.DateTime(), Status = c.Boolean(), Gender = c.Boolean(), Email = c.String(), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AppUserClaims", c => new { UserId = c.String(nullable: false, maxLength: 128), Id = c.Int(nullable: false), ClaimType = c.String(), ClaimValue = c.String(), AppUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.UserId) .ForeignKey("dbo.AppUsers", t => t.AppUser_Id) .Index(t => t.AppUser_Id); CreateTable( "dbo.AppUserLogins", c => new { UserId = c.String(nullable: false, maxLength: 128), LoginProvider = c.String(), ProviderKey = c.String(), AppUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.UserId) .ForeignKey("dbo.AppUsers", t => t.AppUser_Id) .Index(t => t.AppUser_Id); CreateTable( "dbo.Products", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 256), Alias = c.String(nullable: false, maxLength: 256), CategoryID = c.Int(nullable: false), ThumbnailImage = c.String(maxLength: 256), Price = c.Decimal(nullable: false, precision: 18, scale: 2), OriginalPrice = c.Decimal(nullable: false, precision: 18, scale: 2), PromotionPrice = c.Decimal(precision: 18, scale: 2), IncludedVAT = c.Boolean(nullable: false), Warranty = c.Int(), Description = c.String(maxLength: 500), Content = c.String(), HomeFlag = c.Boolean(), HotFlag = c.Boolean(), ViewCount = c.Int(), Tags = c.String(), CreatedDate = c.DateTime(), CreatedBy = c.String(maxLength: 256), UpdatedDate = c.DateTime(), UpdatedBy = c.String(maxLength: 256), MetaKeyword = c.String(maxLength: 256), MetaDescription = c.String(maxLength: 256), Status = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.ProductCategories", t => t.CategoryID, cascadeDelete: true) .Index(t => t.CategoryID); CreateTable( "dbo.ProductCategories", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 256), Alias = c.String(nullable: false, maxLength: 256), Description = c.String(maxLength: 500), ParentID = c.Int(), DisplayOrder = c.Int(), HomeOrder = c.Int(), Image = c.String(maxLength: 256), HomeFlag = c.Boolean(), CreatedDate = c.DateTime(), CreatedBy = c.String(maxLength: 256), UpdatedDate = c.DateTime(), UpdatedBy = c.String(maxLength: 256), MetaKeyword = c.String(maxLength: 256), MetaDescription = c.String(maxLength: 256), Status = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Pages", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 256), Alias = c.String(nullable: false, maxLength: 256, unicode: false), Content = c.String(), CreatedDate = c.DateTime(), CreatedBy = c.String(maxLength: 256), UpdatedDate = c.DateTime(), UpdatedBy = c.String(maxLength: 256), MetaKeyword = c.String(maxLength: 256), MetaDescription = c.String(maxLength: 256), Status = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Permissions", c => new { ID = c.Int(nullable: false, identity: true), RoleId = c.String(maxLength: 128), FunctionId = c.String(maxLength: 50, unicode: false), CanCreate = c.Boolean(nullable: false), CanRead = c.Boolean(nullable: false), CanUpdate = c.Boolean(nullable: false), CanDelete = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.AppRoles", t => t.RoleId) .ForeignKey("dbo.Functions", t => t.FunctionId) .Index(t => t.RoleId) .Index(t => t.FunctionId); CreateTable( "dbo.PostCategories", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 256), Alias = c.String(nullable: false, maxLength: 256, unicode: false), Description = c.String(maxLength: 500), ParentID = c.Int(), DisplayOrder = c.Int(), Image = c.String(maxLength: 256), HomeFlag = c.Boolean(), CreatedDate = c.DateTime(), CreatedBy = c.String(maxLength: 256), UpdatedDate = c.DateTime(), UpdatedBy = c.String(maxLength: 256), MetaKeyword = c.String(maxLength: 256), MetaDescription = c.String(maxLength: 256), Status = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Posts", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 256), Alias = c.String(nullable: false, maxLength: 256, unicode: false), CategoryID = c.Int(nullable: false), Image = c.String(maxLength: 256), Description = c.String(maxLength: 500), Content = c.String(), HomeFlag = c.Boolean(), HotFlag = c.Boolean(), ViewCount = c.Int(), CreatedDate = c.DateTime(), CreatedBy = c.String(maxLength: 256), UpdatedDate = c.DateTime(), UpdatedBy = c.String(maxLength: 256), MetaKeyword = c.String(maxLength: 256), MetaDescription = c.String(maxLength: 256), Status = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.PostCategories", t => t.CategoryID, cascadeDelete: true) .Index(t => t.CategoryID); CreateTable( "dbo.PostTags", c => new { PostID = c.Int(nullable: false), TagID = c.String(nullable: false, maxLength: 50, unicode: false), }) .PrimaryKey(t => new { t.PostID, t.TagID }) .ForeignKey("dbo.Posts", t => t.PostID, cascadeDelete: true) .ForeignKey("dbo.Tags", t => t.TagID, cascadeDelete: true) .Index(t => t.PostID) .Index(t => t.TagID); CreateTable( "dbo.Tags", c => new { ID = c.String(nullable: false, maxLength: 50, unicode: false), Name = c.String(nullable: false, maxLength: 50), Type = c.String(nullable: false, maxLength: 50), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.ProductColors", c => new { ID = c.Int(nullable: false, identity: true), ProductId = c.Int(nullable: false), ColorId = c.Int(nullable: false), Quantity = c.Int(nullable: false), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.Colors", t => t.ColorId, cascadeDelete: true) .ForeignKey("dbo.Products", t => t.ProductId, cascadeDelete: true) .Index(t => t.ProductId) .Index(t => t.ColorId); CreateTable( "dbo.ProductImages", c => new { ID = c.Int(nullable: false, identity: true), ProductId = c.Int(nullable: false), Path = c.String(maxLength: 250), Caption = c.String(maxLength: 250), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.Products", t => t.ProductId, cascadeDelete: true) .Index(t => t.ProductId); CreateTable( "dbo.ProductSizes", c => new { ID = c.Int(nullable: false, identity: true), ProductId = c.Int(nullable: false), SizeId = c.Int(nullable: false), Quantity = c.Int(nullable: false), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.Products", t => t.ProductId, cascadeDelete: true) .ForeignKey("dbo.Sizes", t => t.SizeId, cascadeDelete: true) .Index(t => t.ProductId) .Index(t => t.SizeId); CreateTable( "dbo.Sizes", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(maxLength: 250), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.ProductTags", c => new { ProductID = c.Int(nullable: false), TagID = c.String(nullable: false, maxLength: 50, unicode: false), }) .PrimaryKey(t => new { t.ProductID, t.TagID }) .ForeignKey("dbo.Products", t => t.ProductID, cascadeDelete: true) .ForeignKey("dbo.Tags", t => t.TagID, cascadeDelete: true) .Index(t => t.ProductID) .Index(t => t.TagID); CreateTable( "dbo.Slides", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 256), Description = c.String(maxLength: 256), Image = c.String(maxLength: 256), Url = c.String(maxLength: 256), DisplayOrder = c.Int(), Status = c.Boolean(nullable: false), Content = c.String(), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.SupportOnlines", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), Department = c.String(maxLength: 50), Skype = c.String(maxLength: 50), Mobile = c.String(maxLength: 50), Email = c.String(maxLength: 50), Yahoo = c.String(maxLength: 50), Facebook = c.String(maxLength: 50), Status = c.Boolean(nullable: false), DisplayOrder = c.Int(), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.SystemConfigs", c => new { ID = c.Int(nullable: false, identity: true), Code = c.String(nullable: false, maxLength: 50, unicode: false), ValueString = c.String(maxLength: 50), ValueInt = c.Int(), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.VisitorStatistics", c => new { ID = c.Guid(nullable: false), VisitedDate = c.DateTime(nullable: false), IPAddress = c.String(maxLength: 50), }) .PrimaryKey(t => t.ID); } public override void Down() { DropForeignKey("dbo.AppUserRoles", "IdentityRole_Id", "dbo.AppRoles"); DropForeignKey("dbo.ProductTags", "TagID", "dbo.Tags"); DropForeignKey("dbo.ProductTags", "ProductID", "dbo.Products"); DropForeignKey("dbo.ProductSizes", "SizeId", "dbo.Sizes"); DropForeignKey("dbo.ProductSizes", "ProductId", "dbo.Products"); DropForeignKey("dbo.ProductImages", "ProductId", "dbo.Products"); DropForeignKey("dbo.ProductColors", "ProductId", "dbo.Products"); DropForeignKey("dbo.ProductColors", "ColorId", "dbo.Colors"); DropForeignKey("dbo.PostTags", "TagID", "dbo.Tags"); DropForeignKey("dbo.PostTags", "PostID", "dbo.Posts"); DropForeignKey("dbo.Posts", "CategoryID", "dbo.PostCategories"); DropForeignKey("dbo.Permissions", "FunctionId", "dbo.Functions"); DropForeignKey("dbo.Permissions", "RoleId", "dbo.AppRoles"); DropForeignKey("dbo.OrderDetails", "ProductID", "dbo.Products"); DropForeignKey("dbo.Products", "CategoryID", "dbo.ProductCategories"); DropForeignKey("dbo.OrderDetails", "OrderID", "dbo.Orders"); DropForeignKey("dbo.Orders", "CustomerId", "dbo.AppUsers"); DropForeignKey("dbo.AppUserRoles", "AppUser_Id", "dbo.AppUsers"); DropForeignKey("dbo.AppUserLogins", "AppUser_Id", "dbo.AppUsers"); DropForeignKey("dbo.AppUserClaims", "AppUser_Id", "dbo.AppUsers"); DropForeignKey("dbo.Functions", "ParentId", "dbo.Functions"); DropIndex("dbo.ProductTags", new[] { "TagID" }); DropIndex("dbo.ProductTags", new[] { "ProductID" }); DropIndex("dbo.ProductSizes", new[] { "SizeId" }); DropIndex("dbo.ProductSizes", new[] { "ProductId" }); DropIndex("dbo.ProductImages", new[] { "ProductId" }); DropIndex("dbo.ProductColors", new[] { "ColorId" }); DropIndex("dbo.ProductColors", new[] { "ProductId" }); DropIndex("dbo.PostTags", new[] { "TagID" }); DropIndex("dbo.PostTags", new[] { "PostID" }); DropIndex("dbo.Posts", new[] { "CategoryID" }); DropIndex("dbo.Permissions", new[] { "FunctionId" }); DropIndex("dbo.Permissions", new[] { "RoleId" }); DropIndex("dbo.Products", new[] { "CategoryID" }); DropIndex("dbo.AppUserLogins", new[] { "AppUser_Id" }); DropIndex("dbo.AppUserClaims", new[] { "AppUser_Id" }); DropIndex("dbo.Orders", new[] { "CustomerId" }); DropIndex("dbo.OrderDetails", new[] { "ProductID" }); DropIndex("dbo.OrderDetails", new[] { "OrderID" }); DropIndex("dbo.Functions", new[] { "ParentId" }); DropIndex("dbo.AppUserRoles", new[] { "IdentityRole_Id" }); DropIndex("dbo.AppUserRoles", new[] { "AppUser_Id" }); DropTable("dbo.VisitorStatistics"); DropTable("dbo.SystemConfigs"); DropTable("dbo.SupportOnlines"); DropTable("dbo.Slides"); DropTable("dbo.ProductTags"); DropTable("dbo.Sizes"); DropTable("dbo.ProductSizes"); DropTable("dbo.ProductImages"); DropTable("dbo.ProductColors"); DropTable("dbo.Tags"); DropTable("dbo.PostTags"); DropTable("dbo.Posts"); DropTable("dbo.PostCategories"); DropTable("dbo.Permissions"); DropTable("dbo.Pages"); DropTable("dbo.ProductCategories"); DropTable("dbo.Products"); DropTable("dbo.AppUserLogins"); DropTable("dbo.AppUserClaims"); DropTable("dbo.AppUsers"); DropTable("dbo.Orders"); DropTable("dbo.OrderDetails"); DropTable("dbo.Functions"); DropTable("dbo.Footers"); DropTable("dbo.Feedbacks"); DropTable("dbo.Errors"); DropTable("dbo.ContactDetails"); DropTable("dbo.Colors"); DropTable("dbo.AppUserRoles"); DropTable("dbo.AppRoles"); } } }
#define DISABLE_INC_FINGERPRINTS // Turns off Inc Fingerprinting, defaults to Noninc & Iosif's algo //#define DEBUG_INC_FINGERPRINTS // This checks on each cache hit, if cached fingerprint == uncached //#define PRINT_FINGERPRINTS //#define STATS_INC_FINGERPRINTS // Write stats about Inc Fingeprinting every 1000 traversals #define REUSE_CANONS // An improvement of the inc fingerprint algorithm using System; using System.Collections; using System.Diagnostics; using System.IO; namespace Microsoft.Zing { /// <summary> /// HeapCanonicalizer encodes all the functionalities of heap canonicalization. /// StateImpl forwards all heap canonicalization related functionalities to this class. /// /// The heap canonicalization itself is performed by the HeapCanonicalizationAlgorithm class. /// Currently there are two implemented algorithms: the Iosif algorithm and the Incremental algorithm /// /// Apart from its own state, Heap Canonicalizer is responsible for the following fields /// HeapElement.canonId : The canonical Id for a particular heap element /// HeapElement.fingerprint : The (cached) fingerprint of the heap element /// Note: This fingerprint is a function of: /// * Contents of all non-reference fields of heap element /// * CanonIds of all reference fields /// * Its own canonId /// /// These two fields are 'essential' fields of a heap element. Thus, a heap element gets dirty when these /// fields change. (There is no need to clone the entire object in such a case - TODO for the future) /// /// Additionally, the heap canonicalizer maintains these TEMPORARY fields /// HeapEntry.currCanonId : CanonId in the current traversal /// HeapEntry.fingerprint : Fingeprint in the current traversal /// /// Obviously, these fields are valid only during the heap traversal /// /// The fingerprint computation starts with a call to HeapCanonicalizer.OnFingerprintStart() and ends with /// HeapCanonicalizer.OnFingerprintEnd(). During the computation, the heap canonicalizer computes he.canonId /// using the HeapCanonicalizationAlgorithm. Note, helem.canonId reflects the 'old' canonId before the current /// traversal /// /// </summary> internal class HeapCanonicalizer { #if DISABLE_INC_FINGERPRINTS private IosifAlgorithm algorithm; #else private IncrementalAlgorithm algorithm; #endif public HeapCanonicalizer() { #if DISABLE_INC_FINGERPRINTS algorithm = new IosifAlgorithm(this); #else algorithm = new IncrementalAlgorithm(this); #endif } public HeapCanonicalizer(int SerialNum) : this() { this.SerialNumber = SerialNum; } # region Per Fingerprinting Traversal State // The following state is maintained during a fingerprint traversal // and should be cleared at the end of the traversal. // The list heap objects whose canonicalization state (canonId and fingerprint) // have changed during this traversal private Queue dirtyHeapEntries = new Queue(); //The queue of pending heap objects that need to be traversed during this //fingerprinting traversal // --- This corresponds to StateImpl.sortedHeap in the old implementation private Queue pendingHeapEntries = new Queue(512); //private ArrayQueue pendingHeapEntries = new ArrayQueue(512); // number of heap objects traversed during this traversal // this member is incremented whenever a new heap object is added to pendingHeapEntries private uint numHeapEntries; // The canonical id of the object that is being traversed // currentParentId == 0 means that the global objects are being traversed private int currentParentId; // The offset of the child reference that is being traversed for the currentParentId object // This field is incremented by GetCanonicalId private int currentFieldId; private int currentOffset; #if STATS_INC_FINGERPRINTS private struct IncFingerprintStats { public int numHeapTraversals; public int numHeapEntries; public int numCacheHits; public int numDirtyEntries; public int numDirtyCanonIds; public int numDirtyRefs; public int numCanonIdCacheHits; public int numZeroCanonIds; public int numCanonIdReuses; public int numCanonIdMutations; } private IncFingerprintStats stats; private IncFingerprintStats oldStats; internal void IncCanonIdMutations() { stats.numCanonIdMutations++; } internal void IncCanonIdReuses() { stats.numCanonIdReuses++; } #endif #endregion //---- Old Code // To avoid having to clear the HeapEntry.Order fields in before WriteString // (which turns out to be VERY expensive), we using an incrementing order // base number. Any order values less than orderBase are effectively zero. // When WriteString completes, we bump up orderBase by the number of order // values consumed. We have 2^32 order numbers to work with. For a model // with 1000 heap elements, we could explore over 4M states, which would be // a lot for a model that large. If we eventually scale up to this, we'll // see an exception here and we can bump the order field to a ulong. // //private static uint orderBase = 0; //private static uint nextOrderBase = 0; // //---- Old Code // Fields orderBase and nextOrderBase are not necessary as we keep a table of seen pointers // and clear this table after every traversal // --- madanm // // Hashtable seenPtrs = new Hashtable(); private bool[] seenPtrs; private bool traversingHeap; public int SerialNumber; public void OnHeapTraversalStart(StateImpl state) { //Debug.Assert(!traversingHeap); // VS fails this assert during debugging, for unknown reasons traversingHeap = true; currentParentId = 0; currentFieldId = 0; currentOffset = 0; if (state.Heap != null) { seenPtrs = new bool[state.Heap.Length]; } else { seenPtrs = null; } algorithm.OnStart(); } public void OnHeapTraversalEnd(StateImpl state) { //Debug.Assert(traversingHeap); algorithm.OnEnd(); traversingHeap = false; numHeapEntries = 0; currentOffset = 0; currentFieldId = 0; currentParentId = 0; // Doing Garbage Collection; if (state.Heap != null) { Debug.Assert(seenPtrs != null); for (int ptr = 0; ptr < seenPtrs.Length; ptr++) { if (state.Heap[ptr] != null && !seenPtrs[ptr]) { state.MarkGarbage((Pointer)((uint)ptr)); } } seenPtrs = null; } // Commit in all the canonIds of dirty heap entries while (dirtyHeapEntries.Count > 0) { HeapEntry he = (HeapEntry)dirtyHeapEntries.Dequeue(); HeapElement helem = he.heList; // Since we are modifying the canonId and the fingerprint // we need to make this object dirty helem.SetDirty(); helem.canonId = he.currCanonId; if (he.currFingerprint != null) { helem.fingerprint = he.currFingerprint; } he.currCanonId = 0; he.currFingerprint = null; } #if STATS_INC_FINGERPRINTS stats.numHeapTraversals++; if(stats.numHeapTraversals%5000 == 0) { System.Console.Write("#Travs: {0}, ", stats.numHeapTraversals); System.Console.Write("#HElems: {0}, ", stats.numHeapEntries); System.Console.Write("#Hits: {0:f}, ", stats.numCacheHits*1.0/stats.numHeapEntries*100); System.Console.Write("Misses = [dirty: {0:f}, ", stats.numDirtyEntries*1.0/ stats.numHeapEntries*100); System.Console.Write("childRefs: {0:f}, ", stats.numDirtyRefs*1.0/ stats.numHeapEntries*100); System.Console.Write("canonIds: {0:f} ", stats.numDirtyCanonIds*1.0/ stats.numHeapEntries*100); System.Console.Write("(zero: {0:f}) ] ", stats.numZeroCanonIds*1.0/ stats.numHeapEntries*100); System.Console.Write("#CanonHits: {0:f}, ", stats.numCanonIdCacheHits*1.0/ stats.numHeapEntries*100); System.Console.Write("#CanonReuses: {0:f}, ", stats.numCanonIdReuses); System.Console.Write("#CanonMutations: {0:f}, ", stats.numCanonIdMutations); System.Console.Write("unused: {0}", algorithm.unusedId); System.Console.WriteLine(); System.Console.Write("Diffs: {0,5} ", stats.numHeapTraversals); System.Console.Write("{0,5} ", stats.numHeapEntries - oldStats.numHeapEntries); System.Console.Write("{0,5} ", stats.numDirtyEntries - oldStats.numDirtyEntries); System.Console.Write("{0,5} ", stats.numDirtyCanonIds - oldStats.numDirtyCanonIds); System.Console.Write("{0,5} ", stats.numDirtyRefs - oldStats.numDirtyRefs); System.Console.WriteLine(); oldStats = stats; } #endif // make sure the per traversal state is clean for the next traversal Debug.Assert(dirtyHeapEntries.Count == 0); Debug.Assert(pendingHeapEntries.Count == 0); Debug.Assert(numHeapEntries == 0); Debug.Assert(currentParentId == 0); Debug.Assert(currentFieldId == 0); Debug.Assert(currentOffset == 0); } #region Entry points from StateImpl /// <summary> /// Get the canonicalized version of a particular heap object /// /// When GetCanonicalId is called for a particular heap object /// for the first time in a traversal, the heap object is inserted /// in the pendingHeapEntries queue for future traversals. /// </summary> /// <param name="state"></param> /// <param name="p"></param> /// <returns></returns> internal uint GetCanonicalId(StateImpl state, Pointer p) { //Debug.Assert(traversingHeap); uint ptr = (uint)p; currentFieldId++; if (ptr == 0u) return 0; HeapEntry he = state.Heap[ptr]; Debug.Assert(he != null); if (!seenPtrs[ptr]) { pendingHeapEntries.Enqueue(he); numHeapEntries++; seenPtrs[ptr] = true; HeapElement helem = he.HeapObj; he.currCanonId = algorithm.CanonId(currentParentId, currentFieldId, helem.canonId); #if !DISABLE_INC_FINGERPRINTS if(he.currCanonId != helem.canonId) { // commit this new information at the end of this heap traversal dirtyHeapEntries.Enqueue(he); } #endif } return (uint)he.currCanonId; } /// <summary> /// Write the contents of all the heap objects in a StateImpl /// </summary> /// <param name="state"></param> /// <param name="bw"></param> internal void WriteString(StateImpl state, BinaryWriter bw) { Debug.Assert(traversingHeap); if (pendingHeapEntries.Count != 0) { // During the course if this loop, we may encounter additional, new // heap references, which will cause pendingHeapEntries.Count to increase. while (pendingHeapEntries.Count != 0) { // Using Queue for pendingHeapEntries results in a breadth-first traversal of the heap HeapEntry he = (HeapEntry)pendingHeapEntries.Dequeue(); currentParentId = he.currCanonId; currentFieldId = 0; HeapElement helem = he.HeapObj; helem.WriteString(state, bw); } bw.Write((short)numHeapEntries); } else bw.Write((int)0); } /// <summary> /// ComputeFingerprint computes the fingerprint of the state of heap in a given StateImpl /// after performing heap canonicalization. /// This function assumes that StateImpl has already computed the fingerprints of the globals /// and the process states. /// Thus pendingHeapEntries already contains all the heap objects referenced by these 'root' states /// </summary> /// <param name="state">The StateImpl containing the heap</param> /// <returns>Fingerprint of the heap state in StateImpl</returns> internal Fingerprint ComputeHeapFingerprint(StateImpl state) { Fingerprint heapPrint = new Fingerprint(); if (pendingHeapEntries.Count != 0) { // During the course if this loop, we may encounter additional, new // heap references, which will cause pendingHeapEntries to increase in size while (pendingHeapEntries.Count != 0) { // Using Queue for pendingHeapEntries results in a breadth-first traversal of the heap HeapEntry he = (HeapEntry)pendingHeapEntries.Dequeue(); currentParentId = he.currCanonId; currentFieldId = 0; Fingerprint hePrint = FingerprintHeapEntry(state, he); heapPrint.Concatenate(hePrint); } #if DISABLE_INC_FINGERPRINTS // Add the heap count to the fingerprint, this is for bacward comapitibility with WriteString // But, when we do inc fingerprinting, there is no place to add this extra information (the heap is // no longer contiguous), so we give up compatibility with WriteString short heapCount = (short)numHeapEntries; byte[] len = new byte[2]; // the order is Little Endian to match the corresponding // bw.Write((short) pendingHeapEntries.Count); // in the WriteString method. len[1] = (byte)((heapCount >> 8) & 0xff); len[0] = (byte)((heapCount) & 0xff); Fingerprint lenPrint = computeHASH.GetFingerprint(len, 2, currentOffset); currentOffset += 2; heapPrint.Concatenate(lenPrint); #endif } else { // add in a zero when there are no heap elements for backward compatibility byte[] zer = new byte[4]; zer[0] = 0; zer[1] = 0; zer[2] = 0; zer[3] = 0; Fingerprint zeroPrint = computeHASH.GetFingerprint(zer, 4, currentOffset); currentOffset += 4; heapPrint.Concatenate(zeroPrint); } return heapPrint; } #endregion // Compute the fingerprint of a heap entry // If a cached fingerprint is present and valid, this function returns this value // otherwise, this function calls FingerprintHeapEntryUncached private Fingerprint FingerprintHeapEntry(StateImpl state, HeapEntry he) { HeapElement helem = he.HeapObj; #if DISABLE_INC_FINGERPRINTS helem.fingerprint = FingerprintHeapEntryUncached(state, he); return helem.fingerprint; #endif #if STATS_INC_FINGERPRINTS stats.numHeapEntries ++; #endif // helem.fingerprint is valid if all the following are true // * it is first present // * helem is not dirty // * If helem's canonId did not change // * If the canonId of all its references have not changed if (helem.fingerprint != null && !helem.IsDirty && helem.canonId == he.currCanonId) { bool dirtyRefs = CheckDirtyReferences(state, helem); #if STATS_INC_FINGERPRINTS if(dirtyRefs) stats.numDirtyRefs++; else stats.numCacheHits++; #endif if (!dirtyRefs) { #if DEBUG_INC_FINGERPRINTS int cachedOffset = helem.fingerprintedOffset; byte[] cachedBuffer = helem.fingerprintedBuffer; Fingerprint cached = helem.fingerprint; Fingerprint uncached = FingerprintHeapEntryUncached(state, he); byte[] uncachedBuffer = helem.fingerprintedBuffer; int uncachedOffset = helem.fingerprintedOffset; if(!uncached.Equals(cached)) { System.Console.WriteLine("Incremental Fingerprinting Is Not Working"); System.Console.Write("{0} @{1} : ", cached, cachedOffset); for(int i=0; i<cachedBuffer.Length; i++) System.Console.Write("{0} ", cachedBuffer[i]); System.Console.WriteLine(); System.Console.Write("{0} @{1} : ", uncached, uncachedOffset); for(int i=0; i<uncachedBuffer.Length; i++) System.Console.Write("{0} ", uncachedBuffer[i]); System.Console.WriteLine(); System.Diagnostics.Debugger.Break(); } #endif return helem.fingerprint; } } #if STATS_INC_FINGERPRINTS if(helem.IsDirty) stats.numDirtyEntries ++; if(helem.canonId != he.currCanonId) { if(helem.canonId == 0) { stats.numZeroCanonIds++; } //System.Console.WriteLine("DirtyCanonId from {0} to {1}", helem.canonId, he.currCanonId); stats.numDirtyCanonIds++; } #endif he.currFingerprint = FingerprintHeapEntryUncached(state, he); // he.currFingerprint will be committed to helem.fingerprint at the end of the // fingerprint traversal // if he.canonId != helem.canonId, the heap entry is already in the dirtyHeapEntries queue if (he.currCanonId == helem.canonId) { dirtyHeapEntries.Enqueue(he); } // All info necessary for incremental fingerprinting is cached by the following function // this greatly improves performance UpdateFingerprintCache(helem); return he.currFingerprint; } private static MemoryStream[] memStream = new MemoryStream[ZingerConfiguration.DegreeOfParallelism]; private static BinaryWriter[] binWriter = new BinaryWriter[ZingerConfiguration.DegreeOfParallelism]; // Gives the fingerprint offset for each canonId // Hashtable for integers is expensive due to boxing overhead // TODO in the future private Hashtable OffsetMap = new Hashtable(); private const int startHeapOffset = 8096; public Fingerprint FingerprintNonHeapBuffer(byte[] buffer, int len) { if (currentOffset + len >= startHeapOffset) { Debug.Assert(false, "Recompile with a larger startHeapOffset"); throw new ArgumentException("buffer too large - recompile with a larger startHeapOffset"); } Fingerprint res = computeHASH.GetFingerprint(buffer, len, currentOffset); currentOffset += len; return res; } private Fingerprint FingerprintHeapEntryUncached(StateImpl state, HeapEntry he) { HeapElement helem = he.HeapObj; if (memStream[SerialNumber] == null) { memStream[SerialNumber] = new MemoryStream(); binWriter[SerialNumber] = new BinaryWriter(memStream[SerialNumber]); } binWriter[SerialNumber].Seek(0, SeekOrigin.Begin); currentFieldId = 0; helem.WriteString(state, binWriter[SerialNumber]); int objLen = (int)memStream[SerialNumber].Position; int offset; #if DISABLE_INC_FINGERPRINTS offset = currentOffset; currentOffset += objLen; #else if(OffsetMap.Contains(he.currCanonId)) { offset = (int)OffsetMap[he.currCanonId]; } else { //generate an offset map offset = unusedOffset; unusedOffset += objLen; OffsetMap[he.currCanonId] = offset; #if DEBUG_INC_FINGERPRINTS System.Console.WriteLine("OffsetTable[{0}] = {1}", he.currCanonId, offset); #endif } #endif Fingerprint ret = computeHASH.GetFingerprint(memStream[SerialNumber].GetBuffer(), objLen, offset); #if DEBUG_INC_FINGERPRINTS helem.fingerprintedOffset = offset; helem.fingerprintedBuffer = new byte[objLen]; Array.Copy(memStream.GetBuffer(), 0, helem.fingerprintedBuffer, 0, objLen); #endif #if PRINT_FINGERPRINTS if(StateImpl.printFingerprintsFlag) { System.Console.Write("@{0} ", offset); state.PrintFingerprintBuffer(memStream.GetBuffer(), objLen, true); System.Console.WriteLine("{0}", ret); } #endif return ret; } // This version of dirty references, uses the cache of childReferences // in helem. This is much faster than doing an object traversal private static bool CheckDirtyReferences(StateImpl state, HeapElement helem) { Debug.Assert(helem.childReferences != null); Pointer[] refs = helem.childReferences; for (int i = 0; i < refs.Length; i++) { Pointer ptr = refs[i]; // this call for GetCanonicalId is absolutely necessary: // to mark the child objectss as reachable, // and update their canonId if necessary // To get the currentFieldIds correct, we need to make this call before the null check state.GetCanonicalId(ptr); if (ptr == 0u) continue; HeapEntry he = state.Heap[ptr]; if (he.currCanonId != he.HeapObj.canonId) { return true; } } return false; } private ChildRefGenerator childRefGenerator; private void UpdateFingerprintCache(HeapElement helem) { if (childRefGenerator == null) childRefGenerator = new ChildRefGenerator(); helem.TraverseFields(childRefGenerator); helem.childReferences = childRefGenerator.GetChilRef(); } private class ChildRefGenerator : FieldTraverser { public ArrayList children = new ArrayList(); public int numSymFields; public ChildRefGenerator() { } public override void DoTraversal(Object field) { /* nothing */ } public override void DoTraversal(Pointer ptr) { children.Add(ptr); } public Pointer[] GetChilRef() { Pointer[] ret = new Pointer[children.Count]; for (int i = 0; i < ret.Length; i++) { ret[i] = (Pointer)children[i]; } children.Clear(); return ret; } public int GetNumSymFields() { int ret = numSymFields; numSymFields = 0; return ret; } } #region Heap Canonicalization Algorithms /* // This is the "interface" for the canonicalization algorithm // This is just for documentation and reference, // To avoid the virtual function call, the algorithms do not derive from this interface private interface HeapCanonicalizationAlgorithm { void OnStart(); CanonInfo CanonId(HeapEntry he, uint parentId, uint fieldId, uint oldCanonId); void OnEnd(); } */ private class IosifAlgorithm { private HeapCanonicalizer heapCanonicalizer; private int heapCount; public IosifAlgorithm(HeapCanonicalizer parent) { heapCanonicalizer = parent; } public void OnStart() { heapCount = 0; } public int CanonId(int parentId, int fieldId, int oldCanonId) { heapCount++; return heapCount; } public void OnEnd() { // nothing - sleep tight } } private class IncrementalAlgorithm { private HeapCanonicalizer heapCanonicalizer; private ArrayList canonTable = ArrayList.Repeat(null, 1024); public int unusedId = 1; public IncrementalAlgorithm(HeapCanonicalizer parent) { heapCanonicalizer = parent; } #if REUSE_CANONS private bool[] seen = new bool[1024]; #endif public void OnStart() { // nothing here } public int CanonId(int parentId, int fieldId, int oldCanonId) { if (parentId >= canonTable.Count) { for (int i = canonTable.Count; i <= parentId; i++) canonTable.Add(null); Debug.Assert(canonTable.Count > parentId); } if (canonTable[parentId] == null) { int[] newFieldArray = new int[4]; newFieldArray.Initialize(); canonTable[parentId] = newFieldArray; } int[] fieldArray = (int[])canonTable[parentId]; if (fieldId >= fieldArray.Length) { int newLength = fieldArray.Length * 2; while (fieldId >= newLength) { newLength *= 2; } int[] newFieldArray = new int[newLength]; Array.Copy(fieldArray, 0, newFieldArray, 0, fieldArray.Length); Array.Clear(newFieldArray, fieldArray.Length, newFieldArray.Length - fieldArray.Length); canonTable[parentId] = newFieldArray; fieldArray = newFieldArray; } if (fieldArray[fieldId] == 0) { #if REUSE_CANONS if (oldCanonId != 0) { #if STATS_INC_FINGERPRINTS heapCanonicalizer.IncCanonIdReuses(); System.Console.WriteLine("{0} canon for {1},{2} (reuse)", oldCanonId, parentId, fieldId); #endif fieldArray[fieldId] = oldCanonId; } else { fieldArray[fieldId] = unusedId++; } #else fieldArray[fieldId] = unusedId++; #endif } #if REUSE_CANONS // The returnId is fieldArray[fieldId] // should ensure that this is not seen in the current state if (fieldArray[fieldId] < seen.Length && seen[fieldArray[fieldId]]) { // mutation fieldArray[fieldId] = unusedId++; #if STATS_INC_FINGERPRINTS System.Console.WriteLine("{0} canon for {1},{2} (mutation)", unusedId-1, parentId, fieldId); heapCanonicalizer.IncCanonIdMutations(); #endif } if (fieldArray[fieldId] >= seen.Length) { int newLength = seen.Length * 2; while (fieldArray[fieldId] >= newLength) { newLength *= 2; } bool[] newSeen = new bool[newLength]; Array.Copy(seen, 0, newSeen, 0, seen.Length); seen = newSeen; } seen[fieldArray[fieldId]] = true; #endif return fieldArray[fieldId]; } public void OnEnd() { #if REUSE_CANONS Array.Clear(seen, 0, seen.Length); #endif } } // #endregion } internal class ArrayQueue { // Queue based on a Array - A slightly faster implementation than the one in standard library // At this point, it is not clear if using ArrayQueue (over ArrayList) buys us anything --- madanm // // objList forms a circular queue from head to tail private Object[] objList; private int head; private int tail; private bool empty; // Class Invariant: // head, tail \in [0 .. objList.Length-1] provided objList.Length != 0 // empty => head == tail // !empty => // head points to the first element of the queue // tail points right after the last element in the queue // #if false void CheckInvariant() { Debug.Assert(objList.Length == 0 || 0 <= head && head <= objList.Length-1); Debug.Assert(objList.Length == 0 || 0 <= tail && tail <= objList.Length-1); Debug.Assert(!empty || head == tail); } #endif private void InitializeQueue(int capacity) { objList = new Object[capacity]; head = 0; tail = 0; empty = (capacity != 0); // if capacity is zero, we are full - otherwise we are empty #if false CheckInvariant(); #endif } private void DoubleCapacity() { Debug.Assert(tail == head && !empty); int newCapacity = objList.Length * 2; if (newCapacity == 0) newCapacity = 4; Object[] newList = new Object[newCapacity]; System.Console.WriteLine("Doubling to {0}", newCapacity); Array.Copy(objList, head, newList, 0, objList.Length - head); if (head != 0) { Array.Copy(objList, 0, newList, objList.Length - head, head); } head = 0; tail = objList.Length; objList = newList; #if false CheckInvariant(); #endif } public ArrayQueue() { InitializeQueue(0); } public ArrayQueue(int capacity) { InitializeQueue(capacity); } #if UNUSED public bool IsEmpty(){return empty;} #endif public void Enqueue(Object obj) { if (tail == head && !empty) { // we are full DoubleCapacity(); } objList[tail] = obj; tail++; if (tail >= objList.Length) { tail = 0; } empty = false; #if false CheckInvariant(); #endif } public Object Dequeue() { if (empty) { throw new InvalidOperationException(); } Object ret = objList[head]; objList[head] = null; head++; if (head >= objList.Length) { head = 0; } if (head == tail) { empty = true; } #if false CheckInvariant(); #endif return ret; } public int Count { get { if (empty) return 0; if (head < tail) return tail - head; else return objList.Length + tail - head; } } } } #endregion
// Prexonite // // Copyright (c) 2014, Christian Klauser // 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. // The names of the 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; using System.Collections.Generic; using System.Diagnostics; using System.Text; using JetBrains.Annotations; using Prexonite.Compiler.Symbolic; using NoDebug = System.Diagnostics.DebuggerNonUserCodeAttribute; namespace Prexonite.Compiler.Ast { public class AstBlock : AstExpr, IList<AstNode>, IAstHasExpressions { #region Construction protected AstBlock(ISourcePosition position, [NotNull] SymbolStore symbols, string uid = null, string prefix = null) : base(position) { if (symbols == null) throw new ArgumentNullException("symbols"); _prefix = (prefix ?? DefaultPrefix) + "\\"; _uid = String.IsNullOrEmpty(uid) ? "\\" + Guid.NewGuid().ToString("N") : uid; _symbols = symbols; } protected AstBlock(ISourcePosition position, AstBlock lexicalScope, string prefix = null, string uid = null) : this(position, _deriveSymbolStore(lexicalScope),uid, prefix) { } private static SymbolStore _deriveSymbolStore(AstBlock parentBlock) { return SymbolStore.Create(parentBlock.Symbols); } #endregion [NotNull] private SymbolStore _symbols; /// <summary> /// Symbol table for the scope of this block. /// </summary> [NotNull] public SymbolStore Symbols { get { return _symbols; } } /// <summary> /// Replaces symbol store backing this scope. Does not affect existing nested scopes! /// </summary> /// <param name="newStore">The new symbol store.</param> internal void _ReplaceSymbols([NotNull] SymbolStore newStore) { _symbols = newStore; } [NotNull] private List<AstNode> _statements = new List<AstNode>(); [NotNull] public List<AstNode> Statements { get { return _statements; } set { if (value == null) throw new ArgumentNullException("value"); _statements = value; } } protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics) { EmitCode(target, false, stackSemantics); } public void EmitCode(CompilerTarget target, bool isTopLevel, StackSemantics stackSemantics) { if (target == null) throw new ArgumentNullException("target", "The compiler target cannot be null"); if (isTopLevel) _tailCallOptimizeTopLevelBlock(); foreach (var node in _statements) { var stmt = node; var expr = stmt as AstExpr; if (expr != null) stmt = _GetOptimizedNode(target, expr); stmt.EmitEffectCode(target); } if(Expression != null) Expression.EmitCode(target, stackSemantics); } #region Tail call optimization private static void tail_call_optimize_expressions_of_nested_block( IAstHasExpressions hasExpressions) { foreach (var expression in hasExpressions.Expressions) { var blockItself = expression as AstBlock; var hasExpressionsItself = expression as IAstHasExpressions; var hasBlocksItself = expression as IAstHasBlocks; if (blockItself != null) blockItself._tailCallOptimizeNestedBlock(); else if (hasExpressionsItself != null) tail_call_optimize_expressions_of_nested_block(hasExpressionsItself); else if (hasBlocksItself != null) _tailCallOptimizeAllNestedBlocksOf(hasBlocksItself); } } private void _tailCallOptimizeNestedBlock() { int i; for (i = 1; i < _statements.Count; i++) { var stmt = _statements[i]; var ret = stmt as AstReturn; var getset = _statements[i - 1] as AstGetSet; var hasBlocks = stmt as IAstHasBlocks; var hasExpressions = stmt as IAstHasExpressions; var blockItself = stmt as AstBlock; if (ret != null && ret.Expression == null && (ret.ReturnVariant == ReturnVariant.Exit || ret.ReturnVariant == ReturnVariant.Continue) && getset != null) { //NOTE: Aggressive TCO disabled //ret.Expression = getset; //Statements.RemoveAt(i--); } else if (blockItself != null) { blockItself._tailCallOptimizeNestedBlock(); } else if (hasBlocks != null) { _tailCallOptimizeAllNestedBlocksOf(hasBlocks); } else if (hasExpressions != null) { tail_call_optimize_expressions_of_nested_block(hasExpressions); } } } private static void _tailCallOptimizeAllNestedBlocksOf(IAstHasBlocks hasBlocks) { foreach (var block in hasBlocks.Blocks) block._tailCallOptimizeNestedBlock(); } private void _tailCallOptimizeTopLevelBlock() { // { GetSetComplex; return; } -> { return GetSetComplex; } _tailCallOptimizeNestedBlock(); AstGetSet getset; if (_statements.Count == 0) return; var lastStmt = _statements[_statements.Count - 1]; AstCondition cond; // { if(cond) block1 else block2 } -> { if(cond) block1' else block2' } if ((cond = lastStmt as AstCondition) != null) { cond.IfBlock._tailCallOptimizeTopLevelBlock(); cond.ElseBlock._tailCallOptimizeTopLevelBlock(); } // { ...; GetSet(); } -> { ...; return GetSet(); } else if ((getset = lastStmt as AstGetSet) != null) { var ret = new AstReturn(getset.File, getset.Line, getset.Column, ReturnVariant.Exit) { Expression = getset }; _statements[_statements.Count - 1] = ret; } } #endregion public virtual bool IsEmpty { get { return Count == 0; } } public virtual bool IsSingleStatement { get { return Count == 1; } } #region IList<AstNode> Members [DebuggerStepThrough] public int IndexOf(AstNode item) { return _statements.IndexOf(item); } [DebuggerStepThrough] public void Insert(int index, AstNode item) { if (item == null) throw new ArgumentNullException("item"); _statements.Insert(index, item); } public void InsertRange(int index, IEnumerable<AstNode> items) { if (items == null) throw new ArgumentNullException("items"); _statements.InsertRange(index, items); } [DebuggerStepThrough] public void RemoveAt(int index) { _statements.RemoveAt(index); } public AstNode this[int index] { [DebuggerStepThrough] get { return _statements[index]; } [DebuggerStepThrough] set { if (value == null) throw new ArgumentNullException("value"); _statements[index] = value; } } #endregion #region ICollection<AstNode> Members [DebuggerStepThrough] public void Add(AstNode item) { if (item == null) throw new ArgumentNullException("item"); _statements.Add(item); } [DebuggerStepThrough] public void AddRange(IEnumerable<AstNode> collection) { if (collection == null) throw new ArgumentNullException("collection"); foreach (var node in collection) { if (node == null) throw new ArgumentException( "AstNode collection may not contain null.", "collection"); } _statements.AddRange(collection); } [DebuggerStepThrough] public void Clear() { _statements.Clear(); } [DebuggerStepThrough] public bool Contains(AstNode item) { if (item == null) throw new ArgumentNullException("item"); return _statements.Contains(item); } [DebuggerStepThrough] public void CopyTo(AstNode[] array, int arrayIndex) { _statements.CopyTo(array, arrayIndex); } public int Count { [DebuggerStepThrough] get { return _statements.Count; } } public bool IsReadOnly { [DebuggerStepThrough] get { return ((IList<AstNode>) _statements).IsReadOnly; } } [DebuggerStepThrough] public bool Remove(AstNode item) { if (item == null) throw new ArgumentNullException("item"); return _statements.Remove(item); } #endregion #region IEnumerable<AstNode> Members [DebuggerStepThrough] public IEnumerator<AstNode> GetEnumerator() { return _statements.GetEnumerator(); } #endregion #region IEnumerable Members [DebuggerStepThrough] IEnumerator IEnumerable.GetEnumerator() { return _statements.GetEnumerator(); } #endregion public override string ToString() { var buffer = new StringBuilder(); foreach (var node in _statements) buffer.AppendFormat("{0}; ", node); if (Expression != null) buffer.AppendFormat(" (return {0})", Expression); return buffer.ToString(); } #region Block labels private readonly string _prefix; private readonly string _uid; public AstExpr Expression; public string Prefix { get { return _prefix.Substring(0, _prefix.Length - 1); } } public string BlockUid { get { return _uid; } } public virtual AstExpr[] Expressions { get { if(Expression == null) return new AstExpr[0]; else return new[] {Expression}; } } public const string DefaultPrefix = "_"; public const string RootBlockName = "root"; public string CreateLabel(string verb) { return String.Concat(_prefix, verb, _uid); } #endregion public override bool TryOptimize(CompilerTarget target, out AstExpr expr) { //Will be optimized after code generation, hopefully if (Expression != null) _OptimizeNode(target, ref Expression); expr = null; return false; } public static AstBlock CreateRootBlock(ISourcePosition position, SymbolStore symbols, string prefix, string uid) { return new AstBlock(position,symbols,uid, prefix); } } }
using System; using Lucene.Net.Documents; namespace Lucene.Net.Index { using Lucene.Net.Randomized.Generators; using Lucene.Net.Search; using NUnit.Framework; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using Occur = Lucene.Net.Search.Occur; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestParallelAtomicReader : LuceneTestCase { private IndexSearcher Parallel_Renamed, Single_Renamed; private Directory Dir, Dir1, Dir2; [Test] public virtual void TestQueries() { Single_Renamed = Single(Random()); Parallel_Renamed = Parallel(Random()); QueryTest(new TermQuery(new Term("f1", "v1"))); QueryTest(new TermQuery(new Term("f1", "v2"))); QueryTest(new TermQuery(new Term("f2", "v1"))); QueryTest(new TermQuery(new Term("f2", "v2"))); QueryTest(new TermQuery(new Term("f3", "v1"))); QueryTest(new TermQuery(new Term("f3", "v2"))); QueryTest(new TermQuery(new Term("f4", "v1"))); QueryTest(new TermQuery(new Term("f4", "v2"))); BooleanQuery bq1 = new BooleanQuery(); bq1.Add(new TermQuery(new Term("f1", "v1")), Occur.MUST); bq1.Add(new TermQuery(new Term("f4", "v1")), Occur.MUST); QueryTest(bq1); Single_Renamed.IndexReader.Dispose(); Single_Renamed = null; Parallel_Renamed.IndexReader.Dispose(); Parallel_Renamed = null; Dir.Dispose(); Dir = null; Dir1.Dispose(); Dir1 = null; Dir2.Dispose(); Dir2 = null; } [Test] public virtual void TestFieldNames() { Directory dir1 = GetDir1(Random()); Directory dir2 = GetDir2(Random()); ParallelAtomicReader pr = new ParallelAtomicReader(SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir1)), SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir2))); FieldInfos fieldInfos = pr.FieldInfos; Assert.AreEqual(4, fieldInfos.Count); Assert.IsNotNull(fieldInfos.FieldInfo("f1")); Assert.IsNotNull(fieldInfos.FieldInfo("f2")); Assert.IsNotNull(fieldInfos.FieldInfo("f3")); Assert.IsNotNull(fieldInfos.FieldInfo("f4")); pr.Dispose(); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestRefCounts1() { Directory dir1 = GetDir1(Random()); Directory dir2 = GetDir2(Random()); AtomicReader ir1, ir2; // close subreaders, ParallelReader will not change refCounts, but close on its own close ParallelAtomicReader pr = new ParallelAtomicReader(ir1 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir1)), ir2 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir2))); // check RefCounts Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); pr.Dispose(); Assert.AreEqual(0, ir1.RefCount); Assert.AreEqual(0, ir2.RefCount); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestRefCounts2() { Directory dir1 = GetDir1(Random()); Directory dir2 = GetDir2(Random()); AtomicReader ir1 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir1)); AtomicReader ir2 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir2)); // don't close subreaders, so ParallelReader will increment refcounts ParallelAtomicReader pr = new ParallelAtomicReader(false, ir1, ir2); // check RefCounts Assert.AreEqual(2, ir1.RefCount); Assert.AreEqual(2, ir2.RefCount); pr.Dispose(); Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); ir1.Dispose(); ir2.Dispose(); Assert.AreEqual(0, ir1.RefCount); Assert.AreEqual(0, ir2.RefCount); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestCloseInnerReader() { Directory dir1 = GetDir1(Random()); AtomicReader ir1 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir1)); // with overlapping ParallelAtomicReader pr = new ParallelAtomicReader(true, new AtomicReader[] { ir1 }, new AtomicReader[] { ir1 }); ir1.Dispose(); try { pr.Document(0); Assert.Fail("ParallelAtomicReader should be already closed because inner reader was closed!"); } #pragma warning disable 168 catch (ObjectDisposedException e) #pragma warning restore 168 { // pass } // noop: pr.Dispose(); dir1.Dispose(); } [Test] public virtual void TestIncompatibleIndexes() { // two documents: Directory dir1 = GetDir1(Random()); // one document only: Directory dir2 = NewDirectory(); IndexWriter w2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document d3 = new Document(); d3.Add(NewTextField("f3", "v1", Field.Store.YES)); w2.AddDocument(d3); w2.Dispose(); AtomicReader ir1 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir1)); AtomicReader ir2 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir2)); try { new ParallelAtomicReader(ir1, ir2); Assert.Fail("didn't get exptected exception: indexes don't have same number of documents"); } #pragma warning disable 168 catch (System.ArgumentException e) #pragma warning restore 168 { // expected exception } try { new ParallelAtomicReader(Random().NextBoolean(), new AtomicReader[] { ir1, ir2 }, new AtomicReader[] { ir1, ir2 }); Assert.Fail("didn't get expected exception: indexes don't have same number of documents"); } #pragma warning disable 168 catch (System.ArgumentException e) #pragma warning restore 168 { // expected exception } // check RefCounts Assert.AreEqual(1, ir1.RefCount); Assert.AreEqual(1, ir2.RefCount); ir1.Dispose(); ir2.Dispose(); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void TestIgnoreStoredFields() { Directory dir1 = GetDir1(Random()); Directory dir2 = GetDir2(Random()); AtomicReader ir1 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir1)); AtomicReader ir2 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir2)); // with overlapping ParallelAtomicReader pr = new ParallelAtomicReader(false, new AtomicReader[] { ir1, ir2 }, new AtomicReader[] { ir1 }); Assert.AreEqual("v1", pr.Document(0).Get("f1")); Assert.AreEqual("v1", pr.Document(0).Get("f2")); Assert.IsNull(pr.Document(0).Get("f3")); Assert.IsNull(pr.Document(0).Get("f4")); // check that fields are there Assert.IsNotNull(pr.GetTerms("f1")); Assert.IsNotNull(pr.GetTerms("f2")); Assert.IsNotNull(pr.GetTerms("f3")); Assert.IsNotNull(pr.GetTerms("f4")); pr.Dispose(); // no stored fields at all pr = new ParallelAtomicReader(false, new AtomicReader[] { ir2 }, new AtomicReader[0]); Assert.IsNull(pr.Document(0).Get("f1")); Assert.IsNull(pr.Document(0).Get("f2")); Assert.IsNull(pr.Document(0).Get("f3")); Assert.IsNull(pr.Document(0).Get("f4")); // check that fields are there Assert.IsNull(pr.GetTerms("f1")); Assert.IsNull(pr.GetTerms("f2")); Assert.IsNotNull(pr.GetTerms("f3")); Assert.IsNotNull(pr.GetTerms("f4")); pr.Dispose(); // without overlapping pr = new ParallelAtomicReader(true, new AtomicReader[] { ir2 }, new AtomicReader[] { ir1 }); Assert.AreEqual("v1", pr.Document(0).Get("f1")); Assert.AreEqual("v1", pr.Document(0).Get("f2")); Assert.IsNull(pr.Document(0).Get("f3")); Assert.IsNull(pr.Document(0).Get("f4")); // check that fields are there Assert.IsNull(pr.GetTerms("f1")); Assert.IsNull(pr.GetTerms("f2")); Assert.IsNotNull(pr.GetTerms("f3")); Assert.IsNotNull(pr.GetTerms("f4")); pr.Dispose(); // no main readers try { new ParallelAtomicReader(true, new AtomicReader[0], new AtomicReader[] { ir1 }); Assert.Fail("didn't get expected exception: need a non-empty main-reader array"); } #pragma warning disable 168 catch (System.ArgumentException iae) #pragma warning restore 168 { // pass } dir1.Dispose(); dir2.Dispose(); } private void QueryTest(Query query) { ScoreDoc[] parallelHits = Parallel_Renamed.Search(query, null, 1000).ScoreDocs; ScoreDoc[] singleHits = Single_Renamed.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(parallelHits.Length, singleHits.Length); for (int i = 0; i < parallelHits.Length; i++) { Assert.AreEqual(parallelHits[i].Score, singleHits[i].Score, 0.001f); Document docParallel = Parallel_Renamed.Doc(parallelHits[i].Doc); Document docSingle = Single_Renamed.Doc(singleHits[i].Doc); Assert.AreEqual(docParallel.Get("f1"), docSingle.Get("f1")); Assert.AreEqual(docParallel.Get("f2"), docSingle.Get("f2")); Assert.AreEqual(docParallel.Get("f3"), docSingle.Get("f3")); Assert.AreEqual(docParallel.Get("f4"), docSingle.Get("f4")); } } // Fields 1-4 indexed together: private IndexSearcher Single(Random random) { Dir = NewDirectory(); IndexWriter w = new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document d1 = new Document(); d1.Add(NewTextField("f1", "v1", Field.Store.YES)); d1.Add(NewTextField("f2", "v1", Field.Store.YES)); d1.Add(NewTextField("f3", "v1", Field.Store.YES)); d1.Add(NewTextField("f4", "v1", Field.Store.YES)); w.AddDocument(d1); Document d2 = new Document(); d2.Add(NewTextField("f1", "v2", Field.Store.YES)); d2.Add(NewTextField("f2", "v2", Field.Store.YES)); d2.Add(NewTextField("f3", "v2", Field.Store.YES)); d2.Add(NewTextField("f4", "v2", Field.Store.YES)); w.AddDocument(d2); w.Dispose(); DirectoryReader ir = DirectoryReader.Open(Dir); return NewSearcher(ir); } // Fields 1 & 2 in one index, 3 & 4 in other, with ParallelReader: private IndexSearcher Parallel(Random random) { Dir1 = GetDir1(random); Dir2 = GetDir2(random); ParallelAtomicReader pr = new ParallelAtomicReader(SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(Dir1)), SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(Dir2))); TestUtil.CheckReader(pr); return NewSearcher(pr); } private Directory GetDir1(Random random) { Directory dir1 = NewDirectory(); IndexWriter w1 = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document d1 = new Document(); d1.Add(NewTextField("f1", "v1", Field.Store.YES)); d1.Add(NewTextField("f2", "v1", Field.Store.YES)); w1.AddDocument(d1); Document d2 = new Document(); d2.Add(NewTextField("f1", "v2", Field.Store.YES)); d2.Add(NewTextField("f2", "v2", Field.Store.YES)); w1.AddDocument(d2); w1.Dispose(); return dir1; } private Directory GetDir2(Random random) { Directory dir2 = NewDirectory(); IndexWriter w2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document d3 = new Document(); d3.Add(NewTextField("f3", "v1", Field.Store.YES)); d3.Add(NewTextField("f4", "v1", Field.Store.YES)); w2.AddDocument(d3); Document d4 = new Document(); d4.Add(NewTextField("f3", "v2", Field.Store.YES)); d4.Add(NewTextField("f4", "v2", Field.Store.YES)); w2.AddDocument(d4); w2.Dispose(); return dir2; } } }
using System; using System.Configuration; using System.Text; using log4net; using WaterOneFlowImpl; using System.Web; using System.Web.Services; using System.Xml.Serialization; using System.IO; using System.Xml; using System.Web.Services.Protocols; using WaterOneFlow.Schema.v1_1; using WaterOneFlow; //using Microsoft.Web.Services3; //using Microsoft.Web.Services3.Addressing; //using Microsoft.Web.Services3.Messaging; using WaterOneFlowImpl.geom; namespace WaterOneFlow.odws { namespace v1_1 { using ConstantsNamespace = WaterOneFlowImpl.v1_1.Constants; using IService = WaterOneFlow.v1_1.IService; public class Config { public static string ODDB() { if (ConfigurationManager.ConnectionStrings["ODDB"]!= null) { return ConfigurationManager.ConnectionStrings["ODDB"].ConnectionString; } else { return null; } } } [WebService(Name = WsDescriptions.WsDefaultName, Namespace = ConstantsNamespace.WS_NAMSPACE, Description = WsDescriptions.SvcDevelopementalWarning + WsDescriptions.WsDefaultDescription)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //[SoapActor("*")] public class Service : WebService, IService { //protected ODService ODws; protected CustomService ODws; private Boolean useODForValues; private Boolean requireAuthToken; private static readonly ILog log = LogManager.GetLogger(typeof(Service)); private static readonly ILog queryLog = LogManager.GetLogger("QueryLog"); public Service() { //log4net.Util.LogLog.InternalDebugging = true; ODws = new CustomService(this.Context);//INFO we can extend this for other service types try { useODForValues = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]); } catch (Exception e) { String error = "Missing or invalid value for UseODForValues. Must be true or false"; log.Fatal(error); throw new SoapException("Invalid Server Configuration. " + error, new XmlQualifiedName(SoapExceptionGenerator.ServerError)); } try { requireAuthToken = Boolean.Parse(ConfigurationManager.AppSettings["requireAuthToken"]); } catch (Exception e) { String error = "Missing or invalid value for requireAuthToken. Must be true or false"; log.Fatal(error); throw new SoapException(error, new XmlQualifiedName(SoapExceptionGenerator.ServerError)); } } #region IService Members public string GetSites(string[] SiteNumbers, String authToken) { SiteInfoResponseType aSite = GetSitesObject(SiteNumbers, authToken); string xml = WSUtils.ConvertToXml(aSite, typeof(SiteInfoResponseType)); return xml; } public virtual string GetSiteInfo(string SiteNumber, String authToken) { SiteInfoResponseType aSite = GetSiteInfoObject(SiteNumber, authToken); string xml = WSUtils.ConvertToXml(aSite, typeof(SiteInfoResponseType)); return xml; } public string GetVariableInfo(string variable, String authToken) { VariablesResponseType aVType = GetVariableInfoObject(variable, authToken); string xml = WSUtils.ConvertToXml(aVType, typeof(VariablesResponseType)); return xml; } public SiteInfoResponseType GetSitesObject(string[] site, String authToken) { //GlobalClass.WaterAuth.SitesServiceAllowed(Context, authToken); try { return ODws.GetSites(site); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public virtual SiteInfoResponseType GetSiteInfoObject(string site, String authToken) { //GlobalClass.WaterAuth.SiteInfoServiceAllowed(Context, authToken); try { return ODws.GetSiteInfo(site); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public VariablesResponseType GetVariableInfoObject(string variable, String authToken) { //GlobalClass.WaterAuth.VariableInfoServiceAllowed(Context, authToken); try { return ODws.GetVariableInfo(variable); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public virtual string GetValues( string location, string variable, string startDate, string endDate, String authToken) { TimeSeriesResponseType aSite = GetValuesObject(location, variable, startDate, endDate, null); return WSUtils.ConvertToXml(aSite, typeof(TimeSeriesResponseType)); } public virtual TimeSeriesResponseType GetValuesObject( string location, string variable, string startDate, string endDate, String authToken) { //GlobalClass.WaterAuth.DataValuesServiceAllowed(Context, authToken); if (!useODForValues) throw new SoapException("GetValues implemented external to this service. Call GetSiteInfo, and SeriesCatalog includes the service Wsdl for GetValues. Attribute:serviceWsdl on Element:seriesCatalog XPath://seriesCatalog/[@serviceWsdl]", new XmlQualifiedName("ServiceException")); try { return ODws.GetValues(location, variable, startDate, endDate); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public SiteInfoResponseType GetSiteInfoMultpleObject(string[] site, string authToken) { //GlobalClass.WaterAuth.SiteInfoServiceAllowed(Context, authToken); try { return ODws.GetSiteInfo(site, true); } catch (Exception we) { log.Warn(we.Message); throw SoapExceptionGenerator.WOFExceptionToSoapException(we); } } public SiteInfoResponseType GetSitesByBoxObject(float west, float south, float east, float north, bool IncludeSeries, string authToken) { //GlobalClass.WaterAuth.SiteInfoServiceAllowed(Context, authToken); return ODws.GetSitesInBox( west,south,east, north, IncludeSeries ); } public TimeSeriesResponseType GetValuesForASiteObject(string site, string StartDate, string EndDate, string authToken) { //GlobalClass.WaterAuth.DataValuesServiceAllowed(Context, authToken); return ODws.GetValuesForASite(site, StartDate, EndDate); } public TimeSeriesResponseType GetValuesByBoxObject(string variable, string StartDate, string EndDate, float west, float south, float east, float north, string authToken) { throw new NotImplementedException(); } public string GetVariables(String authToken) { VariablesResponseType aVType = GetVariableInfoObject(null, authToken); string xml = WSUtils.ConvertToXml(aVType, typeof(VariablesResponseType)); return xml; } public VariablesResponseType GetVariablesObject(String authToken) { return GetVariableInfoObject(null, authToken); } public string GetAuthToken(String userName, String password) { //AuthTokenResponseType token = GetAuthTokenObject(userName, password); //string xml = WSUtils.ConvertToXml(token, typeof(AuthTokenResponseType)); //string xml2 = xml.Replace("sitesResponse", "AuthTokenResponse"); //return string.Empty; throw new SoapException("Invalid user name or password", new XmlQualifiedName("authToken")); } public XmlDocument GetAuthTokenObject(String userName, String password) { return new XmlDocument(); //return ODws.GetAuthToken(userName, password); } #endregion } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Description; namespace System.ServiceModel.Dispatcher { internal class ProxyOperationRuntime { private readonly IClientMessageFormatter _formatter; private readonly bool _isInitiating; private readonly bool _isOneWay; private readonly bool _isSessionOpenNotificationEnabled; private readonly string _name; private readonly IParameterInspector[] _parameterInspectors; private readonly IClientFaultFormatter _faultFormatter; private readonly ImmutableClientRuntime _parent; private bool _serializeRequest; private bool _deserializeReply; private string _action; private string _replyAction; private MethodInfo _beginMethod; private MethodInfo _syncMethod; private MethodInfo _taskMethod; private ParameterInfo[] _inParams; private ParameterInfo[] _outParams; private ParameterInfo[] _endOutParams; private ParameterInfo _returnParam; internal ProxyOperationRuntime(ClientOperation operation, ImmutableClientRuntime parent) { if (operation == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation"); if (parent == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent"); _parent = parent; _formatter = operation.Formatter; _isInitiating = operation.IsInitiating; _isOneWay = operation.IsOneWay; _isSessionOpenNotificationEnabled = operation.IsSessionOpenNotificationEnabled; _name = operation.Name; _parameterInspectors = EmptyArray<IParameterInspector>.ToArray(operation.ParameterInspectors); _faultFormatter = operation.FaultFormatter; _serializeRequest = operation.SerializeRequest; _deserializeReply = operation.DeserializeReply; _action = operation.Action; _replyAction = operation.ReplyAction; _beginMethod = operation.BeginMethod; _syncMethod = operation.SyncMethod; _taskMethod = operation.TaskMethod; this.TaskTResult = operation.TaskTResult; if (_beginMethod != null) { _inParams = ServiceReflector.GetInputParameters(_beginMethod, true); if (_syncMethod != null) { _outParams = ServiceReflector.GetOutputParameters(_syncMethod, false); } else { _outParams = Array.Empty<ParameterInfo>(); } _endOutParams = ServiceReflector.GetOutputParameters(operation.EndMethod, true); _returnParam = operation.EndMethod.ReturnParameter; } else if (_syncMethod != null) { _inParams = ServiceReflector.GetInputParameters(_syncMethod, false); _outParams = ServiceReflector.GetOutputParameters(_syncMethod, false); _returnParam = _syncMethod.ReturnParameter; } if (_formatter == null && (_serializeRequest || _deserializeReply)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientRuntimeRequiresFormatter0, _name))); } } internal string Action { get { return _action; } } internal IClientFaultFormatter FaultFormatter { get { return _faultFormatter; } } internal bool IsInitiating { get { return _isInitiating; } } internal bool IsOneWay { get { return _isOneWay; } } internal bool IsSessionOpenNotificationEnabled { get { return _isSessionOpenNotificationEnabled; } } internal string Name { get { return _name; } } internal ImmutableClientRuntime Parent { get { return _parent; } } internal string ReplyAction { get { return _replyAction; } } internal bool DeserializeReply { get { return _deserializeReply; } } internal bool SerializeRequest { get { return _serializeRequest; } } internal Type TaskTResult { get; set; } internal void AfterReply(ref ProxyRpc rpc) { if (!_isOneWay) { Message reply = rpc.Reply; if (_deserializeReply) { if (WcfEventSource.Instance.ClientFormatterDeserializeReplyStartIsEnabled()) { WcfEventSource.Instance.ClientFormatterDeserializeReplyStart(rpc.EventTraceActivity); } rpc.ReturnValue = _formatter.DeserializeReply(reply, rpc.OutputParameters); if (WcfEventSource.Instance.ClientFormatterDeserializeReplyStopIsEnabled()) { WcfEventSource.Instance.ClientFormatterDeserializeReplyStop(rpc.EventTraceActivity); } } else { rpc.ReturnValue = reply; } int offset = _parent.ParameterInspectorCorrelationOffset; try { for (int i = _parameterInspectors.Length - 1; i >= 0; i--) { _parameterInspectors[i].AfterCall(_name, rpc.OutputParameters, rpc.ReturnValue, rpc.Correlation[offset + i]); if (WcfEventSource.Instance.ClientParameterInspectorAfterCallInvokedIsEnabled()) { WcfEventSource.Instance.ClientParameterInspectorAfterCallInvoked(rpc.EventTraceActivity, _parameterInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } if (_parent.ValidateMustUnderstand) { Collection<MessageHeaderInfo> headersNotUnderstood = reply.Headers.GetHeadersNotUnderstood(); if (headersNotUnderstood != null && headersNotUnderstood.Count > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.SFxHeaderNotUnderstood, headersNotUnderstood[0].Name, headersNotUnderstood[0].Namespace))); } } } } internal void BeforeRequest(ref ProxyRpc rpc) { int offset = _parent.ParameterInspectorCorrelationOffset; try { for (int i = 0; i < _parameterInspectors.Length; i++) { rpc.Correlation[offset + i] = _parameterInspectors[i].BeforeCall(_name, rpc.InputParameters); if (WcfEventSource.Instance.ClientParameterInspectorBeforeCallInvokedIsEnabled()) { WcfEventSource.Instance.ClientParameterInspectorBeforeCallInvoked(rpc.EventTraceActivity, _parameterInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } if (_serializeRequest) { if (WcfEventSource.Instance.ClientFormatterSerializeRequestStartIsEnabled()) { WcfEventSource.Instance.ClientFormatterSerializeRequestStart(rpc.EventTraceActivity); } rpc.Request = _formatter.SerializeRequest(rpc.MessageVersion, rpc.InputParameters); if (WcfEventSource.Instance.ClientFormatterSerializeRequestStopIsEnabled()) { WcfEventSource.Instance.ClientFormatterSerializeRequestStop(rpc.EventTraceActivity); } } else { if (rpc.InputParameters[0] == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxProxyRuntimeMessageCannotBeNull, _name))); } rpc.Request = (Message)rpc.InputParameters[0]; if (!IsValidAction(rpc.Request, Action)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidRequestAction, this.Name, rpc.Request.Headers.Action ?? "{NULL}", this.Action))); } } internal static object GetDefaultParameterValue(Type parameterType) { return (parameterType.IsValueType() && parameterType != typeof(void)) ? Activator.CreateInstance(parameterType) : null; } internal bool IsSyncCall(MethodCall methodCall) { if (_syncMethod == null) { return false; } Contract.Assert(methodCall != null); Contract.Assert(methodCall.MethodBase != null); return methodCall.MethodBase.Equals(_syncMethod); } internal bool IsBeginCall(MethodCall methodCall) { if (_beginMethod == null) { return false; } Contract.Assert(methodCall != null); Contract.Assert(methodCall.MethodBase != null); return methodCall.MethodBase.Equals(_beginMethod); } internal bool IsTaskCall(MethodCall methodCall) { if (_taskMethod == null) { return false; } Contract.Assert(methodCall != null); Contract.Assert(methodCall.MethodBase != null); return methodCall.MethodBase.Equals(_taskMethod); } internal object[] MapSyncInputs(MethodCall methodCall, out object[] outs) { if (_outParams.Length == 0) { outs = Array.Empty<object>(); } else { outs = new object[_outParams.Length]; } if (_inParams.Length == 0) return Array.Empty<object>(); return methodCall.Args; } internal object[] MapAsyncBeginInputs(MethodCall methodCall, out AsyncCallback callback, out object asyncState) { object[] ins; if (_inParams.Length == 0) { ins = Array.Empty<object>(); } else { ins = new object[_inParams.Length]; } object[] args = methodCall.Args; for (int i = 0; i < ins.Length; i++) { ins[i] = args[_inParams[i].Position]; } callback = args[methodCall.Args.Length - 2] as AsyncCallback; asyncState = args[methodCall.Args.Length - 1]; return ins; } internal void MapAsyncEndInputs(MethodCall methodCall, out IAsyncResult result, out object[] outs) { outs = new object[_endOutParams.Length]; result = methodCall.Args[methodCall.Args.Length - 1] as IAsyncResult; } internal object[] MapSyncOutputs(MethodCall methodCall, object[] outs, ref object ret) { return MapOutputs(_outParams, methodCall, outs, ref ret); } internal object[] MapAsyncOutputs(MethodCall methodCall, object[] outs, ref object ret) { return MapOutputs(_endOutParams, methodCall, outs, ref ret); } private object[] MapOutputs(ParameterInfo[] parameters, MethodCall methodCall, object[] outs, ref object ret) { if (ret == null && _returnParam != null) { ret = GetDefaultParameterValue(TypeLoader.GetParameterType(_returnParam)); } if (parameters.Length == 0) { return null; } object[] args = methodCall.Args; for (int i = 0; i < parameters.Length; i++) { if (outs[i] == null) { // the RealProxy infrastructure requires a default value for value types args[parameters[i].Position] = GetDefaultParameterValue(TypeLoader.GetParameterType(parameters[i])); } else { args[parameters[i].Position] = outs[i]; } } return args; } static internal bool IsValidAction(Message message, string action) { if (message == null) { return false; } if (message.IsFault) { return true; } if (action == MessageHeaders.WildcardAction) { return true; } return (String.CompareOrdinal(message.Headers.Action, action) == 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** Purpose: This class will encapsulate a short and provide an ** Object representation of it. ** ** ===========================================================*/ using System.Globalization; using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System { // Wrapper for unsigned 16 bit integers. [Serializable] [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct UInt16 : IComparable, IFormattable, IConvertible , IComparable<UInt16>, IEquatable<UInt16> { private ushort m_value; // Do not rename (binary serialization) public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt16, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt16) { return ((int)m_value - (int)(((UInt16)value).m_value)); } throw new ArgumentException(SR.Arg_MustBeUInt16); } public int CompareTo(UInt16 value) { return ((int)m_value - (int)value); } public override bool Equals(Object obj) { if (!(obj is UInt16)) { return false; } return m_value == ((UInt16)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(UInt16 obj) { return m_value == obj; } // Returns a HashCode for the UInt16 public override int GetHashCode() { return (int)m_value; } // Converts the current value to a String in base-10 with no extra padding. public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static ushort Parse(String s) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ushort Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static ushort Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static ushort Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static ushort Parse(String s, NumberStyles style, NumberFormatInfo info) { uint i = 0; try { i = Number.ParseUInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_UInt16, e); } if (i > MaxValue) throw new OverflowException(SR.Overflow_UInt16); return (ushort)i; } [CLSCompliant(false)] public static bool TryParse(String s, out UInt16 result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out UInt16 result) { result = 0; UInt32 i; if (!Number.TryParseUInt32(s, style, info, out i)) { return false; } if (i > MaxValue) { return false; } result = (UInt16)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt16; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return m_value; } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Types { [PythonType("dictproxy")] public class DictProxy : IDictionary, IEnumerable, IDictionary<object, object> { private readonly PythonType/*!*/ _dt; public DictProxy(PythonType/*!*/ dt) { Debug.Assert(dt != null); _dt = dt; } #region Python Public API Surface public int __len__(CodeContext context) { return _dt.GetMemberDictionary(context, false).Count; } public bool __contains__(CodeContext/*!*/ context, object value) { object dummy; return TryGetValue(context, value, out dummy); } public string/*!*/ __str__(CodeContext/*!*/ context) { return DictionaryOps.__repr__(context, this); } public object get(CodeContext/*!*/ context, [NotNull]object k, [DefaultParameterValue(null)]object d) { object res; if (!TryGetValue(context, k, out res)) { res = d; } return res; } public object keys(CodeContext context) { return _dt.GetMemberDictionary(context, false).keys(); } public object values(CodeContext context) { return _dt.GetMemberDictionary(context, false).values(); } public List items(CodeContext context) { return _dt.GetMemberDictionary(context, false).items(); } public PythonDictionary copy(CodeContext/*!*/ context) { return new PythonDictionary(context, this); } public IEnumerator iteritems(CodeContext/*!*/ context) { return new DictionaryItemEnumerator(_dt.GetMemberDictionary(context, false)._storage); } public IEnumerator iterkeys(CodeContext/*!*/ context) { return new DictionaryKeyEnumerator(_dt.GetMemberDictionary(context, false)._storage); } public IEnumerator itervalues(CodeContext/*!*/ context) { return new DictionaryValueEnumerator(_dt.GetMemberDictionary(context, false)._storage); } #endregion #region Object overrides public override bool Equals(object obj) { DictProxy proxy = obj as DictProxy; if (proxy == null) return false; return proxy._dt == _dt; } public override int GetHashCode() { return ~_dt.GetHashCode(); } #endregion #region IDictionary Members public object this[object key] { get { return GetIndex(DefaultContext.Default, key); } [PythonHidden] set { throw PythonOps.TypeError("cannot assign to dictproxy"); } } bool IDictionary.Contains(object key) { return __contains__(DefaultContext.Default, key); } #endregion #region IEnumerable Members System.Collections.IEnumerator IEnumerable.GetEnumerator() { return DictionaryOps.iterkeys(_dt.GetMemberDictionary(DefaultContext.Default, false)); } #endregion #region IDictionary Members [PythonHidden] public void Add(object key, object value) { this[key] = value; } [PythonHidden] public void Clear() { throw new InvalidOperationException("dictproxy is read-only"); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new PythonDictionary.DictEnumerator(_dt.GetMemberDictionary(DefaultContext.Default, false).GetEnumerator()); } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { ICollection<object> res = _dt.GetMemberDictionary(DefaultContext.Default, false).Keys; ICollection coll = res as ICollection; if (coll != null) { return coll; } return new List<object>(res); } } void IDictionary.Remove(object key) { throw new InvalidOperationException("dictproxy is read-only"); } ICollection IDictionary.Values { get { List<object> res = new List<object>(); foreach (KeyValuePair<object, object> kvp in _dt.GetMemberDictionary(DefaultContext.Default, false)) { res.Add(kvp.Value); } return res; } } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { foreach (DictionaryEntry de in (IDictionary)this) { array.SetValue(de, index++); } } int ICollection.Count { get { return __len__(DefaultContext.Default); } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } #endregion #region IDictionary<object,object> Members bool IDictionary<object, object>.ContainsKey(object key) { return __contains__(DefaultContext.Default, key); } ICollection<object> IDictionary<object, object>.Keys { get { return _dt.GetMemberDictionary(DefaultContext.Default, false).Keys; } } bool IDictionary<object, object>.Remove(object key) { throw new InvalidOperationException("dictproxy is read-only"); } bool IDictionary<object, object>.TryGetValue(object key, out object value) { return TryGetValue(DefaultContext.Default, key, out value); } ICollection<object> IDictionary<object, object>.Values { get { return _dt.GetMemberDictionary(DefaultContext.Default, false).Values; } } #endregion #region ICollection<KeyValuePair<object,object>> Members void ICollection<KeyValuePair<object, object>>.Add(KeyValuePair<object, object> item) { this[item.Key] = item.Value; } bool ICollection<KeyValuePair<object, object>>.Contains(KeyValuePair<object, object> item) { return __contains__(DefaultContext.Default, item.Key); } void ICollection<KeyValuePair<object, object>>.CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) { foreach (KeyValuePair<object, object> de in (IEnumerable<KeyValuePair<object, object>>)this) { array.SetValue(de, arrayIndex++); } } int ICollection<KeyValuePair<object, object>>.Count { get { return __len__(DefaultContext.Default); } } bool ICollection<KeyValuePair<object, object>>.IsReadOnly { get { return true; } } bool ICollection<KeyValuePair<object, object>>.Remove(KeyValuePair<object, object> item) { return ((IDictionary<object, object>)this).Remove(item.Key); } #endregion #region IEnumerable<KeyValuePair<object,object>> Members IEnumerator<KeyValuePair<object, object>> IEnumerable<KeyValuePair<object, object>>.GetEnumerator() { return _dt.GetMemberDictionary(DefaultContext.Default, false).GetEnumerator(); } #endregion #region Internal implementation details private object GetIndex(CodeContext context, object index) { string strIndex = index as string; if (strIndex != null) { PythonTypeSlot dts; if (_dt.TryLookupSlot(context, strIndex, out dts)) { PythonTypeUserDescriptorSlot uds = dts as PythonTypeUserDescriptorSlot; if (uds != null) { return uds.Value; } return dts; } } throw PythonOps.KeyError(index.ToString()); } private bool TryGetValue(CodeContext/*!*/ context, object key, out object value) { string strIndex = key as string; if (strIndex != null) { PythonTypeSlot dts; if (_dt.TryLookupSlot(context, strIndex, out dts)) { PythonTypeUserDescriptorSlot uds = dts as PythonTypeUserDescriptorSlot; if (uds != null) { value = uds.Value; return true; } value = dts; return true; } } value = null; return false; } internal PythonType Type { get { return _dt; } } #endregion } }
/* * Velcro Physics: * Copyright (c) 2017 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using Microsoft.Xna.Framework; using VelcroPhysics.Collision.Broadphase; using VelcroPhysics.Collision.ContactSystem; using VelcroPhysics.Collision.Filtering; using VelcroPhysics.Collision.Handlers; using VelcroPhysics.Collision.RayCast; using VelcroPhysics.Collision.Shapes; using VelcroPhysics.Shared; using VelcroPhysics.Templates; namespace VelcroPhysics.Dynamics { /// <summary> /// A fixture is used to attach a Shape to a body for collision detection. A fixture /// inherits its transform from its parent. Fixtures hold additional non-geometric data /// such as friction, collision filters, etc. /// Fixtures are created via Body.CreateFixture. /// Warning: You cannot reuse fixtures. /// </summary> public class Fixture { internal Category _collidesWith; internal Category _collisionCategories; internal short _collisionGroup; private float _friction; private bool _isSensor; private float _restitution; /// <summary> /// Fires after two shapes has collided and are solved. This gives you a chance to get the impact force. /// </summary> public AfterCollisionHandler AfterCollision; /// <summary> /// Fires when two fixtures are close to each other. /// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs. /// </summary> public BeforeCollisionHandler BeforeCollision; public Category IgnoreCCDWith; /// <summary> /// Fires when two shapes collide and a contact is created between them. /// Note that the first fixture argument is always the fixture that the delegate is subscribed to. /// </summary> public OnCollisionHandler OnCollision; /// <summary> /// Fires when two shapes separate and a contact is removed between them. /// Note: This can in some cases be called multiple times, as a fixture can have multiple contacts. /// Note The first fixture argument is always the fixture that the delegate is subscribed to. /// </summary> public OnSeparationHandler OnSeparation; public FixtureProxy[] Proxies; public int ProxyCount; internal Fixture() { _collisionCategories = Settings.DefaultFixtureCollisionCategories; _collidesWith = Settings.DefaultFixtureCollidesWith; _collisionGroup = 0; IgnoreCCDWith = Settings.DefaultFixtureIgnoreCCDWith; } internal Fixture(Body body, FixtureTemplate template) : this() { UserData = template.UserData; Friction = template.Friction; Restitution = template.Restitution; Body = body; IsSensor = template.IsSensor; Shape = template.Shape.Clone(); RegisterFixture(); } /// <summary> /// Defaults to 0 /// If Settings.UseFPECollisionCategories is set to false: /// Collision groups allow a certain group of objects to never collide (negative) /// or always collide (positive). Zero means no collision group. Non-zero group /// filtering always wins against the mask bits. /// If Settings.UseFPECollisionCategories is set to true: /// If 2 fixtures are in the same collision group, they will not collide. /// </summary> public short CollisionGroup { set { if (_collisionGroup == value) return; _collisionGroup = value; Refilter(); } get { return _collisionGroup; } } /// <summary> /// Defaults to Category.All /// The collision mask bits. This states the categories that this /// fixture would accept for collision. /// Use Settings.UseFPECollisionCategories to change the behavior. /// </summary> public Category CollidesWith { get { return _collidesWith; } set { if (_collidesWith == value) return; _collidesWith = value; Refilter(); } } /// <summary> /// The collision categories this fixture is a part of. /// If Settings.UseFPECollisionCategories is set to false: /// Defaults to Category.Cat1 /// If Settings.UseFPECollisionCategories is set to true: /// Defaults to Category.All /// </summary> public Category CollisionCategories { get { return _collisionCategories; } set { if (_collisionCategories == value) return; _collisionCategories = value; Refilter(); } } /// <summary> /// Get the child Shape. You can modify the child Shape, however you should not change the /// number of vertices because this will crash some collision caching mechanisms. /// </summary> /// <value>The shape.</value> public Shape Shape { get; internal set; } /// <summary> /// Gets or sets a value indicating whether this fixture is a sensor. /// </summary> /// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value> public bool IsSensor { get { return _isSensor; } set { if (Body != null) Body.Awake = true; _isSensor = value; } } /// <summary> /// Get the parent body of this fixture. This is null if the fixture is not attached. /// </summary> /// <value>The body.</value> public Body Body { get; internal set; } /// <summary> /// Set the user data. Use this to store your application specific data. /// </summary> /// <value>The user data.</value> public object UserData { get; set; } /// <summary> /// Set the coefficient of friction. This will _not_ change the friction of /// existing contacts. /// </summary> /// <value>The friction.</value> public float Friction { get { return _friction; } set { Debug.Assert(!float.IsNaN(value)); _friction = value; } } /// <summary> /// Set the coefficient of restitution. This will not change the restitution of /// existing contacts. /// </summary> /// <value>The restitution.</value> public float Restitution { get { return _restitution; } set { Debug.Assert(!float.IsNaN(value)); _restitution = value; } } /// <summary> /// Gets a unique ID for this fixture. /// </summary> /// <value>The fixture id.</value> public int FixtureId { get; internal set; } /// <summary> /// Contacts are persistent and will keep being persistent unless they are /// flagged for filtering. /// This methods flags all contacts associated with the body for filtering. /// </summary> private void Refilter() { // Flag associated contacts for filtering. ContactEdge edge = Body.ContactList; while (edge != null) { Contact contact = edge.Contact; Fixture fixtureA = contact.FixtureA; Fixture fixtureB = contact.FixtureB; if (fixtureA == this || fixtureB == this) { contact._flags |= ContactFlags.FilterFlag; } edge = edge.Next; } World world = Body._world; if (world == null) { return; } // Touch each proxy so that new pairs may be created IBroadPhase broadPhase = world.ContactManager.BroadPhase; for (int i = 0; i < ProxyCount; ++i) { broadPhase.TouchProxy(Proxies[i].ProxyId); } } private void RegisterFixture() { // Reserve proxy space Proxies = new FixtureProxy[Shape.ChildCount]; ProxyCount = 0; if (Body.Enabled) { IBroadPhase broadPhase = Body._world.ContactManager.BroadPhase; CreateProxies(broadPhase, ref Body._xf); } Body.FixtureList.Add(this); // Adjust mass properties if needed. if (Shape._density > 0.0f) { Body.ResetMassData(); } // Let the world know we have a new fixture. This will cause new contacts // to be created at the beginning of the next time step. Body._world._worldHasNewFixture = true; //Velcro: Added event Body._world.FixtureAdded?.Invoke(this); } /// <summary> /// Test a point for containment in this fixture. /// </summary> /// <param name="point">A point in world coordinates.</param> /// <returns></returns> public bool TestPoint(ref Vector2 point) { return Shape.TestPoint(ref Body._xf, ref point); } /// <summary> /// Cast a ray against this Shape. /// </summary> /// <param name="output">The ray-cast results.</param> /// <param name="input">The ray-cast input parameters.</param> /// <param name="childIndex">Index of the child.</param> /// <returns></returns> public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex) { return Shape.RayCast(ref input, ref Body._xf, childIndex, out output); } /// <summary> /// Get the fixture's AABB. This AABB may be enlarge and/or stale. /// If you need a more accurate AABB, compute it using the Shape and /// the body transform. /// </summary> /// <param name="aabb">The AABB.</param> /// <param name="childIndex">Index of the child.</param> public void GetAABB(out AABB aabb, int childIndex) { Debug.Assert(0 <= childIndex && childIndex < ProxyCount); aabb = Proxies[childIndex].AABB; } internal void Destroy() { // The proxies must be destroyed before calling this. Debug.Assert(ProxyCount == 0); // Free the proxy array. Proxies = null; Shape = null; //Velcro: We set the userdata to null here to help prevent bugs related to stale references in GC UserData = null; BeforeCollision = null; OnCollision = null; OnSeparation = null; AfterCollision = null; Body._world.FixtureRemoved?.Invoke(this); Body._world.FixtureAdded = null; Body._world.FixtureRemoved = null; OnSeparation = null; OnCollision = null; } // These support body activation/deactivation. internal void CreateProxies(IBroadPhase broadPhase, ref Transform xf) { Debug.Assert(ProxyCount == 0); // Create proxies in the broad-phase. ProxyCount = Shape.ChildCount; for (int i = 0; i < ProxyCount; ++i) { FixtureProxy proxy = new FixtureProxy(); Shape.ComputeAABB(ref xf, i, out proxy.AABB); proxy.Fixture = this; proxy.ChildIndex = i; //Velcro note: This line needs to be after the previous two because FixtureProxy is a struct proxy.ProxyId = broadPhase.AddProxy(ref proxy); Proxies[i] = proxy; } } internal void DestroyProxies(IBroadPhase broadPhase) { // Destroy proxies in the broad-phase. for (int i = 0; i < ProxyCount; ++i) { broadPhase.RemoveProxy(Proxies[i].ProxyId); Proxies[i].ProxyId = -1; } ProxyCount = 0; } internal void Synchronize(IBroadPhase broadPhase, ref Transform transform1, ref Transform transform2) { if (ProxyCount == 0) { return; } for (int i = 0; i < ProxyCount; ++i) { FixtureProxy proxy = Proxies[i]; // Compute an AABB that covers the swept Shape (may miss some rotation effect). AABB aabb1, aabb2; Shape.ComputeAABB(ref transform1, proxy.ChildIndex, out aabb1); Shape.ComputeAABB(ref transform2, proxy.ChildIndex, out aabb2); proxy.AABB.Combine(ref aabb1, ref aabb2); Vector2 displacement = transform2.p - transform1.p; broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement); } } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Orleans.Serialization; using Orleans.CodeGeneration; namespace Orleans.Runtime { /// <summary> /// This is the base class for all typed grain references. /// </summary> [Serializable] public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable { private readonly string genericArguments; private readonly GuidId observerId; [NonSerialized] private static readonly TraceLogger logger = TraceLogger.GetLogger("GrainReference", TraceLogger.LoggerType.Runtime); [NonSerialized] private const bool USE_DEBUG_CONTEXT = true; [NonSerialized] private const bool USE_DEBUG_CONTEXT_PARAMS = false; [NonSerialized] private readonly bool isUnordered = false; internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } } internal bool IsObserverReference { get { return GrainId.IsClient; } } internal GuidId ObserverId { get { return observerId; } } private bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } } internal GrainId GrainId { get; private set; } /// <summary> /// Called from generated code. /// </summary> protected internal readonly SiloAddress SystemTargetSilo; /// <summary> /// Whether the runtime environment for system targets has been initialized yet. /// Called from generated code. /// </summary> protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } } internal bool IsUnordered { get { return isUnordered; } } #region Constructors /// <summary> /// Constructs a reference to the grain with the specified Id. /// </summary> /// <param name="grainId">The Id of the grain to refer to.</param> private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId) { GrainId = grainId; genericArguments = genericArgument; SystemTargetSilo = systemTargetSilo; this.observerId = observerId; if (String.IsNullOrEmpty(genericArgument)) { genericArguments = null; // always keep it null instead of empty. } // SystemTarget checks if (grainId.IsSystemTarget && systemTargetSilo==null) { throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId)); } if (grainId.IsSystemTarget && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsSystemTarget && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument"); } if (!grainId.IsSystemTarget && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo"); } // ObserverId checks if (grainId.IsClient && observerId == null) { throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId)); } if (grainId.IsClient && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsClient && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument"); } if (!grainId.IsClient && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId"); } isUnordered = GetUnordered(); } /// <summary> /// Constructs a copy of a grain reference. /// </summary> /// <param name="other">The reference to copy.</param> protected GrainReference(GrainReference other) : this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId) { } #endregion #region Instance creator factory functions /// <summary> /// Constructs a reference to the grain with the specified ID. /// </summary> /// <param name="grainId">The ID of the grain to refer to.</param> internal static GrainReference FromGrainId(GrainId grainId, string genericArguments = null, SiloAddress systemTargetSilo = null) { return new GrainReference(grainId, genericArguments, systemTargetSilo, null); } internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId) { return new GrainReference(grainId, null, null, observerId); } /// <summary> /// Called from generated code. /// </summary> public static Task<GrainReference> CreateObjectReference(IAddressable o, IGrainMethodInvoker invoker) { return Task.FromResult(RuntimeClient.Current.CreateObjectReference(o, invoker)); } /// <summary> /// Called from generated code. /// </summary> public static Task DeleteObjectReference(IAddressable observer) { RuntimeClient.Current.DeleteObjectReference(observer); return TaskDone.Done; } #endregion /// <summary> /// Tests this reference for equality to another object. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="obj">The object to test for equality against this reference.</param> /// <returns><c>true</c> if the object is equal to this reference.</returns> public override bool Equals(object obj) { return Equals(obj as GrainReference); } public bool Equals(GrainReference other) { if (other == null) return false; if (genericArguments != other.genericArguments) return false; if (!GrainId.Equals(other.GrainId)) { return false; } if (IsSystemTarget) { return Equals(SystemTargetSilo, other.SystemTargetSilo); } if (IsObserverReference) { return observerId.Equals(other.observerId); } return true; } /// <summary> Calculates a hash code for a grain reference. </summary> public override int GetHashCode() { int hash = GrainId.GetHashCode(); if (IsSystemTarget) { hash = hash ^ SystemTargetSilo.GetHashCode(); } if (IsObserverReference) { hash = hash ^ observerId.GetHashCode(); } return hash; } /// <summary>Get a uniform hash code for this grain reference.</summary> public uint GetUniformHashCode() { // GrainId already includes the hashed type code for generic arguments. return GrainId.GetUniformHashCode(); } /// <summary> /// Compares two references for equality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns> public static bool operator ==(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) == null; return reference1.Equals(reference2); } /// <summary> /// Compares two references for inequality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns> public static bool operator !=(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) != null; return !reference1.Equals(reference2); } #region Protected members /// <summary> /// Implemented by generated subclasses to return a constant /// Implemented in generated code. /// </summary> protected virtual int InterfaceId { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual bool IsCompatible(int interfaceId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Return the name of the interface for this GrainReference. /// Implemented in Orleans generated code. /// </summary> public virtual string InterfaceName { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Return the method name associated with the specified interfaceId and methodId values. /// </summary> /// <param name="interfaceId">Interface Id</param> /// <param name="methodId">Method Id</param> /// <returns>Method name string.</returns> protected virtual string GetMethodName(int interfaceId, int methodId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { Task<object> resultTask = InvokeMethodAsync<object>(methodId, arguments, options | InvokeMethodOptions.OneWay); if (!resultTask.IsCompleted && resultTask.Result != null) { throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null."); } } /// <summary> /// Called from generated code. /// </summary> protected async Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { object[] argsDeepCopy = null; if (arguments != null) { CheckForGrainArguments(arguments); argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments); } var request = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy); if (IsUnordered) options |= InvokeMethodOptions.Unordered; Task<object> resultTask = InvokeMethod_Impl(request, null, options); if (resultTask == null) { return default(T); } resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask); return (T) await resultTask; } #endregion #region Private members private Task<object> InvokeMethod_Impl(InvokeMethodRequest request, string debugContext, InvokeMethodOptions options) { if (debugContext == null && USE_DEBUG_CONTEXT) { debugContext = string.Intern(GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments)); } // Call any registered client pre-call interceptor function. CallClientInvokeCallback(request); bool isOneWayCall = ((options & InvokeMethodOptions.OneWay) != 0); var resolver = isOneWayCall ? null : new TaskCompletionSource<object>(); RuntimeClient.Current.SendRequest(this, request, resolver, ResponseCallback, debugContext, options, genericArguments); return isOneWayCall ? null : resolver.Task; } private void CallClientInvokeCallback(InvokeMethodRequest request) { // Make callback to any registered client callback function, allowing opportunity for an application to set any additional RequestContext info, etc. // Should we set some kind of callback-in-progress flag to detect and prevent any inappropriate callback loops on this GrainReference? try { Action<InvokeMethodRequest, IGrain> callback = GrainClient.ClientInvokeCallback; // Take copy to avoid potential race conditions if (callback == null) return; // Call ClientInvokeCallback only for grain calls, not for system targets. if (this is IGrain) { callback(request, (IGrain) this); } } catch (Exception exc) { logger.Warn(ErrorCode.ProxyClient_ClientInvokeCallback_Error, "Error while invoking ClientInvokeCallback function " + GrainClient.ClientInvokeCallback, exc); throw; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static void ResponseCallback(Message message, TaskCompletionSource<object> context) { Response response; if (message.Result != Message.ResponseTypes.Rejection) { try { response = (Response)message.BodyObject; } catch (Exception exc) { // catch the Deserialize exception and break the promise with it. response = Response.ExceptionResponse(exc); } } else { Exception rejection; switch (message.RejectionType) { case Message.RejectionTypes.GatewayTooBusy: rejection = new GatewayTooBusyException(); break; case Message.RejectionTypes.DuplicateRequest: return; // Ignore duplicates default: rejection = message.BodyObject as OrleansException; if (rejection == null) { if (string.IsNullOrEmpty(message.RejectionInfo)) { message.RejectionInfo = "Unable to send request - no rejection info available"; } rejection = new OrleansException(message.RejectionInfo); } break; } response = Response.ExceptionResponse(rejection); } if (!response.ExceptionFlag) { context.TrySetResult(response.Data); } else { context.TrySetException(response.Exception); } } private bool GetUnordered() { if (RuntimeClient.Current == null) return false; return RuntimeClient.Current.GrainTypeResolver != null && RuntimeClient.Current.GrainTypeResolver.IsUnordered(GrainId.GetTypeCode()); } #endregion /// <summary> /// Internal implementation of Cast operation for grain references /// Called from generated code. /// </summary> /// <param name="targetReferenceType">Type that this grain reference should be cast to</param> /// <param name="grainRefCreatorFunc">Delegate function to create grain references of the target type</param> /// <param name="grainRef">Grain reference to cast from</param> /// <param name="interfaceId">Interface id value for the target cast type</param> /// <returns>GrainReference that is usable as the target type</returns> /// <exception cref="System.InvalidCastException">if the grain cannot be cast to the target type</exception> protected internal static IAddressable CastInternal( Type targetReferenceType, Func<GrainReference, IAddressable> grainRefCreatorFunc, IAddressable grainRef, int interfaceId) { if (grainRef == null) throw new ArgumentNullException("grainRef"); Type sourceType = grainRef.GetType(); if (!typeof(IAddressable).IsAssignableFrom(targetReferenceType)) { throw new InvalidCastException(String.Format("Target type must be derived from Orleans.IAddressable - cannot handle {0}", targetReferenceType)); } else if (typeof(Grain).IsAssignableFrom(sourceType)) { Grain grainClassRef = (Grain)grainRef; GrainReference g = FromGrainId(grainClassRef.Data.Identity); grainRef = g; } else if (!typeof(GrainReference).IsAssignableFrom(sourceType)) { throw new InvalidCastException(String.Format("Grain reference object must an Orleans.GrainReference - cannot handle {0}", sourceType)); } if (targetReferenceType.IsAssignableFrom(sourceType)) { // Already compatible - no conversion or wrapping necessary return grainRef; } // We have an untyped grain reference that may resolve eventually successfully -- need to enclose in an apprroately typed wrapper class var grainReference = (GrainReference) grainRef; var grainWrapper = (GrainReference) grainRefCreatorFunc(grainReference); return grainWrapper; } private static String GetDebugContext(string interfaceName, string methodName, object[] arguments) { // String concatenation is approx 35% faster than string.Format here //debugContext = String.Format("{0}:{1}()", this.InterfaceName, GetMethodName(this.InterfaceId, methodId)); var debugContext = new StringBuilder(); debugContext.Append(interfaceName); debugContext.Append(":"); debugContext.Append(methodName); if (USE_DEBUG_CONTEXT_PARAMS && arguments != null && arguments.Length > 0) { debugContext.Append("("); debugContext.Append(Utils.EnumerableToString(arguments)); debugContext.Append(")"); } else { debugContext.Append("()"); } return debugContext.ToString(); } private static void CheckForGrainArguments(object[] arguments) { foreach (var argument in arguments) if (argument is Grain) throw new ArgumentException(String.Format("Cannot pass a grain object {0} as an argument to a method. Pass this.AsReference<GrainInterface>() instead.", argument.GetType().FullName)); } /// <summary> Serializer function for grain reference.</summary> /// <seealso cref="SerializationManager"/> [SerializerMethod] protected internal static void SerializeGrainReference(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (GrainReference)obj; stream.Write(input.GrainId); if (input.IsSystemTarget) { stream.Write((byte)1); stream.Write(input.SystemTargetSilo); } else { stream.Write((byte)0); } if (input.IsObserverReference) { input.observerId.SerializeToStream(stream); } // store as null, serialize as empty. var genericArg = String.Empty; if (input.HasGenericArgument) genericArg = input.genericArguments; stream.Write(genericArg); } /// <summary> Deserializer function for grain reference.</summary> /// <seealso cref="SerializationManager"/> [DeserializerMethod] protected internal static object DeserializeGrainReference(Type t, BinaryTokenStreamReader stream) { GrainId id = stream.ReadGrainId(); SiloAddress silo = null; GuidId observerId = null; byte siloAddressPresent = stream.ReadByte(); if (siloAddressPresent != 0) { silo = stream.ReadSiloAddress(); } bool expectObserverId = id.IsClient; if (expectObserverId) { observerId = GuidId.DeserializeFromStream(stream); } // store as null, serialize as empty. var genericArg = stream.ReadString(); if (String.IsNullOrEmpty(genericArg)) genericArg = null; if (expectObserverId) { return NewObserverGrainReference(id, observerId); } return FromGrainId(id, genericArg, silo); } /// <summary> Copier function for grain reference. </summary> /// <seealso cref="SerializationManager"/> [CopierMethod] protected internal static object CopyGrainReference(object original) { return (GrainReference)original; } private const string GRAIN_REFERENCE_STR = "GrainReference"; private const string SYSTEM_TARGET_STR = "SystemTarget"; private const string OBSERVER_ID_STR = "ObserverId"; private const string GENERIC_ARGUMENTS_STR = "GenericArguments"; /// <summary>Returns a string representation of this reference.</summary> public override string ToString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId, !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } internal string ToDetailedString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString()); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(), !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } /// <summary> Get the key value for this grain, as a string. </summary> public string ToKeyString() { if (IsObserverReference) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString()); } if (IsSystemTarget) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString()); } if (HasGenericArgument) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments); } return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString()); } public static GrainReference FromKeyString(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key"); string trimmed = key.Trim(); string grainIdStr; int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length; int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal); int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal); int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal); if (genericIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim(); string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length); if (String.IsNullOrEmpty(genericStr)) { genericStr = null; } return FromGrainId(GrainId.FromParsableString(grainIdStr), genericStr); } else if (observerIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim(); string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length); GuidId observerId = GuidId.FromParsableString(observerIdStr); return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId); } else if (systemTargetIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim(); string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length); SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr); return FromGrainId(GrainId.FromParsableString(grainIdStr), null, siloAddress); } else { grainIdStr = trimmed.Substring(grainIdIndex); return FromGrainId(GrainId.FromParsableString(grainIdStr)); } //return FromGrainId(GrainId.FromParsableString(grainIdStr), generic); } #region ISerializable Members public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string)); if (IsSystemTarget) { info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string)); } if (IsObserverReference) { info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string)); } string genericArg = String.Empty; if (HasGenericArgument) genericArg = genericArguments; info.AddValue("GenericArguments", genericArg, typeof(string)); } // The special constructor is used to deserialize values. protected GrainReference(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. var grainIdStr = info.GetString("GrainId"); GrainId = GrainId.FromParsableString(grainIdStr); if (IsSystemTarget) { var siloAddressStr = info.GetString("SystemTargetSilo"); SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr); } if (IsObserverReference) { var observerIdStr = info.GetString(OBSERVER_ID_STR); observerId = GuidId.FromParsableString(observerIdStr); } var genericArg = info.GetString("GenericArguments"); if (String.IsNullOrEmpty(genericArg)) genericArg = null; genericArguments = genericArg; } #endregion } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NSubstitute; using NUnit.Framework; using System; using System.Diagnostics; using System.IO; using YetiVSI.Metrics; using YetiVSI.Shared.Metrics; using YetiVSI.Test.Metrics.TestSupport; namespace YetiVSI.Test.Metrics { [TestFixture] public class ExceptionRecorderTests { const int _maxExceptionsChainLength = 2; const int _maxStackTraceFrames = 2; IMetrics _fakeMetrics; ExceptionRecorder _exceptionRecorder; [SetUp] public void SetUp() { _fakeMetrics = Substitute.For<IMetrics>(); _exceptionRecorder = new ExceptionRecorder(_fakeMetrics, _maxExceptionsChainLength, _maxStackTraceFrames); } [Test] public void Record() { var ex = new TestException1("outer", new TestException2()); _exceptionRecorder.Record(TestClass.MethodInfo1, ex); var exceptionData = new VSIExceptionData { CatchSite = TestClass.MethodInfo1.GetProto() }; exceptionData.ExceptionsChain.Add( new VSIExceptionData.Types.Exception { ExceptionType = typeof(TestException1).GetProto() }); exceptionData.ExceptionsChain.Add( new VSIExceptionData.Types.Exception { ExceptionType = typeof(TestException2).GetProto() }); var logEvent = new DeveloperLogEvent { StatusCode = DeveloperEventStatus.Types.Code.InternalError }; logEvent.ExceptionsData.Add(exceptionData); _fakeMetrics.Received() .RecordEvent(DeveloperEventType.Types.Type.VsiException, logEvent); } [Test] public void RecordWithStackTrace() { var ex = new TestException2(); // Throw exception to capture the stack trace try { throw ex; } catch (TestException2) { } _exceptionRecorder.Record(TestClass.MethodInfo1, ex); var exceptionData = new VSIExceptionData { CatchSite = TestClass.MethodInfo1.GetProto() }; var firstExceptionInChain = new VSIExceptionData.Types.Exception { ExceptionType = typeof(TestException2).GetProto() }; var stackTraceFrame = new StackTrace(ex, true).GetFrame(0); firstExceptionInChain.ExceptionStackTraceFrames.Add( new VSIExceptionData.Types.Exception.Types.StackTraceFrame { AllowedNamespace = true, Method = stackTraceFrame.GetMethod().GetProto(), Filename = Path.GetFileName(stackTraceFrame.GetFileName()), LineNumber = (uint?) stackTraceFrame.GetFileLineNumber() }); exceptionData.ExceptionsChain.Add(firstExceptionInChain); var logEvent = new DeveloperLogEvent { StatusCode = DeveloperEventStatus.Types.Code.InternalError }; logEvent.ExceptionsData.Add(exceptionData); _fakeMetrics.Received() .RecordEvent(DeveloperEventType.Types.Type.VsiException, logEvent); } [Test] public void RecordExceptionChainTooLong() { var ex = new TestException1("level1", new TestException1( "level2", new TestException1("level3", new TestException2()))); _exceptionRecorder.Record(TestClass.MethodInfo1, ex); _fakeMetrics.Received() .RecordEvent(DeveloperEventType.Types.Type.VsiException, Arg.Is<DeveloperLogEvent>( p => ExceptionChainOverflowRecorded(p.ExceptionsData[0]))); } [Test] public void RecordExceptionInNotAllowedNamespace() { var ex = NotAllowedNamespace.Test.ThrowException(); _exceptionRecorder.Record(TestClass.MethodInfo1, ex); var exceptionData = new VSIExceptionData { CatchSite = TestClass.MethodInfo1.GetProto() }; var firstExceptionInChain = new VSIExceptionData.Types.Exception { ExceptionType = typeof(Exception).GetProto() }; firstExceptionInChain.ExceptionStackTraceFrames.Add( new VSIExceptionData.Types.Exception.Types.StackTraceFrame { AllowedNamespace = false }); exceptionData.ExceptionsChain.Add(firstExceptionInChain); var logEvent = new DeveloperLogEvent { StatusCode = DeveloperEventStatus.Types.Code.InternalError }; logEvent.ExceptionsData.Add(exceptionData); _fakeMetrics.Received(1) .RecordEvent(DeveloperEventType.Types.Type.VsiException, logEvent); } [Test] public void RecordNullArgumentsFail() { Assert.Catch<ArgumentNullException>( () => _exceptionRecorder.Record(TestClass.MethodInfo1, null)); Assert.Catch<ArgumentNullException>( () => _exceptionRecorder.Record(null, new TestException2())); } [Test] public void NewRecorderWithNullMetricsFail() { Assert.Catch<ArgumentNullException>(() => new ExceptionRecorder(null)); } static bool ExceptionChainOverflowRecorded(VSIExceptionData data) { return data.ExceptionsChain.Count == _maxExceptionsChainLength + 1 && data .ExceptionsChain[(int) _maxExceptionsChainLength] .ExceptionType.Equals(typeof(ExceptionRecorder.ChainTooLongException).GetProto()); } class TestException1 : Exception { public TestException1(string message, Exception inner) : base(message, inner) { } } class TestException2 : Exception { } } } namespace NotAllowedNamespace { static class Test { public static Exception ThrowException() { try { throw new Exception("Test"); } catch (Exception ex) { return ex; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Represents a try/catch/finally/fault block. /// /// The body is protected by the try block. /// The handlers consist of a set of <see cref="CatchBlock"/>s that can either be catch or filters. /// The fault runs if an exception is thrown. /// The finally runs regardless of how control exits the body. /// Only one of fault or finally can be supplied. /// The return type of the try block must match the return type of any associated catch statements. /// </summary> [DebuggerTypeProxy(typeof(Expression.TryExpressionProxy))] public sealed class TryExpression : Expression { private readonly Type _type; private readonly Expression _body; private readonly ReadOnlyCollection<CatchBlock> _handlers; private readonly Expression _finally; private readonly Expression _fault; internal TryExpression(Type type, Expression body, Expression @finally, Expression fault, ReadOnlyCollection<CatchBlock> handlers) { _type = type; _body = body; _handlers = handlers; _finally = @finally; _fault = fault; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Try; } } /// <summary> /// Gets the <see cref="Expression"/> representing the body of the try block. /// </summary> public Expression Body { get { return _body; } } /// <summary> /// Gets the collection of <see cref="CatchBlock"/>s associated with the try block. /// </summary> public ReadOnlyCollection<CatchBlock> Handlers { get { return _handlers; } } /// <summary> /// Gets the <see cref="Expression"/> representing the finally block. /// </summary> public Expression Finally { get { return _finally; } } /// <summary> /// Gets the <see cref="Expression"/> representing the fault block. /// </summary> public Expression Fault { get { return _fault; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTry(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="Body" /> property of the result.</param> /// <param name="handlers">The <see cref="Handlers" /> property of the result.</param> /// <param name="finally">The <see cref="Finally" /> property of the result.</param> /// <param name="fault">The <see cref="Fault" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TryExpression Update(Expression body, IEnumerable<CatchBlock> handlers, Expression @finally, Expression fault) { if (body == Body && handlers == Handlers && @finally == Finally && fault == Fault) { return this; } return Expression.MakeTry(Type, body, @finally, fault, handlers); } } public partial class Expression { /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with a fault block and no catch statements. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="fault">The body of the fault block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryFault(Expression body, Expression fault) { return MakeTry(null, body, null, fault, null); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with a finally block and no catch statements. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryFinally(Expression body, Expression @finally) { return MakeTry(null, body, @finally, null, null); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and neither a fault nor finally block. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryCatch(Expression body, params CatchBlock[] handlers) { return MakeTry(null, body, null, null, handlers); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and a finally block. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block.</param> /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryCatchFinally(Expression body, Expression @finally, params CatchBlock[] handlers) { return MakeTry(null, body, @finally, null, handlers); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with the specified elements. /// </summary> /// <param name="type">The result type of the try expression. If null, body and all handlers must have identical type.</param> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block. Pass null if the try block has no finally block associated with it.</param> /// <param name="fault">The body of the t block. Pass null if the try block has no fault block associated with it.</param> /// <param name="handlers">A collection of <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression MakeTry(Type type, Expression body, Expression @finally, Expression fault, IEnumerable<CatchBlock> handlers) { RequiresCanRead(body, "body"); var @catch = handlers.ToReadOnly(); ContractUtils.RequiresNotNullItems(@catch, "handlers"); ValidateTryAndCatchHaveSameType(type, body, @catch); if (fault != null) { if (@finally != null || @catch.Count > 0) { throw Error.FaultCannotHaveCatchOrFinally(); } RequiresCanRead(fault, "fault"); } else if (@finally != null) { RequiresCanRead(@finally, "finally"); } else if (@catch.Count == 0) { throw Error.TryMustHaveCatchFinallyOrFault(); } return new TryExpression(type ?? body.Type, body, @finally, fault, @catch); } //Validate that the body of the try expression must have the same type as the body of every try block. private static void ValidateTryAndCatchHaveSameType(Type type, Expression tryBody, ReadOnlyCollection<CatchBlock> handlers) { // Type unification ... all parts must be reference assignable to "type" if (type != null) { if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, tryBody.Type)) { throw Error.ArgumentTypesMustMatch(); } foreach (var cb in handlers) { if (!TypeUtils.AreReferenceAssignable(type, cb.Body.Type)) { throw Error.ArgumentTypesMustMatch(); } } } } else if (tryBody == null || tryBody.Type == typeof(void)) { //The body of every try block must be null or have void type. foreach (CatchBlock cb in handlers) { if (cb.Body != null && cb.Body.Type != typeof(void)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); } } } else { //Body of every catch must have the same type of body of try. type = tryBody.Type; foreach (CatchBlock cb in handlers) { if (cb.Body == null || !TypeUtils.AreEquivalent(cb.Body.Type, type)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); } } } } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.MathUtil.Matrices; using Encog.ML; using Encog.ML.Data; using Encog.ML.Data.Specific; namespace Encog.Neural.ART { /// <summary> /// Implements an ART1 neural network. An ART1 neural network is trained to /// recognize bipolar patterns as it is presented data. There is no distinct /// learning phase, like there is with other neural network types. /// The ART1 neural network is a type of Adaptive Resonance Theory (ART) neural /// network. ART1 was developed by Stephen Grossberg and Gail Carpenter. /// This neural network type supports only bipolar input. The ART1 neural /// network is trained as it is used. New patterns are presented to the ART1 /// network, and they are classified into either new, or existing, classes. /// Once the maximum number of classes have been used the network will report /// that it is out of classes. ART1 neural networks are used for classification. /// There are essentially 2 layers in an ART1 network. The first, named the /// F1 layer, acts as the input. The F1 layer receives bipolar patterns that /// the network is to classify. The F2 layer specifies the maximum number /// classes that the ART1 network can recognize. /// Plasticity is an important part for all Adaptive Resonance Theory (ART) /// neural networks. Unlike most neural networks, ART1 does not have a /// distinct training and usage stage. The ART1 network will learn as it is /// used. /// </summary> [Serializable] public class ART1 : BasicART, IMLResettable, IMLClassification { /// <summary> /// A parameter for F1 layer. /// </summary> /// private double _a1; /// <summary> /// B parameter for F1 layer. /// </summary> /// private double _b1; /// <summary> /// C parameter for F1 layer. /// </summary> /// private double _c1; /// <summary> /// D parameter for F1 layer. /// </summary> /// private double _d1; /// <summary> /// The F1 layer neuron count. /// </summary> /// private int _f1Count; /// <summary> /// The F2 layer neuron count. /// </summary> /// private int _f2Count; /// <summary> /// Allows members of the F2 layer to be inhibited. /// </summary> [NonSerialized] private bool[] _inhibitF2; /// <summary> /// L parameter for net. /// </summary> /// private double _l; /// <summary> /// This is the value that is returned if there is no winner. /// This value is generally set to the number of classes, plus 1. /// </summary> /// private int _noWinner; /// <summary> /// The output from the F1 layer. /// </summary> /// private BiPolarMLData _outputF1; /// <summary> /// The output from the F2 layer. /// </summary> /// private BiPolarMLData _outputF2; /// <summary> /// The vigilance parameter. /// </summary> /// private double _vigilance; /// <summary> /// Weights from f1 to f2. /// </summary> /// private Matrix _weightsF1ToF2; /// <summary> /// Weights from f2 to f1. /// </summary> /// private Matrix _weightsF2ToF1; /// <summary> /// Default constructor, used mainly for persistence. /// </summary> /// public ART1() { _a1 = 1; _b1 = 1.5d; _c1 = 5; _d1 = 0.9d; _l = 3; _vigilance = 0.9d; } /// <summary> /// Construct the ART1 network. /// </summary> /// /// <param name="theF1Count">The neuron count for the f1 layer.</param> /// <param name="theF2Count">The neuron count for the f2 layer.</param> public ART1(int theF1Count, int theF2Count) { _a1 = 1; _b1 = 1.5d; _c1 = 5; _d1 = 0.9d; _l = 3; _vigilance = 0.9d; _f1Count = theF1Count; _f2Count = theF2Count; _weightsF1ToF2 = new Matrix(_f1Count, _f2Count); _weightsF2ToF1 = new Matrix(_f2Count, _f1Count); _inhibitF2 = new bool[_f2Count]; _outputF1 = new BiPolarMLData(_f1Count); _outputF2 = new BiPolarMLData(_f2Count); _noWinner = _f2Count; Reset(); } /// <summary> /// Set the A1 parameter. /// </summary> /// /// <value>The new value.</value> public double A1 { get { return _a1; } set { _a1 = value; } } /// <summary> /// Set the B1 parameter. /// </summary> public double B1 { get { return _b1; } set { _b1 = value; } } /// <summary> /// Set the C1 parameter. /// </summary> /// /// <value>The new value.</value> public double C1 { get { return _c1; } set { _c1 = value; } } /// <summary> /// Set the D1 parameter. /// </summary> /// /// <value>The new value.</value> public double D1 { get { return _d1; } set { _d1 = value; } } /// <summary> /// Set the F1 count. The F1 layer is the input layer. /// </summary> public int F1Count { get { return _f1Count; } set { _f1Count = value; _outputF1 = new BiPolarMLData(_f1Count); } } /// <summary> /// Set the F2 count. The F2 layer is the output layer. /// </summary> /// /// <value>The count.</value> public int F2Count { get { return _f2Count; } set { _f2Count = value; _inhibitF2 = new bool[_f2Count]; _outputF2 = new BiPolarMLData(_f2Count); } } /// <summary> /// Set the L parameter. /// </summary> /// /// <value>The new value.</value> public double L { get { return _l; } set { _l = value; } } /// <summary> /// This is the value that is returned if there is no winner. /// This value is generally set to the index of the last classes, plus 1. /// For example, if there were 3 classes, the network would return 0-2 to /// represent what class was found, in this case the no winner property /// would be set to 3. /// </summary> public int NoWinner { get { return _noWinner; } set { _noWinner = value; } } /// <summary> /// Set the vigilance. /// </summary> public double Vigilance { get { return _vigilance; } set { _vigilance = value; } } /// <summary> /// Set the f1 to f2 matrix. /// </summary> public Matrix WeightsF1ToF2 { get { return _weightsF1ToF2; } set { _weightsF1ToF2 = value; } } /// <summary> /// Set the f2 to f1 matrix. /// </summary> public Matrix WeightsF2ToF1 { get { return _weightsF2ToF1; } set { _weightsF2ToF1 = value; } } /// <value>The winning neuron.</value> public int Winner { get; private set; } /// <returns>Does this network have a "winner"?</returns> public bool HasWinner { get { return Winner != _noWinner; } } /// <summary> /// Set the input to the neural network. /// </summary> private BiPolarMLData Input { set { for (int i = 0; i < _f1Count; i++) { double activation = ((value.GetBoolean(i)) ? 1 : 0) /(1 + _a1*(((value.GetBoolean(i)) ? 1 : 0) + _b1) + _c1); _outputF1.SetBoolean(i, (activation > 0)); } } } #region MLClassification Members /// <summary> /// Classify the input data to a class number. /// </summary> /// /// <param name="input">The input data.</param> /// <returns>The class that the data belongs to.</returns> public int Classify(IMLData input) { var input2 = new BiPolarMLData(_f1Count); var output = new BiPolarMLData(_f2Count); if (input.Count != input2.Count) { throw new NeuralNetworkError("Input array size does not match."); } for (int i = 0; i < input2.Count; i++) { input2.SetBoolean(i, input[i] > 0); } Compute(input2, output); return HasWinner ? Winner : -1; } /// <summary> /// The input count. /// </summary> public int InputCount { get { return _f1Count; } } /// <value>The number of neurons in the output count, which is the f2 layer /// count.</value> public int OutputCount { get { return _f2Count; } } #endregion #region MLResettable Members /// <summary> /// Reset the weight matrix back to starting values. /// </summary> /// public void Reset() { Reset(0); } /// <summary> /// Reset with a specic seed. /// </summary> /// /// <param name="seed">The seed to reset with.</param> public void Reset(int seed) { for (int i = 0; i < _f1Count; i++) { for (int j = 0; j < _f2Count; j++) { _weightsF1ToF2[i, j] = (_b1 - 1)/_d1 + 0.2d; _weightsF2ToF1[j, i] = _l /(_l - 1 + _f1Count) - 0.1d; } } } #endregion /// <summary> /// Adjust the weights for the pattern just presented. /// </summary> /// public void AdjustWeights() { for (int i = 0; i < _f1Count; i++) { if (_outputF1.GetBoolean(i)) { double magnitudeInput = Magnitude(_outputF1); _weightsF1ToF2[i, Winner] = 1; _weightsF2ToF1[Winner, i] = _l /(_l - 1 + magnitudeInput); } else { _weightsF1ToF2[i, Winner] = 0; _weightsF2ToF1[Winner, i] = 0; } } } /// <summary> /// Compute the output from the ART1 network. This can be called directly or /// used by the BasicNetwork class. Both input and output should be bipolar /// numbers. /// </summary> /// /// <param name="input">The input to the network.</param> /// <param name="output">The output from the network.</param> public void Compute(BiPolarMLData input, BiPolarMLData output) { int i; for (i = 0; i < _f2Count; i++) { _inhibitF2[i] = false; } bool resonance = false; bool exhausted = false; do { Input = input; ComputeF2(); GetOutput(output); if (Winner != _noWinner) { ComputeF1(input); double magnitudeInput1 = Magnitude(input); double magnitudeInput2 = Magnitude(_outputF1); if ((magnitudeInput2/magnitudeInput1) < _vigilance) { _inhibitF2[Winner] = true; } else { resonance = true; } } else { exhausted = true; } } while (!(resonance || exhausted)); if (resonance) { AdjustWeights(); } } /// <summary> /// Compute the output for the BasicNetwork class. /// </summary> /// /// <param name="input">The input to the network.</param> /// <returns>The output from the network.</returns> public IMLData Compute(IMLData input) { if (!(input is BiPolarMLData)) { throw new NeuralNetworkError( "Input to ART1 logic network must be BiPolarNeuralData."); } var output = new BiPolarMLData(_f1Count); Compute((BiPolarMLData) input, output); return output; } /// <summary> /// Compute the output from the F1 layer. /// </summary> /// /// <param name="input">The input to the F1 layer.</param> private void ComputeF1(BiPolarMLData input) { for (int i = 0; i < _f1Count; i++) { double sum = _weightsF1ToF2[i, Winner] *((_outputF2.GetBoolean(Winner)) ? 1 : 0); double activation = (((input.GetBoolean(i)) ? 1 : 0) + _d1*sum - _b1) /(1 + _a1 *(((input.GetBoolean(i)) ? 1 : 0) + _d1*sum) + _c1); _outputF1.SetBoolean(i, activation > 0); } } /// <summary> /// Compute the output from the F2 layer. /// </summary> /// private void ComputeF2() { int i; double maxOut = Double.NegativeInfinity; Winner = _noWinner; for (i = 0; i < _f2Count; i++) { if (!_inhibitF2[i]) { double sum = 0; int j; for (j = 0; j < _f1Count; j++) { sum += _weightsF2ToF1[i, j] *((_outputF1.GetBoolean(j)) ? 1 : 0); } if (sum > maxOut) { maxOut = sum; Winner = i; } } _outputF2.SetBoolean(i, false); } if (Winner != _noWinner) { _outputF2.SetBoolean(Winner, true); } } /// <summary> /// Copy the output from the network to another object. /// </summary> /// /// <param name="output">The target object for the output from the network.</param> private void GetOutput(BiPolarMLData output) { for (int i = 0; i < _f2Count; i++) { output.SetBoolean(i, _outputF2.GetBoolean(i)); } } /// <summary> /// Get the magnitude of the specified input. /// </summary> /// /// <param name="input">The input to calculate the magnitude for.</param> /// <returns>The magnitude of the specified pattern.</returns> public double Magnitude(BiPolarMLData input) { double result; result = 0; for (int i = 0; i < _f1Count; i++) { result += (input.GetBoolean(i)) ? 1 : 0; } return result; } } }
// -------------------------------------------------------------------------------------------------------------------- // <author> // HiddenMonk // http://answers.unity3d.com/users/496850/hiddenmonk.html // // Johannes Deml // send@johannesdeml.com // </author> // -------------------------------------------------------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Mana // renamed from Supyrb { using System; using UnityEngine; using UnityEditor; using System.Reflection; /// <summary> /// Extension class for SerializedProperties that makes it easier to get and set values /// See also: http://answers.unity3d.com/questions/627090/convert-serializedproperty-to-custom-class.html /// </summary> public static class SerializedPropertyExtensions { /// <summary> /// Get the object the serialized property holds by using reflection /// </summary> /// <typeparam name="T">The object type that the property contains</typeparam> /// <param name="property"></param> /// <returns>Returns the object type T if it is the type the property actually contains</returns> public static T GetValue<T>(this SerializedProperty property) { return GetNestedObject<T>(property.propertyPath, GetSerializedPropertyRootComponent(property)); } /// <summary> /// Set the value of a field of the property with the type T /// </summary> /// <typeparam name="T">The type of the field that is set</typeparam> /// <param name="property">The serialized property that should be set</param> /// <param name="value">The new value for the specified property</param> /// <returns>Returns if the operation was successful or failed</returns> public static bool SetValue<T>(this SerializedProperty property, T value) { object obj = GetSerializedPropertyRootComponent(property); //Iterate to parent object of the value, necessary if it is a nested object string[] fieldStructure = property.propertyPath.Split('.'); for (int i = 0; i < fieldStructure.Length - 1; i++) { obj = GetFieldOrPropertyValue<object>(fieldStructure[i], obj); } string fieldName = fieldStructure.Last(); return SetFieldOrPropertyValue(fieldName, obj, value); } /// <summary> /// Get the component of a serialized property /// </summary> /// <param name="property">The property that is part of the component</param> /// <returns>The root component of the property</returns> public static Component GetSerializedPropertyRootComponent(SerializedProperty property) { return (Component)property.serializedObject.targetObject; } /// <summary> /// Iterates through objects to handle objects that are nested in the root object /// </summary> /// <typeparam name="T">The type of the nested object</typeparam> /// <param name="path">Path to the object through other properties e.g. PlayerInformation.Health</param> /// <param name="obj">The root object from which this path leads to the property</param> /// <param name="includeAllBases">Include base classes and interfaces as well</param> /// <returns>Returns the nested object casted to the type T</returns> public static T GetNestedObject<T>(string path, object obj, bool includeAllBases = false) { string[] paths = path.Split('.'); if (paths.Length > 0) { int lastIndex = paths.Length - 1; if (paths[lastIndex].Contains("[") && paths[lastIndex].Contains("]")) { string arrayIndex = Regex.Replace(paths[lastIndex], @"[^\d]", ""); if (!string.IsNullOrEmpty(arrayIndex)) { string arrayName = paths[0]; obj = GetFieldOrPropertyValue<object>(arrayName, obj, includeAllBases, Int32.Parse(arrayIndex)); return (T)obj; } } } foreach (string part in paths) { obj = GetFieldOrPropertyValue<object>(part, obj, includeAllBases); } return (T)obj; } public static T GetFieldOrPropertyValue<T>(string fieldName, object obj, bool includeAllBases = false, int? arrayIndex = null, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) { if (arrayIndex != null) { FieldInfo arrayProperty = obj.GetType().GetField(fieldName, bindings); IList castedList = arrayProperty.GetValue(obj) as IList; return (T)castedList[arrayIndex.Value]; } FieldInfo field = obj.GetType().GetField(fieldName, bindings); if (field != null) return (T)field.GetValue(obj); PropertyInfo property = obj.GetType().GetProperty(fieldName, bindings); if (property != null) return (T)property.GetValue(obj, null); if (includeAllBases) { foreach (Type type in GetBaseClassesAndInterfaces(obj.GetType())) { field = type.GetField(fieldName, bindings); if (field != null) return (T)field.GetValue(obj); property = type.GetProperty(fieldName, bindings); if (property != null) return (T)property.GetValue(obj, null); } } return default(T); } public static bool SetFieldOrPropertyValue(string fieldName, object obj, object value, bool includeAllBases = false, int? arrayIndex = null, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) { FieldInfo field = obj.GetType().GetField(fieldName, bindings); if (field != null) { field.SetValue(obj, value); return true; } PropertyInfo property = obj.GetType().GetProperty(fieldName, bindings); if (property != null) { property.SetValue(obj, value, null); return true; } if (includeAllBases) { foreach (Type type in GetBaseClassesAndInterfaces(obj.GetType())) { field = type.GetField(fieldName, bindings); if (field != null) { field.SetValue(obj, value); return true; } property = type.GetProperty(fieldName, bindings); if (property != null) { property.SetValue(obj, value, null); return true; } } } return false; } public static IEnumerable<Type> GetBaseClassesAndInterfaces(this Type type, bool includeSelf = false) { List<Type> allTypes = new List<Type>(); if (includeSelf) allTypes.Add(type); if (type.BaseType == typeof(object)) { allTypes.AddRange(type.GetInterfaces()); } else { allTypes.AddRange( Enumerable .Repeat(type.BaseType, 1) .Concat(type.GetInterfaces()) .Concat(type.BaseType.GetBaseClassesAndInterfaces()) .Distinct()); } return allTypes; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; using Microsoft.Win32; namespace System.Diagnostics { [ ToolboxItem(false), DesignTimeVisible(false), ] public sealed class EventLogEntry : Component, ISerializable { internal byte[] dataBuf; internal int bufOffset; private EventLogInternal owner; private string category; private string message; internal EventLogEntry(byte[] buf, int offset, EventLogInternal log) { this.dataBuf = buf; this.bufOffset = offset; this.owner = log; GC.SuppressFinalize(this); } /// <summary> /// The machine on which this event log resides. /// </summary> public string MachineName { get { // first skip over the source name int pos = bufOffset + FieldOffsets.RAWDATA; while (CharFrom(dataBuf, pos) != '\0') pos += 2; pos += 2; char ch = CharFrom(dataBuf, pos); StringBuilder buf = new StringBuilder(); while (ch != '\0') { buf.Append(ch); pos += 2; ch = CharFrom(dataBuf, pos); } return buf.ToString(); } } /// <summary> /// The binary data associated with this entry in the event log. /// </summary> public byte[] Data { get { int dataLen = IntFrom(dataBuf, bufOffset + FieldOffsets.DATALENGTH); byte[] data = new byte[dataLen]; Array.Copy(dataBuf, bufOffset + IntFrom(dataBuf, bufOffset + FieldOffsets.DATAOFFSET), data, 0, dataLen); return data; } } /// <summary> /// The sequence of this entry in the event log. /// </summary> public int Index { get { return IntFrom(dataBuf, bufOffset + FieldOffsets.RECORDNUMBER); } } /// <summary> /// The category for this message. /// </summary> public string Category { get { if (category == null) { string dllName = GetMessageLibraryNames("CategoryMessageFile"); string cat = owner.FormatMessageWrapper(dllName, (uint)CategoryNumber, null); if (cat == null) category = "(" + CategoryNumber.ToString(CultureInfo.CurrentCulture) + ")"; else category = cat; } return category; } } /// <summary> /// An application-specific category number assigned to this entry. /// </summary> public short CategoryNumber { get { return ShortFrom(dataBuf, bufOffset + FieldOffsets.EVENTCATEGORY); } } /// <summary> /// The number identifying the message for this source. /// </summary> [Obsolete("This property has been deprecated. Please use System.Diagnostics.EventLogEntry.InstanceId instead. https://go.microsoft.com/fwlink/?linkid=14202")] public int EventID { get { return IntFrom(dataBuf, bufOffset + FieldOffsets.EVENTID) & 0x3FFFFFFF; } } /// <summary> /// The type of entry - Information, Warning, etc. /// </summary> public EventLogEntryType EntryType { get { return (EventLogEntryType)ShortFrom(dataBuf, bufOffset + FieldOffsets.EVENTTYPE); } } /// <summary> /// The text of the message for this entry. /// </summary> public string Message { get { if (message == null) { string dllNames = GetMessageLibraryNames("EventMessageFile"); int msgId = IntFrom(dataBuf, bufOffset + FieldOffsets.EVENTID); string msg = owner.FormatMessageWrapper(dllNames, (uint)msgId, ReplacementStrings); if (msg == null) { StringBuilder msgBuf = new StringBuilder(SR.Format(SR.MessageNotFormatted, msgId, Source)); string[] strings = ReplacementStrings; for (int i = 0; i < strings.Length; i++) { if (i != 0) msgBuf.Append(", "); msgBuf.Append("'"); msgBuf.Append(strings[i]); msgBuf.Append("'"); } msg = msgBuf.ToString(); } else msg = ReplaceMessageParameters(msg, ReplacementStrings); message = msg; } return message; } } /// <summary> /// The name of the application that wrote this entry. /// </summary> public string Source { get { StringBuilder buf = new StringBuilder(); int pos = bufOffset + FieldOffsets.RAWDATA; char ch = CharFrom(dataBuf, pos); while (ch != '\0') { buf.Append(ch); pos += 2; ch = CharFrom(dataBuf, pos); } return buf.ToString(); } } /// <summary> /// The application-supplied strings used in the message. /// </summary> public string[] ReplacementStrings { get { string[] strings = new string[ShortFrom(dataBuf, bufOffset + FieldOffsets.NUMSTRINGS)]; int i = 0; int bufpos = bufOffset + IntFrom(dataBuf, bufOffset + FieldOffsets.STRINGOFFSET); StringBuilder buf = new StringBuilder(); while (i < strings.Length) { char ch = CharFrom(dataBuf, bufpos); if (ch != '\0') buf.Append(ch); else { strings[i] = buf.ToString(); i++; buf = new StringBuilder(); } bufpos += 2; } return strings; } } /// <summary> /// The full number identifying the message in the event message dll. /// </summary> public long InstanceId { get { return (uint)IntFrom(dataBuf, bufOffset + FieldOffsets.EVENTID); } } /// <summary> /// The time at which the application logged this entry. /// </summary> public DateTime TimeGenerated { get { return beginningOfTime.AddSeconds(IntFrom(dataBuf, bufOffset + FieldOffsets.TIMEGENERATED)).ToLocalTime(); } } /// <summary> /// The time at which the system logged this entry to the event log. /// </summary> public DateTime TimeWritten { get { return beginningOfTime.AddSeconds(IntFrom(dataBuf, bufOffset + FieldOffsets.TIMEWRITTEN)).ToLocalTime(); } } /// <summary> /// The username of the account associated with this entry by the writing application. /// </summary> public string UserName { get { int sidLen = IntFrom(dataBuf, bufOffset + FieldOffsets.USERSIDLENGTH); if (sidLen == 0) return null; byte[] sid = new byte[sidLen]; Array.Copy(dataBuf, bufOffset + IntFrom(dataBuf, bufOffset + FieldOffsets.USERSIDOFFSET), sid, 0, sid.Length); int userNameLen = 256; int domainNameLen = 256; int sidNameUse = 0; StringBuilder bufUserName = new StringBuilder(userNameLen); StringBuilder bufDomainName = new StringBuilder(domainNameLen); StringBuilder retUserName = new StringBuilder(); if (Interop.Kernel32.LookupAccountSid(MachineName, sid, bufUserName, ref userNameLen, bufDomainName, ref domainNameLen, ref sidNameUse) != 0) { retUserName.Append(bufDomainName.ToString()); retUserName.Append("\\"); retUserName.Append(bufUserName.ToString()); } return retUserName.ToString(); } } private char CharFrom(byte[] buf, int offset) { return (char)ShortFrom(buf, offset); } public bool Equals(EventLogEntry otherEntry) { if (otherEntry == null) return false; int ourLen = IntFrom(dataBuf, bufOffset + FieldOffsets.LENGTH); int theirLen = IntFrom(otherEntry.dataBuf, otherEntry.bufOffset + FieldOffsets.LENGTH); if (ourLen != theirLen) { return false; } int min = bufOffset; int max = bufOffset + ourLen; int j = otherEntry.bufOffset; for (int i = min; i < max; i++, j++) if (dataBuf[i] != otherEntry.dataBuf[j]) { return false; } return true; } private int IntFrom(byte[] buf, int offset) { // assumes Little Endian byte order. return (unchecked((int)0xFF000000) & (buf[offset + 3] << 24)) | (0xFF0000 & (buf[offset + 2] << 16)) | (0xFF00 & (buf[offset + 1] << 8)) | (0xFF & (buf[offset])); } internal string ReplaceMessageParameters(string msg, string[] insertionStrings) { int percentIdx = msg.IndexOf('%'); if (percentIdx < 0) return msg; int startCopyIdx = 0; int msgLength = msg.Length; StringBuilder buf = new StringBuilder(); string paramDLLNames = GetMessageLibraryNames("ParameterMessageFile"); while (percentIdx >= 0) { string param = null; int lasNumIdx = percentIdx + 1; while (lasNumIdx < msgLength && char.IsDigit(msg, lasNumIdx)) lasNumIdx++; uint paramMsgID = 0; if (lasNumIdx != percentIdx + 1) uint.TryParse(msg.Substring(percentIdx + 1, lasNumIdx - percentIdx - 1), out paramMsgID); if (paramMsgID != 0) param = owner.FormatMessageWrapper(paramDLLNames, paramMsgID, insertionStrings); if (param != null) { if (percentIdx > startCopyIdx) buf.Append(msg, startCopyIdx, percentIdx - startCopyIdx); // original chars from msg buf.Append(param); startCopyIdx = lasNumIdx; } percentIdx = msg.IndexOf('%', percentIdx + 1); } if (msgLength - startCopyIdx > 0) buf.Append(msg, startCopyIdx, msgLength - startCopyIdx); // last span of original msg return buf.ToString(); } private static RegistryKey GetSourceRegKey(string logName, string source, string machineName) { RegistryKey eventKey = null; RegistryKey logKey = null; try { eventKey = EventLog.GetEventLogRegKey(machineName, false); return eventKey?.OpenSubKey(logName ?? "Application", /*writable*/false)?.OpenSubKey(source, /*writeable*/false); } finally { eventKey?.Close(); logKey?.Close(); } } private string GetMessageLibraryNames(string libRegKey) { // get the value stored in the registry string fileName = null; RegistryKey regKey = null; try { regKey = GetSourceRegKey(owner.Log, Source, owner.MachineName); if (regKey != null) { fileName = (string)regKey.GetValue(libRegKey); } } finally { regKey?.Close(); } if (fileName == null) return null; // convert any absolute paths on a remote machine to use the \\MACHINENAME\DRIVELETTER$ shares if (owner.MachineName != ".") { string[] fileNames = fileName.Split(';'); StringBuilder result = new StringBuilder(); for (int i = 0; i < fileNames.Length; i++) { if (fileNames[i].Length >= 2 && fileNames[i][1] == ':') { result.Append(@"\\"); result.Append(owner.MachineName); result.Append(@"\"); result.Append(fileNames[i][0]); result.Append("$"); result.Append(fileNames[i], 2, fileNames[i].Length - 2); result.Append(';'); } } if (result.Length == 0) { return null; } else { return result.ToString(0, result.Length - 1); } } else { return fileName; } } private short ShortFrom(byte[] buf, int offset) { // assumes little Endian byte order. return (short)((0xFF00 & (buf[offset + 1] << 8)) | (0xFF & buf[offset])); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } private static class FieldOffsets { internal const int LENGTH = 0; internal const int RESERVED = 4; internal const int RECORDNUMBER = 8; internal const int TIMEGENERATED = 12; internal const int TIMEWRITTEN = 16; internal const int EVENTID = 20; internal const int EVENTTYPE = 24; internal const int NUMSTRINGS = 26; internal const int EVENTCATEGORY = 28; internal const int RESERVEDFLAGS = 30; internal const int CLOSINGRECORDNUMBER = 32; internal const int STRINGOFFSET = 36; internal const int USERSIDLENGTH = 40; internal const int USERSIDOFFSET = 44; internal const int DATALENGTH = 48; internal const int DATAOFFSET = 52; internal const int RAWDATA = 56; } private static readonly DateTime beginningOfTime = new DateTime(1970, 1, 1, 0, 0, 0); private const int OFFSETFIXUP = 4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 2 + 2 + 4 + 4 + 4 + 4 + 4 + 4; } }
namespace android.preference { [global::MonoJavaBridge.JavaClass()] public partial class Preference : java.lang.Object, java.lang.Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Preference(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class BaseSavedState : android.view.AbsSavedState { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected BaseSavedState(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public BaseSavedState(android.os.Parcel arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.Preference.BaseSavedState._m0.native == global::System.IntPtr.Zero) global::android.preference.Preference.BaseSavedState._m0 = @__env.GetMethodIDNoThrow(global::android.preference.Preference.BaseSavedState.staticClass, "<init>", "(Landroid/os/Parcel;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.Preference.BaseSavedState.staticClass, global::android.preference.Preference.BaseSavedState._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m1; public BaseSavedState(android.os.Parcelable arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.Preference.BaseSavedState._m1.native == global::System.IntPtr.Zero) global::android.preference.Preference.BaseSavedState._m1 = @__env.GetMethodIDNoThrow(global::android.preference.Preference.BaseSavedState.staticClass, "<init>", "(Landroid/os/Parcelable;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.Preference.BaseSavedState.staticClass, global::android.preference.Preference.BaseSavedState._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _CREATOR4052; public static global::android.os.Parcelable_Creator CREATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.preference.Preference.BaseSavedState.staticClass, _CREATOR4052)) as android.os.Parcelable_Creator; } } static BaseSavedState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.Preference.BaseSavedState.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/Preference$BaseSavedState")); global::android.preference.Preference.BaseSavedState._CREATOR4052 = @__env.GetStaticFieldIDNoThrow(global::android.preference.Preference.BaseSavedState.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.Preference.OnPreferenceChangeListener_))] public partial interface OnPreferenceChangeListener : global::MonoJavaBridge.IJavaObject { bool onPreferenceChange(android.preference.Preference arg0, java.lang.Object arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.Preference.OnPreferenceChangeListener))] internal sealed partial class OnPreferenceChangeListener_ : java.lang.Object, OnPreferenceChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnPreferenceChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; bool android.preference.Preference.OnPreferenceChangeListener.onPreferenceChange(android.preference.Preference arg0, java.lang.Object arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.OnPreferenceChangeListener_.staticClass, "onPreferenceChange", "(Landroid/preference/Preference;Ljava/lang/Object;)Z", ref global::android.preference.Preference.OnPreferenceChangeListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } static OnPreferenceChangeListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.Preference.OnPreferenceChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/Preference$OnPreferenceChangeListener")); } } public delegate bool OnPreferenceChangeListenerDelegate(android.preference.Preference arg0, java.lang.Object arg1); internal partial class OnPreferenceChangeListenerDelegateWrapper : java.lang.Object, OnPreferenceChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnPreferenceChangeListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnPreferenceChangeListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper.staticClass, global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper._m0); Init(@__env, handle); } static OnPreferenceChangeListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/Preference_OnPreferenceChangeListenerDelegateWrapper")); } } internal partial class OnPreferenceChangeListenerDelegateWrapper { private OnPreferenceChangeListenerDelegate myDelegate; public bool onPreferenceChange(android.preference.Preference arg0, java.lang.Object arg1) { return myDelegate(arg0, arg1); } public static implicit operator OnPreferenceChangeListenerDelegateWrapper(OnPreferenceChangeListenerDelegate d) { global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper ret = new global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.Preference.OnPreferenceClickListener_))] public partial interface OnPreferenceClickListener : global::MonoJavaBridge.IJavaObject { bool onPreferenceClick(android.preference.Preference arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.Preference.OnPreferenceClickListener))] internal sealed partial class OnPreferenceClickListener_ : java.lang.Object, OnPreferenceClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnPreferenceClickListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; bool android.preference.Preference.OnPreferenceClickListener.onPreferenceClick(android.preference.Preference arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.OnPreferenceClickListener_.staticClass, "onPreferenceClick", "(Landroid/preference/Preference;)Z", ref global::android.preference.Preference.OnPreferenceClickListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static OnPreferenceClickListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.Preference.OnPreferenceClickListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/Preference$OnPreferenceClickListener")); } } public delegate bool OnPreferenceClickListenerDelegate(android.preference.Preference arg0); internal partial class OnPreferenceClickListenerDelegateWrapper : java.lang.Object, OnPreferenceClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnPreferenceClickListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnPreferenceClickListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.Preference.OnPreferenceClickListenerDelegateWrapper.staticClass, global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper._m0); Init(@__env, handle); } static OnPreferenceClickListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/Preference_OnPreferenceClickListenerDelegateWrapper")); } } internal partial class OnPreferenceClickListenerDelegateWrapper { private OnPreferenceClickListenerDelegate myDelegate; public bool onPreferenceClick(android.preference.Preference arg0) { return myDelegate(arg0); } public static implicit operator OnPreferenceClickListenerDelegateWrapper(OnPreferenceClickListenerDelegate d) { global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper ret = new global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.preference.Preference.staticClass, "toString", "()Ljava/lang/String;", ref global::android.preference.Preference._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public virtual int compareTo(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.Preference.staticClass, "compareTo", "(Ljava/lang/Object;)I", ref global::android.preference.Preference._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public virtual int compareTo(android.preference.Preference arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.Preference.staticClass, "compareTo", "(Landroid/preference/Preference;)I", ref global::android.preference.Preference._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.lang.String Key { get { return getKey(); } set { setKey(value); } } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.lang.String getKey() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.preference.Preference.staticClass, "getKey", "()Ljava/lang/String;", ref global::android.preference.Preference._m3) as java.lang.String; } public new global::android.content.Context Context { get { return getContext(); } } private static global::MonoJavaBridge.MethodId _m4; public virtual global::android.content.Context getContext() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.Preference.staticClass, "getContext", "()Landroid/content/Context;", ref global::android.preference.Preference._m4) as android.content.Context; } private static global::MonoJavaBridge.MethodId _m5; public virtual void setKey(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setKey", "(Ljava/lang/String;)V", ref global::android.preference.Preference._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; protected virtual void onClick() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onClick", "()V", ref global::android.preference.Preference._m6); } public new global::android.content.SharedPreferences SharedPreferences { get { return getSharedPreferences(); } } private static global::MonoJavaBridge.MethodId _m7; public virtual global::android.content.SharedPreferences getSharedPreferences() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.content.SharedPreferences>(this, global::android.preference.Preference.staticClass, "getSharedPreferences", "()Landroid/content/SharedPreferences;", ref global::android.preference.Preference._m7) as android.content.SharedPreferences; } private static global::MonoJavaBridge.MethodId _m8; public virtual bool isEnabled() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "isEnabled", "()Z", ref global::android.preference.Preference._m8); } public new bool Enabled { set { setEnabled(value); } } private static global::MonoJavaBridge.MethodId _m9; public virtual void setEnabled(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setEnabled", "(Z)V", ref global::android.preference.Preference._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.content.Intent Intent { get { return getIntent(); } set { setIntent(value); } } private static global::MonoJavaBridge.MethodId _m10; public virtual global::android.content.Intent getIntent() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.Preference.staticClass, "getIntent", "()Landroid/content/Intent;", ref global::android.preference.Preference._m10) as android.content.Intent; } private static global::MonoJavaBridge.MethodId _m11; public virtual void setIntent(android.content.Intent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setIntent", "(Landroid/content/Intent;)V", ref global::android.preference.Preference._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m12; protected virtual void onRestoreInstanceState(android.os.Parcelable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onRestoreInstanceState", "(Landroid/os/Parcelable;)V", ref global::android.preference.Preference._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m13; protected virtual global::android.os.Parcelable onSaveInstanceState() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.os.Parcelable>(this, global::android.preference.Preference.staticClass, "onSaveInstanceState", "()Landroid/os/Parcelable;", ref global::android.preference.Preference._m13) as android.os.Parcelable; } public new bool Persistent { set { setPersistent(value); } } private static global::MonoJavaBridge.MethodId _m14; public virtual void setPersistent(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setPersistent", "(Z)V", ref global::android.preference.Preference._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; public virtual bool isPersistent() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "isPersistent", "()Z", ref global::android.preference.Preference._m15); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setTitle(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setTitle", "(I)V", ref global::android.preference.Preference._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public virtual void setTitle(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setTitle", "(Ljava/lang/CharSequence;)V", ref global::android.preference.Preference._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setTitle(string arg0) { setTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0); } public new string Title { get { return getTitle().toString(); } set { setTitle((global::java.lang.CharSequence)(global::java.lang.String)value); } } private static global::MonoJavaBridge.MethodId _m18; public virtual global::java.lang.CharSequence getTitle() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.preference.Preference.staticClass, "getTitle", "()Ljava/lang/CharSequence;", ref global::android.preference.Preference._m18) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m19; protected virtual global::android.view.View onCreateView(android.view.ViewGroup arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.Preference.staticClass, "onCreateView", "(Landroid/view/ViewGroup;)Landroid/view/View;", ref global::android.preference.Preference._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.View; } private static global::MonoJavaBridge.MethodId _m20; public virtual void saveHierarchyState(android.os.Bundle arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "saveHierarchyState", "(Landroid/os/Bundle;)V", ref global::android.preference.Preference._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m21; public virtual void restoreHierarchyState(android.os.Bundle arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "restoreHierarchyState", "(Landroid/os/Bundle;)V", ref global::android.preference.Preference._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Order { get { return getOrder(); } set { setOrder(value); } } private static global::MonoJavaBridge.MethodId _m22; public virtual int getOrder() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.Preference.staticClass, "getOrder", "()I", ref global::android.preference.Preference._m22); } private static global::MonoJavaBridge.MethodId _m23; public virtual global::android.view.View getView(android.view.View arg0, android.view.ViewGroup arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.Preference.staticClass, "getView", "(Landroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", ref global::android.preference.Preference._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.view.View; } private static global::MonoJavaBridge.MethodId _m24; public virtual bool isSelectable() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "isSelectable", "()Z", ref global::android.preference.Preference._m24); } private static global::MonoJavaBridge.MethodId _m25; public virtual void setOrder(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setOrder", "(I)V", ref global::android.preference.Preference._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; protected virtual void notifyChanged() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "notifyChanged", "()V", ref global::android.preference.Preference._m26); } private static global::MonoJavaBridge.MethodId _m27; protected virtual void onBindView(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onBindView", "(Landroid/view/View;)V", ref global::android.preference.Preference._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m28; public virtual bool shouldDisableDependents() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "shouldDisableDependents", "()Z", ref global::android.preference.Preference._m28); } private static global::MonoJavaBridge.MethodId _m29; protected virtual global::java.lang.Object onGetDefaultValue(android.content.res.TypedArray arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.Preference.staticClass, "onGetDefaultValue", "(Landroid/content/res/TypedArray;I)Ljava/lang/Object;", ref global::android.preference.Preference._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m30; protected virtual void onSetInitialValue(bool arg0, java.lang.Object arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onSetInitialValue", "(ZLjava/lang/Object;)V", ref global::android.preference.Preference._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m31; public virtual void setLayoutResource(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setLayoutResource", "(I)V", ref global::android.preference.Preference._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int LayoutResource { get { return getLayoutResource(); } set { setLayoutResource(value); } } private static global::MonoJavaBridge.MethodId _m32; public virtual int getLayoutResource() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.Preference.staticClass, "getLayoutResource", "()I", ref global::android.preference.Preference._m32); } private static global::MonoJavaBridge.MethodId _m33; public virtual void setWidgetLayoutResource(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setWidgetLayoutResource", "(I)V", ref global::android.preference.Preference._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int WidgetLayoutResource { get { return getWidgetLayoutResource(); } set { setWidgetLayoutResource(value); } } private static global::MonoJavaBridge.MethodId _m34; public virtual int getWidgetLayoutResource() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.Preference.staticClass, "getWidgetLayoutResource", "()I", ref global::android.preference.Preference._m34); } public new string Summary { get { return getSummary().toString(); } set { setSummary((global::java.lang.CharSequence)(global::java.lang.String)value); } } private static global::MonoJavaBridge.MethodId _m35; public virtual global::java.lang.CharSequence getSummary() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.preference.Preference.staticClass, "getSummary", "()Ljava/lang/CharSequence;", ref global::android.preference.Preference._m35) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m36; public virtual void setSummary(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setSummary", "(I)V", ref global::android.preference.Preference._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m37; public virtual void setSummary(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setSummary", "(Ljava/lang/CharSequence;)V", ref global::android.preference.Preference._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setSummary(string arg0) { setSummary((global::java.lang.CharSequence)(global::java.lang.String)arg0); } public new bool Selectable { set { setSelectable(value); } } private static global::MonoJavaBridge.MethodId _m38; public virtual void setSelectable(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setSelectable", "(Z)V", ref global::android.preference.Preference._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m39; public virtual void setShouldDisableView(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setShouldDisableView", "(Z)V", ref global::android.preference.Preference._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new bool ShouldDisableView { get { return getShouldDisableView(); } set { setShouldDisableView(value); } } private static global::MonoJavaBridge.MethodId _m40; public virtual bool getShouldDisableView() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "getShouldDisableView", "()Z", ref global::android.preference.Preference._m40); } private static global::MonoJavaBridge.MethodId _m41; public virtual bool hasKey() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "hasKey", "()Z", ref global::android.preference.Preference._m41); } private static global::MonoJavaBridge.MethodId _m42; protected virtual bool shouldPersist() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "shouldPersist", "()Z", ref global::android.preference.Preference._m42); } private static global::MonoJavaBridge.MethodId _m43; protected virtual bool callChangeListener(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "callChangeListener", "(Ljava/lang/Object;)Z", ref global::android.preference.Preference._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m44; public virtual void setOnPreferenceChangeListener(android.preference.Preference.OnPreferenceChangeListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setOnPreferenceChangeListener", "(Landroid/preference/Preference$OnPreferenceChangeListener;)V", ref global::android.preference.Preference._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnPreferenceChangeListener(global::android.preference.Preference.OnPreferenceChangeListenerDelegate arg0) { setOnPreferenceChangeListener((global::android.preference.Preference.OnPreferenceChangeListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m45; public virtual global::android.preference.Preference.OnPreferenceChangeListener getOnPreferenceChangeListener() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.preference.Preference.OnPreferenceChangeListener>(this, global::android.preference.Preference.staticClass, "getOnPreferenceChangeListener", "()Landroid/preference/Preference$OnPreferenceChangeListener;", ref global::android.preference.Preference._m45) as android.preference.Preference.OnPreferenceChangeListener; } private static global::MonoJavaBridge.MethodId _m46; public virtual void setOnPreferenceClickListener(android.preference.Preference.OnPreferenceClickListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setOnPreferenceClickListener", "(Landroid/preference/Preference$OnPreferenceClickListener;)V", ref global::android.preference.Preference._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnPreferenceClickListener(global::android.preference.Preference.OnPreferenceClickListenerDelegate arg0) { setOnPreferenceClickListener((global::android.preference.Preference.OnPreferenceClickListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m47; public virtual global::android.preference.Preference.OnPreferenceClickListener getOnPreferenceClickListener() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.preference.Preference.OnPreferenceClickListener>(this, global::android.preference.Preference.staticClass, "getOnPreferenceClickListener", "()Landroid/preference/Preference$OnPreferenceClickListener;", ref global::android.preference.Preference._m47) as android.preference.Preference.OnPreferenceClickListener; } public new global::android.content.SharedPreferences_Editor Editor { get { return getEditor(); } } private static global::MonoJavaBridge.MethodId _m48; public virtual global::android.content.SharedPreferences_Editor getEditor() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.content.SharedPreferences_Editor>(this, global::android.preference.Preference.staticClass, "getEditor", "()Landroid/content/SharedPreferences$Editor;", ref global::android.preference.Preference._m48) as android.content.SharedPreferences_Editor; } private static global::MonoJavaBridge.MethodId _m49; public virtual bool shouldCommit() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "shouldCommit", "()Z", ref global::android.preference.Preference._m49); } private static global::MonoJavaBridge.MethodId _m50; protected virtual void notifyHierarchyChanged() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "notifyHierarchyChanged", "()V", ref global::android.preference.Preference._m50); } public new global::android.preference.PreferenceManager PreferenceManager { get { return getPreferenceManager(); } } private static global::MonoJavaBridge.MethodId _m51; public virtual global::android.preference.PreferenceManager getPreferenceManager() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.Preference.staticClass, "getPreferenceManager", "()Landroid/preference/PreferenceManager;", ref global::android.preference.Preference._m51) as android.preference.PreferenceManager; } private static global::MonoJavaBridge.MethodId _m52; protected virtual void onAttachedToHierarchy(android.preference.PreferenceManager arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onAttachedToHierarchy", "(Landroid/preference/PreferenceManager;)V", ref global::android.preference.Preference._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m53; protected virtual void onAttachedToActivity() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onAttachedToActivity", "()V", ref global::android.preference.Preference._m53); } private static global::MonoJavaBridge.MethodId _m54; protected virtual global::android.preference.Preference findPreferenceInHierarchy(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.Preference.staticClass, "findPreferenceInHierarchy", "(Ljava/lang/String;)Landroid/preference/Preference;", ref global::android.preference.Preference._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.preference.Preference; } private static global::MonoJavaBridge.MethodId _m55; public virtual void notifyDependencyChange(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "notifyDependencyChange", "(Z)V", ref global::android.preference.Preference._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m56; public virtual void onDependencyChanged(android.preference.Preference arg0, bool arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onDependencyChanged", "(Landroid/preference/Preference;Z)V", ref global::android.preference.Preference._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m57; public virtual void setDependency(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setDependency", "(Ljava/lang/String;)V", ref global::android.preference.Preference._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.lang.String Dependency { get { return getDependency(); } set { setDependency(value); } } private static global::MonoJavaBridge.MethodId _m58; public virtual global::java.lang.String getDependency() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.preference.Preference.staticClass, "getDependency", "()Ljava/lang/String;", ref global::android.preference.Preference._m58) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m59; protected virtual void onPrepareForRemoval() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "onPrepareForRemoval", "()V", ref global::android.preference.Preference._m59); } public new global::java.lang.Object DefaultValue { set { setDefaultValue(value); } } private static global::MonoJavaBridge.MethodId _m60; public virtual void setDefaultValue(java.lang.Object arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.Preference.staticClass, "setDefaultValue", "(Ljava/lang/Object;)V", ref global::android.preference.Preference._m60, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m61; protected virtual bool persistString(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "persistString", "(Ljava/lang/String;)Z", ref global::android.preference.Preference._m61, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m62; protected virtual global::java.lang.String getPersistedString(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.preference.Preference.staticClass, "getPersistedString", "(Ljava/lang/String;)Ljava/lang/String;", ref global::android.preference.Preference._m62, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m63; protected virtual bool persistInt(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "persistInt", "(I)Z", ref global::android.preference.Preference._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m64; protected virtual int getPersistedInt(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.Preference.staticClass, "getPersistedInt", "(I)I", ref global::android.preference.Preference._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m65; protected virtual bool persistFloat(float arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "persistFloat", "(F)Z", ref global::android.preference.Preference._m65, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m66; protected virtual float getPersistedFloat(float arg0) { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.preference.Preference.staticClass, "getPersistedFloat", "(F)F", ref global::android.preference.Preference._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m67; protected virtual bool persistLong(long arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "persistLong", "(J)Z", ref global::android.preference.Preference._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m68; protected virtual long getPersistedLong(long arg0) { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.preference.Preference.staticClass, "getPersistedLong", "(J)J", ref global::android.preference.Preference._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m69; protected virtual bool persistBoolean(bool arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "persistBoolean", "(Z)Z", ref global::android.preference.Preference._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m70; protected virtual bool getPersistedBoolean(bool arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.preference.Preference.staticClass, "getPersistedBoolean", "(Z)Z", ref global::android.preference.Preference._m70, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m71; public Preference(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.Preference._m71.native == global::System.IntPtr.Zero) global::android.preference.Preference._m71 = @__env.GetMethodIDNoThrow(global::android.preference.Preference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.Preference.staticClass, global::android.preference.Preference._m71, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m72; public Preference(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.Preference._m72.native == global::System.IntPtr.Zero) global::android.preference.Preference._m72 = @__env.GetMethodIDNoThrow(global::android.preference.Preference.staticClass, "<init>", "(Landroid/content/Context;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.Preference.staticClass, global::android.preference.Preference._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m73; public Preference(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.Preference._m73.native == global::System.IntPtr.Zero) global::android.preference.Preference._m73 = @__env.GetMethodIDNoThrow(global::android.preference.Preference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.Preference.staticClass, global::android.preference.Preference._m73, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } public static int DEFAULT_ORDER { get { return 2147483647; } } static Preference() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.Preference.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/Preference")); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Globalization; using System.Text.RegularExpressions; using mshtml; using OpenLiveWriter.Api; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.Extensibility.ImageEditing; namespace OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators { /// <summary> /// Summary description for Decorator. /// </summary> public class HtmlMarginDecorator : IImageDecorator, IImageDecoratorDefaultSettingsCustomizer { public readonly static string Id = "HtmlMargin"; public HtmlMarginDecorator() { } public void Decorate(ImageDecoratorContext context) { if(context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert || context.InvocationSource == ImageDecoratorInvocationSource.Reset) { HtmlMarginDecoratorSettings settings = new HtmlMarginDecoratorSettings(context.Settings, context.ImgElement); if (settings.UseUserCustomMargin) { settings.Margin = settings.UserDefaultMargin; } else { settings.Margin = HtmlMarginDecoratorSettings.WriterDefaultMargin; } } } public ImageDecoratorEditor CreateEditor(CommandManager commandManager) { return new HtmlMarginEditor(commandManager); } void IImageDecoratorDefaultSettingsCustomizer.CustomizeDefaultSettingsBeforeSave(ImageDecoratorEditorContext context, IProperties defaultSettings) { HtmlMarginDecoratorSettings settings = new HtmlMarginDecoratorSettings(defaultSettings, context.ImgElement); settings.UseUserCustomMargin = settings.HasCustomMargin; settings.UserDefaultMargin = settings.Margin; } } internal class HtmlMarginDecoratorSettings { private const string CUSTOM_MARGIN = "UseUserCustomMargin"; private const string MARGIN_TOP = "DefaultMarginTop"; private const string MARGIN_RIGHT = "DefaultMarginRight"; private const string MARGIN_BOTTOM = "DefaultMarginBottom"; private const string MARGIN_LEFT = "DefaultMarginLeft"; private readonly IProperties Settings; private readonly IHTMLElement ImgElement; public HtmlMarginDecoratorSettings(IProperties settings, IHTMLElement imgElement) { Settings = settings; ImgElement = imgElement; } public bool UseUserCustomMargin { get { return Settings.GetBoolean(CUSTOM_MARGIN, false); } set { Settings.SetBoolean(CUSTOM_MARGIN, value); } } /// <summary> /// Get/Set the user-supplied default margin of the image. /// </summary> public MarginStyle UserDefaultMargin { get { int top = Settings.GetInt(MARGIN_TOP, WriterDefaultMargin.Top); int right = Settings.GetInt(MARGIN_RIGHT, WriterDefaultMargin.Right); int bottom = Settings.GetInt(MARGIN_BOTTOM, WriterDefaultMargin.Bottom); int left = Settings.GetInt(MARGIN_LEFT, WriterDefaultMargin.Left); return new MarginStyle(top, right, bottom, left, StyleSizeUnit.PX); } set { Settings.SetInt(MARGIN_TOP, value.Top); Settings.SetInt(MARGIN_RIGHT, value.Right); Settings.SetInt(MARGIN_BOTTOM, value.Bottom); Settings.SetInt(MARGIN_LEFT, value.Left); } } /// <summary> /// Get/Set the Writer default margin of the image. /// </summary> public static MarginStyle WriterDefaultMargin { get { return new MarginStyle(0, 0, 0, 0, StyleSizeUnit.PX); } } public bool HasCustomMargin { get { string margin = ImgElement.style.margin; if (margin != null && margin != "auto") return true; else return Margin != WriterDefaultMargin; } } public static MarginStyle GetImageMargin(IProperties props) { if (props.GetBoolean(CUSTOM_MARGIN, false)) { int top = props.GetInt(MARGIN_TOP, WriterDefaultMargin.Top); int right = props.GetInt(MARGIN_RIGHT, WriterDefaultMargin.Right); int bottom = props.GetInt(MARGIN_BOTTOM, WriterDefaultMargin.Bottom); int left = props.GetInt(MARGIN_LEFT, WriterDefaultMargin.Left); return new MarginStyle(top, right, bottom, left, StyleSizeUnit.PX); } else { return WriterDefaultMargin; } } /// <summary> /// Get/Set the margin of the image. /// </summary> public MarginStyle Margin { get { return GetMarginStyleFromHtml(ImgElement); } set { if(value != null) ImgElement.style.margin = GetHtmlMarginFromMarginStyle(value, ImgElement); else //unset any explicit margin style info so that the default is inherited. ImgElement.style.margin = null; } } private static string GetHtmlMarginFromMarginStyle(MarginStyle margin, IHTMLElement element) { string unitSize = margin.SizeUnit.ToString().ToLower(CultureInfo.InvariantCulture); string marginRight = margin.Right.ToString(CultureInfo.InvariantCulture) + unitSize; string marginLeft = margin.Left.ToString(CultureInfo.InvariantCulture) + unitSize; string currentRightMargin = ""; if(element.style.marginRight != null) currentRightMargin = element.style.marginRight.ToString(); string currentLeftMargin = ""; if (element.style.marginLeft != null) currentLeftMargin = element.style.marginLeft.ToString(); // This is because margins and centering images can conflict with eachother if (margin.Right == 0 && currentRightMargin == "auto" && margin.Left == 0 && currentLeftMargin == "auto") { marginRight = "auto"; marginLeft = "auto"; } else if ((margin.Right != 0 || margin.Left != 0) && currentRightMargin == "auto" && currentLeftMargin == "auto") { // The user is breaking their centered image by setting a L/R margin element.style.display = "inline"; } string marginString = String.Format(CultureInfo.InvariantCulture, "{0}{4} {1} {2}{4} {3}", margin.Top, marginRight, margin.Bottom, marginLeft, unitSize); return marginString; } public MarginStyle GetMarginStyleFromHtml(IHTMLElement img) { IHTMLElement2 img2 = (IHTMLElement2)img; int marginTop = GetPixels(img2.currentStyle.marginTop as string); int marginRight = GetPixels(img2.currentStyle.marginRight as string); int marginBottom = GetPixels(img2.currentStyle.marginBottom as string); int marginLeft = GetPixels(img2.currentStyle.marginLeft as string); MarginStyle margin = new MarginStyle(marginTop, marginRight, marginBottom, marginLeft, StyleSizeUnit.PX); return margin; } public static int GetPixels(object pixelString) { if(pixelString == null) return 0; string htmlString = pixelString.ToString(); Match match = marginRegex.Match(htmlString); string pixelCount = match.Groups["pixels"].Value; if(pixelCount == null || pixelCount == String.Empty) return 0; else { try { return Int32.Parse(pixelCount, CultureInfo.InvariantCulture); } catch(Exception) { return 0; } } } private static Regex marginRegex = new Regex(@"(?<pixels>\d{1,4})\s*px"); } public enum StyleSizeUnit { PX, EM }; public class MarginStyle { public MarginStyle(int top, int right, int bottom, int left, StyleSizeUnit unit) { Top = top; Right = right; Bottom = bottom; Left = left; SizeUnit = unit; } public int Top; public int Bottom; public int Left; public int Right; public StyleSizeUnit SizeUnit; public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "{0}{4} {1}{4} {2}{4} {3}{4}", Top, Right, Bottom, Left, SizeUnit.ToString().ToLower(CultureInfo.InvariantCulture)); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// Contains information for transfering values between Salesforce data fields and DocuSign Tabs. /// </summary> [DataContract] public partial class MergeField : IEquatable<MergeField>, IValidatableObject { public MergeField() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="MergeField" /> class. /// </summary> /// <param name="AllowSenderToEdit">When set to **true**, the sender can modify the value of the custom tab during the sending process..</param> /// <param name="AllowSenderToEditMetadata">AllowSenderToEditMetadata.</param> /// <param name="ConfigurationType">If merge field&#39;s are being used, specifies the type of the merge field. The only supported value is **salesforce**..</param> /// <param name="ConfigurationTypeMetadata">ConfigurationTypeMetadata.</param> /// <param name="Path">Sets the object associated with the custom tab. Currently this is the Salesforce Object..</param> /// <param name="PathExtended">PathExtended.</param> /// <param name="PathExtendedMetadata">PathExtendedMetadata.</param> /// <param name="PathMetadata">PathMetadata.</param> /// <param name="Row">Specifies the row number in a Salesforce table that the merge field value corresponds to..</param> /// <param name="RowMetadata">RowMetadata.</param> /// <param name="WriteBack">When wet to true, the information entered in the tab automatically updates the related Salesforce data when an envelope is completed..</param> /// <param name="WriteBackMetadata">WriteBackMetadata.</param> public MergeField(string AllowSenderToEdit = default(string), PropertyMetadata AllowSenderToEditMetadata = default(PropertyMetadata), string ConfigurationType = default(string), PropertyMetadata ConfigurationTypeMetadata = default(PropertyMetadata), string Path = default(string), List<PathExtendedElement> PathExtended = default(List<PathExtendedElement>), PropertyMetadata PathExtendedMetadata = default(PropertyMetadata), PropertyMetadata PathMetadata = default(PropertyMetadata), string Row = default(string), PropertyMetadata RowMetadata = default(PropertyMetadata), string WriteBack = default(string), PropertyMetadata WriteBackMetadata = default(PropertyMetadata)) { this.AllowSenderToEdit = AllowSenderToEdit; this.AllowSenderToEditMetadata = AllowSenderToEditMetadata; this.ConfigurationType = ConfigurationType; this.ConfigurationTypeMetadata = ConfigurationTypeMetadata; this.Path = Path; this.PathExtended = PathExtended; this.PathExtendedMetadata = PathExtendedMetadata; this.PathMetadata = PathMetadata; this.Row = Row; this.RowMetadata = RowMetadata; this.WriteBack = WriteBack; this.WriteBackMetadata = WriteBackMetadata; } /// <summary> /// When set to **true**, the sender can modify the value of the custom tab during the sending process. /// </summary> /// <value>When set to **true**, the sender can modify the value of the custom tab during the sending process.</value> [DataMember(Name="allowSenderToEdit", EmitDefaultValue=false)] public string AllowSenderToEdit { get; set; } /// <summary> /// Gets or Sets AllowSenderToEditMetadata /// </summary> [DataMember(Name="allowSenderToEditMetadata", EmitDefaultValue=false)] public PropertyMetadata AllowSenderToEditMetadata { get; set; } /// <summary> /// If merge field&#39;s are being used, specifies the type of the merge field. The only supported value is **salesforce**. /// </summary> /// <value>If merge field&#39;s are being used, specifies the type of the merge field. The only supported value is **salesforce**.</value> [DataMember(Name="configurationType", EmitDefaultValue=false)] public string ConfigurationType { get; set; } /// <summary> /// Gets or Sets ConfigurationTypeMetadata /// </summary> [DataMember(Name="configurationTypeMetadata", EmitDefaultValue=false)] public PropertyMetadata ConfigurationTypeMetadata { get; set; } /// <summary> /// Sets the object associated with the custom tab. Currently this is the Salesforce Object. /// </summary> /// <value>Sets the object associated with the custom tab. Currently this is the Salesforce Object.</value> [DataMember(Name="path", EmitDefaultValue=false)] public string Path { get; set; } /// <summary> /// Gets or Sets PathExtended /// </summary> [DataMember(Name="pathExtended", EmitDefaultValue=false)] public List<PathExtendedElement> PathExtended { get; set; } /// <summary> /// Gets or Sets PathExtendedMetadata /// </summary> [DataMember(Name="pathExtendedMetadata", EmitDefaultValue=false)] public PropertyMetadata PathExtendedMetadata { get; set; } /// <summary> /// Gets or Sets PathMetadata /// </summary> [DataMember(Name="pathMetadata", EmitDefaultValue=false)] public PropertyMetadata PathMetadata { get; set; } /// <summary> /// Specifies the row number in a Salesforce table that the merge field value corresponds to. /// </summary> /// <value>Specifies the row number in a Salesforce table that the merge field value corresponds to.</value> [DataMember(Name="row", EmitDefaultValue=false)] public string Row { get; set; } /// <summary> /// Gets or Sets RowMetadata /// </summary> [DataMember(Name="rowMetadata", EmitDefaultValue=false)] public PropertyMetadata RowMetadata { get; set; } /// <summary> /// When wet to true, the information entered in the tab automatically updates the related Salesforce data when an envelope is completed. /// </summary> /// <value>When wet to true, the information entered in the tab automatically updates the related Salesforce data when an envelope is completed.</value> [DataMember(Name="writeBack", EmitDefaultValue=false)] public string WriteBack { get; set; } /// <summary> /// Gets or Sets WriteBackMetadata /// </summary> [DataMember(Name="writeBackMetadata", EmitDefaultValue=false)] public PropertyMetadata WriteBackMetadata { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class MergeField {\n"); sb.Append(" AllowSenderToEdit: ").Append(AllowSenderToEdit).Append("\n"); sb.Append(" AllowSenderToEditMetadata: ").Append(AllowSenderToEditMetadata).Append("\n"); sb.Append(" ConfigurationType: ").Append(ConfigurationType).Append("\n"); sb.Append(" ConfigurationTypeMetadata: ").Append(ConfigurationTypeMetadata).Append("\n"); sb.Append(" Path: ").Append(Path).Append("\n"); sb.Append(" PathExtended: ").Append(PathExtended).Append("\n"); sb.Append(" PathExtendedMetadata: ").Append(PathExtendedMetadata).Append("\n"); sb.Append(" PathMetadata: ").Append(PathMetadata).Append("\n"); sb.Append(" Row: ").Append(Row).Append("\n"); sb.Append(" RowMetadata: ").Append(RowMetadata).Append("\n"); sb.Append(" WriteBack: ").Append(WriteBack).Append("\n"); sb.Append(" WriteBackMetadata: ").Append(WriteBackMetadata).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as MergeField); } /// <summary> /// Returns true if MergeField instances are equal /// </summary> /// <param name="other">Instance of MergeField to be compared</param> /// <returns>Boolean</returns> public bool Equals(MergeField other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AllowSenderToEdit == other.AllowSenderToEdit || this.AllowSenderToEdit != null && this.AllowSenderToEdit.Equals(other.AllowSenderToEdit) ) && ( this.AllowSenderToEditMetadata == other.AllowSenderToEditMetadata || this.AllowSenderToEditMetadata != null && this.AllowSenderToEditMetadata.Equals(other.AllowSenderToEditMetadata) ) && ( this.ConfigurationType == other.ConfigurationType || this.ConfigurationType != null && this.ConfigurationType.Equals(other.ConfigurationType) ) && ( this.ConfigurationTypeMetadata == other.ConfigurationTypeMetadata || this.ConfigurationTypeMetadata != null && this.ConfigurationTypeMetadata.Equals(other.ConfigurationTypeMetadata) ) && ( this.Path == other.Path || this.Path != null && this.Path.Equals(other.Path) ) && ( this.PathExtended == other.PathExtended || this.PathExtended != null && this.PathExtended.SequenceEqual(other.PathExtended) ) && ( this.PathExtendedMetadata == other.PathExtendedMetadata || this.PathExtendedMetadata != null && this.PathExtendedMetadata.Equals(other.PathExtendedMetadata) ) && ( this.PathMetadata == other.PathMetadata || this.PathMetadata != null && this.PathMetadata.Equals(other.PathMetadata) ) && ( this.Row == other.Row || this.Row != null && this.Row.Equals(other.Row) ) && ( this.RowMetadata == other.RowMetadata || this.RowMetadata != null && this.RowMetadata.Equals(other.RowMetadata) ) && ( this.WriteBack == other.WriteBack || this.WriteBack != null && this.WriteBack.Equals(other.WriteBack) ) && ( this.WriteBackMetadata == other.WriteBackMetadata || this.WriteBackMetadata != null && this.WriteBackMetadata.Equals(other.WriteBackMetadata) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AllowSenderToEdit != null) hash = hash * 59 + this.AllowSenderToEdit.GetHashCode(); if (this.AllowSenderToEditMetadata != null) hash = hash * 59 + this.AllowSenderToEditMetadata.GetHashCode(); if (this.ConfigurationType != null) hash = hash * 59 + this.ConfigurationType.GetHashCode(); if (this.ConfigurationTypeMetadata != null) hash = hash * 59 + this.ConfigurationTypeMetadata.GetHashCode(); if (this.Path != null) hash = hash * 59 + this.Path.GetHashCode(); if (this.PathExtended != null) hash = hash * 59 + this.PathExtended.GetHashCode(); if (this.PathExtendedMetadata != null) hash = hash * 59 + this.PathExtendedMetadata.GetHashCode(); if (this.PathMetadata != null) hash = hash * 59 + this.PathMetadata.GetHashCode(); if (this.Row != null) hash = hash * 59 + this.Row.GetHashCode(); if (this.RowMetadata != null) hash = hash * 59 + this.RowMetadata.GetHashCode(); if (this.WriteBack != null) hash = hash * 59 + this.WriteBack.GetHashCode(); if (this.WriteBackMetadata != null) hash = hash * 59 + this.WriteBackMetadata.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ImplicitModel operations. /// </summary> public partial class ImplicitModel : IServiceOperations<AutoRestRequiredOptionalTestService>, IImplicitModel { /// <summary> /// Initializes a new instance of the ImplicitModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ImplicitModel(AutoRestRequiredOptionalTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestRequiredOptionalTestService /// </summary> public AutoRestRequiredOptionalTestService Client { get; private set; } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='pathParameter'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> GetRequiredPathWithHttpMessagesAsync(string pathParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (pathParameter == null) { throw new ValidationException(ValidationRules.CannotBeNull, "pathParameter"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("pathParameter", pathParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetRequiredPath", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/required/path/{pathParameter}").ToString(); _url = _url.Replace("{pathParameter}", System.Uri.EscapeDataString(pathParameter)); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='queryParameter'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutOptionalQueryWithHttpMessagesAsync(string queryParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("queryParameter", queryParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutOptionalQuery", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/query").ToString(); List<string> _queryParameters = new List<string>(); if (queryParameter != null) { _queryParameters.Add(string.Format("queryParameter={0}", System.Uri.EscapeDataString(queryParameter))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='queryParameter'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutOptionalHeaderWithHttpMessagesAsync(string queryParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("queryParameter", queryParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutOptionalHeader", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/header").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (queryParameter != null) { if (_httpRequest.Headers.Contains("queryParameter")) { _httpRequest.Headers.Remove("queryParameter"); } _httpRequest.Headers.TryAddWithoutValidation("queryParameter", queryParameter); } 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutOptionalBodyWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutOptionalBody", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/body").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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(bodyParameter != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(bodyParameter, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> GetRequiredGlobalPathWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.RequiredGlobalPath == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RequiredGlobalPath"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetRequiredGlobalPath", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/required/path/{required-global-path}").ToString(); _url = _url.Replace("{required-global-path}", System.Uri.EscapeDataString(Client.RequiredGlobalPath)); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> GetRequiredGlobalQueryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.RequiredGlobalQuery == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RequiredGlobalQuery"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetRequiredGlobalQuery", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/required/query").ToString(); List<string> _queryParameters = new List<string>(); if (Client.RequiredGlobalQuery != null) { _queryParameters.Add(string.Format("required-global-query={0}", System.Uri.EscapeDataString(Client.RequiredGlobalQuery))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> GetOptionalGlobalQueryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetOptionalGlobalQuery", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/optional/query").ToString(); List<string> _queryParameters = new List<string>(); if (Client.OptionalGlobalQuery != null) { _queryParameters.Add(string.Format("optional-global-query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(Client.OptionalGlobalQuery, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Data; using System.Data.SQLite; using System.Collections; namespace System.Data.SQLite.Benchmark { using sqlite = Sqlite3.sqlite3; using Vdbe = Sqlite3.Vdbe; /// <summary> /// C#-SQLite wrapper with functions for opening, closing and executing queries. /// </summary> public class SQLiteDatabase { // pointer to database private sqlite db; /// <summary> /// Creates new instance of SQLiteBase class with no database attached. /// </summary> public SQLiteDatabase() { db = null; } /// <summary> /// Creates new instance of SQLiteDatabase class and opens database with given name. /// </summary> /// <param name="DatabaseName">Name (and path) to SQLite database file</param> public SQLiteDatabase(String DatabaseName) { OpenDatabase(DatabaseName); } /// <summary> /// Opens database. /// </summary> /// <param name="DatabaseName">Name of database file</param> public void OpenDatabase(String DatabaseName) { // opens database if(Sqlite3.sqlite3_open(DatabaseName, out db) != Sqlite3.SQLITE_OK) { // if there is some error, database pointer is set to 0 and exception is throws db = null; throw new Exception("Error with opening database " + DatabaseName + "!"); } } /// <summary> /// Closes opened database. /// </summary> public void CloseDatabase() { // closes the database if there is one opened if(db != null) { Sqlite3.sqlite3_close(db); } } /// <summary> /// Returns connection /// </summary> public sqlite Connection() { return db; } /// <summary> /// Returns the list of tables in opened database. /// </summary> /// <returns></returns> public ArrayList GetTables() { // executes query that select names of all tables in master table of the database String query = "SELECT name FROM sqlite_master " + "WHERE type = 'table'" + "ORDER BY 1"; DataTable table = ExecuteQuery(query); // Return all table names in the ArrayList ArrayList list = new ArrayList(); foreach(DataRow row in table.Rows) { list.Add(row.ItemArray[0].ToString()); } return list; } /// <summary> /// Executes query that does not return anything (e.g. UPDATE, INSERT, DELETE). /// </summary> /// <param name="query"></param> public void ExecuteNonQuery(String query) { // calles SQLite function that executes non-query Sqlite3.exec(db, query, 0, 0, 0); // if there is error, excetion is thrown if(db.errCode != Sqlite3.SQLITE_OK) throw new Exception("Error with executing non-query: \"" + query + "\"!\n" + Sqlite3.sqlite3_errmsg(db)); } /// <summary> /// Executes query that does return something (e.g. SELECT). /// </summary> /// <param name="query"></param> /// <returns></returns> public DataTable ExecuteQuery(String query) { // compiled query SQLiteVdbe statement = new SQLiteVdbe(this, query); // table for result of query DataTable table = new DataTable(); // create new instance of DataTable with name "resultTable" table = new DataTable("resultTable"); // reads rows do { } while ( ReadNextRow( statement.VirtualMachine(), table ) == Sqlite3.SQLITE_ROW ); // finalize executing this query statement.Close(); // returns table return table; } // private function for reading rows and creating table and columns private int ReadNextRow(Vdbe vm, DataTable table) { int columnCount = table.Columns.Count; if(columnCount == 0) { if((columnCount = ReadColumnNames(vm, table)) == 0) return Sqlite3.SQLITE_ERROR; } int resultType; if((resultType = Sqlite3.sqlite3_step(vm)) == Sqlite3.SQLITE_ROW) { object[] columnValues = new object[columnCount]; for(int i = 0; i < columnCount; i++) { int columnType = Sqlite3.sqlite3_column_type(vm, i); switch(columnType) { case Sqlite3.SQLITE_INTEGER: { table.Columns[i].DataType = typeof(Int64); columnValues[i] = Sqlite3.sqlite3_column_int(vm, i); break; } case Sqlite3.SQLITE_FLOAT: { table.Columns[i].DataType = typeof(Double); columnValues[i] = Sqlite3.sqlite3_column_double(vm, i); break; } case Sqlite3.SQLITE_TEXT: { table.Columns[i].DataType = typeof(String); columnValues[i] = Sqlite3.sqlite3_column_text(vm, i); break; } case Sqlite3.SQLITE_BLOB: { table.Columns[i].DataType = typeof(Byte[]); columnValues[i] = Sqlite3.sqlite3_column_blob(vm, i); break; } default: { table.Columns[i].DataType = null; columnValues[i] = ""; break; } } } table.Rows.Add(columnValues); } return resultType; } // private function for creating Column Names // Return number of colums read private int ReadColumnNames(Vdbe vm, DataTable table) { String columnName = ""; int columnType = 0; // returns number of columns returned by statement int columnCount = Sqlite3.sqlite3_column_count(vm); object[] columnValues = new object[columnCount]; try { // reads columns one by one for(int i = 0; i < columnCount; i++) { columnName = Sqlite3.sqlite3_column_name(vm, i); columnType = Sqlite3.sqlite3_column_type(vm, i); switch(columnType) { case Sqlite3.SQLITE_INTEGER: { // adds new integer column to table table.Columns.Add(columnName, Type.GetType("System.Int64")); break; } case Sqlite3.SQLITE_FLOAT: { table.Columns.Add(columnName, Type.GetType("System.Double")); break; } case Sqlite3.SQLITE_TEXT: { table.Columns.Add(columnName, Type.GetType("System.String")); break; } case Sqlite3.SQLITE_BLOB: { table.Columns.Add(columnName, Type.GetType("System.byte[]")); break; } default: { table.Columns.Add(columnName, Type.GetType("System.String")); break; } } } } catch { return 0; } return table.Columns.Count; } } }
using System; using System.Collections.Generic; using UnityEngine; using MessageStream2; using DarkMultiPlayerCommon; namespace DarkMultiPlayer { public class ScreenshotWorker { //Height setting public int screenshotHeight = 720; private static ScreenshotWorker singleton; //GUI stuff private bool initialized; private bool isWindowLocked = false; public bool workerEnabled; private GUIStyle windowStyle; private GUILayoutOption[] windowLayoutOption; private GUIStyle buttonStyle; private GUIStyle highlightStyle; private GUILayoutOption[] fixedButtonSizeOption; private GUIStyle scrollStyle; public bool display; private bool safeDisplay; private Rect windowRect; private Rect moveRect; private Vector2 scrollPos; //State tracking public bool screenshotButtonHighlighted; List<string> highlightedPlayers = new List<string>(); private string selectedPlayer = ""; private string safeSelectedPlayer = ""; private Dictionary<string, Texture2D> screenshots = new Dictionary<string, Texture2D>(); private bool uploadEventHandled = true; public bool uploadScreenshot = false; private float lastScreenshotSend; private Queue<ScreenshotEntry> newScreenshotQueue = new Queue<ScreenshotEntry>(); private Queue<ScreenshotWatchEntry> newScreenshotWatchQueue = new Queue<ScreenshotWatchEntry>(); private Queue<string> newScreenshotNotifiyQueue = new Queue<string>(); private Dictionary<string, string> watchPlayers = new Dictionary<string, string>(); //Screenshot uploading message private bool displayScreenshotUploadingMessage = false; public bool finishedUploadingScreenshot = false; public string downloadingScreenshotFromPlayer; private float lastScreenshotMessageCheck; ScreenMessage screenshotUploadMessage; ScreenMessage screenshotDownloadMessage; //delay the screenshot message until we've taken a screenshot public bool screenshotTaken; //const private const float MIN_WINDOW_HEIGHT = 200; private const float MIN_WINDOW_WIDTH = 150; private const float BUTTON_WIDTH = 150; private const float SCREENSHOT_MESSAGE_CHECK_INTERVAL = .2f; private const float MIN_SCREENSHOT_SEND_INTERVAL = 3f; public static ScreenshotWorker fetch { get { return singleton; } } private void InitGUI() { windowRect = new Rect(50, (Screen.height / 2f) - (MIN_WINDOW_HEIGHT / 2f), MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT); moveRect = new Rect(0, 0, 10000, 20); windowLayoutOption = new GUILayoutOption[4]; windowLayoutOption[0] = GUILayout.MinWidth(MIN_WINDOW_WIDTH); windowLayoutOption[1] = GUILayout.MinHeight(MIN_WINDOW_HEIGHT); windowLayoutOption[2] = GUILayout.ExpandWidth(true); windowLayoutOption[3] = GUILayout.ExpandHeight(true); windowStyle = new GUIStyle(GUI.skin.window); buttonStyle = new GUIStyle(GUI.skin.button); highlightStyle = new GUIStyle(GUI.skin.button); highlightStyle.normal.textColor = Color.red; highlightStyle.active.textColor = Color.red; highlightStyle.hover.textColor = Color.red; fixedButtonSizeOption = new GUILayoutOption[2]; fixedButtonSizeOption[0] = GUILayout.Width(BUTTON_WIDTH); fixedButtonSizeOption[1] = GUILayout.ExpandWidth(true); scrollStyle = new GUIStyle(GUI.skin.scrollView); scrollPos = new Vector2(0, 0); } private void Update() { safeDisplay = display; if (workerEnabled) { while (newScreenshotNotifiyQueue.Count > 0) { string notifyPlayer = newScreenshotNotifiyQueue.Dequeue(); if (!display) { screenshotButtonHighlighted = true; } if (selectedPlayer != notifyPlayer) { if (!highlightedPlayers.Contains(notifyPlayer)) { highlightedPlayers.Add(notifyPlayer); } } ChatWorker.fetch.QueueChannelMessage("Server", "", notifyPlayer + " shared screenshot"); } //Update highlights if (screenshotButtonHighlighted && display) { screenshotButtonHighlighted = false; } if (highlightedPlayers.Contains(selectedPlayer)) { highlightedPlayers.Remove(selectedPlayer); } while (newScreenshotQueue.Count > 0) { ScreenshotEntry se = newScreenshotQueue.Dequeue(); Texture2D screenshotTexture = new Texture2D(4, 4, TextureFormat.RGB24, false, true); if (screenshotTexture.LoadImage(se.screenshotData)) { screenshotTexture.Apply(); //Make sure screenshots aren't bigger than 2/3rds of the screen. ResizeTextureIfNeeded(ref screenshotTexture); //Save the texture in memory screenshots[se.fromPlayer] = screenshotTexture; DarkLog.Debug("Loaded screenshot from " + se.fromPlayer); } else { DarkLog.Debug("Error loading screenshot from " + se.fromPlayer); } } while (newScreenshotWatchQueue.Count > 0) { ScreenshotWatchEntry swe = newScreenshotWatchQueue.Dequeue(); if (swe.watchPlayer != "") { watchPlayers[swe.fromPlayer] = swe.watchPlayer; } else { if (watchPlayers.ContainsKey(swe.fromPlayer)) { watchPlayers.Remove(swe.fromPlayer); } } } if (safeSelectedPlayer != selectedPlayer) { windowRect.height = 0; windowRect.width = 0; safeSelectedPlayer = selectedPlayer; WatchPlayer(selectedPlayer); } if (Input.GetKey(Settings.fetch.screenshotKey)) { uploadEventHandled = false; } if (!uploadEventHandled) { uploadEventHandled = true; if ((UnityEngine.Time.realtimeSinceStartup - lastScreenshotSend) > MIN_SCREENSHOT_SEND_INTERVAL) { lastScreenshotSend = UnityEngine.Time.realtimeSinceStartup; screenshotTaken = false; finishedUploadingScreenshot = false; uploadScreenshot = true; displayScreenshotUploadingMessage = true; } } if ((UnityEngine.Time.realtimeSinceStartup - lastScreenshotMessageCheck) > SCREENSHOT_MESSAGE_CHECK_INTERVAL) { if (screenshotTaken && displayScreenshotUploadingMessage) { lastScreenshotMessageCheck = UnityEngine.Time.realtimeSinceStartup; if (screenshotUploadMessage != null) { screenshotUploadMessage.duration = 0f; } if (finishedUploadingScreenshot) { displayScreenshotUploadingMessage = false; screenshotUploadMessage = ScreenMessages.PostScreenMessage("Screenshot uploaded!", 2f, ScreenMessageStyle.UPPER_CENTER); } else { screenshotUploadMessage = ScreenMessages.PostScreenMessage("Uploading screenshot...", 1f, ScreenMessageStyle.UPPER_CENTER); } } if (downloadingScreenshotFromPlayer != null) { if (screenshotDownloadMessage != null) { screenshotDownloadMessage.duration = 0f; } screenshotDownloadMessage = ScreenMessages.PostScreenMessage("Downloading screenshot...", 1f, ScreenMessageStyle.UPPER_CENTER); } } if (downloadingScreenshotFromPlayer == null && screenshotDownloadMessage != null) { screenshotDownloadMessage.duration = 0f; screenshotDownloadMessage = null; } } } private void ResizeTextureIfNeeded(ref Texture2D screenshotTexture) { //Make sure screenshots aren't bigger than 2/3rds of the screen. int resizeWidth = (int)(Screen.width * .66); int resizeHeight = (int)(Screen.height * .66); if (screenshotTexture.width > resizeWidth || screenshotTexture.height > resizeHeight) { RenderTexture renderTexture = new RenderTexture(resizeWidth, resizeHeight, 24); renderTexture.useMipMap = false; Graphics.Blit(screenshotTexture, renderTexture); RenderTexture.active = renderTexture; Texture2D resizeTexture = new Texture2D(resizeWidth, resizeHeight, TextureFormat.RGB24, false); resizeTexture.ReadPixels(new Rect(0, 0, resizeWidth, resizeHeight), 0, 0); resizeTexture.Apply(); screenshotTexture = resizeTexture; RenderTexture.active = null; } } private void Draw() { if (!initialized) { initialized = true; InitGUI(); } if (safeDisplay) { windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6710 + Client.WINDOW_OFFSET, windowRect, DrawContent, "Screenshots", windowStyle, windowLayoutOption)); } CheckWindowLock(); } private void DrawContent(int windowID) { GUI.DragWindow(moveRect); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); scrollPos = GUILayout.BeginScrollView(scrollPos, scrollStyle, fixedButtonSizeOption); DrawPlayerButton(Settings.fetch.playerName); foreach (PlayerStatus player in PlayerStatusWorker.fetch.playerStatusList) { DrawPlayerButton(player.playerName); } GUILayout.EndScrollView(); GUILayout.FlexibleSpace(); GUI.enabled = ((UnityEngine.Time.realtimeSinceStartup - lastScreenshotSend) > MIN_SCREENSHOT_SEND_INTERVAL); if (GUILayout.Button("Upload (" + Settings.fetch.screenshotKey.ToString() + ")", buttonStyle)) { uploadEventHandled = false; } GUI.enabled = true; GUILayout.EndVertical(); if (safeSelectedPlayer != "") { if (screenshots.ContainsKey(safeSelectedPlayer)) { GUILayout.Box(screenshots[safeSelectedPlayer]); } } GUILayout.EndHorizontal(); } private void CheckWindowLock() { if (!Client.fetch.gameRunning) { RemoveWindowLock(); return; } if (HighLogic.LoadedSceneIsFlight) { RemoveWindowLock(); return; } if (safeDisplay) { Vector2 mousePos = Input.mousePosition; mousePos.y = Screen.height - mousePos.y; bool shouldLock = windowRect.Contains(mousePos); if (shouldLock && !isWindowLocked) { InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_ScreenshotLock"); isWindowLocked = true; } if (!shouldLock && isWindowLocked) { RemoveWindowLock(); } } if (!safeDisplay && isWindowLocked) { RemoveWindowLock(); } } private void RemoveWindowLock() { if (isWindowLocked) { isWindowLocked = false; InputLockManager.RemoveControlLock("DMP_ScreenshotLock"); } } private void DrawPlayerButton(string playerName) { GUIStyle playerButtonStyle = buttonStyle; if (highlightedPlayers.Contains(playerName)) { playerButtonStyle = highlightStyle; } bool newValue = GUILayout.Toggle(safeSelectedPlayer == playerName, playerName, playerButtonStyle); if (newValue && (safeSelectedPlayer != playerName)) { selectedPlayer = playerName; } if (!newValue && (safeSelectedPlayer == playerName)) { selectedPlayer = ""; } } private void WatchPlayer(string playerName) { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ScreenshotMessageType.WATCH); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(playerName); NetworkWorker.fetch.SendScreenshotMessage(mw.GetMessageBytes()); } } //Called from main due to WaitForEndOfFrame timing. public void SendScreenshot() { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ScreenshotMessageType.SCREENSHOT); mw.Write<string>(Settings.fetch.playerName); mw.Write<byte[]>(GetScreenshotBytes()); NetworkWorker.fetch.SendScreenshotMessage(mw.GetMessageBytes()); } } //Adapted from KMP. private byte[] GetScreenshotBytes() { int screenshotWidth = (int)(Screen.width * (screenshotHeight / (float)Screen.height)); //Read the screen pixels into a texture Texture2D fullScreenTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); fullScreenTexture.filterMode = FilterMode.Bilinear; fullScreenTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false); fullScreenTexture.Apply(); RenderTexture renderTexture = new RenderTexture(screenshotWidth, screenshotHeight, 24); renderTexture.useMipMap = false; Graphics.Blit(fullScreenTexture, renderTexture); //Blit the screen texture to a render texture RenderTexture.active = renderTexture; //Read the pixels from the render texture into a Texture2D Texture2D resizedTexture = new Texture2D(screenshotWidth, screenshotHeight, TextureFormat.RGB24, false); Texture2D ourTexture = new Texture2D(screenshotWidth, screenshotHeight, TextureFormat.RGB24, false); resizedTexture.ReadPixels(new Rect(0, 0, screenshotWidth, screenshotHeight), 0, 0); resizedTexture.Apply(); //Save a copy locally in case we need to resize it. ourTexture.ReadPixels(new Rect(0, 0, screenshotWidth, screenshotHeight), 0, 0); ourTexture.Apply(); ResizeTextureIfNeeded(ref ourTexture); //Save our texture in memory. screenshots[Settings.fetch.playerName] = ourTexture; RenderTexture.active = null; return resizedTexture.EncodeToPNG(); } public void QueueNewScreenshot(string fromPlayer, byte[] screenshotData) { downloadingScreenshotFromPlayer = null; ScreenshotEntry se = new ScreenshotEntry(); se.fromPlayer = fromPlayer; se.screenshotData = screenshotData; newScreenshotQueue.Enqueue(se); } public void QueueNewScreenshotWatch(string fromPlayer, string watchPlayer) { ScreenshotWatchEntry swe = new ScreenshotWatchEntry(); swe.fromPlayer = fromPlayer; swe.watchPlayer = watchPlayer; newScreenshotWatchQueue.Enqueue(swe); } public void QueueNewNotify(string fromPlayer) { newScreenshotNotifiyQueue.Enqueue(fromPlayer); } public static void Reset() { lock (Client.eventLock) { if (singleton != null) { singleton.workerEnabled = false; singleton.RemoveWindowLock(); Client.updateEvent.Remove(singleton.Update); Client.drawEvent.Remove(singleton.Draw); } singleton = new ScreenshotWorker(); Client.updateEvent.Add(singleton.Update); Client.drawEvent.Add(singleton.Draw); } } } class ScreenshotEntry { public string fromPlayer; public byte[] screenshotData; } class ScreenshotWatchEntry { public string fromPlayer; public string watchPlayer; } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using UnityEngine; using UnityEditor; using System; namespace AmplifyShaderEditor { [Serializable] [NodeAttributes( "Float", "Constants", "Float property", null, KeyCode.Alpha1 )] public sealed class RangedFloatNode : PropertyNode { private const int OriginalFontSize = 11; private const string MinValueStr = "Min"; private const string MaxValueStr = "Max"; private const float LabelWidth = 8; [SerializeField] private float m_defaultValue = 0; [SerializeField] private float m_materialValue = 0; [SerializeField] private float m_min = 0; [SerializeField] private float m_max = 0; [SerializeField] private bool m_floatMode = true; private int m_cachedPropertyId = -1; public RangedFloatNode() : base() { } public RangedFloatNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { } protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue ); m_insideSize.Set( 50, 0 ); m_showPreview = false; m_selectedLocation = PreviewLocation.BottomCenter; m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ); m_availableAttribs.Add( new PropertyAttributes( "Toggle", "[Toggle]" ) ); m_availableAttribs.Add( new PropertyAttributes( "Int Range", "[IntRange]" ) ); m_previewShaderGUID = "d9ca47581ac157145bff6f72ac5dd73e"; } public void SetFloatMode( bool value ) { m_floatMode = value; if ( value ) { m_insideSize.x = 50;// + ( m_showPreview ? 50 : 0 ); //m_firstPreviewDraw = true; } else { m_insideSize.x = 200;// + ( m_showPreview ? 0 : 0 ); //m_firstPreviewDraw = true; } m_sizeIsDirty = true; } public override void CopyDefaultsToMaterial() { m_materialValue = m_defaultValue; } public override void DrawSubProperties() { EditorGUI.BeginChangeCheck(); m_min = EditorGUILayoutFloatField( MinValueStr, m_min ); m_max = EditorGUILayoutFloatField( MaxValueStr, m_max ); if ( m_min > m_max ) m_min = m_max; if ( m_max < m_min ) m_max = m_min; if ( EditorGUI.EndChangeCheck() ) { SetFloatMode( m_min == m_max ); } if ( m_floatMode ) { m_defaultValue = EditorGUILayoutFloatField( Constants.DefaultValueLabel, m_defaultValue ); } else { m_defaultValue = EditorGUILayoutSlider( Constants.DefaultValueLabel, m_defaultValue, m_min, m_max ); } } public override void DrawMaterialProperties() { EditorGUI.BeginChangeCheck(); m_min = EditorGUILayoutFloatField( MinValueStr, m_min ); m_max = EditorGUILayoutFloatField( MaxValueStr, m_max ); if ( m_min > m_max ) m_min = m_max; if ( m_max < m_min ) m_max = m_min; if ( EditorGUI.EndChangeCheck() ) { SetFloatMode( m_min == m_max ); } EditorGUI.BeginChangeCheck(); if ( m_floatMode ) { m_materialValue = EditorGUILayoutFloatField( Constants.MaterialValueLabel, m_materialValue ); } else { m_materialValue = EditorGUILayoutSlider( Constants.MaterialValueLabel, m_materialValue, m_min, m_max ); } if ( EditorGUI.EndChangeCheck() ) { //MarkForPreviewUpdate(); if ( m_materialMode ) m_requireMaterialUpdate = true; } } public override void SetPreviewInputs() { base.SetPreviewInputs(); if ( m_cachedPropertyId == -1 ) m_cachedPropertyId = Shader.PropertyToID( "_InputFloat" ); if ( m_materialMode && m_currentParameterType != PropertyType.Constant ) PreviewMaterial.SetFloat( m_cachedPropertyId, m_materialValue ); else PreviewMaterial.SetFloat( m_cachedPropertyId, m_defaultValue ); } public override void Draw( DrawInfo drawInfo ) { base.Draw( drawInfo ); if ( m_isVisible ) { if ( m_floatMode ) { m_propertyDrawPos.x = m_remainingBox.x - LabelWidth * drawInfo.InvertedZoom; m_propertyDrawPos.y = m_outputPorts[ 0 ].Position.y - 2 * drawInfo.InvertedZoom; m_propertyDrawPos.width = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_WIDTH_FIELD_SIZE; m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE; } else { m_propertyDrawPos.x = m_remainingBox.x; m_propertyDrawPos.y = m_outputPorts[ 0 ].Position.y - 2 * drawInfo.InvertedZoom; m_propertyDrawPos.width = 0.7f * m_globalPosition.width; m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE; } if ( m_materialMode && m_currentParameterType != PropertyType.Constant ) { EditorGUI.BeginChangeCheck(); if ( m_floatMode ) { UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_materialValue, LabelWidth * drawInfo.InvertedZoom ); } else { DrawSlider( ref m_materialValue, drawInfo ); } if ( EditorGUI.EndChangeCheck() ) { m_requireMaterialUpdate = true; if ( m_currentParameterType != PropertyType.Constant ) { //MarkForPreviewUpdate(); BeginDelayedDirtyProperty(); } } } else { EditorGUI.BeginChangeCheck(); if ( m_floatMode ) { UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_defaultValue, LabelWidth * drawInfo.InvertedZoom ); } else { DrawSlider( ref m_defaultValue, drawInfo ); } if ( EditorGUI.EndChangeCheck() ) { //MarkForPreviewUpdate(); BeginDelayedDirtyProperty(); } } } } void DrawSlider( ref float value, DrawInfo drawInfo ) { int originalFontSize = EditorStyles.numberField.fontSize; EditorStyles.numberField.fontSize = ( int ) ( OriginalFontSize * drawInfo.InvertedZoom ); float rangeWidth = 30 * drawInfo.InvertedZoom; float rangeSpacing = 5 * drawInfo.InvertedZoom; //Min m_propertyDrawPos.width = rangeWidth; m_min = EditorGUIFloatField( m_propertyDrawPos, m_min, UIUtils.MainSkin.textField ); //Value Slider m_propertyDrawPos.x += m_propertyDrawPos.width + rangeSpacing; m_propertyDrawPos.width = 0.65f * ( m_globalPosition.width - 3 * m_propertyDrawPos.width ); Rect slider = m_propertyDrawPos; slider.height = 5 * drawInfo.InvertedZoom; slider.y += m_propertyDrawPos.height * 0.5f - slider.height * 0.5f; GUI.Box( slider, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SliderStyle ) ); value = GUI.HorizontalSlider( m_propertyDrawPos, value, m_min, m_max, GUIStyle.none, UIUtils.RangedFloatSliderThumbStyle ); //Value Area m_propertyDrawPos.x += m_propertyDrawPos.width + rangeSpacing; m_propertyDrawPos.width = rangeWidth; value = EditorGUIFloatField( m_propertyDrawPos, value, UIUtils.MainSkin.textField ); //Max m_propertyDrawPos.x += m_propertyDrawPos.width + rangeSpacing; m_propertyDrawPos.width = rangeWidth; m_max = EditorGUIFloatField( m_propertyDrawPos, m_max, UIUtils.MainSkin.textField ); EditorStyles.numberField.fontSize = originalFontSize; } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar ) { base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar ); m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ); if ( m_currentParameterType != PropertyType.Constant ) return PropertyData; return IOUtils.Floatify( m_defaultValue ); } public override string GetPropertyValue() { if ( m_floatMode ) { return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Float) = " + m_defaultValue; } else { return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Range( " + m_min + " , " + m_max + ")) = " + m_defaultValue; } } public override void UpdateMaterial( Material mat ) { base.UpdateMaterial( mat ); if ( UIUtils.IsProperty( m_currentParameterType ) ) { mat.SetFloat( m_propertyName, m_materialValue ); } } public override void SetMaterialMode( Material mat ) { base.SetMaterialMode( mat ); if ( m_materialMode && UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) ) { m_materialValue = mat.GetFloat( m_propertyName ); } } public override void ForceUpdateFromMaterial( Material material ) { if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) ) m_materialValue = material.GetFloat( m_propertyName ); } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); m_defaultValue = Convert.ToSingle( GetCurrentParam( ref nodeParams ) ); m_min = Convert.ToSingle( GetCurrentParam( ref nodeParams ) ); m_max = Convert.ToSingle( GetCurrentParam( ref nodeParams ) ); SetFloatMode( m_min == m_max ); } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue ); IOUtils.AddFieldValueToString( ref nodeInfo, m_min ); IOUtils.AddFieldValueToString( ref nodeInfo, m_max ); } public override string GetPropertyValStr() { return ( m_materialMode && m_currentParameterType != PropertyType.Constant ) ? m_materialValue.ToString( Mathf.Abs( m_materialValue ) > 1000 ? Constants.PropertyBigFloatFormatLabel : Constants.PropertyFloatFormatLabel ) : m_defaultValue.ToString( Mathf.Abs( m_defaultValue ) > 1000 ? Constants.PropertyBigFloatFormatLabel : Constants.PropertyFloatFormatLabel ); } public float Value { get { return m_defaultValue; } set { m_defaultValue = value; } } } }
#region Using directives #define USE_TRACING using System; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Xml; #endregion // <summary>Contains AtomSource, an object to represent the atom:source // element.</summary> namespace Google.GData.Client { /// <summary>TypeConverter, so that AtomHead shows up in the property pages /// </summary> [ComVisible(false)] public class AtomSourceConverter : ExpandableObjectConverter { ///<summary>Standard type converter method</summary> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof (AtomSource) || destinationType == typeof (AtomFeed)) { return true; } return base.CanConvertTo(context, destinationType); } ///<summary>Standard type converter method</summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { AtomSource atomSource = value as AtomSource; if (destinationType == typeof (string) && atomSource != null) { return "Feed: " + atomSource.Title; } return base.ConvertTo(context, culture, value, destinationType); } } /// <summary>Represents the AtomSource object. If an atom:entry is copied from one feed /// into another feed, then the source atom:feed's metadata (all child elements of atom:feed other /// than the atom:entry elements) MAY be preserved within the copied entry by adding an atom:source /// child element, if it is not already present in the entry, and including some or all of the source /// feed's Metadata elements as the atom:source element's children. Such metadata SHOULD be preserved /// if the source atom:feed contains any of the child elements atom:author, atom:contributor, /// atom:rights, or atom:category and those child elements are not present in the source atom:entry. /// </summary> /* atomSource = element atom:source { atomCommonAttributes, (atomAuthor? & atomCategory* & atomContributor* & atomGenerator? & atomIcon? & atomId? & atomLink* & atomLogo? & atomRights? & atomSubtitle? & atomTitle? & atomUpdated? & extensionElement*) } */ [TypeConverter(typeof (AtomSourceConverter)), Description("Expand to see the options for the feed")] public class AtomSource : AtomBase { /// <summary>author collection</summary> private AtomPersonCollection authors; /// <summary>category collection</summary> private AtomCategoryCollection categories; /// <summary>contributors collection</summary> private AtomPersonCollection contributors; /// <summary>the generator</summary> private AtomGenerator generator; /// <summary>icon, essentially an atom link</summary> private AtomIcon icon; /// <summary>ID</summary> private AtomId id; /// <summary>link collection</summary> private AtomLinkCollection links; /// <summary>logo, essentially an image link</summary> private AtomLogo logo; /// <summary>rights, former copyrights</summary> private AtomTextConstruct rights; /// <summary>subtitle as string</summary> private AtomTextConstruct subTitle; /// <summary>title property as string</summary> private AtomTextConstruct title; /// <summary>updated time stamp</summary> private DateTime updated; /// <summary>public void AtomSource()</summary> public AtomSource() { } /// <summary>public AtomSource(AtomFeed feed)</summary> public AtomSource(AtomFeed feed) : this() { Tracing.Assert(feed != null, "feed should not be null"); if (feed == null) { throw new ArgumentNullException("feed"); } // now copy them authors = feed.Authors; contributors = feed.Contributors; categories = feed.Categories; Generator = feed.Generator; Icon = feed.Icon; Logo = feed.Logo; Id = feed.Id; links = feed.Links; Rights = feed.Rights; Subtitle = feed.Subtitle; Title = feed.Title; Updated = feed.Updated; } /// <summary>accessor method public Authors AtomPersonCollection</summary> /// <returns> </returns> public AtomPersonCollection Authors { get { if (authors == null) { authors = new AtomPersonCollection(); } return authors; } } /// <summary>accessor method public Contributors AtomPersonCollection</summary> /// <returns> </returns> public AtomPersonCollection Contributors { get { if (contributors == null) { contributors = new AtomPersonCollection(); } return contributors; } } /// <summary>accessor method public Links AtomLinkCollection</summary> /// <returns> </returns> public AtomLinkCollection Links { get { if (links == null) { links = new AtomLinkCollection(); } return links; } } /// <summary>returns the category collection</summary> public AtomCategoryCollection Categories { get { if (categories == null) { categories = new AtomCategoryCollection(); } return categories; } } /// <summary>accessor method public FeedGenerator Generator</summary> /// <returns> </returns> public AtomGenerator Generator { get { return generator; } set { Dirty = true; generator = value; } } /// <summary>accessor method public AtomIcon Icon</summary> /// <returns> </returns> public AtomIcon Icon { get { return icon; } set { Dirty = true; icon = value; } } /// <summary>accessor method public AtomLogo Logo</summary> /// <returns> </returns> public AtomLogo Logo { get { return logo; } set { Dirty = true; logo = value; } } /// <summary>accessor method public DateTime LastUpdated</summary> /// <returns> </returns> public DateTime Updated { get { return updated; } set { Dirty = true; updated = value; } } /// <summary>accessor method public string Title</summary> /// <returns> </returns> public AtomTextConstruct Title { get { return title; } set { Dirty = true; title = value; } } /// <summary>accessor method public string Subtitle</summary> /// <returns> </returns> public AtomTextConstruct Subtitle { get { return subTitle; } set { Dirty = true; subTitle = value; } } /// <summary>accessor method public string Id</summary> /// <returns> </returns> public AtomId Id { get { return id; } set { Dirty = true; id = value; } } /// <summary>accessor method public string Rights</summary> /// <returns> </returns> public AtomTextConstruct Rights { get { return rights; } set { Dirty = true; rights = value; } } #region Persistence overloads /// <summary>Returns the constant representing this XML element.</summary> public override string XmlName { get { return AtomParserNameTable.XmlSourceElement; } } /// <summary>saves the inner state of the element</summary> /// <param name="writer">the xmlWriter to save into </param> protected override void SaveInnerXml(XmlWriter writer) { base.SaveInnerXml(writer); // saving Authors foreach (AtomPerson person in Authors) { person.SaveToXml(writer); } // saving Contributors foreach (AtomPerson person in Contributors) { person.SaveToXml(writer); } // saving Categories foreach (AtomCategory category in Categories) { category.SaveToXml(writer); } // saving the generator if (Generator != null) { Generator.SaveToXml(writer); } // save the icon if (Icon != null) { Icon.SaveToXml(writer); } // save the logo if (Logo != null) { Logo.SaveToXml(writer); } // save the ID if (Id != null) { Id.SaveToXml(writer); } // save the Links foreach (AtomLink link in Links) { link.SaveToXml(writer); } if (Rights != null) { Rights.SaveToXml(writer); } if (Subtitle != null) { Subtitle.SaveToXml(writer); } if (Title != null) { Title.SaveToXml(writer); } // date time construct, save here. WriteLocalDateTimeElement(writer, AtomParserNameTable.XmlUpdatedElement, Updated); } #endregion #region overloaded for property changes, xml:base /// <summary>just go down the child collections</summary> /// <param name="uriBase"> as currently calculated</param> internal override void BaseUriChanged(AtomUri uriBase) { base.BaseUriChanged(uriBase); foreach (AtomPerson person in Authors) { person.BaseUriChanged(uriBase); } // saving Contributors foreach (AtomPerson person in Contributors) { person.BaseUriChanged(uriBase); } // saving Categories foreach (AtomCategory category in Categories) { category.BaseUriChanged(uriBase); } // saving the generator if (Generator != null) { Generator.BaseUriChanged(uriBase); } // save the icon if (Icon != null) { Icon.BaseUriChanged(uriBase); } // save the logo if (Logo != null) { Logo.BaseUriChanged(uriBase); } // save the ID if (Id != null) { Id.BaseUriChanged(uriBase); } // save the Links foreach (AtomLink link in Links) { link.BaseUriChanged(uriBase); } if (Rights != null) { Rights.BaseUriChanged(uriBase); } if (Subtitle != null) { Subtitle.BaseUriChanged(uriBase); } if (Title != null) { Title.BaseUriChanged(uriBase); } } /// <summary>calls the action on this object and all children</summary> /// <param name="action">an IAtomBaseAction interface to call </param> /// <returns>true or false, pending outcome</returns> public override bool WalkTree(IBaseWalkerAction action) { if (base.WalkTree(action)) { return true; } foreach (AtomPerson person in Authors) { if (person.WalkTree(action)) { return true; } } // saving Contributors foreach (AtomPerson person in Contributors) { if (person.WalkTree(action)) { return true; } } // saving Categories foreach (AtomCategory category in Categories) { if (category.WalkTree(action)) { return true; } } // saving the generator if (Generator != null) { if (Generator.WalkTree(action)) { return true; } } // save the icon if (Icon != null) { if (Icon.WalkTree(action)) { return true; } } // save the logo if (Logo != null) { if (Logo.WalkTree(action)) { return true; } } // save the ID if (Id != null) { if (Id.WalkTree(action)) { return true; } } // save the Links foreach (AtomLink link in Links) { if (link.WalkTree(action)) { return true; } } if (Rights != null) { if (Rights.WalkTree(action)) { return true; } } if (Subtitle != null) { if (Subtitle.WalkTree(action)) { return true; } } if (Title != null) { if (Title.WalkTree(action)) { return true; } } return false; } #endregion } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; using System.IO; using System.Text; using System.Collections; using System.Globalization; using System.Collections.Generic; namespace Spine { public static class Json { public static object Deserialize (TextReader text) { var parser = new SharpJson.JsonDecoder(); parser.parseNumbersAsFloat = true; return parser.Decode(text.ReadToEnd()); } } } /** * * Copyright (c) 2016 Adriano Tinoco d'Oliveira Rezende * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/news/view/14605/14863/how-do-i-write-my-own-parser-(for-json).html * * Changes made: * * - Optimized parser speed (deserialize roughly near 3x faster than original) * - Added support to handle lexer/parser error messages with line numbers * - Added more fine grained control over type conversions during the parsing * - Refactory API (Separate Lexer code from Parser code and the Encoder from Decoder) * * * 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 SharpJson { class Lexer { public enum Token { None, Null, True, False, Colon, Comma, String, Number, CurlyOpen, CurlyClose, SquaredOpen, SquaredClose, }; public bool hasError { get { return !success; } } public int lineNumber { get; private set; } public bool parseNumbersAsFloat { get; set; } char[] json; int index = 0; bool success = true; char[] stringBuffer = new char[4096]; public Lexer(string text) { Reset(); json = text.ToCharArray(); parseNumbersAsFloat = false; } public void Reset() { index = 0; lineNumber = 1; success = true; } public string ParseString() { int idx = 0; StringBuilder builder = null; SkipWhiteSpaces(); // " char c = json[index++]; bool failed = false; bool complete = false; while (!complete && !failed) { if (index == json.Length) break; c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\') { if (index == json.Length) break; c = json[index++]; switch (c) { case '"': stringBuffer[idx++] = '"'; break; case '\\': stringBuffer[idx++] = '\\'; break; case '/': stringBuffer[idx++] = '/'; break; case 'b': stringBuffer[idx++] = '\b'; break; case'f': stringBuffer[idx++] = '\f'; break; case 'n': stringBuffer[idx++] = '\n'; break; case 'r': stringBuffer[idx++] = '\r'; break; case 't': stringBuffer[idx++] = '\t'; break; case 'u': int remainingLength = json.Length - index; if (remainingLength >= 4) { var hex = new string(json, index, 4); // XXX: handle UTF stringBuffer[idx++] = (char) Convert.ToInt32(hex, 16); // skip 4 chars index += 4; } else { failed = true; } break; } } else { stringBuffer[idx++] = c; } if (idx >= stringBuffer.Length) { if (builder == null) builder = new StringBuilder(); builder.Append(stringBuffer, 0, idx); idx = 0; } } if (!complete) { success = false; return null; } if (builder != null) return builder.ToString (); else return new string (stringBuffer, 0, idx); } string GetNumberString() { SkipWhiteSpaces(); int lastIndex = GetLastIndexOfNumber(index); int charLength = (lastIndex - index) + 1; var result = new string (json, index, charLength); index = lastIndex + 1; return result; } public float ParseFloatNumber() { float number; var str = GetNumberString (); if (!float.TryParse (str, NumberStyles.Float, CultureInfo.InvariantCulture, out number)) return 0; return number; } public double ParseDoubleNumber() { double number; var str = GetNumberString (); if (!double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out number)) return 0; return number; } int GetLastIndexOfNumber(int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) { char ch = json[lastIndex]; if ((ch < '0' || ch > '9') && ch != '+' && ch != '-' && ch != '.' && ch != 'e' && ch != 'E') break; } return lastIndex - 1; } void SkipWhiteSpaces() { for (; index < json.Length; index++) { char ch = json[index]; if (ch == '\n') lineNumber++; if (!char.IsWhiteSpace(json[index])) break; } } public Token LookAhead() { SkipWhiteSpaces(); int savedIndex = index; return NextToken(json, ref savedIndex); } public Token NextToken() { SkipWhiteSpaces(); return NextToken(json, ref index); } static Token NextToken(char[] json, ref int index) { if (index == json.Length) return Token.None; char c = json[index++]; switch (c) { case '{': return Token.CurlyOpen; case '}': return Token.CurlyClose; case '[': return Token.SquaredOpen; case ']': return Token.SquaredClose; case ',': return Token.Comma; case '"': return Token.String; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return Token.Number; case ':': return Token.Colon; } index--; int remainingLength = json.Length - index; // false if (remainingLength >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return Token.False; } } // true if (remainingLength >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return Token.True; } } // null if (remainingLength >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return Token.Null; } } return Token.None; } } public class JsonDecoder { public string errorMessage { get; private set; } public bool parseNumbersAsFloat { get; set; } Lexer lexer; public JsonDecoder() { errorMessage = null; parseNumbersAsFloat = false; } public object Decode(string text) { errorMessage = null; lexer = new Lexer(text); lexer.parseNumbersAsFloat = parseNumbersAsFloat; return ParseValue(); } public static object DecodeText(string text) { var builder = new JsonDecoder(); return builder.Decode(text); } IDictionary<string, object> ParseObject() { var table = new Dictionary<string, object>(); // { lexer.NextToken(); while (true) { var token = lexer.LookAhead(); switch (token) { case Lexer.Token.None: TriggerError("Invalid token"); return null; case Lexer.Token.Comma: lexer.NextToken(); break; case Lexer.Token.CurlyClose: lexer.NextToken(); return table; default: // name string name = EvalLexer(lexer.ParseString()); if (errorMessage != null) return null; // : token = lexer.NextToken(); if (token != Lexer.Token.Colon) { TriggerError("Invalid token; expected ':'"); return null; } // value object value = ParseValue(); if (errorMessage != null) return null; table[name] = value; break; } } //return null; // Unreachable code } IList<object> ParseArray() { var array = new List<object>(); // [ lexer.NextToken(); while (true) { var token = lexer.LookAhead(); switch (token) { case Lexer.Token.None: TriggerError("Invalid token"); return null; case Lexer.Token.Comma: lexer.NextToken(); break; case Lexer.Token.SquaredClose: lexer.NextToken(); return array; default: object value = ParseValue(); if (errorMessage != null) return null; array.Add(value); break; } } //return null; // Unreachable code } object ParseValue() { switch (lexer.LookAhead()) { case Lexer.Token.String: return EvalLexer(lexer.ParseString()); case Lexer.Token.Number: if (parseNumbersAsFloat) return EvalLexer(lexer.ParseFloatNumber()); else return EvalLexer(lexer.ParseDoubleNumber()); case Lexer.Token.CurlyOpen: return ParseObject(); case Lexer.Token.SquaredOpen: return ParseArray(); case Lexer.Token.True: lexer.NextToken(); return true; case Lexer.Token.False: lexer.NextToken(); return false; case Lexer.Token.Null: lexer.NextToken(); return null; case Lexer.Token.None: break; } TriggerError("Unable to parse value"); return null; } void TriggerError(string message) { errorMessage = string.Format("Error: '{0}' at line {1}", message, lexer.lineNumber); } T EvalLexer<T>(T value) { if (lexer.hasError) TriggerError("Lexical error ocurred"); return value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; namespace System.Reflection.Tests { public class RuntimeReflectionExtensionsTests { [Fact] public void GetMethodInfo() { Assert.Equal(typeof(RuntimeReflectionExtensionsTests).GetMethod("GetMethodInfo"), ((Action)GetMethodInfo).GetMethodInfo()); } [Fact] public void GetMethodInfoOnNull() => AssertExtensions.Throws<ArgumentNullException>("del", () => default(Action).GetMethodInfo()); [Fact] public void GetRuntimeBaseDefinition() { MethodInfo derivedFoo = typeof(TestDerived).GetMethod(nameof(TestDerived.Foo)); MethodInfo baseFoo = typeof(TestBase).GetMethod(nameof(TestBase.Foo)); MethodInfo actual = derivedFoo.GetRuntimeBaseDefinition(); Assert.Equal(baseFoo, actual); } [Fact] public void GetRuntimeBaseDefinitionOnNull() => Assert.Throws<ArgumentNullException>(() => default(MethodInfo).GetRuntimeBaseDefinition()); private abstract class TestBase { public abstract void Foo(); } private class TestDerived : TestBase { public override void Foo() { throw null; } } [Fact] public void GetRuntimeEvent() { Assert.Equal(typeof(TestType).GetEvent("StuffHappened"), typeof(TestType).GetRuntimeEvent("StuffHappened")); } [Fact] public void GetRuntimeEventOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeEvent("")); [Fact] public void GetRuntimeEventWithNull() => Assert.Throws<ArgumentNullException>(null, () => typeof(TestType).GetRuntimeEvent(null)); [Fact] public void GetRuntimeEventEmptyName() => Assert.Null(typeof(TestType).GetRuntimeEvent("")); [Fact] public void GetRuntimeField() { Assert.Equal(typeof(TestType).GetField("_pizzaSize"), typeof(TestType).GetRuntimeField("_pizzaSize")); } [Fact] public void GetRuntimeFieldOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeField("")); [Fact] public void GetRuntimeFieldWithNull() => Assert.Throws<ArgumentNullException>(null, () => typeof(TestType).GetRuntimeField(null)); [Fact] public void GetRuntimeFieldEmptyName() => Assert.Null(typeof(TestType).GetRuntimeField("")); [Fact] public void GetRuntimeMethod() { Assert.Equal(typeof(TestType).GetMethod("Flush"), typeof(TestType).GetRuntimeMethod("Flush", Array.Empty<Type>())); } [Fact] public void GetRuntimeMethodOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeMethod("", Type.EmptyTypes)); [Fact] public void GetRuntimeMethodWithNullName() => AssertExtensions.Throws<ArgumentNullException>("name", () => typeof(TestType).GetRuntimeMethod(null, Type.EmptyTypes)); [Fact] public void GetRuntimeMethodWithNullTypes() => AssertExtensions.Throws<ArgumentNullException>("types", () => typeof(TestType).GetRuntimeMethod("", null)); [Fact] public void GetRuntimeMethodEmptyName() => Assert.Null(typeof(TestType).GetRuntimeMethod("", Type.EmptyTypes)); [Fact] public void GetRuntimeProperty() { Assert.Equal(typeof(TestType).GetProperty("Length"), typeof(TestType).GetRuntimeProperty("Length")); } [Fact] public void GetRuntimePropertyOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeProperty("")); [Fact] public void GetRuntimePropertyWithNull() => AssertExtensions.Throws<ArgumentNullException>("name", () => typeof(TestType).GetRuntimeProperty(null)); [Fact] public void GetRuntimePropertyEmptyName() => Assert.Null(typeof(TestType).GetRuntimeProperty("")); [Fact] public void GetRuntimeEvents() { List<EventInfo> events = typeof(TestType).GetRuntimeEvents().ToList(); Assert.Equal(1, events.Count); Assert.Equal("StuffHappened", events[0].Name); } [Fact] public void GetRuntimeEventsOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeEvents()); [Fact] public void GetRuntimeFields() { List<FieldInfo> fields = typeof(TestType).GetRuntimeFields().ToList(); Assert.Equal(2, fields.Count); List<string> fieldNames = fields.Select(f => f.Name).ToList(); Assert.Contains("StuffHappened", fieldNames); Assert.Contains("_pizzaSize", fieldNames); } [Fact] public void GetRuntimeFieldsOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeFields()); [Fact] public void GetRuntimeMethods() { List<MethodInfo> methods = typeof(TestType).GetRuntimeMethods().ToList(); List<string> methodNames = methods.Select(m => m.Name).Distinct().ToList(); Assert.Contains("remove_StuffHappened", methodNames); Assert.Contains("add_StuffHappened", methodNames); Assert.Contains("Equals", methodNames); Assert.Contains("GetHashCode", methodNames); Assert.Contains("ToString", methodNames); Assert.Contains("get_CanRead", methodNames); Assert.Contains("Read", methodNames); } [Fact] public void GetRuntimeMethodsOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeMethods()); [Fact] public void GetRuntimeProperties() { List<PropertyInfo> properties = typeof(TestType).GetRuntimeProperties().ToList(); List<string> propertyNames = properties.Select(p => p.Name).Distinct().ToList(); Assert.Equal(5, properties.Count); Assert.Contains("Length", propertyNames); Assert.Contains("Position", propertyNames); Assert.Contains("CanRead", propertyNames); Assert.Contains("CanWrite", propertyNames); Assert.Contains("CanSeek", propertyNames); } [Fact] public void GetRuntimePropertiesOnNull() => AssertExtensions.Throws<ArgumentNullException>("type", () => default(Type).GetRuntimeProperties()); [Fact] public void GetRuntimeInterfaceMap() { InterfaceMapping map = typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(IDisposable)); Assert.Same(typeof(TestType), map.TargetType); Assert.Same(typeof(IDisposable), map.InterfaceType); Assert.Equal(1, map.InterfaceMethods.Length); Assert.Equal(1, map.TargetMethods.Length); MethodInfo ifaceDispose = map.InterfaceMethods[0]; MethodInfo targetDispose = map.TargetMethods[0]; Assert.Equal(ifaceDispose.CallingConvention, targetDispose.CallingConvention); Assert.Equal(ifaceDispose.Name, targetDispose.Name); Assert.Same(ifaceDispose.ReturnType, targetDispose.ReturnType); Assert.Equal(ifaceDispose.GetParameters().Length, targetDispose.GetParameters().Length); Assert.Same(typeof(TestTypeBase), targetDispose.DeclaringType); Assert.Same(typeof(IDisposable), ifaceDispose.DeclaringType); } [Fact] public void GetRuntimeInterfaceMapOnNull() => AssertExtensions.Throws<ArgumentNullException>("typeInfo", () => default(TypeInfo).GetRuntimeInterfaceMap(typeof(ICloneable))); [Fact] public void GetRuntimeInterfaceMapWithNull() => AssertExtensions.Throws<ArgumentNullException>("ifaceType", () => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(null)); [Fact] public void GetRuntimeInterfaceMapNotImplemented() => Assert.Throws<ArgumentException>(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(ICloneable))); [Fact] public void GetRuntimeInterfaceMapNotInterface() => Assert.Throws<ArgumentException>(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(string))); } }
using System; using System.Runtime.InteropServices; using MonoTouch.ObjCRuntime; namespace KS_PSPDFKitBindings { public enum PSPDFThumbnailBarMode { PSPDFThumbnailBarModeNone, // Don't show thumbnail bottom bar. PSPDFThumbnailBarModeScrobbleBar, // Show scrobble bar (like iBooks, PSPDFScrobbleBar) PSPDFThumbnailBarModeScrollable, // Show scrollable thumbnail bar (PSPDFThumbnailBar) }; /// PSPDFOutlineBarButtonItem options public enum PSPDFOutlineBarButtonItemOption : uint { Outline, // The outline (Table of Contents) controller. Bookmarks, // Bookmark list controller. Annotations, // Annotation list controller. PSPDFKit Annotate only. }; ////////////////////////////////////////// //// PSPDFKitGlobal.h enums // //// Start // ////////////////////////////////////////// public enum PSPDFErrorCode { PageInvalid = 100, UnableToOpenPDF = 200, UnableToGetPageReference = 210, PageRenderSizeIsEmpty = 220, PageRenderClipRectTooLarge = 230, PageRenderGraphicsContextNil = 240, DocumentLocked = 300, FailedToLoadAnnotations = 400, FailedToWriteAnnotations = 410, FailedToLoadBookmarks = 450, OutlineParser = 500, UnableToConvertToDataRepresentation = 600, RemoveCacheError = 700, FailedToConvertToPDF = 800, FailedToGeneratePDFInvalidArguments = 810, FailedToGeneratePDFDocumentInvalid = 820, CodeFailedToUpdatePageObject = 850, Unknown = 900, } public enum PSPDFLogLevel { Nothing = 0, Error, Warning, Info, Verbose } public enum PSPDFAnimate { Never, ModernDevices, Everywhere } ////////////////////////////////////////// //// PSPDFViewController.h enums // //// Start // ////////////////////////////////////////// public enum PSPDFPageTransition { PerPage, // One scrollView per page. ScrollContinuous, // Similar to UIWebView. Ignores PSPDFPageModeDouble. Curl // iBooks } public enum PSPDFViewMode { Document, Thumbnails } public enum PSPDFPageMode { Single, // Default on iPhone. Double, Automatic // single in portrait, double in landscape if the document's height > width. Default on iPad. } public enum PSPDFScrollDirection { Horizontal, // default Vertical } public enum PSPDFStatusBarStyleSetting { Inherit, /// Don't change status bar style, but show/hide statusbar on HUD events. SmartBlack, /// UIStatusBarStyleBlackOpaque on iPad, UIStatusBarStyleBlackTranslucent on iPhone. SmartBlackHideOnIpad,/// Similar to PSPDFStatusBarSmartBlack, but also hides statusBar on iPad. BlackOpaque, /// Opaque Black everywhere. Default, /// Default statusbar (white on iPhone/black on iPad). Disable /// Never show status bar. } public enum PSPDFHUDViewMode { Always, /// Always show the HUD. Automatic, /// Show HUD on touch and first/last page. AutomaticNoFirstLastPage, /// Show HUD on touch. Never /// Never show the HUD. } public enum PSPDFHUDViewAnimation { None, Fade, Slide } public enum PSPDFLinkAction { None, /// Link actions are ignored. AlertView, /// Link actions open an UIAlertView. OpenSafari, /// Link actions directly open Safari. InlineBrowser /// Link actions open in an inline browser. } public enum PSPDFPageRenderingMode { ThumbailThenFullPage, // load cached page async FullPage, // load cached page async, no upscaled thumb FullPageBlocking, // load cached page directly ThumbnailThenRender, // don't use cached page but thumb Render // don't use cached page nor thumb } ////////////////////////////////////// //// PSPDFDocument.h enums // //// Start // ////////////////////////////////////// public enum PSPDFAnnotationSaveMode { Disabled, ExternalFile, Embedded, WithExternalFileAsFallback } public enum PSPDFTextCheckingType : uint { Link = 1 << 0, // URLs PhoneNumber = 1 << 1, // Phone numbers All = uint.MaxValue } [Flags] public enum PSPDFDocumentMenuAction : uint { Search = 1 << 0, Define = 1 << 1, WikipediaAsFallback = 1 << 2, All = uint.MaxValue } ////////////////////////////////////////// //// PSPDFAnnotation.h enums // //// Start // ////////////////////////////////////////// [Flags] public enum PSPDFAnnotationType : uint { None = 0, Undefined = 1 << 0, Link = 1 << 1, Highlight = 1 << 2, Text = 1 << 3, Ink = 1 << 4, Shape = 1 << 5, Line = 1 << 6, Note = 1 << 7, Stamp = 1 << 8, Caret = 1 << 9, RichMedia = 1 << 10, Screen = 1 << 11, Widget = 1 << 12, All = uint.MaxValue } public enum PSPDFAnnotationBorderStyle : uint { None, Solid, Dashed, Belved, Inset, Underline, Unknown } ////////////////////////////////////////////////// //// PSPDFHighlightAnnotation.h enums // //// Start // ////////////////////////////////////////////////// public enum PSPDFHighlightAnnotationType { Unknown, Highlight, Underline, StrikeOut } ////////////////////////////////////////// //// PSPDFScrollView.h enums // //// Start // ////////////////////////////////////////// public enum PSPDFShadowStyle { Flat, // flat shadow style (Default) Curl // curled shadow style } ////////////////////////////////////////////// //// PSPDFSearchOperation.h enums // //// Start // ////////////////////////////////////////////// public enum PSPDFSearchMode { Basic, Highlighting } ////////////////////////////////////////////// //// PSPDFLineAnnotation.h enums // //// Start // ////////////////////////////////////////////// public enum PSPDFLineEndType { None, Square, Circle, Diamond, OpenArrow, ClosedArrow, Butt, ReverseOpenArrow, ReverseClosedArrow, Slash } ////////////////////////////////////////////// //// PSPDFLinkAnnotation.h enums // //// Start // ////////////////////////////////////////////// public enum PSPDFLinkAnnotationType { Page = 0, WebURL, // 1 Document,// 2 Video, // 3 YouTube, // 4 Audio, // 5 Image, // 6 Browser, // 7 Custom /// any annotation format that is not recognized is custom, calling the delegate viewForAnnotation: } ////////////////////////////////////////////// //// PSPDFShapeAnnotation.h enums // //// Start // ////////////////////////////////////////////// public enum PSPDFShapeAnnotationType { Unknown, Square, Circle } ////////////////////////////////////////////// //// PSPDFWebViewController.h enums // //// Start // ////////////////////////////////////////////// [Flags] public enum PSPDFWebViewControllerAvailableActions : uint { None = 0, OpenInSafari = 1, MailLink = 2, CopyLink = 4, Print = 8, StopReload = 16, Back = 32, Forward = 64, All = 16777215 } ////////////////////////////////// //// PSPDFCache.h enums // //// Start // ////////////////////////////////// public enum PSPDFDiskCacheStrategy { Nothing, Thumbnails, NearPages, Everything } ////////////////////////////////////////////////// //// PSCollectionViewFlowLayout.h enums // //// Start // ////////////////////////////////////////////////// public enum PSPDFImageResizingMethod { Crop, // analogous to UIViewContentModeScaleAspectFill, i.e. "best fit" with no space around. CropStart, CropEnd, Scale // analogous to UIViewContentModeScaleAspectFit, i.e. scale down to fit, leaving space around if necessary. } ////////////////////////////////////////////////// //// PSPDFSearchViewController.h enums // //// Start // ////////////////////////////////////////////////// public enum PSPDFSearchStatus { Idle, Active, Finished, Cancelled } ////////////////////////////////////////////////// //// PSPDFAnnotationToolbar.h enums // //// Start // ////////////////////////////////////////////////// public enum PSPDFAnnotationToolbarMode : uint { None, Note, Highlight, StrikeOut, Underline, FreeText, Draw, Rectangle, Ellipse, Line, Signature, Stamp, Image } ////////////////////////////////////// //// PSPDFColorView.h enums // //// Start // ////////////////////////////////////// public enum PSPDFColorViewBorderStyle { Single = 0, Top, Middle, Bottom } ////////////////////////////////////// //// PSPDFColorView.h enums // //// Start // ////////////////////////////////////// public enum PSPDFGradientViewDirection { Horizontal, Vertical } ////////////////////////////////////////// //// PSPDFProgressHUD.h enums // //// Start // ////////////////////////////////////////// public enum PSPDFProgressHUDMaskType : uint { None = 1, // allow user interactions while HUD is displayed Clear, // don't allow Black, // don't allow and dim the UI in the back of the HUD Gradient // don't allow and dim the UI with a a-la-alert-view bg gradient } ////////////////////////////////////// //// PSPDFLabelView.h enums // //// Start // ////////////////////////////////////// public enum PSPDFLabelStyle : uint { Flat, Bordered } ////////////////////////////////////////////////// //// PSPDFEmailBarButtonItem.h enums // //// Start // ////////////////////////////////////////////////// [Flags] public enum PSPDFEmailSendOptions : uint { CurrentPageOnly = 1, CurrentPageOnlyFlattened = 2, VisiblePages = 4, VisiblePagesFlattened = 8, MergedFilesIfNeeded = 16, MergedFilesIfNeededFlattened = 32, OriginalDocumentFiles = 64 } ////////////////////////////////////////// //// PSPDFResizableView.h enums // //// Start // ////////////////////////////////////////// public enum PSPDFSelectionBorderKnobType : uint { None, Move, TopLeft, TopMiddle, TopRight, MiddleLeft, MiddleRight, BottomLeft, BottomMiddle, BottomRight, Custom } ////////////////////////////////////////////////////////// //// PSPDFColorSelectionViewController.h enums // //// Start // ////////////////////////////////////////////////////////// public enum PSPDFColorPickerStyle : uint { Rainbow, Modern, Vintage, Monochrome, HSVPicker } ////////////////////////////////////////////// //// PSPDFBrightnessSlider.h enums // //// Start // ////////////////////////////////////////////// public enum PSPDFThumbImageStyle { Default = 0, HourGlass, ArrowLoop, } public enum PSPDFSliderBackgroundStyle { Default = 0, Grayscale, Colorful, } ////////////////////////////////////////// //// PSPDFBarButtonItem.h enums // //// Start // ////////////////////////////////////////// [Flags] public enum PSPDFPrintOptions : uint { DocumentOnly = 1, IncludeAnnotations = 2 } ////////////////////////////////////////////////// //// PSPDFOpenInBarButtonItem.h enums // //// Start // ////////////////////////////////////////////////// [Flags] public enum PSPDFOpenInOptions : uint { Original = 1, FlattenAnnotations = 2 } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// General Ledger Sub Programs /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KGLSUB : EduHubEntity { #region Navigation Property Cache private KGLPROG Cache_GL_PROGRAM_KGLPROG; #endregion #region Foreign Navigation Properties private IReadOnlyList<ARF> Cache_SUBPROGRAM_ARF_SUBPROGRAM; private IReadOnlyList<CRF> Cache_SUBPROGRAM_CRF_SUBPROGRAM; private IReadOnlyList<CRPR> Cache_SUBPROGRAM_CRPR_SUBPROGRAM; private IReadOnlyList<DFF> Cache_SUBPROGRAM_DFF_SUBPROGRAM; private IReadOnlyList<DRF> Cache_SUBPROGRAM_DRF_SUBPROGRAM; private IReadOnlyList<GLCF> Cache_SUBPROGRAM_GLCF_SUBPROGRAM; private IReadOnlyList<GLCFPREV> Cache_SUBPROGRAM_GLCFPREV_SUBPROGRAM; private IReadOnlyList<GLF> Cache_SUBPROGRAM_GLF_SUBPROGRAM; private IReadOnlyList<GLFBANK> Cache_SUBPROGRAM_GLFBANK_SUBPROGRAM; private IReadOnlyList<GLFPREV> Cache_SUBPROGRAM_GLFPREV_SUBPROGRAM; private IReadOnlyList<PC> Cache_SUBPROGRAM_PC_SUBPROGRAM; private IReadOnlyList<PD> Cache_SUBPROGRAM_PD_SUBPROGRAM; private IReadOnlyList<PEF> Cache_SUBPROGRAM_PEF_SUBPROGRAM; private IReadOnlyList<PEFH> Cache_SUBPROGRAM_PEFH_SUBPROGRAM; private IReadOnlyList<PEPS> Cache_SUBPROGRAM_PEPS_SUBPROGRAM; private IReadOnlyList<PEPU> Cache_SUBPROGRAM_PEPU_SUBPROGRAM; private IReadOnlyList<PEPUH> Cache_SUBPROGRAM_PEPUH_SUBPROGRAM; private IReadOnlyList<PI> Cache_SUBPROGRAM_PI_SUBPROGRAM; private IReadOnlyList<PN> Cache_SUBPROGRAM_PN_SUBPROGRAM; private IReadOnlyList<RQGL> Cache_SUBPROGRAM_RQGL_SUBPROGRAM; private IReadOnlyList<RQT> Cache_SUBPROGRAM_RQT_SUBPROGRAM; private IReadOnlyList<SA> Cache_SUBPROGRAM_SA_SUBPROGRAM; private IReadOnlyList<SDFC> Cache_SUBPROGRAM_SDFC_SUBPROGRAM; private IReadOnlyList<SGFC> Cache_SUBPROGRAM_SGFC_SUBPROGRAM; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Type key, eg I /// [Uppercase Alphanumeric (4)] /// </summary> public string SUBPROGRAM { get; internal set; } /// <summary> /// eg, INCOME /// [Alphanumeric (30)] /// </summary> public string TITLE { get; internal set; } /// <summary> /// Each subprogram belongs to a program /// [Uppercase Alphanumeric (3)] /// </summary> public string GL_PROGRAM { get; internal set; } /// <summary> /// Allow account to be used(Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string ACTIVE { get; internal set; } /// <summary> /// To allow editing of the description /// [Uppercase Alphanumeric (1)] /// </summary> public string USER_DEFINABLE { get; internal set; } /// <summary> /// To prevent re-activation of old codes /// [Uppercase Alphanumeric (1)] /// </summary> public string RESERVED { get; internal set; } /// <summary> /// Allow account to be processed (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string BATCHABLE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// KGLPROG (General Ledger Programs) related entity by [KGLSUB.GL_PROGRAM]-&gt;[KGLPROG.GLPROGRAM] /// Each subprogram belongs to a program /// </summary> public KGLPROG GL_PROGRAM_KGLPROG { get { if (GL_PROGRAM == null) { return null; } if (Cache_GL_PROGRAM_KGLPROG == null) { Cache_GL_PROGRAM_KGLPROG = Context.KGLPROG.FindByGLPROGRAM(GL_PROGRAM); } return Cache_GL_PROGRAM_KGLPROG; } } #endregion #region Foreign Navigation Properties /// <summary> /// ARF (Asset Financial Transactions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[ARF.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<ARF> SUBPROGRAM_ARF_SUBPROGRAM { get { if (Cache_SUBPROGRAM_ARF_SUBPROGRAM == null && !Context.ARF.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_ARF_SUBPROGRAM)) { Cache_SUBPROGRAM_ARF_SUBPROGRAM = new List<ARF>().AsReadOnly(); } return Cache_SUBPROGRAM_ARF_SUBPROGRAM; } } /// <summary> /// CRF (Creditor Financial Transaction) related entities by [KGLSUB.SUBPROGRAM]-&gt;[CRF.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<CRF> SUBPROGRAM_CRF_SUBPROGRAM { get { if (Cache_SUBPROGRAM_CRF_SUBPROGRAM == null && !Context.CRF.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_CRF_SUBPROGRAM)) { Cache_SUBPROGRAM_CRF_SUBPROGRAM = new List<CRF>().AsReadOnly(); } return Cache_SUBPROGRAM_CRF_SUBPROGRAM; } } /// <summary> /// CRPR (Creditor Purchase Requisitions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[CRPR.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<CRPR> SUBPROGRAM_CRPR_SUBPROGRAM { get { if (Cache_SUBPROGRAM_CRPR_SUBPROGRAM == null && !Context.CRPR.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_CRPR_SUBPROGRAM)) { Cache_SUBPROGRAM_CRPR_SUBPROGRAM = new List<CRPR>().AsReadOnly(); } return Cache_SUBPROGRAM_CRPR_SUBPROGRAM; } } /// <summary> /// DFF (Family Financial Transactions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[DFF.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<DFF> SUBPROGRAM_DFF_SUBPROGRAM { get { if (Cache_SUBPROGRAM_DFF_SUBPROGRAM == null && !Context.DFF.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_DFF_SUBPROGRAM)) { Cache_SUBPROGRAM_DFF_SUBPROGRAM = new List<DFF>().AsReadOnly(); } return Cache_SUBPROGRAM_DFF_SUBPROGRAM; } } /// <summary> /// DRF (DR Transactions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[DRF.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<DRF> SUBPROGRAM_DRF_SUBPROGRAM { get { if (Cache_SUBPROGRAM_DRF_SUBPROGRAM == null && !Context.DRF.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_DRF_SUBPROGRAM)) { Cache_SUBPROGRAM_DRF_SUBPROGRAM = new List<DRF>().AsReadOnly(); } return Cache_SUBPROGRAM_DRF_SUBPROGRAM; } } /// <summary> /// GLCF (GL Combined Financial Trans) related entities by [KGLSUB.SUBPROGRAM]-&gt;[GLCF.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<GLCF> SUBPROGRAM_GLCF_SUBPROGRAM { get { if (Cache_SUBPROGRAM_GLCF_SUBPROGRAM == null && !Context.GLCF.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_GLCF_SUBPROGRAM)) { Cache_SUBPROGRAM_GLCF_SUBPROGRAM = new List<GLCF>().AsReadOnly(); } return Cache_SUBPROGRAM_GLCF_SUBPROGRAM; } } /// <summary> /// GLCFPREV (Last Years GL Combined Financial Trans) related entities by [KGLSUB.SUBPROGRAM]-&gt;[GLCFPREV.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<GLCFPREV> SUBPROGRAM_GLCFPREV_SUBPROGRAM { get { if (Cache_SUBPROGRAM_GLCFPREV_SUBPROGRAM == null && !Context.GLCFPREV.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_GLCFPREV_SUBPROGRAM)) { Cache_SUBPROGRAM_GLCFPREV_SUBPROGRAM = new List<GLCFPREV>().AsReadOnly(); } return Cache_SUBPROGRAM_GLCFPREV_SUBPROGRAM; } } /// <summary> /// GLF (General Ledger Transactions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[GLF.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<GLF> SUBPROGRAM_GLF_SUBPROGRAM { get { if (Cache_SUBPROGRAM_GLF_SUBPROGRAM == null && !Context.GLF.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_GLF_SUBPROGRAM)) { Cache_SUBPROGRAM_GLF_SUBPROGRAM = new List<GLF>().AsReadOnly(); } return Cache_SUBPROGRAM_GLF_SUBPROGRAM; } } /// <summary> /// GLFBANK (Financial Commitments) related entities by [KGLSUB.SUBPROGRAM]-&gt;[GLFBANK.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<GLFBANK> SUBPROGRAM_GLFBANK_SUBPROGRAM { get { if (Cache_SUBPROGRAM_GLFBANK_SUBPROGRAM == null && !Context.GLFBANK.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_GLFBANK_SUBPROGRAM)) { Cache_SUBPROGRAM_GLFBANK_SUBPROGRAM = new List<GLFBANK>().AsReadOnly(); } return Cache_SUBPROGRAM_GLFBANK_SUBPROGRAM; } } /// <summary> /// GLFPREV (Last Years GL Financial Trans) related entities by [KGLSUB.SUBPROGRAM]-&gt;[GLFPREV.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<GLFPREV> SUBPROGRAM_GLFPREV_SUBPROGRAM { get { if (Cache_SUBPROGRAM_GLFPREV_SUBPROGRAM == null && !Context.GLFPREV.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_GLFPREV_SUBPROGRAM)) { Cache_SUBPROGRAM_GLFPREV_SUBPROGRAM = new List<GLFPREV>().AsReadOnly(); } return Cache_SUBPROGRAM_GLFPREV_SUBPROGRAM; } } /// <summary> /// PC (Cost Centres) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PC.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PC> SUBPROGRAM_PC_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PC_SUBPROGRAM == null && !Context.PC.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PC_SUBPROGRAM)) { Cache_SUBPROGRAM_PC_SUBPROGRAM = new List<PC>().AsReadOnly(); } return Cache_SUBPROGRAM_PC_SUBPROGRAM; } } /// <summary> /// PD (Departments) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PD.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PD> SUBPROGRAM_PD_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PD_SUBPROGRAM == null && !Context.PD.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PD_SUBPROGRAM)) { Cache_SUBPROGRAM_PD_SUBPROGRAM = new List<PD>().AsReadOnly(); } return Cache_SUBPROGRAM_PD_SUBPROGRAM; } } /// <summary> /// PEF (Payroll Transactions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PEF.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PEF> SUBPROGRAM_PEF_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PEF_SUBPROGRAM == null && !Context.PEF.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PEF_SUBPROGRAM)) { Cache_SUBPROGRAM_PEF_SUBPROGRAM = new List<PEF>().AsReadOnly(); } return Cache_SUBPROGRAM_PEF_SUBPROGRAM; } } /// <summary> /// PEFH (Payroll Transaction History) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PEFH.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PEFH> SUBPROGRAM_PEFH_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PEFH_SUBPROGRAM == null && !Context.PEFH.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PEFH_SUBPROGRAM)) { Cache_SUBPROGRAM_PEFH_SUBPROGRAM = new List<PEFH>().AsReadOnly(); } return Cache_SUBPROGRAM_PEFH_SUBPROGRAM; } } /// <summary> /// PEPS (Standard and Last Pays) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PEPS.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PEPS> SUBPROGRAM_PEPS_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PEPS_SUBPROGRAM == null && !Context.PEPS.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PEPS_SUBPROGRAM)) { Cache_SUBPROGRAM_PEPS_SUBPROGRAM = new List<PEPS>().AsReadOnly(); } return Cache_SUBPROGRAM_PEPS_SUBPROGRAM; } } /// <summary> /// PEPU (Super (SGL and Employee) YTD Transactions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PEPU.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PEPU> SUBPROGRAM_PEPU_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PEPU_SUBPROGRAM == null && !Context.PEPU.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PEPU_SUBPROGRAM)) { Cache_SUBPROGRAM_PEPU_SUBPROGRAM = new List<PEPU>().AsReadOnly(); } return Cache_SUBPROGRAM_PEPU_SUBPROGRAM; } } /// <summary> /// PEPUH (Super (SGL and Employee) History YTD Transactions) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PEPUH.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PEPUH> SUBPROGRAM_PEPUH_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PEPUH_SUBPROGRAM == null && !Context.PEPUH.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PEPUH_SUBPROGRAM)) { Cache_SUBPROGRAM_PEPUH_SUBPROGRAM = new List<PEPUH>().AsReadOnly(); } return Cache_SUBPROGRAM_PEPUH_SUBPROGRAM; } } /// <summary> /// PI (Pay Items) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PI.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PI> SUBPROGRAM_PI_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PI_SUBPROGRAM == null && !Context.PI.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PI_SUBPROGRAM)) { Cache_SUBPROGRAM_PI_SUBPROGRAM = new List<PI>().AsReadOnly(); } return Cache_SUBPROGRAM_PI_SUBPROGRAM; } } /// <summary> /// PN (Payroll Groups) related entities by [KGLSUB.SUBPROGRAM]-&gt;[PN.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<PN> SUBPROGRAM_PN_SUBPROGRAM { get { if (Cache_SUBPROGRAM_PN_SUBPROGRAM == null && !Context.PN.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_PN_SUBPROGRAM)) { Cache_SUBPROGRAM_PN_SUBPROGRAM = new List<PN>().AsReadOnly(); } return Cache_SUBPROGRAM_PN_SUBPROGRAM; } } /// <summary> /// RQGL (Purchasing Group GL Codes) related entities by [KGLSUB.SUBPROGRAM]-&gt;[RQGL.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<RQGL> SUBPROGRAM_RQGL_SUBPROGRAM { get { if (Cache_SUBPROGRAM_RQGL_SUBPROGRAM == null && !Context.RQGL.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_RQGL_SUBPROGRAM)) { Cache_SUBPROGRAM_RQGL_SUBPROGRAM = new List<RQGL>().AsReadOnly(); } return Cache_SUBPROGRAM_RQGL_SUBPROGRAM; } } /// <summary> /// RQT (Purchase Requisition Transaction) related entities by [KGLSUB.SUBPROGRAM]-&gt;[RQT.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<RQT> SUBPROGRAM_RQT_SUBPROGRAM { get { if (Cache_SUBPROGRAM_RQT_SUBPROGRAM == null && !Context.RQT.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_RQT_SUBPROGRAM)) { Cache_SUBPROGRAM_RQT_SUBPROGRAM = new List<RQT>().AsReadOnly(); } return Cache_SUBPROGRAM_RQT_SUBPROGRAM; } } /// <summary> /// SA (Fees) related entities by [KGLSUB.SUBPROGRAM]-&gt;[SA.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<SA> SUBPROGRAM_SA_SUBPROGRAM { get { if (Cache_SUBPROGRAM_SA_SUBPROGRAM == null && !Context.SA.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_SA_SUBPROGRAM)) { Cache_SUBPROGRAM_SA_SUBPROGRAM = new List<SA>().AsReadOnly(); } return Cache_SUBPROGRAM_SA_SUBPROGRAM; } } /// <summary> /// SDFC (Sundry Debtor Fees) related entities by [KGLSUB.SUBPROGRAM]-&gt;[SDFC.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<SDFC> SUBPROGRAM_SDFC_SUBPROGRAM { get { if (Cache_SUBPROGRAM_SDFC_SUBPROGRAM == null && !Context.SDFC.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_SDFC_SUBPROGRAM)) { Cache_SUBPROGRAM_SDFC_SUBPROGRAM = new List<SDFC>().AsReadOnly(); } return Cache_SUBPROGRAM_SDFC_SUBPROGRAM; } } /// <summary> /// SGFC (General Ledger Fees) related entities by [KGLSUB.SUBPROGRAM]-&gt;[SGFC.SUBPROGRAM] /// Type key, eg I /// </summary> public IReadOnlyList<SGFC> SUBPROGRAM_SGFC_SUBPROGRAM { get { if (Cache_SUBPROGRAM_SGFC_SUBPROGRAM == null && !Context.SGFC.TryFindBySUBPROGRAM(SUBPROGRAM, out Cache_SUBPROGRAM_SGFC_SUBPROGRAM)) { Cache_SUBPROGRAM_SGFC_SUBPROGRAM = new List<SGFC>().AsReadOnly(); } return Cache_SUBPROGRAM_SGFC_SUBPROGRAM; } } #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.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public static class MemberAccessTests { private class UnreadableIndexableClass { public int this[int index] { set { } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructInstanceFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(new FS() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructStaticFieldTest(bool useInterpreter) { FS.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { FS.SI = 0; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructConstFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "CI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructStaticReadOnlyFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "RI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructInstancePropertyTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(new PS() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructStaticPropertyTest(bool useInterpreter) { PS.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( null, typeof(PS), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { PS.SI = 0; } } [Theory, ClassData(typeof(CompilationTypes))] public static void NullNullableValueException(bool useInterpreter) { string localizedMessage = null; try { int dummy = default(int?).Value; } catch (InvalidOperationException ioe) { localizedMessage = ioe.Message; } Expression<Func<long>> e = () => default(long?).Value; Func<long> f = e.Compile(useInterpreter); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => f()); Assert.Equal(localizedMessage, exception.Message); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(new FC() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassStaticFieldTest(bool useInterpreter) { FC.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { FC.SI = 0; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassConstFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "CI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassStaticReadOnlyFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "RI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Fact] public static void Field_NullField_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("field", () => Expression.Field(null, (FieldInfo)null)); AssertExtensions.Throws<ArgumentNullException>("fieldName", () => Expression.Field(Expression.Constant(new FC()), (string)null)); } [Fact] public static void Field_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Field(Expression.Constant(new FC()), null, "AField")); } [Fact] public static void Field_StaticField_NonNullExpression_ThrowsArgumentException() { Expression expression = Expression.Constant(new FC()); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC), nameof(FC.SI))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.SI)))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.SI)))); } [Fact] public static void Field_ByrefTypeFieldAccessor_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Expression.Property(null, typeof(GenericClass<string>).MakeByRefType(), nameof(GenericClass<string>.Field))); } [Fact] public static void Field_GenericFieldAccessor_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Expression.Property(null, typeof(GenericClass<>), nameof(GenericClass<string>.Field))); } [Fact] public static void Field_InstanceField_NullExpression_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Field(null, "fieldName")); AssertExtensions.Throws<ArgumentException>("field", () => Expression.Field(null, typeof(FC), nameof(FC.II))); AssertExtensions.Throws<ArgumentException>("field", () => Expression.Field(null, typeof(FC).GetField(nameof(FC.II)))); AssertExtensions.Throws<ArgumentException>("field", () => Expression.MakeMemberAccess(null, typeof(FC).GetField(nameof(FC.II)))); } [Fact] public static void Field_ExpressionNotReadable_ThrowsArgumentException() { Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, "fieldName")); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC), nameof(FC.SI))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.SI)))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.SI)))); } [Fact] public static void Field_ExpressionNotTypeOfDeclaringType_ThrowsArgumentException() { Expression expression = Expression.Constant(new PC()); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(expression, typeof(FC), nameof(FC.II))); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.II)))); AssertExtensions.Throws<ArgumentException>(null, () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.II)))); } [Fact] public static void Field_NoSuchFieldName_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(Expression.Constant(new FC()), "NoSuchField")); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Field(Expression.Constant(new FC()), typeof(FC), "NoSuchField")); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstancePropertyTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(new PC() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassStaticPropertyTest(bool useInterpreter) { PC.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( null, typeof(PC), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { PC.SI = 0; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceFieldNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(null, typeof(FC)), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceFieldAssignNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Assign( Expression.Field( Expression.Constant(null, typeof(FC)), "II"), Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstancePropertyNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(null, typeof(PC)), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceIndexerNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(null, typeof(PC)), "Item", Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceIndexerAssignNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Assign( Expression.Property( Expression.Constant(null, typeof(PC)), "Item", Expression.Constant(1)), Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Fact] public static void AccessIndexedPropertyWithoutIndex() { AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(Expression.Default(typeof(List<int>)), typeof(List<int>).GetProperty("Item"))); } [Fact] public static void AccessIndexedPropertyWithoutIndexWriteOnly() { AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(Expression.Default(typeof(UnreadableIndexableClass)), typeof(UnreadableIndexableClass).GetProperty("Item"))); } [Fact] public static void Property_NullProperty_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("property", () => Expression.Property(null, (PropertyInfo)null)); AssertExtensions.Throws<ArgumentNullException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), (string)null)); } [Fact] public static void Property_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Property(Expression.Constant(new PC()), null, "AProperty")); } [Fact] public static void Property_StaticProperty_NonNullExpression_ThrowsArgumentException() { Expression expression = Expression.Constant(new PC()); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC), nameof(PC.SI))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)).GetGetMethod())); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(PC).GetProperty(nameof(PC.SI)))); } [Fact] public static void Property_InstanceProperty_NullExpression_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Property(null, "propertyName")); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC), nameof(PC.II))); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC).GetProperty(nameof(PC.II)))); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC).GetProperty(nameof(PC.II)).GetGetMethod())); AssertExtensions.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(null, typeof(PC).GetProperty(nameof(PC.II)))); } [Fact] public static void Property_ExpressionNotReadable_ThrowsArgumentException() { Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, "fieldName")); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC), nameof(PC.SI))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)))); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)).GetGetMethod())); } [Fact] public static void Property_ExpressionNotTypeOfDeclaringType_ThrowsArgumentException() { Expression expression = Expression.Constant(new FC()); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC), nameof(PC.II))); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.II)))); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.II)).GetGetMethod())); AssertExtensions.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(expression, typeof(PC).GetProperty(nameof(PC.II)))); } [Fact] public static void Property_NoSuchPropertyName_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), "NoSuchProperty")); AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), typeof(PC), "NoSuchProperty")); } [Fact] public static void Property_NullPropertyAccessor_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.Property(Expression.Constant(new PC()), (MethodInfo)null)); } [Fact] public static void Property_GenericPropertyAccessor_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(GenericClass<>).GetProperty(nameof(GenericClass<string>.Property)).GetGetMethod())); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)))); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(GenericClass<>).GetProperty(nameof(GenericClass<string>.Property)))); } [Fact] public static void Property_PropertyAccessorNotFromProperty_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticMethod)))); } [Fact] public static void Property_ByRefStaticAccess_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Expression.Property(null, typeof(NonGenericClass).MakeByRefType(), nameof(NonGenericClass.NonGenericProperty))); } [Fact] public static void PropertyOrField_NullExpression_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.PropertyOrField(null, "APropertyOrField")); } [Fact] public static void PropertyOrField_ExpressionNotReadable_ThrowsArgumentNullException() { Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.PropertyOrField(expression, "APropertyOrField")); } [Fact] public static void PropertyOrField_NoSuchPropertyOrField_ThrowsArgumentException() { Expression expression = Expression.Constant(new PC()); AssertExtensions.Throws<ArgumentException>("propertyOrFieldName", () => Expression.PropertyOrField(expression, "NoSuchPropertyOrField")); } [Fact] public static void MakeMemberAccess_NullMember_ThrowsArgumentNullExeption() { AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.MakeMemberAccess(Expression.Constant(new PC()), null)); } [Fact] public static void MakeMemberAccess_MemberNotFieldOrProperty_ThrowsArgumentExeption() { MemberInfo member = typeof(NonGenericClass).GetEvent("Event"); AssertExtensions.Throws<ArgumentException>("member", () => Expression.MakeMemberAccess(Expression.Constant(new PC()), member)); } #if FEATURE_COMPILE [Fact] public static void Property_NoGetOrSetAccessors_ThrowsArgumentException() { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Module"); TypeBuilder type = module.DefineType("Type"); PropertyBuilder property = type.DefineProperty("Property", PropertyAttributes.None, typeof(void), new Type[0]); TypeInfo createdType = type.CreateTypeInfo(); PropertyInfo createdProperty = createdType.DeclaredProperties.First(); Expression expression = Expression.Constant(Activator.CreateInstance(createdType)); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, createdProperty)); AssertExtensions.Throws<ArgumentException>("property", () => Expression.Property(expression, createdProperty.Name)); AssertExtensions.Throws<ArgumentException>("property", () => Expression.PropertyOrField(expression, createdProperty.Name)); AssertExtensions.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(expression, createdProperty)); } #endif [Fact] public static void ToStringTest() { MemberExpression e1 = Expression.Property(null, typeof(DateTime).GetProperty(nameof(DateTime.Now))); Assert.Equal("DateTime.Now", e1.ToString()); MemberExpression e2 = Expression.Property(Expression.Parameter(typeof(DateTime), "d"), typeof(DateTime).GetProperty(nameof(DateTime.Year))); Assert.Equal("d.Year", e2.ToString()); } [Fact] public static void UpdateSameResturnsSame() { var exp = Expression.Constant(new PS {II = 42}); var pro = Expression.Property(exp, nameof(PS.II)); Assert.Same(pro, pro.Update(exp)); } [Fact] public static void UpdateStaticResturnsSame() { var pro = Expression.Property(null, typeof(PS), nameof(PS.SI)); Assert.Same(pro, pro.Update(null)); } [Fact] public static void UpdateDifferentResturnsDifferent() { var pro = Expression.Property(Expression.Constant(new PS {II = 42}), nameof(PS.II)); Assert.NotSame(pro, pro.Update(Expression.Constant(new PS {II = 42}))); } } }
// // PangoUtils.cs // // Author: // Michael Hutchinson <mhutchinson@novell.com> // // Copyright (c) 2010 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Gtk; using System.Runtime.InteropServices; namespace Pinta.Docking { static class PangoUtil { internal const string LIBGTK = "libgtk-win32-2.0-0.dll"; internal const string LIBATK = "libatk-1.0-0.dll"; internal const string LIBGLIB = "libglib-2.0-0.dll"; internal const string LIBGDK = "libgdk-win32-2.0-0.dll"; internal const string LIBGOBJECT = "libgobject-2.0-0.dll"; internal const string LIBPANGO = "libpango-1.0-0.dll"; internal const string LIBPANGOCAIRO = "libpangocairo-1.0-0.dll"; internal const string LIBQUARTZ = "libgtk-quartz-2.0.dylib"; internal const string LIBGTKGLUE = "gtksharpglue-2"; /// <summary> /// This doesn't leak Pango layouts, unlike some other ways to create them in GTK# &lt;= 2.12.11 /// </summary> public static Pango.Layout CreateLayout (Widget widget) { var ptr = gtk_widget_create_pango_layout (widget.Handle, IntPtr.Zero); return ptr == IntPtr.Zero? null : new Pango.Layout (ptr); } public static Pango.Layout CreateLayout (Widget widget, string text) { IntPtr textPtr = text == null? IntPtr.Zero : GLib.Marshaller.StringToPtrGStrdup (text); var ptr = gtk_widget_create_pango_layout (widget.Handle, textPtr); if (textPtr != IntPtr.Zero) GLib.Marshaller.Free (textPtr); return ptr == IntPtr.Zero? null : new Pango.Layout (ptr); } public static Pango.Layout CreateLayout (PrintContext context) { var ptr = gtk_print_context_create_pango_layout (context.Handle); return ptr == IntPtr.Zero? null : new Pango.Layout (ptr); } [DllImport (LIBGTK, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr gtk_widget_create_pango_layout (IntPtr widget, IntPtr text); [DllImport (LIBGTK, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr gtk_print_context_create_pango_layout (IntPtr context); } /// <summary> /// This creates a Pango list and applies attributes to it with *much* less overhead than the GTK# version. /// </summary> class FastPangoAttrList : IDisposable { IntPtr list; public FastPangoAttrList () { list = pango_attr_list_new (); } public void AddStyleAttribute (Pango.Style style, uint start, uint end) { Add (pango_attr_style_new (style), start, end); } public void AddWeightAttribute (Pango.Weight weight, uint start, uint end) { Add (pango_attr_weight_new (weight), start, end); } public void AddForegroundAttribute (Gdk.Color color, uint start, uint end) { Add (pango_attr_foreground_new (color.Red, color.Green, color.Blue), start, end); } public void AddBackgroundAttribute (Gdk.Color color, uint start, uint end) { Add (pango_attr_background_new (color.Red, color.Green, color.Blue), start, end); } public void AddUnderlineAttribute (Pango.Underline underline, uint start, uint end) { Add (pango_attr_underline_new (underline), start, end); } void Add (IntPtr attribute, uint start, uint end) { unsafe { PangoAttribute *attPtr = (PangoAttribute *) attribute; attPtr->start_index = start; attPtr->end_index = end; } pango_attr_list_insert (list, attribute); } /// <summary> /// Like Splice, except it only offsets/clamps the inserted items, doesn't affect items already in the list. /// </summary> public void InsertOffsetList (Pango.AttrList atts, uint startOffset, uint endOffset) { //HACK: atts.Iterator.Attrs broken (throws NRE), so manually P/Invoke var iter = pango_attr_list_get_iterator (atts.Handle); try { do { IntPtr list = pango_attr_iterator_get_attrs (iter); try { int len = g_slist_length (list); for (uint i = 0; i < len; i++) { IntPtr val = g_slist_nth_data (list, i); AddOffsetCopy (val, startOffset, endOffset); } } finally { g_slist_free (list); } } while (pango_attr_iterator_next (iter)); } finally { pango_attr_iterator_destroy (iter); } } void AddOffsetCopy (IntPtr attr, uint startOffset, uint endOffset) { var copy = pango_attribute_copy (attr); unsafe { PangoAttribute *attPtr = (PangoAttribute *) copy; attPtr->start_index = startOffset + attPtr->start_index; attPtr->end_index = System.Math.Min (endOffset, startOffset + attPtr->end_index); } pango_attr_list_insert (list, copy); } [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_style_new (Pango.Style style); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_stretch_new (Pango.Stretch stretch); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_weight_new (Pango.Weight weight); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_foreground_new (ushort red, ushort green, ushort blue); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_background_new (ushort red, ushort green, ushort blue); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_underline_new (Pango.Underline underline); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_list_new (); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_attr_list_unref (IntPtr list); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_attr_list_insert (IntPtr list, IntPtr attr); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_layout_set_attributes (IntPtr layout, IntPtr attrList); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_attr_list_splice (IntPtr attr_list, IntPtr other, Int32 pos, Int32 len); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attribute_copy (IntPtr attr); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_list_get_iterator (IntPtr list); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern bool pango_attr_iterator_next (IntPtr iterator); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_attr_iterator_destroy (IntPtr iterator); [DllImport (PangoUtil.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_iterator_get_attrs (IntPtr iterator); [DllImport (PangoUtil.LIBGLIB, CallingConvention = CallingConvention.Cdecl)] private static extern int g_slist_length (IntPtr l); [DllImport (PangoUtil.LIBGLIB, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr g_slist_nth_data (IntPtr l, uint n); [DllImport (PangoUtil.LIBGLIB, CallingConvention = CallingConvention.Cdecl)] private static extern void g_slist_free (IntPtr l); public void Splice (Pango.AttrList attrs, int pos, int len) { pango_attr_list_splice (list, attrs.Handle, pos, len); } public void AssignTo (Pango.Layout layout) { pango_layout_set_attributes (layout.Handle, list); } [StructLayout (LayoutKind.Sequential)] struct PangoAttribute { public IntPtr klass; public uint start_index; public uint end_index; } public void Dispose () { if (list != IntPtr.Zero) { GC.SuppressFinalize (this); Destroy (); } } //NOTE: the list destroys all its attributes when the ref count reaches zero void Destroy () { pango_attr_list_unref (list); list = IntPtr.Zero; } ~FastPangoAttrList () { GLib.Idle.Add (delegate { Destroy (); return false; }); } } }
using System; using System.Windows.Forms; using Microsoft.VisualStudio.Tools.Applications.Runtime; using Word = Microsoft.Office.Interop.Word; using Office = Microsoft.Office.Core; namespace AlfrescoWord2007 { public partial class ThisAddIn { private const int ALFRESCO_PANE_WIDTH = 296; // Object references only used in "single window" mode private AlfrescoPane m_AlfrescoPane; private Microsoft.Office.Tools.CustomTaskPane m_CustomTaskPane; private void ThisAddIn_Startup(object sender, System.EventArgs e) { // Register event interest with the Word Application Application.DocumentBeforeClose += new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose); Application.DocumentChange += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentChangeEventHandler(Application_DocumentChange); } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { } #region VSTO generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion /// <summary> /// Fired when active document changes /// </summary> void Application_DocumentChange() { // Check Word UI mode if (this.Application.ShowWindowsInTaskbar) { // Multiple window mode // Update the ribbon button to reflect the new state Microsoft.Office.Tools.CustomTaskPane customTaskPane = this.FindActiveTaskPane(); if (customTaskPane != null) { m_Ribbon.ToggleAlfrescoState = customTaskPane.Visible; } else { m_Ribbon.ToggleAlfrescoState = false; } // As recommended by http://msdn2.microsoft.com/en-us/library/bb264456.aspx RemoveOrphanedTaskPanes(); } else { // Single window mode if (m_AlfrescoPane != null) { m_AlfrescoPane.OnDocumentChanged(); } } } /// <summary> /// Fired as a document is being closed /// </summary> /// <param name="Doc"></param> /// <param name="Cancel"></param> void Application_DocumentBeforeClose(Word.Document Doc, ref bool Cancel) { // Check Word UI mode if (this.Application.ShowWindowsInTaskbar) { // Multiple window mode // No action } else { // Single window mode if (m_AlfrescoPane != null) { m_AlfrescoPane.OnDocumentBeforeClose(); } } } /// <summary> /// Fired on the ribbon toggle button "show" event /// </summary> void Ribbon_OnAlfrescoShow() { ShowAlfrescoPane(); } /// <summary> /// Fired on the ribbon toggle button "hide" event /// </summary> void Ribbon_OnAlfrescoHide() { HideAlfrescoPane(); } /// <summary> /// Fired when the CustomTaskPane visibility changes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void CustomTaskPane_VisibleChanged(object sender, EventArgs e) { // Update the ribbon button to reflect the new state Microsoft.Office.Tools.CustomTaskPane customTaskPane = (Microsoft.Office.Tools.CustomTaskPane)sender; m_Ribbon.ToggleAlfrescoState = customTaskPane.Visible; } /// <summary> /// Show the Alfresco pane /// </summary> /// <param name="Show"></param> private void ShowAlfrescoPane() { // Try to get active document Word.Document activeDoc = null; try { activeDoc = this.Application.ActiveDocument; } catch { activeDoc = null; } // Check Word UI mode if (this.Application.ShowWindowsInTaskbar) { // Multiple window mode Microsoft.Office.Tools.CustomTaskPane customTaskPane = this.FindActiveTaskPane(); if (customTaskPane == null) { AlfrescoPane alfrescoPane = new AlfrescoPane(); alfrescoPane.WordApplication = this.Application; alfrescoPane.DefaultTemplate = "wcservice/office/"; customTaskPane = CustomTaskPanes.Add(alfrescoPane, "Alfresco"); try { if (Application.ActiveDocument != null) { alfrescoPane.OnDocumentChanged(); } else { alfrescoPane.showHome(false); } } catch { // Almost certainlty as a result of no active document alfrescoPane.showHome(false); } } customTaskPane.Visible = true; customTaskPane.Width = ALFRESCO_PANE_WIDTH; customTaskPane.VisibleChanged += new EventHandler(CustomTaskPane_VisibleChanged); } else { // Single window mode } /* if (m_CustomTaskPane == null) { m_CustomTaskPane = CustomTaskPanes.Add(m_AlfrescoPane, "Alfresco"); m_CustomTaskPane.VisibleChanged += new EventHandler(CustomTaskPane_VisibleChanged); } if (m_AlfrescoPane == null) { m_AlfrescoPane = new AlfrescoPane(); m_AlfrescoPane.WordApplication = Application; m_AlfrescoPane.DefaultTemplate = "wcservice/office/"; } if (Show) { AddCustomTaskPane(); m_CustomTaskPane.Visible = true; m_CustomTaskPane.Width = ALFRESCO_PANE_WIDTH; m_AlfrescoPane.Show(); if (Application.ActiveDocument != null) { m_AlfrescoPane.OnDocumentChanged(); } else { m_AlfrescoPane.showHome(false); } } */ } private void HideAlfrescoPane() { // Check Word UI mode if (this.Application.ShowWindowsInTaskbar) { // Multiple window mode Microsoft.Office.Tools.CustomTaskPane customTaskPane = this.FindActiveTaskPane(); if (customTaskPane != null) { customTaskPane.Visible = false; } } else { // Single window mode if (m_CustomTaskPane != null) { m_CustomTaskPane.Visible = false; } } } private Microsoft.Office.Tools.CustomTaskPane FindActiveTaskPane() { try { // Check if this window already has an AlfrescoPane if (CustomTaskPanes.Count > 0) { foreach (Microsoft.Office.Tools.CustomTaskPane ctp in CustomTaskPanes) { try { if (ctp.Window == this.Application.ActiveWindow) { return ctp; } } catch (Exception e) { // Likely due to no active window if (ctp.Window == null) { // This is the one return ctp; } } } } } catch { } return null; } private void RemoveOrphanedTaskPanes() { Microsoft.Office.Tools.CustomTaskPane ctp; for (int i = this.CustomTaskPanes.Count; i > 0; i--) { ctp = this.CustomTaskPanes[i - 1]; if (ctp.Window == null) { this.CustomTaskPanes.Remove(ctp); } } } } }
using System; using System.Collections.Generic; using BTDB.Buffer; using BTDB.KVDBLayer.BTree; namespace BTDB.KVDBLayer { class KeyValueDBTransaction : IKeyValueDBTransaction { readonly KeyValueDB _keyValueDB; IBTreeRootNode _btreeRoot; readonly List<NodeIdxPair> _stack = new List<NodeIdxPair>(); byte[] _prefix; bool _writting; readonly bool _readOnly; bool _preapprovedWritting; long _prefixKeyStart; long _prefixKeyCount; long _keyIndex; public KeyValueDBTransaction(KeyValueDB keyValueDB, IBTreeRootNode btreeRoot, bool writting, bool readOnly) { _preapprovedWritting = writting; _readOnly = readOnly; _keyValueDB = keyValueDB; _btreeRoot = btreeRoot; _prefix = BitArrayManipulation.EmptyByteArray; _prefixKeyStart = 0; _prefixKeyCount = -1; _keyIndex = -1; _keyValueDB.StartedUsingBTreeRoot(_btreeRoot); } internal IBTreeRootNode BtreeRoot { get { return _btreeRoot; } } public void SetKeyPrefix(ByteBuffer prefix) { _prefix = prefix.ToByteArray(); _prefixKeyStart = _prefix.Length == 0 ? 0 : -1; _prefixKeyCount = -1; InvalidateCurrentKey(); } public bool FindFirstKey() { return SetKeyIndex(0); } public bool FindLastKey() { var count = GetKeyValueCount(); if (count <= 0) return false; return SetKeyIndex(count - 1); } public bool FindPreviousKey() { if (_keyIndex < 0) return FindLastKey(); if (BtreeRoot.FindPreviousKey(_stack)) { if (CheckPrefixIn(GetCurrentKeyFromStack())) { _keyIndex--; return true; } } InvalidateCurrentKey(); return false; } public bool FindNextKey() { if (_keyIndex < 0) return FindFirstKey(); if (BtreeRoot.FindNextKey(_stack)) { if (CheckPrefixIn(GetCurrentKeyFromStack())) { _keyIndex++; return true; } } InvalidateCurrentKey(); return false; } public FindResult Find(ByteBuffer key) { return BtreeRoot.FindKey(_stack, out _keyIndex, _prefix, key); } public bool CreateOrUpdateKeyValue(ByteBuffer key, ByteBuffer value) { MakeWrittable(); uint valueFileId; uint valueOfs; int valueSize; _keyValueDB.WriteCreateOrUpdateCommand(_prefix, key, value, out valueFileId, out valueOfs, out valueSize); var ctx = new CreateOrUpdateCtx { KeyPrefix = _prefix, Key = key, ValueFileId = valueFileId, ValueOfs = valueOfs, ValueSize = valueSize, Stack = _stack }; BtreeRoot.CreateOrUpdate(ctx); _keyIndex = ctx.KeyIndex; if (ctx.Created && _prefixKeyCount >= 0) _prefixKeyCount++; return ctx.Created; } void MakeWrittable() { if (_writting) return; if (_preapprovedWritting) { _writting = true; _preapprovedWritting = false; _keyValueDB.WriteStartTransaction(); return; } if (_readOnly) { throw new BTDBTransactionRetryException("Cannot write from readOnly transaction"); } var oldBTreeRoot = BtreeRoot; _btreeRoot = _keyValueDB.MakeWrittableTransaction(this, oldBTreeRoot); _keyValueDB.StartedUsingBTreeRoot(_btreeRoot); _keyValueDB.FinishedUsingBTreeRoot(oldBTreeRoot); _writting = true; InvalidateCurrentKey(); _keyValueDB.WriteStartTransaction(); } public long GetKeyValueCount() { if (_prefixKeyCount >= 0) return _prefixKeyCount; if (_prefix.Length == 0) { _prefixKeyCount = BtreeRoot.CalcKeyCount(); return _prefixKeyCount; } CalcPrefixKeyStart(); if (_prefixKeyStart < 0) { _prefixKeyCount = 0; return 0; } _prefixKeyCount = BtreeRoot.FindLastWithPrefix(_prefix) - _prefixKeyStart + 1; return _prefixKeyCount; } public long GetKeyIndex() { if (_keyIndex < 0) return -1; CalcPrefixKeyStart(); return _keyIndex - _prefixKeyStart; } void CalcPrefixKeyStart() { if (_prefixKeyStart >= 0) return; if (BtreeRoot.FindKey(new List<NodeIdxPair>(), out _prefixKeyStart, _prefix, ByteBuffer.NewEmpty()) == FindResult.NotFound) { _prefixKeyStart = -1; } } public bool SetKeyIndex(long index) { CalcPrefixKeyStart(); if (_prefixKeyStart < 0) { InvalidateCurrentKey(); return false; } _keyIndex = index + _prefixKeyStart; if (_keyIndex >= BtreeRoot.CalcKeyCount()) { InvalidateCurrentKey(); return false; } BtreeRoot.FillStackByIndex(_stack, _keyIndex); if (_prefixKeyCount >= 0) return true; var key = GetCurrentKeyFromStack(); if (CheckPrefixIn(key)) { return true; } InvalidateCurrentKey(); return false; } bool CheckPrefixIn(ByteBuffer key) { return BTreeRoot.KeyStartsWithPrefix(_prefix, key); } ByteBuffer GetCurrentKeyFromStack() { var nodeIdxPair = _stack[_stack.Count - 1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx); } public void InvalidateCurrentKey() { _keyIndex = -1; _stack.Clear(); } public bool IsValidKey() { return _keyIndex >= 0; } public ByteBuffer GetKey() { if (!IsValidKey()) return ByteBuffer.NewEmpty(); var wholeKey = GetCurrentKeyFromStack(); return ByteBuffer.NewAsync(wholeKey.Buffer, wholeKey.Offset + _prefix.Length, wholeKey.Length - _prefix.Length); } public ByteBuffer GetValue() { if (!IsValidKey()) return ByteBuffer.NewEmpty(); var nodeIdxPair = _stack[_stack.Count - 1]; var leafMember = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); return _keyValueDB.ReadValue(leafMember.ValueFileId, leafMember.ValueOfs, leafMember.ValueSize); } void EnsureValidKey() { if (_keyIndex < 0) { throw new InvalidOperationException("Current key is not valid"); } } public void SetValue(ByteBuffer value) { EnsureValidKey(); var keyIndexBackup = _keyIndex; MakeWrittable(); if (_keyIndex != keyIndexBackup) { _keyIndex = keyIndexBackup; BtreeRoot.FillStackByIndex(_stack, _keyIndex); } var nodeIdxPair = _stack[_stack.Count - 1]; var memberValue = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); var memberKey = ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx); _keyValueDB.WriteCreateOrUpdateCommand(BitArrayManipulation.EmptyByteArray, memberKey, value, out memberValue.ValueFileId, out memberValue.ValueOfs, out memberValue.ValueSize); ((IBTreeLeafNode)nodeIdxPair.Node).SetMemberValue(nodeIdxPair.Idx, memberValue); } public void EraseCurrent() { EnsureValidKey(); EraseRange(GetKeyIndex(), GetKeyIndex()); } public void EraseAll() { EraseRange(0, long.MaxValue); } public void EraseRange(long firstKeyIndex, long lastKeyIndex) { if (firstKeyIndex < 0) firstKeyIndex = 0; if (lastKeyIndex >= GetKeyValueCount()) lastKeyIndex = _prefixKeyCount - 1; if (lastKeyIndex < firstKeyIndex) return; MakeWrittable(); firstKeyIndex += _prefixKeyStart; lastKeyIndex += _prefixKeyStart; InvalidateCurrentKey(); _prefixKeyCount -= lastKeyIndex - firstKeyIndex + 1; BtreeRoot.FillStackByIndex(_stack, firstKeyIndex); if (firstKeyIndex == lastKeyIndex) { _keyValueDB.WriteEraseOneCommand(GetCurrentKeyFromStack()); } else { var firstKey = GetCurrentKeyFromStack(); BtreeRoot.FillStackByIndex(_stack, lastKeyIndex); _keyValueDB.WriteEraseRangeCommand(firstKey, GetCurrentKeyFromStack()); } BtreeRoot.EraseRange(firstKeyIndex, lastKeyIndex); } public bool IsWritting() { return _writting; } public void Commit() { if (BtreeRoot == null) throw new BTDBException("Transaction already commited or disposed"); InvalidateCurrentKey(); var currentBtreeRoot = _btreeRoot; _keyValueDB.FinishedUsingBTreeRoot(_btreeRoot); _btreeRoot = null; if (_preapprovedWritting) { _preapprovedWritting = false; _keyValueDB.RevertWrittingTransaction(true); } else if (_writting) { _keyValueDB.CommitWrittingTransaction(currentBtreeRoot); _writting = false; } } public void Dispose() { if (_writting || _preapprovedWritting) { _keyValueDB.RevertWrittingTransaction(_preapprovedWritting); _writting = false; _preapprovedWritting = false; } if (_btreeRoot == null) return; _keyValueDB.FinishedUsingBTreeRoot(_btreeRoot); _btreeRoot = null; } public long GetTransactionNumber() { return _btreeRoot.TransactionId; } public KeyValuePair<uint, uint> GetStorageSizeOfCurrentKey() { if (!IsValidKey()) return new KeyValuePair<uint, uint>(); var nodeIdxPair = _stack[_stack.Count - 1]; var leafMember = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); return new KeyValuePair<uint, uint>( (uint) ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).Length, _keyValueDB.CalcValueSize(leafMember.ValueFileId, leafMember.ValueOfs, leafMember.ValueSize)); } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Linq; using Microsoft.Data.Edm.Annotations; using Microsoft.Data.Edm.Csdl.Internal.Parsing.Ast; using Microsoft.Data.Edm.Expressions; using Microsoft.Data.Edm.Internal; using Microsoft.Data.Edm.Library; using Microsoft.Data.Edm.Library.Annotations; using Microsoft.Data.Edm.Validation; namespace Microsoft.Data.Edm.Csdl.Internal.CsdlSemantics { /// <summary> /// Provides semantics for CsdlMetadataModel. /// </summary> internal class CsdlSemanticsModel : EdmModelBase, IEdmCheckable { private readonly CsdlModel astModel; private readonly List<CsdlSemanticsSchema> schemata = new List<CsdlSemanticsSchema>(); private readonly Dictionary<string, List<CsdlSemanticsAnnotations>> outOfLineAnnotations = new Dictionary<string, List<CsdlSemanticsAnnotations>>(); private readonly Dictionary<CsdlVocabularyAnnotationBase, CsdlSemanticsVocabularyAnnotation> wrappedAnnotations = new Dictionary<CsdlVocabularyAnnotationBase, CsdlSemanticsVocabularyAnnotation>(); private readonly Dictionary<string, IEdmAssociation> associationDictionary = new Dictionary<string, IEdmAssociation>(); private readonly Dictionary<string, List<IEdmStructuredType>> derivedTypeMappings = new Dictionary<string, List<IEdmStructuredType>>(); public CsdlSemanticsModel(CsdlModel astModel, EdmDirectValueAnnotationsManager annotationsManager, IEnumerable<IEdmModel> referencedModels) : base(referencedModels, annotationsManager) { this.astModel = astModel; foreach (CsdlSchema schema in this.astModel.Schemata) { this.AddSchema(schema); } } public override IEnumerable<IEdmSchemaElement> SchemaElements { get { foreach (CsdlSemanticsSchema schema in this.schemata) { foreach (IEdmSchemaType type in schema.Types) { yield return type; } foreach (IEdmSchemaElement function in schema.Functions) { yield return function; } foreach (IEdmSchemaElement valueTerm in schema.ValueTerms) { yield return valueTerm; } foreach (IEdmEntityContainer entityContainer in schema.EntityContainers) { yield return entityContainer; } } } } public override IEnumerable<IEdmVocabularyAnnotation> VocabularyAnnotations { get { List<IEdmVocabularyAnnotation> result = new List<IEdmVocabularyAnnotation>(); foreach (CsdlSemanticsSchema schema in this.schemata) { foreach (CsdlAnnotations sourceAnnotations in ((CsdlSchema)schema.Element).OutOfLineAnnotations) { CsdlSemanticsAnnotations annotations = new CsdlSemanticsAnnotations(schema, sourceAnnotations); foreach (CsdlVocabularyAnnotationBase sourceAnnotation in sourceAnnotations.Annotations) { IEdmVocabularyAnnotation vocabAnnotation = this.WrapVocabularyAnnotation(sourceAnnotation, schema, null, annotations, sourceAnnotations.Qualifier); vocabAnnotation.SetSerializationLocation(this, EdmVocabularyAnnotationSerializationLocation.OutOfLine); vocabAnnotation.SetSchemaNamespace(this, schema.Namespace); result.Add(vocabAnnotation); } } } foreach (IEdmSchemaElement element in this.SchemaElements) { result.AddRange(((CsdlSemanticsElement)element).InlineVocabularyAnnotations); CsdlSemanticsStructuredTypeDefinition type = element as CsdlSemanticsStructuredTypeDefinition; if (type != null) { foreach (IEdmProperty property in type.DeclaredProperties) { result.AddRange(((CsdlSemanticsElement)property).InlineVocabularyAnnotations); } } CsdlSemanticsFunction function = element as CsdlSemanticsFunction; if (function != null) { foreach (IEdmFunctionParameter parameter in function.Parameters) { result.AddRange(((CsdlSemanticsElement)parameter).InlineVocabularyAnnotations); } } CsdlSemanticsEntityContainer container = element as CsdlSemanticsEntityContainer; if (container != null) { foreach (IEdmEntityContainerElement containerElement in container.Elements) { result.AddRange(((CsdlSemanticsElement)containerElement).InlineVocabularyAnnotations); CsdlSemanticsFunctionImport functionImport = containerElement as CsdlSemanticsFunctionImport; if (functionImport != null) { foreach (IEdmFunctionParameter parameter in functionImport.Parameters) { result.AddRange(((CsdlSemanticsElement)parameter).InlineVocabularyAnnotations); } } } } } return result; } } /// <summary> /// Gets an error if one exists with the current object. /// </summary> public IEnumerable<EdmError> Errors { get { List<EdmError> errors = new List<EdmError>(); foreach (IEdmAssociation association in this.associationDictionary.Values) { string associationFullName = association.Namespace + "." + association.Name; if (association.IsBad()) { AmbiguousAssociationBinding ambiguous = association as AmbiguousAssociationBinding; if (ambiguous != null) { // Ambiguous bindings don't have usable locations, so get locations from the individual bindings. bool skipFirst = true; foreach (IEdmAssociation duplicate in ambiguous.Bindings) { if (skipFirst) { skipFirst = false; } else { errors.Add(new EdmError(duplicate.Location(), EdmErrorCode.AlreadyDefined, Strings.EdmModel_Validator_Semantic_SchemaElementNameAlreadyDefined(associationFullName))); } } } else { errors.AddRange(association.Errors()); } } else { if (this.FindDeclaredType(associationFullName) != null || this.FindDeclaredValueTerm(associationFullName) != null || this.FindDeclaredFunctions(associationFullName).Count() != 0) { errors.Add(new EdmError(association.Location(), EdmErrorCode.AlreadyDefined, Strings.EdmModel_Validator_Semantic_SchemaElementNameAlreadyDefined(associationFullName))); } errors.AddRange(association.End1.Errors()); errors.AddRange(association.End2.Errors()); if (association.ReferentialConstraint != null) { errors.AddRange(association.ReferentialConstraint.Errors()); } } } foreach (CsdlSemanticsSchema schema in this.schemata) { errors.AddRange(schema.Errors()); } return errors; } } /// <summary> /// Searches for an association with the given name in this model and returns null if no such association exists. /// </summary> /// <param name="qualifiedName">The qualified name of the type being found.</param> /// <returns>The requested association, or null if no such type exists.</returns> public IEdmAssociation FindAssociation(string qualifiedName) { IEdmAssociation result; this.associationDictionary.TryGetValue(qualifiedName, out result); return result; } /// <summary> /// Searches for vocabulary annotations specified by this model. /// </summary> /// <param name="element">The annotated element.</param> /// <returns>The vocabulary annotations for the element.</returns> public override IEnumerable<IEdmVocabularyAnnotation> FindDeclaredVocabularyAnnotations(IEdmVocabularyAnnotatable element) { // Include the inline annotations only if this model is the one that defined them. CsdlSemanticsElement semanticsElement = element as CsdlSemanticsElement; IEnumerable<IEdmVocabularyAnnotation> inlineAnnotations = semanticsElement != null && semanticsElement.Model == this ? semanticsElement.InlineVocabularyAnnotations : Enumerable.Empty<IEdmVocabularyAnnotation>(); List<CsdlSemanticsAnnotations> elementAnnotations; string fullName = EdmUtil.FullyQualifiedName(element); if (fullName != null && this.outOfLineAnnotations.TryGetValue(fullName, out elementAnnotations)) { List<IEdmVocabularyAnnotation> result = new List<IEdmVocabularyAnnotation>(); foreach (CsdlSemanticsAnnotations annotations in elementAnnotations) { foreach (CsdlVocabularyAnnotationBase annotation in annotations.Annotations.Annotations) { result.Add(this.WrapVocabularyAnnotation(annotation, annotations.Context, null, annotations, annotations.Annotations.Qualifier)); } } return inlineAnnotations.Concat(result); } return inlineAnnotations; } public override IEnumerable<IEdmStructuredType> FindDirectlyDerivedTypes(IEdmStructuredType baseType) { List<IEdmStructuredType> candidates; if (this.derivedTypeMappings.TryGetValue(((IEdmSchemaType)baseType).Name, out candidates)) { return candidates.Where(t => t.BaseType == baseType); } return Enumerable.Empty<IEdmStructuredType>(); } internal static IEdmExpression WrapExpression(CsdlExpressionBase expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) { if (expression != null) { switch (expression.ExpressionKind) { case EdmExpressionKind.AssertType: return new CsdlSemanticsAssertTypeExpression((CsdlAssertTypeExpression)expression, bindingContext, schema); case EdmExpressionKind.BinaryConstant: return new CsdlSemanticsBinaryConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.BooleanConstant: return new CsdlSemanticsBooleanConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.Collection: return new CsdlSemanticsCollectionExpression((CsdlCollectionExpression)expression, bindingContext, schema); case EdmExpressionKind.DateTimeConstant: return new CsdlSemanticsDateTimeConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.DateTimeOffsetConstant: return new CsdlSemanticsDateTimeOffsetConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.DecimalConstant: return new CsdlSemanticsDecimalConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.EntitySetReference: return new CsdlSemanticsEntitySetReferenceExpression((CsdlEntitySetReferenceExpression)expression, bindingContext, schema); case EdmExpressionKind.EnumMemberReference: return new CsdlSemanticsEnumMemberReferenceExpression((CsdlEnumMemberReferenceExpression)expression, bindingContext, schema); case EdmExpressionKind.FloatingConstant: return new CsdlSemanticsFloatingConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.Null: return new CsdlSemanticsNullExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.FunctionApplication: return new CsdlSemanticsApplyExpression((CsdlApplyExpression)expression, bindingContext, schema); case EdmExpressionKind.FunctionReference: return new CsdlSemanticsFunctionReferenceExpression((CsdlFunctionReferenceExpression)expression, bindingContext, schema); case EdmExpressionKind.GuidConstant: return new CsdlSemanticsGuidConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.If: return new CsdlSemanticsIfExpression((CsdlIfExpression)expression, bindingContext, schema); case EdmExpressionKind.IntegerConstant: return new CsdlSemanticsIntConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.IsType: return new CsdlSemanticsIsTypeExpression((CsdlIsTypeExpression)expression, bindingContext, schema); case EdmExpressionKind.LabeledExpressionReference: return new CsdlSemanticsLabeledExpressionReferenceExpression((CsdlLabeledExpressionReferenceExpression)expression, bindingContext, schema); case EdmExpressionKind.Labeled: return schema.WrapLabeledElement((CsdlLabeledExpression)expression, bindingContext); case EdmExpressionKind.ParameterReference: return new CsdlSemanticsParameterReferenceExpression((CsdlParameterReferenceExpression)expression, bindingContext, schema); case EdmExpressionKind.Path: return new CsdlSemanticsPathExpression((CsdlPathExpression)expression, bindingContext, schema); case EdmExpressionKind.PropertyReference: return new CsdlSemanticsPropertyReferenceExpression((CsdlPropertyReferenceExpression)expression, bindingContext, schema); case EdmExpressionKind.Record: return new CsdlSemanticsRecordExpression((CsdlRecordExpression)expression, bindingContext, schema); case EdmExpressionKind.StringConstant: return new CsdlSemanticsStringConstantExpression((CsdlConstantExpression)expression, schema); case EdmExpressionKind.TimeConstant: return new CsdlSemanticsTimeConstantExpression((CsdlConstantExpression)expression, schema); } } return null; } internal static IEdmTypeReference WrapTypeReference(CsdlSemanticsSchema schema, CsdlTypeReference type) { var typeReference = type as CsdlNamedTypeReference; if (typeReference != null) { var primitiveReference = typeReference as CsdlPrimitiveTypeReference; if (primitiveReference != null) { switch (primitiveReference.Kind) { case EdmPrimitiveTypeKind.Boolean: case EdmPrimitiveTypeKind.Byte: case EdmPrimitiveTypeKind.Double: case EdmPrimitiveTypeKind.Guid: case EdmPrimitiveTypeKind.Int16: case EdmPrimitiveTypeKind.Int32: case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.SByte: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Stream: return new CsdlSemanticsPrimitiveTypeReference(schema, primitiveReference); case EdmPrimitiveTypeKind.Binary: return new CsdlSemanticsBinaryTypeReference(schema, (CsdlBinaryTypeReference)primitiveReference); case EdmPrimitiveTypeKind.DateTime: case EdmPrimitiveTypeKind.DateTimeOffset: case EdmPrimitiveTypeKind.Time: return new CsdlSemanticsTemporalTypeReference(schema, (CsdlTemporalTypeReference)primitiveReference); case EdmPrimitiveTypeKind.Decimal: return new CsdlSemanticsDecimalTypeReference(schema, (CsdlDecimalTypeReference)primitiveReference); case EdmPrimitiveTypeKind.String: return new CsdlSemanticsStringTypeReference(schema, (CsdlStringTypeReference)primitiveReference); case EdmPrimitiveTypeKind.Geography: case EdmPrimitiveTypeKind.GeographyPoint: case EdmPrimitiveTypeKind.GeographyLineString: case EdmPrimitiveTypeKind.GeographyPolygon: case EdmPrimitiveTypeKind.GeographyCollection: case EdmPrimitiveTypeKind.GeographyMultiPolygon: case EdmPrimitiveTypeKind.GeographyMultiLineString: case EdmPrimitiveTypeKind.GeographyMultiPoint: case EdmPrimitiveTypeKind.Geometry: case EdmPrimitiveTypeKind.GeometryPoint: case EdmPrimitiveTypeKind.GeometryLineString: case EdmPrimitiveTypeKind.GeometryPolygon: case EdmPrimitiveTypeKind.GeometryCollection: case EdmPrimitiveTypeKind.GeometryMultiPolygon: case EdmPrimitiveTypeKind.GeometryMultiLineString: case EdmPrimitiveTypeKind.GeometryMultiPoint: return new CsdlSemanticsSpatialTypeReference(schema, (CsdlSpatialTypeReference)primitiveReference); } } return new CsdlSemanticsNamedTypeReference(schema, typeReference); } var typeExpression = type as CsdlExpressionTypeReference; if (typeExpression != null) { var rowType = typeExpression.TypeExpression as CsdlRowType; if (rowType != null) { return new CsdlSemanticsRowTypeExpression(typeExpression, new CsdlSemanticsRowTypeDefinition(schema, rowType)); } var collectionType = typeExpression.TypeExpression as CsdlCollectionType; if (collectionType != null) { return new CsdlSemanticsCollectionTypeExpression(typeExpression, new CsdlSemanticsCollectionTypeDefinition(schema, collectionType)); } var entityReferenceType = typeExpression.TypeExpression as CsdlEntityReferenceType; if (entityReferenceType != null) { return new CsdlSemanticsEntityReferenceTypeExpression(typeExpression, new CsdlSemanticsEntityReferenceTypeDefinition(schema, entityReferenceType)); } } return null; } internal static IEdmAssociation CreateAmbiguousAssociationBinding(IEdmAssociation first, IEdmAssociation second) { var ambiguous = first as AmbiguousAssociationBinding; if (ambiguous != null) { ambiguous.AddBinding(second); return ambiguous; } return new AmbiguousAssociationBinding(first, second); } internal IEnumerable<IEdmVocabularyAnnotation> WrapInlineVocabularyAnnotations(CsdlSemanticsElement element, CsdlSemanticsSchema schema) { IEdmVocabularyAnnotatable vocabularyAnnotatableElement = element as IEdmVocabularyAnnotatable; if (vocabularyAnnotatableElement != null) { IEnumerable<CsdlVocabularyAnnotationBase> vocabularyAnnotations = element.Element.VocabularyAnnotations; if (vocabularyAnnotations.FirstOrDefault() != null) { List<IEdmVocabularyAnnotation> wrappedAnnotations = new List<IEdmVocabularyAnnotation>(); foreach (CsdlVocabularyAnnotationBase vocabularyAnnotation in vocabularyAnnotations) { IEdmVocabularyAnnotation vocabAnnotation = this.WrapVocabularyAnnotation(vocabularyAnnotation, schema, vocabularyAnnotatableElement, null, vocabularyAnnotation.Qualifier); vocabAnnotation.SetSerializationLocation(this, EdmVocabularyAnnotationSerializationLocation.Inline); wrappedAnnotations.Add(vocabAnnotation); } return wrappedAnnotations; } } return Enumerable.Empty<IEdmVocabularyAnnotation>(); } private IEdmVocabularyAnnotation WrapVocabularyAnnotation(CsdlVocabularyAnnotationBase annotation, CsdlSemanticsSchema schema, IEdmVocabularyAnnotatable targetContext, CsdlSemanticsAnnotations annotationsContext, string qualifier) { CsdlSemanticsVocabularyAnnotation result; // Guarantee that multiple calls to wrap a given annotation all return the same object. if (this.wrappedAnnotations.TryGetValue(annotation, out result)) { return result; } CsdlValueAnnotation valueAnnotation = annotation as CsdlValueAnnotation; result = valueAnnotation != null ? (CsdlSemanticsVocabularyAnnotation)new CsdlSemanticsValueAnnotation(schema, targetContext, annotationsContext, valueAnnotation, qualifier) : (CsdlSemanticsVocabularyAnnotation)new CsdlSemanticsTypeAnnotation(schema, targetContext, annotationsContext, (CsdlTypeAnnotation)annotation, qualifier); this.wrappedAnnotations[annotation] = result; return result; } private void AddSchema(CsdlSchema schema) { CsdlSemanticsSchema schemaWrapper = new CsdlSemanticsSchema(this, schema); this.schemata.Add(schemaWrapper); foreach (IEdmSchemaType type in schemaWrapper.Types) { CsdlSemanticsStructuredTypeDefinition structuredType = type as CsdlSemanticsStructuredTypeDefinition; if (structuredType != null) { string baseTypeNamespace; string baseTypeName; string baseTypeFullName = ((CsdlNamedStructuredType)structuredType.Element).BaseTypeName; if (baseTypeFullName != null) { EdmUtil.TryGetNamespaceNameFromQualifiedName(baseTypeFullName, out baseTypeNamespace, out baseTypeName); if (baseTypeName != null) { List<IEdmStructuredType> derivedTypes; if (!this.derivedTypeMappings.TryGetValue(baseTypeName, out derivedTypes)) { derivedTypes = new List<IEdmStructuredType>(); this.derivedTypeMappings[baseTypeName] = derivedTypes; } derivedTypes.Add(structuredType); } } } RegisterElement(type); } foreach (CsdlSemanticsAssociation association in schemaWrapper.Associations) { RegistrationHelper.AddElement(association, association.Namespace + "." + association.Name, this.associationDictionary, CreateAmbiguousAssociationBinding); } foreach (IEdmFunction function in schemaWrapper.Functions) { RegisterElement(function); } foreach (IEdmValueTerm valueTerm in schemaWrapper.ValueTerms) { RegisterElement(valueTerm); } foreach (IEdmEntityContainer container in schemaWrapper.EntityContainers) { RegisterElement(container); } foreach (CsdlAnnotations schemaOutOfLineAnnotations in schema.OutOfLineAnnotations) { string target = schemaOutOfLineAnnotations.Target; string replaced = schemaWrapper.ReplaceAlias(target); if (replaced != null) { target = replaced; } List<CsdlSemanticsAnnotations> annotations; if (!this.outOfLineAnnotations.TryGetValue(target, out annotations)) { annotations = new List<CsdlSemanticsAnnotations>(); this.outOfLineAnnotations[target] = annotations; } annotations.Add(new CsdlSemanticsAnnotations(schemaWrapper, schemaOutOfLineAnnotations)); } foreach (CsdlUsing used in schema.Usings) { this.SetNamespaceAlias(used.Namespace, used.Alias); } var edmVersion = this.GetEdmVersion(); if (edmVersion == null || edmVersion < schema.Version) { this.SetEdmVersion(schema.Version); } } } }
// 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 gax = Google.Api.Gax; using gccv = Google.Cloud.Channel.V1; using sys = System; namespace Google.Cloud.Channel.V1 { /// <summary>Resource name for the <c>Entitlement</c> resource.</summary> public sealed partial class EntitlementName : gax::IResourceName, sys::IEquatable<EntitlementName> { /// <summary>The possible contents of <see cref="EntitlementName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c>. /// </summary> AccountCustomerEntitlement = 1, } private static gax::PathTemplate s_accountCustomerEntitlement = new gax::PathTemplate("accounts/{account}/customers/{customer}/entitlements/{entitlement}"); /// <summary>Creates a <see cref="EntitlementName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="EntitlementName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static EntitlementName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new EntitlementName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="EntitlementName"/> with the pattern /// <c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c>. /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entitlementId">The <c>Entitlement</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="EntitlementName"/> constructed from the provided ids.</returns> public static EntitlementName FromAccountCustomerEntitlement(string accountId, string customerId, string entitlementId) => new EntitlementName(ResourceNameType.AccountCustomerEntitlement, accountId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), entitlementId: gax::GaxPreconditions.CheckNotNullOrEmpty(entitlementId, nameof(entitlementId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="EntitlementName"/> with pattern /// <c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c>. /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entitlementId">The <c>Entitlement</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EntitlementName"/> with pattern /// <c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c>. /// </returns> public static string Format(string accountId, string customerId, string entitlementId) => FormatAccountCustomerEntitlement(accountId, customerId, entitlementId); /// <summary> /// Formats the IDs into the string representation of this <see cref="EntitlementName"/> with pattern /// <c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c>. /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entitlementId">The <c>Entitlement</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EntitlementName"/> with pattern /// <c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c>. /// </returns> public static string FormatAccountCustomerEntitlement(string accountId, string customerId, string entitlementId) => s_accountCustomerEntitlement.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entitlementId, nameof(entitlementId))); /// <summary>Parses the given resource name string into a new <see cref="EntitlementName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c></description> /// </item> /// </list> /// </remarks> /// <param name="entitlementName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EntitlementName"/> if successful.</returns> public static EntitlementName Parse(string entitlementName) => Parse(entitlementName, false); /// <summary> /// Parses the given resource name string into a new <see cref="EntitlementName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="entitlementName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="EntitlementName"/> if successful.</returns> public static EntitlementName Parse(string entitlementName, bool allowUnparsed) => TryParse(entitlementName, allowUnparsed, out EntitlementName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EntitlementName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c></description> /// </item> /// </list> /// </remarks> /// <param name="entitlementName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="EntitlementName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string entitlementName, out EntitlementName result) => TryParse(entitlementName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EntitlementName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="entitlementName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="EntitlementName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string entitlementName, bool allowUnparsed, out EntitlementName result) { gax::GaxPreconditions.CheckNotNull(entitlementName, nameof(entitlementName)); gax::TemplatedResourceName resourceName; if (s_accountCustomerEntitlement.TryParseName(entitlementName, out resourceName)) { result = FromAccountCustomerEntitlement(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(entitlementName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private EntitlementName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string accountId = null, string customerId = null, string entitlementId = null) { Type = type; UnparsedResource = unparsedResourceName; AccountId = accountId; CustomerId = customerId; EntitlementId = entitlementId; } /// <summary> /// Constructs a new instance of a <see cref="EntitlementName"/> class from the component parts of pattern /// <c>accounts/{account}/customers/{customer}/entitlements/{entitlement}</c> /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entitlementId">The <c>Entitlement</c> ID. Must not be <c>null</c> or empty.</param> public EntitlementName(string accountId, string customerId, string entitlementId) : this(ResourceNameType.AccountCustomerEntitlement, accountId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), entitlementId: gax::GaxPreconditions.CheckNotNullOrEmpty(entitlementId, nameof(entitlementId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Account</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AccountId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Entitlement</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EntitlementId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.AccountCustomerEntitlement: return s_accountCustomerEntitlement.Expand(AccountId, CustomerId, EntitlementId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as EntitlementName); /// <inheritdoc/> public bool Equals(EntitlementName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(EntitlementName a, EntitlementName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(EntitlementName a, EntitlementName b) => !(a == b); } public partial class Entitlement { /// <summary> /// <see cref="gccv::EntitlementName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::EntitlementName EntitlementName { get => string.IsNullOrEmpty(Name) ? null : gccv::EntitlementName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary><see cref="OfferName"/>-typed view over the <see cref="Offer"/> resource name property.</summary> public OfferName OfferAsOfferName { get => string.IsNullOrEmpty(Offer) ? null : OfferName.Parse(Offer, allowUnparsed: true); set => Offer = value?.ToString() ?? ""; } } public partial class AssociationInfo { /// <summary> /// <see cref="EntitlementName"/>-typed view over the <see cref="BaseEntitlement"/> resource name property. /// </summary> public EntitlementName BaseEntitlementAsEntitlementName { get => string.IsNullOrEmpty(BaseEntitlement) ? null : EntitlementName.Parse(BaseEntitlement, allowUnparsed: true); set => BaseEntitlement = value?.ToString() ?? ""; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyNumber { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Number operations. /// </summary> public partial interface INumber { /// <summary> /// Get null Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid float Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetInvalidFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid double Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetInvalidDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid decimal Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetInvalidDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big float value 3.402823e+20 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigFloatWithHttpMessagesAsync(double numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big float value 3.402823e+20 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big double value 2.5976931e+101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDoubleWithHttpMessagesAsync(double numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 2.5976931e+101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big double value 99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDoublePositiveDecimalWithHttpMessagesAsync(double numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigDoublePositiveDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big double value -99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDoubleNegativeDecimalWithHttpMessagesAsync(double numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value -99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigDoubleNegativeDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big decimal value 2.5976931e+101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDecimalWithHttpMessagesAsync(decimal numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big decimal value 2.5976931e+101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetBigDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big decimal value 99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDecimalPositiveDecimalWithHttpMessagesAsync(decimal numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big decimal value 99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetBigDecimalPositiveDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big decimal value -99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDecimalNegativeDecimalWithHttpMessagesAsync(decimal numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big decimal value -99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetBigDecimalNegativeDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put small float value 3.402823e-20 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutSmallFloatWithHttpMessagesAsync(double numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 3.402823e-20 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetSmallFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put small double value 2.5976931e-101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutSmallDoubleWithHttpMessagesAsync(double numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 2.5976931e-101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetSmallDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put small decimal value 2.5976931e-101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutSmallDecimalWithHttpMessagesAsync(decimal numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get small decimal value 2.5976931e-101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetSmallDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Collections; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// The test class for the TaskExecutionHost /// </summary> public class TaskExecutionHost_Tests : ITestTaskHost, IBuildEngine2, IDisposable { /// <summary> /// The set of parameters which have been initialized on the task. /// </summary> private Dictionary<string, object> _parametersSetOnTask; /// <summary> /// The set of outputs which were read from the task. /// </summary> private Dictionary<string, object> _outputsReadFromTask; /// <summary> /// The task execution host /// </summary> private ITaskExecutionHost _host; /// <summary> /// The mock logging service /// </summary> private ILoggingService _loggingService; /// <summary> /// The mock logger /// </summary> private MockLogger _logger; /// <summary> /// Array containing one item, used for ITaskItem tests. /// </summary> private ITaskItem[] _oneItem; /// <summary> /// Array containing two items, used for ITaskItem tests. /// </summary> private ITaskItem[] _twoItems; /// <summary> /// The bucket which receives outputs. /// </summary> private ItemBucket _bucket; /// <summary> /// Unused. /// </summary> public bool IsRunningMultipleNodes { get { return false; } } /// <summary> /// Unused. /// </summary> public bool ContinueOnError { get { throw new NotImplementedException(); } } /// <summary> /// Unused. /// </summary> public int LineNumberOfTaskNode { get { throw new NotImplementedException(); } } /// <summary> /// Unused. /// </summary> public int ColumnNumberOfTaskNode { get { throw new NotImplementedException(); } } /// <summary> /// Unused. /// </summary> public string ProjectFileOfTaskNode { get { throw new NotImplementedException(); } } /// <summary> /// Prepares the environment for the test. /// </summary> public TaskExecutionHost_Tests() { InitializeHost(false); } /// <summary> /// Cleans up after the test /// </summary> public void Dispose() { if (_host != null) { ((IDisposable)_host).Dispose(); } _host = null; } /// <summary> /// Validate that setting parameters with only the required parameters works. /// </summary> [Fact] public void ValidateNoParameters() { Dictionary<string, Tuple<string, ElementLocation>> parameters = new Dictionary<string, Tuple<string, ElementLocation>>(StringComparer.OrdinalIgnoreCase); parameters["ExecuteReturnParam"] = new Tuple<string, ElementLocation>("true", ElementLocation.Create("foo.proj")); Assert.True(_host.SetTaskParameters(parameters)); Assert.Single(_parametersSetOnTask); Assert.True(_parametersSetOnTask.ContainsKey("ExecuteReturnParam")); } /// <summary> /// Validate that setting no parameters when a required parameter exists fails and throws an exception. /// </summary> [Fact] public void ValidateNoParameters_MissingRequired() { Assert.Throws<InvalidProjectFileException>(() => { Dictionary<string, Tuple<string, ElementLocation>> parameters = new Dictionary<string, Tuple<string, ElementLocation>>(StringComparer.OrdinalIgnoreCase); _host.SetTaskParameters(parameters); } ); } /// <summary> /// Validate that setting a non-existent parameter fails, but does not throw an exception. /// </summary> [Fact] public void ValidateNonExistantParameter() { Dictionary<string, Tuple<string, ElementLocation>> parameters = new Dictionary<string, Tuple<string, ElementLocation>>(StringComparer.OrdinalIgnoreCase); parameters["NonExistantParam"] = new Tuple<string, ElementLocation>("foo", ElementLocation.Create("foo.proj")); Assert.False(_host.SetTaskParameters(parameters)); } #region Bool Params /// <summary> /// Validate that setting a bool param works and sets the right value. /// </summary> [Fact] public void TestSetBoolParam() { ValidateTaskParameter("BoolParam", "true", true); } /// <summary> /// Validate that setting a bool param works and sets the right value. /// </summary> [Fact] public void TestSetBoolParamFalse() { ValidateTaskParameter("BoolParam", "false", false); } /// <summary> /// Validate that setting a bool param with an empty value does not cause the parameter to get set. /// </summary> [Fact] public void TestSetBoolParamEmptyAttribute() { ValidateTaskParameterNotSet("BoolParam", ""); } /// <summary> /// Validate that setting a bool param with a property which evaluates to nothing does not cause the parameter to get set. /// </summary> [Fact] public void TestSetBoolParamEmptyProperty() { ValidateTaskParameterNotSet("BoolParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting a bool param with an item which evaluates to nothing does not cause the parameter to get set. /// </summary> [Fact] public void TestSetBoolParamEmptyItem() { ValidateTaskParameterNotSet("BoolParam", "@(NonExistantItem)"); } #endregion #region Bool Array Params /// <summary> /// Validate that setting a bool array with a single true sets the array to one 'true' value. /// </summary> [Fact] public void TestSetBoolArrayParamOneItem() { ValidateTaskParameterArray("BoolArrayParam", "true", new bool[] { true }); } /// <summary> /// Validate that setting a bool array with a list of two values sets them appropriately. /// </summary> [Fact] public void TestSetBoolArrayParamTwoItems() { ValidateTaskParameterArray("BoolArrayParam", "false;true", new bool[] { false, true }); } /// <summary> /// Validate that setting the parameter with an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetBoolArrayParamEmptyAttribute() { ValidateTaskParameterNotSet("BoolArrayParam", ""); } /// <summary> /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetBoolArrayParamEmptyProperty() { ValidateTaskParameterNotSet("BoolArrayParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetBoolArrayParamEmptyItem() { ValidateTaskParameterNotSet("BoolArrayParam", "@(NonExistantItem)"); } #endregion #region Int Params /// <summary> /// Validate that setting an int param with a value of 0 causes it to get the correct value. /// </summary> [Fact] public void TestSetIntParamZero() { ValidateTaskParameter("IntParam", "0", 0); } /// <summary> /// Validate that setting an int param with a value of 1 causes it to get the correct value. /// </summary> [Fact] public void TestSetIntParamOne() { ValidateTaskParameter("IntParam", "1", 1); } /// <summary> /// Validate that setting the parameter with an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetIntParamEmptyAttribute() { ValidateTaskParameterNotSet("IntParam", ""); } /// <summary> /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetIntParamEmptyProperty() { ValidateTaskParameterNotSet("IntParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetIntParamEmptyItem() { ValidateTaskParameterNotSet("IntParam", "@(NonExistantItem)"); } #endregion #region Int Array Params /// <summary> /// Validate that setting an int array with a single value causes it to get a single value. /// </summary> [Fact] public void TestSetIntArrayParamOneItem() { ValidateTaskParameterArray("IntArrayParam", "0", new int[] { 0 }); } /// <summary> /// Validate that setting an int array with a list of values causes it to get the correct values. /// </summary> [Fact] public void TestSetIntArrayParamTwoItems() { SetTaskParameter("IntArrayParam", "1;0"); Assert.True(_parametersSetOnTask.ContainsKey("IntArrayParam")); Assert.Equal(1, ((int[])_parametersSetOnTask["IntArrayParam"])[0]); Assert.Equal(0, ((int[])_parametersSetOnTask["IntArrayParam"])[1]); } /// <summary> /// Validate that setting the parameter with an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetIntArrayParamEmptyAttribute() { ValidateTaskParameterNotSet("IntArrayParam", ""); } /// <summary> /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetIntArrayParamEmptyProperty() { ValidateTaskParameterNotSet("IntArrayParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetIntArrayParamEmptyItem() { ValidateTaskParameterNotSet("IntArrayParam", "@(NonExistantItem)"); } #endregion #region String Params /// <summary> /// Test that setting a string param sets the correct value. /// </summary> [Fact] public void TestSetStringParam() { ValidateTaskParameter("StringParam", "0", "0"); } /// <summary> /// Test that setting a string param sets the correct value. /// </summary> [Fact] public void TestSetStringParamOne() { ValidateTaskParameter("StringParam", "1", "1"); } /// <summary> /// Validate that setting the parameter with an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetStringParamEmptyAttribute() { ValidateTaskParameterNotSet("StringParam", ""); } /// <summary> /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetStringParamEmptyProperty() { ValidateTaskParameterNotSet("StringParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetStringParamEmptyItem() { ValidateTaskParameterNotSet("StringParam", "@(NonExistantItem)"); } #endregion #region String Array Params /// <summary> /// Validate that setting a string array with a single value sets the correct value. /// </summary> [Fact] public void TestSetStringArrayParam() { ValidateTaskParameterArray("StringArrayParam", "0", new string[] { "0" }); } /// <summary> /// Validate that setting a string array with a list of two values sets the correct values. /// </summary> [Fact] public void TestSetStringArrayParamOne() { ValidateTaskParameterArray("StringArrayParam", "1;0", new string[] { "1", "0" }); } /// <summary> /// Validate that setting the parameter with an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetStringArrayParamEmptyAttribute() { ValidateTaskParameterNotSet("StringArrayParam", ""); } /// <summary> /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetStringArrayParamEmptyProperty() { ValidateTaskParameterNotSet("StringArrayParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetStringArrayParamEmptyItem() { ValidateTaskParameterNotSet("StringArrayParam", "@(NonExistantItem)"); } #endregion #region ITaskItem Params /// <summary> /// Validate that setting an item with an item list evaluating to one item sets the value appropriately, including metadata. /// </summary> [Fact] public void TestSetItemParamSingle() { ValidateTaskParameterItem("ItemParam", "@(ItemListContainingOneItem)", _oneItem[0]); } /// <summary> /// Validate that setting an item with an item list evaluating to two items sets the value appropriately, including metadata. /// </summary> [Fact] public void TestSetItemParamDouble() { Assert.Throws<InvalidProjectFileException>(() => { ValidateTaskParameterItems("ItemParam", "@(ItemListContainingTwoItems)", _twoItems); } ); } /// <summary> /// Validate that setting an item with a string results in an item with the evaluated include set to the string. /// </summary> [Fact] public void TestSetItemParamString() { ValidateTaskParameterItem("ItemParam", "MyItemName"); } /// <summary> /// Validate that setting the parameter with an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetItemParamEmptyAttribute() { ValidateTaskParameterNotSet("ItemParam", ""); } /// <summary> /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetItemParamEmptyProperty() { ValidateTaskParameterNotSet("ItemParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetItemParamEmptyItem() { ValidateTaskParameterNotSet("ItemParam", "@(NonExistantItem)"); } #endregion #region ITaskItem Array Params /// <summary> /// Validate that setting an item array using an item list containing one item sets a single item. /// </summary> [Fact] public void TestSetItemArrayParamSingle() { ValidateTaskParameterItems("ItemArrayParam", "@(ItemListContainingOneItem)", _oneItem); } /// <summary> /// Validate that setting an item array using an item list containing two items sets both items. /// </summary> [Fact] public void TestSetItemArrayParamDouble() { ValidateTaskParameterItems("ItemArrayParam", "@(ItemListContainingTwoItems)", _twoItems); } /// <summary> /// Validate that setting an item array with /// </summary> [Fact] public void TestSetItemArrayParamString() { ValidateTaskParameterItems("ItemArrayParam", "MyItemName"); } /// <summary> /// Validate that setting an item array with a list with multiple values creates multiple items. /// </summary> [Fact] public void TestSetItemArrayParamTwoStrings() { ValidateTaskParameterItems("ItemArrayParam", "MyItemName;MyOtherItemName", new string[] { "MyItemName", "MyOtherItemName" }); } /// <summary> /// Validate that setting the parameter with an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetItemArrayParamEmptyAttribute() { ValidateTaskParameterNotSet("ItemArrayParam", ""); } /// <summary> /// Validate that setting the parameter with a parameter which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetItemArrayParamEmptyProperty() { ValidateTaskParameterNotSet("ItemArrayParam", "$(NonExistantProperty)"); } /// <summary> /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. /// </summary> [Fact] public void TestSetItemArrayParamEmptyItem() { ValidateTaskParameterNotSet("ItemArrayParam", "@(NonExistantItem)"); } #endregion #region Execute Tests /// <summary> /// Tests that successful execution returns true. /// </summary> [Fact] public void TestExecuteTrue() { Dictionary<string, Tuple<string, ElementLocation>> parameters = new Dictionary<string, Tuple<string, ElementLocation>>(StringComparer.OrdinalIgnoreCase); parameters["ExecuteReturnParam"] = new Tuple<string, ElementLocation>("true", ElementLocation.Create("foo.proj")); Assert.True(_host.SetTaskParameters(parameters)); bool executeValue = _host.Execute(); Assert.True(executeValue); } /// <summary> /// Tests that unsuccessful execution returns false. /// </summary> [Fact] public void TestExecuteFalse() { Dictionary<string, Tuple<string, ElementLocation>> parameters = new Dictionary<string, Tuple<string, ElementLocation>>(StringComparer.OrdinalIgnoreCase); parameters["ExecuteReturnParam"] = new Tuple<string, ElementLocation>("false", ElementLocation.Create("foo.proj")); Assert.True(_host.SetTaskParameters(parameters)); bool executeValue = _host.Execute(); Assert.False(executeValue); } /// <summary> /// Tests that when Execute throws, the exception bubbles up. /// </summary> [Fact] public void TestExecuteThrow() { Assert.Throws<IndexOutOfRangeException>(() => { Dictionary<string, Tuple<string, ElementLocation>> parameters = new Dictionary<string, Tuple<string, ElementLocation>>(StringComparer.OrdinalIgnoreCase); parameters["ExecuteReturnParam"] = new Tuple<string, ElementLocation>("false", ElementLocation.Create("foo.proj")); Dispose(); InitializeHost(true); Assert.True(_host.SetTaskParameters(parameters)); _host.Execute(); } ); } #endregion #region Bool Outputs /// <summary> /// Validate that boolean output to an item produces the correct evaluated include. /// </summary> [Fact] public void TestOutputBoolToItem() { SetTaskParameter("BoolParam", "true"); ValidateOutputItem("BoolOutput", "True"); } /// <summary> /// Validate that boolean output to a property produces the correct evaluated value. /// </summary> [Fact] public void TestOutputBoolToProperty() { SetTaskParameter("BoolParam", "true"); ValidateOutputProperty("BoolOutput", "True"); } /// <summary> /// Validate that boolean array output to an item array produces the correct evaluated includes. /// </summary> [Fact] public void TestOutputBoolArrayToItems() { SetTaskParameter("BoolArrayParam", "false;true"); ValidateOutputItems("BoolArrayOutput", new string[] { "False", "True" }); } /// <summary> /// Validate that boolean array output to an item produces the correct semi-colon-delimited evaluated value. /// </summary> [Fact] public void TestOutputBoolArrayToProperty() { SetTaskParameter("BoolArrayParam", "false;true"); ValidateOutputProperty("BoolArrayOutput", "False;True"); } #endregion #region Int Outputs /// <summary> /// Validate that an int output to an item produces the correct evaluated include /// </summary> [Fact] public void TestOutputIntToItem() { SetTaskParameter("IntParam", "42"); ValidateOutputItem("IntOutput", "42"); } /// <summary> /// Validate that an int output to an property produces the correct evaluated value. /// </summary> [Fact] public void TestOutputIntToProperty() { SetTaskParameter("IntParam", "42"); ValidateOutputProperty("IntOutput", "42"); } /// <summary> /// Validate that an int array output to an item produces the correct evaluated includes. /// </summary> [Fact] public void TestOutputIntArrayToItems() { SetTaskParameter("IntArrayParam", "42;99"); ValidateOutputItems("IntArrayOutput", new string[] { "42", "99" }); } /// <summary> /// Validate that an int array output to a property produces the correct semi-colon-delimited evaluated value. /// </summary> [Fact] public void TestOutputIntArrayToProperty() { SetTaskParameter("IntArrayParam", "42;99"); ValidateOutputProperty("IntArrayOutput", "42;99"); } #endregion #region String Outputs /// <summary> /// Validate that a string output to an item produces the correct evaluated include. /// </summary> [Fact] public void TestOutputStringToItem() { SetTaskParameter("StringParam", "FOO"); ValidateOutputItem("StringOutput", "FOO"); } /// <summary> /// Validate that a string output to a property produces the correct evaluated value. /// </summary> [Fact] public void TestOutputStringToProperty() { SetTaskParameter("StringParam", "FOO"); ValidateOutputProperty("StringOutput", "FOO"); } /// <summary> /// Validate that an empty string output overwrites the property value /// </summary> [Fact] public void TestOutputEmptyStringToProperty() { _bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue")); ValidateOutputProperty("EmptyStringOutput", String.Empty); } /// <summary> /// Validate that an empty string array output overwrites the property value /// </summary> [Fact] public void TestOutputEmptyStringArrayToProperty() { _bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue")); ValidateOutputProperty("EmptyStringArrayOutput", String.Empty); } /// <summary> /// A string output returning null should not cause any property set. /// </summary> [Fact] public void TestOutputNullStringToProperty() { _bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue")); ValidateOutputProperty("NullStringOutput", "initialvalue"); } /// <summary> /// A string output returning null should not cause any property set. /// </summary> [Fact] public void TestOutputNullITaskItemToProperty() { _bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue")); ValidateOutputProperty("NullITaskItemOutput", "initialvalue"); } /// <summary> /// A string output returning null should not cause any property set. /// </summary> [Fact] public void TestOutputNullStringArrayToProperty() { _bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue")); ValidateOutputProperty("NullStringArrayOutput", "initialvalue"); } /// <summary> /// A string output returning null should not cause any property set. /// </summary> [Fact] public void TestOutputNullITaskItemArrayToProperty() { _bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue")); ValidateOutputProperty("NullITaskItemArrayOutput", "initialvalue"); } /// <summary> /// Validate that a string array output to an item produces the correct evaluated includes. /// </summary> [Fact] public void TestOutputStringArrayToItems() { SetTaskParameter("StringArrayParam", "FOO;bar"); ValidateOutputItems("StringArrayOutput", new string[] { "FOO", "bar" }); } /// <summary> /// Validate that a string array output to a property produces the correct semi-colon-delimited evaluated value. /// </summary> [Fact] public void TestOutputStringArrayToProperty() { SetTaskParameter("StringArrayParam", "FOO;bar"); ValidateOutputProperty("StringArrayOutput", "FOO;bar"); } #endregion #region Item Outputs /// <summary> /// Validate that an item output to an item replicates the item, with metadata /// </summary> [Fact] public void TestOutputItemToItem() { SetTaskParameter("ItemParam", "@(ItemListContainingOneItem)"); ValidateOutputItems("ItemOutput", _oneItem); } /// <summary> /// Validate than an item output to a property produces the correct evaluated value. /// </summary> [Fact] public void TestOutputItemToProperty() { SetTaskParameter("ItemParam", "@(ItemListContainingOneItem)"); ValidateOutputProperty("ItemOutput", _oneItem[0].ItemSpec); } /// <summary> /// Validate that an item array output to an item replicates the items, with metadata. /// </summary> [Fact] public void TestOutputItemArrayToItems() { SetTaskParameter("ItemArrayParam", "@(ItemListContainingTwoItems)"); ValidateOutputItems("ItemArrayOutput", _twoItems); } /// <summary> /// Validate that an item array output to a property produces the correct semi-colon-delimited evaluated value. /// </summary> [Fact] public void TestOutputItemArrayToProperty() { SetTaskParameter("ItemArrayParam", "@(ItemListContainingTwoItems)"); ValidateOutputProperty("ItemArrayOutput", String.Concat(_twoItems[0].ItemSpec, ";", _twoItems[1].ItemSpec)); } #endregion #region Other Output Tests /// <summary> /// Attempts to gather outputs into an item list from an string task parameter that /// returns an empty string. This should be a no-op. /// </summary> [Fact] public void TestEmptyStringInStringArrayParameterIntoItemList() { SetTaskParameter("StringArrayParam", ""); ValidateOutputItems("StringArrayOutput", new ITaskItem[] { }); } /// <summary> /// Attempts to gather outputs into an item list from an string task parameter that /// returns an empty string. This should be a no-op. /// </summary> [Fact] public void TestEmptyStringParameterIntoItemList() { SetTaskParameter("StringParam", ""); ValidateOutputItems("StringOutput", new ITaskItem[] { }); } /// <summary> /// Attempts to gather outputs from a null task parameter of type "ITaskItem[]". This should succeed. /// </summary> [Fact] public void TestNullITaskItemArrayParameter() { ValidateOutputItems("ItemArrayNullOutput", new ITaskItem[] { }); } /// <summary> /// Attempts to gather outputs from a task parameter of type "ArrayList". This should fail. /// </summary> [Fact] public void TestArrayListParameter() { Assert.Throws<InvalidProjectFileException>(() => { ValidateOutputItems("ArrayListOutput", new ITaskItem[] { }); } ); } /// <summary> /// Attempts to gather outputs from a non-existent output. This should fail. /// </summary> [Fact] public void TestNonexistantOutput() { Assert.Throws<InvalidProjectFileException>(() => { Assert.False(_host.GatherTaskOutputs("NonExistantOutput", ElementLocation.Create(".", 1, 1), true, "output")); } ); } /// <summary> /// object[] should not be a supported output type. /// </summary> [Fact] public void TestOutputObjectArrayToProperty() { Assert.Throws<InvalidProjectFileException>(() => { ValidateOutputProperty("ObjectArrayOutput", ""); } ); } #endregion #region Other Tests /// <summary> /// Test that cleanup for task clears out the task instance. /// </summary> [Fact] public void TestCleanupForTask() { _host.CleanupForBatch(); Assert.NotNull((_host as TaskExecutionHost)._UNITTESTONLY_TaskFactoryWrapper); _host.CleanupForTask(); Assert.Null((_host as TaskExecutionHost)._UNITTESTONLY_TaskFactoryWrapper); } /// <summary> /// Test that a using task which specifies an invalid assembly produces an exception. /// </summary> [Fact] public void TestTaskResolutionFailureWithUsingTask() { Assert.Throws<InvalidProjectFileException>(() => { _loggingService = new MockLoggingService(); Dispose(); _host = new TaskExecutionHost(); TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1)); ProjectInstance project = CreateTestProject(); _host.InitializeForTask ( this, tlc, project, "TaskWithMissingAssembly", ElementLocation.Create("none", 1, 1), this, false, #if FEATURE_APPDOMAIN null, #endif false, CancellationToken.None ); _host.FindTask(null); _host.InitializeForBatch(new TaskLoggingContext(_loggingService, tlc.BuildEventContext), _bucket, null); } ); } /// <summary> /// Test that specifying a task with no using task logs an error, but does not throw. /// </summary> [Fact] public void TestTaskResolutionFailureWithNoUsingTask() { Dispose(); _host = new TaskExecutionHost(); TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1)); ProjectInstance project = CreateTestProject(); _host.InitializeForTask ( this, tlc, project, "TaskWithNoUsingTask", ElementLocation.Create("none", 1, 1), this, false, #if FEATURE_APPDOMAIN null, #endif false, CancellationToken.None ); _host.FindTask(null); _host.InitializeForBatch(new TaskLoggingContext(_loggingService, tlc.BuildEventContext), _bucket, null); _logger.AssertLogContains("MSB4036"); } #endregion #region ITestTaskHost Members #pragma warning disable xUnit1013 /// <summary> /// Records that a parameter was set on the task. /// </summary> public void ParameterSet(string parameterName, object valueSet) { _parametersSetOnTask[parameterName] = valueSet; } /// <summary> /// Records that an output was read from the task. /// </summary> public void OutputRead(string parameterName, object actualValue) { _outputsReadFromTask[parameterName] = actualValue; } #endregion #region IBuildEngine2 Members /// <summary> /// Unused. /// </summary> public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion) { throw new NotImplementedException(); } /// <summary> /// Unused. /// </summary> public bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion) { throw new NotImplementedException(); } #endregion #region IBuildEngine Members /// <summary> /// Unused. /// </summary> public void LogErrorEvent(BuildErrorEventArgs e) { throw new NotImplementedException(); } /// <summary> /// Unused. /// </summary> public void LogWarningEvent(BuildWarningEventArgs e) { throw new NotImplementedException(); } /// <summary> /// Unused. /// </summary> public void LogMessageEvent(BuildMessageEventArgs e) { throw new NotImplementedException(); } /// <summary> /// Unused. /// </summary> public void LogCustomEvent(CustomBuildEventArgs e) { throw new NotImplementedException(); } /// <summary> /// Unused. /// </summary> public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs) { throw new NotImplementedException(); } #pragma warning restore xUnit1013 #endregion #region Validation Routines /// <summary> /// Is the class a task factory /// </summary> private static bool IsTaskFactoryClass(Type type, object unused) { return (type.GetTypeInfo().IsClass && !type.GetTypeInfo().IsAbstract && #if FEATURE_TYPE_GETINTERFACE (type.GetInterface("Microsoft.Build.Framework.ITaskFactory") != null)); #else type.GetInterfaces().Any(interfaceType => interfaceType.FullName == "Microsoft.Build.Framework.ITaskFactory")); #endif } /// <summary> /// Initialize the host object /// </summary> /// <param name="throwOnExecute">Should the task throw when executed</param> private void InitializeHost(bool throwOnExecute) { _loggingService = LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); _logger = new MockLogger(); _loggingService.RegisterLogger(_logger); _host = new TaskExecutionHost(); TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1)); // Set up a temporary project and add some items to it. ProjectInstance project = CreateTestProject(); TypeLoader typeLoader = new TypeLoader(IsTaskFactoryClass); #if FEATURE_ASSEMBLY_LOADFROM AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(Assembly.GetAssembly(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory)).FullName, null); #else AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory).GetTypeInfo().FullName, null); #endif LoadedType loadedType = new LoadedType(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory), loadInfo); TaskBuilderTestTask.TaskBuilderTestTaskFactory taskFactory = new TaskBuilderTestTask.TaskBuilderTestTaskFactory(); taskFactory.ThrowOnExecute = throwOnExecute; string taskName = "TaskBuilderTestTask"; (_host as TaskExecutionHost)._UNITTESTONLY_TaskFactoryWrapper = new TaskFactoryWrapper(taskFactory, loadedType, taskName, null); _host.InitializeForTask ( this, tlc, project, taskName, ElementLocation.Create("none", 1, 1), this, false, #if FEATURE_APPDOMAIN null, #endif false, CancellationToken.None ); ProjectTaskInstance taskInstance = project.Targets["foo"].Tasks.First(); TaskLoggingContext talc = tlc.LogTaskBatchStarted(".", taskInstance); ItemDictionary<ProjectItemInstance> itemsByName = new ItemDictionary<ProjectItemInstance>(); ProjectItemInstance item = new ProjectItemInstance(project, "ItemListContainingOneItem", "a.cs", "."); item.SetMetadata("Culture", "fr-fr"); itemsByName.Add(item); _oneItem = new ITaskItem[] { new TaskItem(item) }; item = new ProjectItemInstance(project, "ItemListContainingTwoItems", "b.cs", "."); ProjectItemInstance item2 = new ProjectItemInstance(project, "ItemListContainingTwoItems", "c.cs", "."); item.SetMetadata("HintPath", "c:\\foo"); item2.SetMetadata("HintPath", "c:\\bar"); itemsByName.Add(item); itemsByName.Add(item2); _twoItems = new ITaskItem[] { new TaskItem(item), new TaskItem(item2) }; _bucket = new ItemBucket(new string[0], new Dictionary<string, string>(), new Lookup(itemsByName, new PropertyDictionary<ProjectPropertyInstance>()), 0); _host.FindTask(null); _host.InitializeForBatch(talc, _bucket, null); _parametersSetOnTask = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); _outputsReadFromTask = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Helper method for tests /// </summary> private void ValidateOutputItem(string outputName, string value) { Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output")); Assert.True(_outputsReadFromTask.ContainsKey(outputName)); Assert.Single(_bucket.Lookup.GetItems("output")); Assert.Equal(value, _bucket.Lookup.GetItems("output").First().EvaluatedInclude); } /// <summary> /// Helper method for tests /// </summary> private void ValidateOutputItem(string outputName, ITaskItem value) { Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output")); Assert.True(_outputsReadFromTask.ContainsKey(outputName)); Assert.Single(_bucket.Lookup.GetItems("output")); Assert.Equal(0, TaskItemComparer.Instance.Compare(value, new TaskItem(_bucket.Lookup.GetItems("output").First()))); } /// <summary> /// Helper method for tests /// </summary> private void ValidateOutputItems(string outputName, string[] values) { Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output")); Assert.True(_outputsReadFromTask.ContainsKey(outputName)); Assert.Equal(values.Length, _bucket.Lookup.GetItems("output").Count); for (int i = 0; i < values.Length; i++) { Assert.Equal(values[i], _bucket.Lookup.GetItems("output").ElementAt(i).EvaluatedInclude); } } /// <summary> /// Helper method for tests /// </summary> private void ValidateOutputItems(string outputName, ITaskItem[] values) { Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output")); Assert.True(_outputsReadFromTask.ContainsKey(outputName)); Assert.Equal(values.Length, _bucket.Lookup.GetItems("output").Count); for (int i = 0; i < values.Length; i++) { Assert.Equal(0, TaskItemComparer.Instance.Compare(values[i], new TaskItem(_bucket.Lookup.GetItems("output").ElementAt(i)))); } } /// <summary> /// Helper method for tests /// </summary> private void ValidateOutputProperty(string outputName, string value) { Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), false, "output")); Assert.True(_outputsReadFromTask.ContainsKey(outputName)); Assert.NotNull(_bucket.Lookup.GetProperty("output")); Assert.Equal(value, _bucket.Lookup.GetProperty("output").EvaluatedValue); } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameter(string parameterName, string value, object expectedValue) { SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); Assert.Equal(expectedValue, _parametersSetOnTask[parameterName]); } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameterItem(string parameterName, string value) { SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); ITaskItem actualItem = _parametersSetOnTask[parameterName] as ITaskItem; Assert.Equal(value, actualItem.ItemSpec); Assert.Equal(BuiltInMetadata.MetadataCount, actualItem.MetadataCount); } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameterItem(string parameterName, string value, ITaskItem expectedItem) { SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); ITaskItem actualItem = _parametersSetOnTask[parameterName] as ITaskItem; Assert.Equal(0, TaskItemComparer.Instance.Compare(expectedItem, actualItem)); } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameterItems(string parameterName, string value) { SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); ITaskItem[] actualItems = _parametersSetOnTask[parameterName] as ITaskItem[]; Assert.Single(actualItems); Assert.Equal(value, actualItems[0].ItemSpec); } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameterItems(string parameterName, string value, ITaskItem[] expectedItems) { SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); ITaskItem[] actualItems = _parametersSetOnTask[parameterName] as ITaskItem[]; Assert.Equal(expectedItems.Length, actualItems.Length); for (int i = 0; i < expectedItems.Length; i++) { Assert.Equal(0, TaskItemComparer.Instance.Compare(expectedItems[i], actualItems[i])); } } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameterItems(string parameterName, string value, string[] expectedItems) { SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); ITaskItem[] actualItems = _parametersSetOnTask[parameterName] as ITaskItem[]; Assert.Equal(expectedItems.Length, actualItems.Length); for (int i = 0; i < expectedItems.Length; i++) { Assert.Equal(expectedItems[i], actualItems[i].ItemSpec); } } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameterArray(string parameterName, string value, object expectedValue) { SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); Array expectedArray = expectedValue as Array; Array actualArray = _parametersSetOnTask[parameterName] as Array; Assert.Equal(expectedArray.Length, actualArray.Length); for (int i = 0; i < expectedArray.Length; i++) { Assert.Equal(expectedArray.GetValue(i), actualArray.GetValue(i)); } } /// <summary> /// Helper method for tests /// </summary> private void ValidateTaskParameterNotSet(string parameterName, string value) { SetTaskParameter(parameterName, value); Assert.False(_parametersSetOnTask.ContainsKey(parameterName)); } #endregion /// <summary> /// Helper method for tests /// </summary> private void SetTaskParameter(string parameterName, string value) { Dictionary<string, Tuple<string, ElementLocation>> parameters = GetStandardParametersDictionary(true); parameters[parameterName] = new Tuple<string, ElementLocation>(value, ElementLocation.Create("foo.proj")); bool success = _host.SetTaskParameters(parameters); Assert.True(success); } /// <summary> /// Helper method for tests /// </summary> private Dictionary<string, Tuple<string, ElementLocation>> GetStandardParametersDictionary(bool returnParam) { Dictionary<string, Tuple<string, ElementLocation>> parameters = new Dictionary<string, Tuple<string, ElementLocation>>(StringComparer.OrdinalIgnoreCase); parameters["ExecuteReturnParam"] = new Tuple<string, ElementLocation>(returnParam ? "true" : "false", ElementLocation.Create("foo.proj")); return parameters; } /// <summary> /// Creates a test project. /// </summary> /// <returns>The project.</returns> private ProjectInstance CreateTestProject() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <UsingTask TaskName='TaskWithMissingAssembly' AssemblyName='madeup' /> <ItemGroup> <Compile Include='b.cs' /> <Compile Include='c.cs' /> </ItemGroup> <ItemGroup> <Reference Include='System' /> </ItemGroup> <Target Name='Empty' /> <Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' /> <Target Name='Error' > <ErrorTask1 ContinueOnError='True'/> <ErrorTask2 ContinueOnError='False'/> <ErrorTask3 /> <OnError ExecuteTargets='Foo'/> <OnError ExecuteTargets='Bar'/> </Target> <Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'> <FooTask1/> </Target> <Target Name='Bar'> <BarTask1/> </Target> <Target Name='Baz' DependsOnTargets='Bar'> <BazTask1/> <BazTask2/> </Target> <Target Name='Baz2' DependsOnTargets='Bar;Foo'> <Baz2Task1/> <Baz2Task2/> <Baz2Task3/> </Target> <Target Name='DepSkip' DependsOnTargets='Skip'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> <Target Name='DepError' DependsOnTargets='Foo;Skip;Error'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); return project.CreateProjectInstance(); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Retail.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedProductServiceClientTest { [xunit::FactAttribute] public void CreateProductRequestObject() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "product_idde82ea9b", }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.CreateProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.CreateProduct(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateProductRequestObjectAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "product_idde82ea9b", }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.CreateProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.CreateProductAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.CreateProductAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateProduct() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "product_idde82ea9b", }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.CreateProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.CreateProduct(request.Parent, request.Product, request.ProductId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateProductAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "product_idde82ea9b", }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.CreateProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.CreateProductAsync(request.Parent, request.Product, request.ProductId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.CreateProductAsync(request.Parent, request.Product, request.ProductId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateProductResourceNames() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "product_idde82ea9b", }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.CreateProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.CreateProduct(request.ParentAsBranchName, request.Product, request.ProductId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateProductResourceNamesAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "product_idde82ea9b", }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.CreateProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.CreateProductAsync(request.ParentAsBranchName, request.Product, request.ProductId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.CreateProductAsync(request.ParentAsBranchName, request.Product, request.ProductId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetProductRequestObject() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.GetProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.GetProduct(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetProductRequestObjectAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.GetProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.GetProductAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.GetProductAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetProduct() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.GetProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.GetProduct(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetProductAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.GetProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.GetProductAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.GetProductAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetProductResourceNames() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.GetProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.GetProduct(request.ProductName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetProductResourceNamesAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.GetProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.GetProductAsync(request.ProductName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.GetProductAsync(request.ProductName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateProductRequestObject() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateProductRequest request = new UpdateProductRequest { Product = new Product(), UpdateMask = new wkt::FieldMask(), AllowMissing = true, }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.UpdateProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.UpdateProduct(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateProductRequestObjectAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateProductRequest request = new UpdateProductRequest { Product = new Product(), UpdateMask = new wkt::FieldMask(), AllowMissing = true, }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.UpdateProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.UpdateProductAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.UpdateProductAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateProduct() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateProductRequest request = new UpdateProductRequest { Product = new Product(), UpdateMask = new wkt::FieldMask(), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.UpdateProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product response = client.UpdateProduct(request.Product, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateProductAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateProductRequest request = new UpdateProductRequest { Product = new Product(), UpdateMask = new wkt::FieldMask(), }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", CollectionMemberIds = { "collection_member_ids3c9b26a9", }, Gtin = "gtin79aaf991", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Brands = { "brandsd5b53f63", }, Description = "description2cf9da67", LanguageCode = "language_code2f6c7160", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), Rating = new Rating(), ExpireTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, FulfillmentInfo = { new FulfillmentInfo(), }, Uri = "uri3db70593", Images = { new Image(), }, Audience = new Audience(), ColorInfo = new ColorInfo(), Sizes = { "sizes8e1627b0", }, Materials = { "materials38c02a2d", }, Patterns = { "patternsb451ea9d", }, Conditions = { "conditionsec99b3b5", }, RetrievableFields = new wkt::FieldMask(), Variants = { new Product(), }, PublishTime = new wkt::Timestamp(), Promotions = { new Promotion(), }, }; mockGrpcClient.Setup(x => x.UpdateProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.UpdateProductAsync(request.Product, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.UpdateProductAsync(request.Product, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteProductRequestObject() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); client.DeleteProduct(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteProductRequestObjectAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteProductAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteProductAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteProduct() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); client.DeleteProduct(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteProductAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteProductAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteProductAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteProductResourceNames() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteProduct(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); client.DeleteProduct(request.ProductName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteProductResourceNamesAsync() { moq::Mock<ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock<ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteProductAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteProductAsync(request.ProductName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteProductAsync(request.ProductName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector3 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x + transform.up*m_Input.z; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; m_MoveDir.y = desiredMove.y * speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; // Read input float leftright = CrossPlatformInputManager.GetAxis("Horizontal"); float forwardback = CrossPlatformInputManager.GetAxis("Vertical"); float updown = 0.0F; if (Input.GetKey(KeyCode.Q)) { updown = -speed; } else if (Input.GetKey(KeyCode.E)) { updown = speed; } m_Input = new Vector3(leftright, forwardback, updown); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Windows.Controls; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.IocContainer.Wpf.Tests.Support; using Prism.Logging; using Prism.Regions; namespace Prism.Mef.Wpf.Tests { [TestClass] public class MefBootstrapperRunMethodFixture : BootstrapperFixtureBase { // TODO: Tests for ordering of calls in RUN [TestMethod] public void CanRunBootstrapper() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); } [TestMethod] public void RunShouldCallCreateLogger() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateLoggerCalled); } [TestMethod] public void RunConfiguresServiceLocatorProvider() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(Microsoft.Practices.ServiceLocation.ServiceLocator.Current is MefServiceLocatorAdapter); } [TestMethod] public void RunShouldCallCreateAggregateCatalog() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateAggregateCatalogCalled); } [TestMethod] public void RunShouldCallCreateModuleCatalog() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateModuleCatalogCalled); } [TestMethod] public void RunShouldCallConfigureAggregateCatalog() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureAggregateCatalogCalled); } [TestMethod] public void RunShouldCallConfigureModuleCatalog() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureModuleCatalogCalled); } [TestMethod] public void RunShouldCallCreateContainer() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateContainerCalled); } [TestMethod] public void RunShouldCallConfigureContainer() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureContainerCalled); } [TestMethod] public void RunShouldCallConfigureRegionAdapterMappings() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureRegionAdapterMappingsCalled); } [TestMethod] public void RunShouldCallConfigureDefaultRegionBehaviors() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.ConfigureDefaultRegionBehaviorsCalled); } [TestMethod] public void RunShouldCallRegisterFrameworkExceptionTypes() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.RegisterFrameworkExceptionTypesCalled); } [TestMethod] public void RunShouldCallCreateShell() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.CreateShellCalled); } [TestMethod] public void RunShouldCallInitializeShellWhenShellSucessfullyCreated() { var bootstrapper = new DefaultMefBootstrapper { ShellObject = new UserControl() }; bootstrapper.Run(); Assert.IsTrue(bootstrapper.InitializeShellCalled); } [TestMethod] public void RunShouldNotCallInitializeShellWhenShellNotCreated() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsFalse(bootstrapper.InitializeShellCalled); } [TestMethod] public void RunShouldCallInitializeModules() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.InitializeModulesCalled); } [TestMethod] public void RunShouldAssignRegionManagerToReturnedShell() { var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.ShellObject = new UserControl(); bootstrapper.Run(); Assert.IsNotNull(RegionManager.GetRegionManager(bootstrapper.BaseShell)); } [TestMethod] public void RunShouldLogLoggerCreationSuccess() { const string expectedMessageText = "Logger was created successfully."; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutModuleCatalogCreation() { const string expectedMessageText = "Creating module catalog."; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringModuleCatalog() { const string expectedMessageText = "Configuring module catalog."; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutAggregateCatalogCreation() { const string expectedMessageText = "Creating catalog for MEF"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringAggregateCatalog() { const string expectedMessageText = "Configuring catalog for MEF"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutCreatingTheContainer() { const string expectedMessageText = "Creating Mef container"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringContainer() { const string expectedMessageText = "Configuring MEF container"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringRegionAdapters() { const string expectedMessageText = "Configuring region adapters"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutConfiguringRegionBehaviors() { const string expectedMessageText = "Configuring default region behaviors"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutRegisteringFrameworkExceptionTypes() { const string expectedMessageText = "Registering Framework Exception Types"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutSettingTheRegionManager() { const string expectedMessageText = "Setting the RegionManager."; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.ShellObject = new UserControl(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutUpdatingRegions() { const string expectedMessageText = "Updating Regions."; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.ShellObject = new UserControl(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutCreatingTheShell() { const string expectedMessageText = "Creating shell"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutInitializingTheShellIfShellCreated() { const string expectedMessageText = "Initializing shell"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.ShellObject = new UserControl(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldNotLogAboutInitializingTheShellIfShellIsNotCreated() { const string expectedMessageText = "Initializing shell"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsFalse(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutInitializingModules() { const string expectedMessageText = "Initializing modules"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldLogAboutRunCompleting() { const string expectedMessageText = "Bootstrapper sequence completed"; var bootstrapper = new DefaultMefBootstrapper(); bootstrapper.Run(); Assert.IsTrue(bootstrapper.TestLog.LogMessages.Contains(expectedMessageText)); } [TestMethod] public void RunShouldCallTheMethodsInOrder() { var bootstrapper = new DefaultMefBootstrapper{ShellObject = new UserControl()}; bootstrapper.Run(); Assert.AreEqual("CreateLogger", bootstrapper.MethodCalls[0]); Assert.AreEqual("CreateModuleCatalog", bootstrapper.MethodCalls[1]); Assert.AreEqual("ConfigureModuleCatalog", bootstrapper.MethodCalls[2]); Assert.AreEqual("CreateAggregateCatalog", bootstrapper.MethodCalls[3]); Assert.AreEqual("ConfigureAggregateCatalog", bootstrapper.MethodCalls[4]); Assert.AreEqual("CreateContainer", bootstrapper.MethodCalls[5]); Assert.AreEqual("ConfigureContainer", bootstrapper.MethodCalls[6]); Assert.AreEqual("ConfigureServiceLocator", bootstrapper.MethodCalls[7]); Assert.AreEqual("ConfigureRegionAdapterMappings", bootstrapper.MethodCalls[8]); Assert.AreEqual("ConfigureDefaultRegionBehaviors", bootstrapper.MethodCalls[9]); Assert.AreEqual("RegisterFrameworkExceptionTypes", bootstrapper.MethodCalls[10]); Assert.AreEqual("CreateShell", bootstrapper.MethodCalls[11]); Assert.AreEqual("InitializeShell", bootstrapper.MethodCalls[12]); Assert.AreEqual("InitializeModules", bootstrapper.MethodCalls[13]); } } internal class TestLogger : ILoggerFacade { public List<string> LogMessages = new List<string>(); public void Log(string message, Category category, Priority priority) { LogMessages.Add(message); } } }
// ----------------------------------------------------------------------------------------- // <copyright file="ClientConvert.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Table.Queryable { #region Namespaces. using Microsoft.WindowsAzure.Storage.Core; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Xml; #endregion Namespaces. internal static class FXAssembly { internal const string Version = "4.0.0.0"; } [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed.")] internal static class AssemblyRef { internal const string MicrosoftPublicKeyToken = "b03f5f7f11d50a3a"; internal const string EcmaPublicKeyToken = "b77a5c561934e089"; } internal static class ClientConvert { #if !ASTORIA_LIGHT private const string SystemDataLinq = "System.Data.Linq, Version=" + FXAssembly.Version + ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken; #endif private static readonly Type[] KnownTypes = CreateKnownPrimitives(); private static readonly Dictionary<string, Type> NamedTypesMap = CreateKnownNamesMap(); #if !ASTORIA_LIGHT private static bool needSystemDataLinqBinary = true; #endif internal enum StorageType { Boolean, Byte, ByteArray, Char, CharArray, DateTime, DateTimeOffset, Decimal, Double, Guid, Int16, Int32, Int64, Single, String, SByte, TimeSpan, Type, UInt16, UInt32, UInt64, Uri, XDocument, XElement, #if !ASTORIA_LIGHT Binary, #endif } internal static object ChangeType(string propertyValue, Type propertyType) { // Debug.Assert(null != propertyValue, "should never be passed null"); try { switch ((StorageType)IndexOfStorage(propertyType)) { case StorageType.Boolean: return XmlConvert.ToBoolean(propertyValue); case StorageType.Byte: return XmlConvert.ToByte(propertyValue); case StorageType.ByteArray: return Convert.FromBase64String(propertyValue); case StorageType.Char: return XmlConvert.ToChar(propertyValue); case StorageType.CharArray: return propertyValue.ToCharArray(); case StorageType.DateTime: return XmlConvert.ToDateTime(propertyValue, XmlDateTimeSerializationMode.RoundtripKind); case StorageType.DateTimeOffset: return XmlConvert.ToDateTimeOffset(propertyValue); case StorageType.Decimal: return XmlConvert.ToDecimal(propertyValue); case StorageType.Double: return XmlConvert.ToDouble(propertyValue); case StorageType.Guid: return new Guid(propertyValue); case StorageType.Int16: return XmlConvert.ToInt16(propertyValue); case StorageType.Int32: return XmlConvert.ToInt32(propertyValue); case StorageType.Int64: return XmlConvert.ToInt64(propertyValue); case StorageType.Single: return XmlConvert.ToSingle(propertyValue); case StorageType.String: return propertyValue; case StorageType.SByte: return XmlConvert.ToSByte(propertyValue); case StorageType.TimeSpan: return XmlConvert.ToTimeSpan(propertyValue); case StorageType.Type: return Type.GetType(propertyValue, true); case StorageType.UInt16: return XmlConvert.ToUInt16(propertyValue); case StorageType.UInt32: return XmlConvert.ToUInt32(propertyValue); case StorageType.UInt64: return XmlConvert.ToUInt64(propertyValue); case StorageType.Uri: return ClientConvert.CreateUri(propertyValue, UriKind.RelativeOrAbsolute); case StorageType.XDocument: return 0 < propertyValue.Length ? System.Xml.Linq.XDocument.Parse(propertyValue) : new System.Xml.Linq.XDocument(); case StorageType.XElement: return System.Xml.Linq.XElement.Parse(propertyValue); #if !ASTORIA_LIGHT case StorageType.Binary: // Debug.Assert(null != KnownTypes[(int)StorageType.Binary], "null typeof(System.Data.Linq.Binary)"); return Activator.CreateInstance(KnownTypes[(int)StorageType.Binary], Convert.FromBase64String(propertyValue)); #endif default: // Debug.Assert(false, "new StorageType without update to knownTypes"); return propertyValue; } } catch (FormatException ex) { propertyValue = 0 == propertyValue.Length ? "String.Empty" : "String"; throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The current value '{1}' type is not compatible with the expected '{0}' type.", propertyType.ToString(), propertyValue), ex); } catch (OverflowException ex) { propertyValue = 0 == propertyValue.Length ? "String.Empty" : "String"; throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The current value '{1}' type is not compatible with the expected '{0}' type.", propertyType.ToString(), propertyValue), ex); // Strings.Deserialize_Current(propertyType.ToString(), propertyValue), ex); } } #if !ASTORIA_LIGHT internal static bool IsBinaryValue(object value) { // Debug.Assert(value != null, "value != null"); return StorageType.Binary == (StorageType)IndexOfStorage(value.GetType()); } internal static bool TryKeyBinaryToString(object binaryValue, out string result) { // Debug.Assert(binaryValue != null, "binaryValue != null"); // Debug.Assert(IsBinaryValue(binaryValue), "IsBinaryValue(binaryValue) - otherwise TryKeyBinaryToString shouldn't have been called."); const System.Reflection.BindingFlags Flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod; byte[] bytes = (byte[])binaryValue.GetType().InvokeMember("ToArray", Flags, null, binaryValue, null, null /* ParamModifiers */, System.Globalization.CultureInfo.InvariantCulture, null /* NamedParams */); return Microsoft.WindowsAzure.Storage.Table.Queryable.WebConvert.TryKeyPrimitiveToString(bytes, out result); } #endif internal static bool TryKeyPrimitiveToString(object value, out string result) { // Debug.Assert(value != null, "value != null"); #if !ASTORIA_LIGHT if (IsBinaryValue(value)) { return TryKeyBinaryToString(value, out result); } #endif // Support DateTimeOffset if (value is DateTimeOffset) { value = ((DateTimeOffset)value).UtcDateTime; } else if (value is DateTimeOffset?) { value = ((DateTimeOffset?)value).Value.UtcDateTime; } return Microsoft.WindowsAzure.Storage.Table.Queryable.WebConvert.TryKeyPrimitiveToString(value, out result); } internal static bool ToNamedType(string typeName, out Type type) { type = typeof(string); return string.IsNullOrEmpty(typeName) || ClientConvert.NamedTypesMap.TryGetValue(typeName, out type); } internal static string ToTypeName(Type type) { // Debug.Assert(type != null, "type != null"); foreach (var pair in ClientConvert.NamedTypesMap) { if (pair.Value == type) { return pair.Key; } } return type.FullName; } internal static string ToString(object propertyValue, bool atomDateConstruct) { // Debug.Assert(null != propertyValue, "null should be handled by caller"); switch ((StorageType)IndexOfStorage(propertyValue.GetType())) { case StorageType.Boolean: return XmlConvert.ToString((bool)propertyValue); case StorageType.Byte: return XmlConvert.ToString((byte)propertyValue); case StorageType.ByteArray: return Convert.ToBase64String((byte[])propertyValue); case StorageType.Char: return XmlConvert.ToString((char)propertyValue); case StorageType.CharArray: return new string((char[])propertyValue); case StorageType.DateTime: DateTime dt = (DateTime)propertyValue; return XmlConvert.ToString(dt.Kind == DateTimeKind.Unspecified && atomDateConstruct ? new DateTime(dt.Ticks, DateTimeKind.Utc) : dt, XmlDateTimeSerializationMode.RoundtripKind); case StorageType.DateTimeOffset: return XmlConvert.ToString((DateTimeOffset)propertyValue); case StorageType.Decimal: return XmlConvert.ToString((decimal)propertyValue); case StorageType.Double: return XmlConvert.ToString((double)propertyValue); case StorageType.Guid: return ((Guid)propertyValue).ToString(); case StorageType.Int16: return XmlConvert.ToString((short)propertyValue); case StorageType.Int32: return XmlConvert.ToString((int)propertyValue); case StorageType.Int64: return XmlConvert.ToString((long)propertyValue); case StorageType.Single: return XmlConvert.ToString((float)propertyValue); case StorageType.String: return (string)propertyValue; case StorageType.SByte: return XmlConvert.ToString((sbyte)propertyValue); case StorageType.TimeSpan: return XmlConvert.ToString((TimeSpan)propertyValue); case StorageType.Type: return ((Type)propertyValue).AssemblyQualifiedName; case StorageType.UInt16: return XmlConvert.ToString((ushort)propertyValue); case StorageType.UInt32: return XmlConvert.ToString((uint)propertyValue); case StorageType.UInt64: return XmlConvert.ToString((ulong)propertyValue); case StorageType.Uri: return ((Uri)propertyValue).ToString(); case StorageType.XDocument: return ((System.Xml.Linq.XDocument)propertyValue).ToString(); case StorageType.XElement: return ((System.Xml.Linq.XElement)propertyValue).ToString(); #if !ASTORIA_LIGHT case StorageType.Binary: // Debug.Assert(null != KnownTypes[(int)StorageType.Binary], "null typeof(System.Data.Linq.Binary)"); // Debug.Assert(KnownTypes[(int)StorageType.Binary].IsInstanceOfType(propertyValue), "not IsInstanceOfType System.Data.Linq.Binary"); return propertyValue.ToString(); #endif default: // Debug.Assert(false, "new StorageType without update to knownTypes"); return propertyValue.ToString(); } } internal static bool IsKnownType(Type type) { return 0 <= IndexOfStorage(type); } internal static bool IsKnownNullableType(Type type) { return IsKnownType(Nullable.GetUnderlyingType(type) ?? type); } internal static bool IsSupportedPrimitiveTypeForUri(Type type) { return ClientConvert.ContainsReference(NamedTypesMap.Values.ToArray(), type); } internal static bool ContainsReference<T>(T[] array, T value) where T : class { return 0 <= IndexOfReference<T>(array, value); } internal static string GetEdmType(Type propertyType) { switch ((StorageType)IndexOfStorage(propertyType)) { case StorageType.Boolean: return XmlConstants.EdmBooleanTypeName; case StorageType.Byte: return XmlConstants.EdmByteTypeName; #if !ASTORIA_LIGHT case StorageType.Binary: #endif case StorageType.ByteArray: return XmlConstants.EdmBinaryTypeName; case StorageType.DateTime: return XmlConstants.EdmDateTimeTypeName; case StorageType.Decimal: return XmlConstants.EdmDecimalTypeName; case StorageType.Double: return XmlConstants.EdmDoubleTypeName; case StorageType.Guid: return XmlConstants.EdmGuidTypeName; case StorageType.Int16: return XmlConstants.EdmInt16TypeName; case StorageType.Int32: return XmlConstants.EdmInt32TypeName; case StorageType.Int64: return XmlConstants.EdmInt64TypeName; case StorageType.Single: return XmlConstants.EdmSingleTypeName; case StorageType.SByte: return XmlConstants.EdmSByteTypeName; case StorageType.DateTimeOffset: case StorageType.TimeSpan: case StorageType.UInt16: case StorageType.UInt32: case StorageType.UInt64: throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantCastToUnsupportedPrimitive, propertyType.Name)); case StorageType.Char: case StorageType.CharArray: case StorageType.String: case StorageType.Type: case StorageType.Uri: case StorageType.XDocument: case StorageType.XElement: return null; default: // Debug.Assert(false, "knowntype without reverse mapping"); return null; } } private static Type[] CreateKnownPrimitives() { #if !ASTORIA_LIGHT Type[] types = new Type[1 + (int)StorageType.Binary]; #else Type[] types = new Type[1 + (int)StorageType.XElement]; #endif types[(int)StorageType.Boolean] = typeof(bool); types[(int)StorageType.Byte] = typeof(byte); types[(int)StorageType.ByteArray] = typeof(byte[]); types[(int)StorageType.Char] = typeof(char); types[(int)StorageType.CharArray] = typeof(char[]); types[(int)StorageType.DateTime] = typeof(DateTime); types[(int)StorageType.DateTimeOffset] = typeof(DateTimeOffset); types[(int)StorageType.Decimal] = typeof(decimal); types[(int)StorageType.Double] = typeof(double); types[(int)StorageType.Guid] = typeof(Guid); types[(int)StorageType.Int16] = typeof(short); types[(int)StorageType.Int32] = typeof(int); types[(int)StorageType.Int64] = typeof(long); types[(int)StorageType.Single] = typeof(float); types[(int)StorageType.String] = typeof(string); types[(int)StorageType.SByte] = typeof(sbyte); types[(int)StorageType.TimeSpan] = typeof(TimeSpan); types[(int)StorageType.Type] = typeof(Type); types[(int)StorageType.UInt16] = typeof(ushort); types[(int)StorageType.UInt32] = typeof(uint); types[(int)StorageType.UInt64] = typeof(ulong); types[(int)StorageType.Uri] = typeof(Uri); types[(int)StorageType.XDocument] = typeof(System.Xml.Linq.XDocument); types[(int)StorageType.XElement] = typeof(System.Xml.Linq.XElement); #if !ASTORIA_LIGHT types[(int)StorageType.Binary] = null; #endif return types; } private static Dictionary<string, Type> CreateKnownNamesMap() { Dictionary<string, Type> named = new Dictionary<string, Type>(EqualityComparer<string>.Default); named.Add(XmlConstants.EdmStringTypeName, typeof(string)); named.Add(XmlConstants.EdmBooleanTypeName, typeof(bool)); named.Add(XmlConstants.EdmByteTypeName, typeof(byte)); named.Add(XmlConstants.EdmDateTimeTypeName, typeof(DateTime)); named.Add(XmlConstants.EdmDecimalTypeName, typeof(decimal)); named.Add(XmlConstants.EdmDoubleTypeName, typeof(double)); named.Add(XmlConstants.EdmGuidTypeName, typeof(Guid)); named.Add(XmlConstants.EdmInt16TypeName, typeof(short)); named.Add(XmlConstants.EdmInt32TypeName, typeof(int)); named.Add(XmlConstants.EdmInt64TypeName, typeof(long)); named.Add(XmlConstants.EdmSByteTypeName, typeof(sbyte)); named.Add(XmlConstants.EdmSingleTypeName, typeof(float)); named.Add(XmlConstants.EdmBinaryTypeName, typeof(byte[])); return named; } private static int IndexOfStorage(Type type) { int index = ClientConvert.IndexOfReference(ClientConvert.KnownTypes, type); #if !ASTORIA_LIGHT if ((index < 0) && needSystemDataLinqBinary && (type.Name == "Binary")) { return LoadSystemDataLinqBinary(type); } #endif return index; } internal static int IndexOfReference<T>(T[] array, T value) where T : class { // Debug.Assert(null != array, "null array"); for (int i = 0; i < array.Length; ++i) { if (object.ReferenceEquals(array[i], value)) { return i; } } return -1; } internal static Uri CreateUri(string value, UriKind kind) { return value == null ? null : new Uri(value, kind); } #if !ASTORIA_LIGHT private static int LoadSystemDataLinqBinary(Type type) { if (type.Namespace == "System.Data.Linq" && System.Reflection.AssemblyName.ReferenceMatchesDefinition(type.Assembly.GetName(), new System.Reflection.AssemblyName(SystemDataLinq))) { ClientConvert.KnownTypes[(int)StorageType.Binary] = type; needSystemDataLinqBinary = false; return (int)StorageType.Binary; } return -1; } #endif } }
using System; #if FRB_MDX using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Direct3D=Microsoft.DirectX.Direct3D; using Keys = Microsoft.DirectX.DirectInput.Key; #else using Microsoft.Xna.Framework.Input; #endif using FlatRedBall.Graphics; using FlatRedBall.Input; using System.Collections.Generic; namespace FlatRedBall.Gui { /// <summary> /// Summary description for TextInputWindow. /// </summary> public class MessageBox : Window, IInputReceiver { #region Fields internal Button okButton; TextField textDisplay; //float mTextRed; //float mTextGreen; //float mTextBlue; IInputReceiver mNextInTabSequence; List<Keys> mIgnoredKeys = new List<Keys>(); #endregion #region Properties public List<Keys> IgnoredKeys { get { return mIgnoredKeys; } } public IInputReceiver NextInTabSequence { get { return mNextInTabSequence; } set { mNextInTabSequence = value; } } #endregion #region Events public event GuiMessage GainFocus; public event FocusUpdateDelegate FocusUpdate; public event GuiMessage OkClick; #endregion #region Event-calling methods public void OnFocusUpdate() { if (FocusUpdate != null) FocusUpdate(this); } #endregion #region Methods public MessageBox(Cursor cursor) : base(cursor) { okButton = new Button(mCursor); AddWindow(okButton); this.HasMoveBar = true; this.HasCloseButton = true; Visible = false; textDisplay = new TextField(); textDisplay.mAlignment = HorizontalAlignment.Left; //mTextRed = mTextGreen = mTextBlue = 20; } public void Activate(string textToDisplay, string Name) { Visible = true; mName = Name; ScaleX = 19; ScaleY = 9; textDisplay.SetDimensions((Window)this); textDisplay.DisplayText = textToDisplay; textDisplay.mZ = 100; textDisplay.WindowParent = this; okButton.ScaleX = 5; okButton.ScaleY = 1.5f; okButton.Text = "Ok"; okButton.SetPositionTL(ScaleX, 2*ScaleY - 2); textDisplay.FillLines(); while(13f + textDisplay.mLines.Count*2 > this.ScaleY*2) { this.ScaleX = System.Math.Min(52, ScaleX + 2) ; this.ScaleY += 2; textDisplay.SetDimensions((Window)this); textDisplay.mLines.Clear(); textDisplay.FillLines(); okButton.SetPositionTL(ScaleX, 2*ScaleY - 2); } textDisplay.SetDimensions((Window)this, 1); } public override void ClearEvents() { base.ClearEvents(); OkClick = null; } internal override void DrawSelfAndChildren(Camera camera) { #if !SILVERLIGHT if (Visible == false) return; // TODO: Set TextManager vertex drawing fields here. textDisplay.TextHeight = GuiManager.TextHeight; base.DrawSelfAndChildren(camera); TextManager.Draw(textDisplay); #endif } internal override int GetNumberOfVerticesToDraw() { return base.GetNumberOfVerticesToDraw() + textDisplay.DisplayText.Replace("\n", "").Replace(" ", "").Length * 6; } public void OnGainFocus() { if (GainFocus != null) GainFocus(this); } public override void TestCollision(Cursor cursor) { base.TestCollision(cursor); if(cursor.PrimaryClick) { if(cursor.WindowOver == okButton) { if(OkClick != null) OkClick(this); Visible = false; cursor.WindowClosing = this; } } } void onEnter(Window callingWindow) { if(OkClick != null) this.OkClick(this); if (InputManager.ReceivingInput == this) InputManager.ReceivingInput = null; Visible = false; } #region IInputReceiver Members public void LoseFocus() { } public void ReceiveInput() { #if FRB_MDX if(InputManager.Keyboard.KeyPushed(Keys.Return) || InputManager.Keyboard.KeyPushed(Keys.NumPadEnter)) #else if(InputManager.Keyboard.KeyPushed(Keys.Enter)) #endif { onEnter(this); } } public bool TakingInput { get { return true; } } #endregion #endregion } }
#pragma warning disable 1591 #pragma warning disable 0108 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Team Development for Sitecore. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Sitecore.Mapper.Configuration.Attributes; using Glass.Sitecore.Mapper.Configuration; using Glass.Sitecore.Mapper.FieldTypes; using Sitecore.Globalization; namespace SUGNL.TDS.Website { public interface IGlassBase{ [SitecoreId] Guid Id{ get; } [SitecoreInfo(SitecoreInfoType.Language)] Language Language{ get; } [SitecoreInfo(SitecoreInfoType.Version)] int Version { get; } } public abstract class GlassBase : IGlassBase{ [SitecoreId] public virtual Guid Id{ get; private set;} [SitecoreInfo(SitecoreInfoType.Language)] public virtual Language Language{ get; private set; } [SitecoreInfo(SitecoreInfoType.Version)] public virtual int Version { get; private set; } } } namespace SUGNL.TDS.Website { /// <summary> /// ITitleBase Interface /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/TitleBase</para> /// <para>ID: 02b041f5-3b31-4724-818b-ac33e5412024</para> /// </summary> public interface ITitleBase : IGlassBase { /// <summary> /// The Title field. /// <para></para> /// <para>Field Type: Single-Line Text</para> /// <para>Field ID: fc20530b-c1f3-421c-b724-321a36152e91</para> /// <para>Custom Data: </para> /// </summary> string Title {get; set;} } /// <summary> /// TitleBase /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/TitleBase</para> /// <para>ID: 02b041f5-3b31-4724-818b-ac33e5412024</para> /// </summary> [SitecoreClass(TemplateId="02b041f5-3b31-4724-818b-ac33e5412024")] public partial class TitleBase : GlassBase, ITitleBase { /// <summary> /// The Title field. /// <para></para> /// <para>Field Type: Single-Line Text</para> /// <para>Field ID: fc20530b-c1f3-421c-b724-321a36152e91</para> /// <para>Custom Data: </para> /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")] [SitecoreField("Title")] public virtual string Title {get; set;} } } namespace SUGNL.TDS.Website { /// <summary> /// IMetaBase Interface /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/MetaBase</para> /// <para>ID: 0a6cbac6-346f-4053-ab0f-dcac5463c2f9</para> /// </summary> public interface IMetaBase : IGlassBase { /// <summary> /// The MetaDescription field. /// <para></para> /// <para>Field Type: Single-Line Text</para> /// <para>Field ID: 411f83b0-ffcf-4c64-bb8d-5c4b251493a3</para> /// <para>Custom Data: </para> /// </summary> string MetaDescription {get; set;} /// <summary> /// The MetaKeywords field. /// <para></para> /// <para>Field Type: Single-Line Text</para> /// <para>Field ID: f29a2f77-3034-4307-84ba-0c48cdc8188d</para> /// <para>Custom Data: </para> /// </summary> string MetaKeywords {get; set;} } /// <summary> /// MetaBase /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/MetaBase</para> /// <para>ID: 0a6cbac6-346f-4053-ab0f-dcac5463c2f9</para> /// </summary> [SitecoreClass(TemplateId="0a6cbac6-346f-4053-ab0f-dcac5463c2f9")] public partial class MetaBase : GlassBase, IMetaBase { /// <summary> /// The MetaDescription field. /// <para></para> /// <para>Field Type: Single-Line Text</para> /// <para>Field ID: 411f83b0-ffcf-4c64-bb8d-5c4b251493a3</para> /// <para>Custom Data: </para> /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")] [SitecoreField("MetaDescription")] public virtual string MetaDescription {get; set;} /// <summary> /// The MetaKeywords field. /// <para></para> /// <para>Field Type: Single-Line Text</para> /// <para>Field ID: f29a2f77-3034-4307-84ba-0c48cdc8188d</para> /// <para>Custom Data: </para> /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")] [SitecoreField("MetaKeywords")] public virtual string MetaKeywords {get; set;} } } namespace SUGNL.TDS.Website { /// <summary> /// IIntroBase Interface /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/IntroBase</para> /// <para>ID: 29ec2750-290b-4561-ab53-34c1d3e82bae</para> /// </summary> public interface IIntroBase : IGlassBase { /// <summary> /// The Intro field. /// <para></para> /// <para>Field Type: Multi-Line Text</para> /// <para>Field ID: 5e82bcb3-e174-4f0d-9248-24be233a4635</para> /// <para>Custom Data: </para> /// </summary> string Intro {get; set;} } /// <summary> /// IntroBase /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/IntroBase</para> /// <para>ID: 29ec2750-290b-4561-ab53-34c1d3e82bae</para> /// </summary> [SitecoreClass(TemplateId="29ec2750-290b-4561-ab53-34c1d3e82bae")] public partial class IntroBase : GlassBase, IIntroBase { /// <summary> /// The Intro field. /// <para></para> /// <para>Field Type: Multi-Line Text</para> /// <para>Field ID: 5e82bcb3-e174-4f0d-9248-24be233a4635</para> /// <para>Custom Data: </para> /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")] [SitecoreField("Intro")] public virtual string Intro {get; set;} } } namespace SUGNL.TDS.Website { /// <summary> /// IPageBase Interface /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/PageBase</para> /// <para>ID: 4cf43de9-a89b-4139-9ed2-14b267e0ddd6</para> /// </summary> public interface IPageBase : IGlassBase { } /// <summary> /// PageBase /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/PageBase</para> /// <para>ID: 4cf43de9-a89b-4139-9ed2-14b267e0ddd6</para> /// </summary> [SitecoreClass(TemplateId="4cf43de9-a89b-4139-9ed2-14b267e0ddd6")] public partial class PageBase : GlassBase, IPageBase { } } namespace SUGNL.TDS.Website { /// <summary> /// IContentTextBase Interface /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/ContentTextBase</para> /// <para>ID: efca2812-d85a-414d-80c4-8998f543b44e</para> /// </summary> public interface IContentTextBase : IGlassBase { /// <summary> /// The Content field. /// <para></para> /// <para>Field Type: Rich Text</para> /// <para>Field ID: 3089399a-4f48-4bfe-b0b6-34f63c28797f</para> /// <para>Custom Data: </para> /// </summary> string Content {get; set;} } /// <summary> /// ContentTextBase /// <para></para> /// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/BaseTemplates/ContentTextBase</para> /// <para>ID: efca2812-d85a-414d-80c4-8998f543b44e</para> /// </summary> [SitecoreClass(TemplateId="efca2812-d85a-414d-80c4-8998f543b44e")] public partial class ContentTextBase : GlassBase, IContentTextBase { /// <summary> /// The Content field. /// <para></para> /// <para>Field Type: Rich Text</para> /// <para>Field ID: 3089399a-4f48-4bfe-b0b6-34f63c28797f</para> /// <para>Custom Data: </para> /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")] [SitecoreField("Content")] public virtual string Content {get; set;} } }
namespace WebAPI.Testing { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http; using RouteParameter = System.Web.Http.RouteParameter; /// <summary> /// Provides the capability of executing a request with WebAPI, using a specific configuration provided by an <see cref="IWebAPIBootstrapper"/> instance. /// </summary> public class Browser : IHideObjectMembers, IDisposable { private readonly bool _disposeServerAfterRequest; private readonly HttpServer _server; private readonly IDictionary<string, string> cookies = new Dictionary<string, string>(); public HttpClient BrowserHttpClient { get; set; } public Browser(bool disposeServerAfterRequest = true) { _disposeServerAfterRequest = disposeServerAfterRequest; var config = new HttpConfiguration(); config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; _server = new HttpServer(config); } public Browser(HttpConfiguration httpConfiguration, bool disposeServerAfterRequest = true) { _disposeServerAfterRequest = disposeServerAfterRequest; HttpConfiguration config = httpConfiguration; _server = new HttpServer(config); } /// <summary> /// Performs a DELETE requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Delete(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(HttpMethod.Delete, path, browserContext); } /// <summary> /// Performs a GET requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Get(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(HttpMethod.Get, path, browserContext); } /// <summary> /// Performs a HEAD requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Head(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(HttpMethod.Head, path, browserContext); } /// <summary> /// Performs a OPTIONS requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Options(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(HttpMethod.Options, path, browserContext); } ///// <summary> ///// Performs a PATCH requests against WebAPI. ///// </summary> ///// <param name="path">The path that is being requested.</param> ///// <param name="browserContext">An closure for providing browser context for the request.</param> ///// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> //public HttpResponseMessage Patch(string path, Action<BrowserContext> browserContext = null) //{ // return this.HandleRequest(HttpMethod., path, browserContext); //} /// <summary> /// Performs a POST requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Post(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(HttpMethod.Post, path, browserContext); } /// <summary> /// Performs a PUT requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Put(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(HttpMethod.Put, path, browserContext); } /// <summary> /// Performs a PATCH requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Patch(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(new HttpMethod("PATCH"), path, browserContext); } /// <summary> /// Performs a TRACE requests against WebAPI. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="HttpResponseMessage"/> instance of the executed request.</returns> public HttpResponseMessage Trace(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest(HttpMethod.Trace, path, browserContext); } private HttpResponseMessage HandleRequest(HttpMethod method, string path, Action<BrowserContext> browserContext) { var request = CreateRequest(method, path, browserContext ?? this.DefaultBrowserContext); if (BrowserHttpClient == null) BrowserHttpClient = new HttpClient(_server); HttpResponseMessage response = BrowserHttpClient.SendAsync(request).Result; request.Dispose(); if (_disposeServerAfterRequest && _server != null) { _server.Dispose(); } return response; } private void DefaultBrowserContext(BrowserContext context) { context.HttpRequest(); } private void SetCookies(BrowserContext context) { if (!this.cookies.Any()) { return; } var cookieString = this.cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); context.Header("Cookie", cookieString); } private static void BuildRequestBody(IBrowserContextValues contextValues) { if (contextValues.Body != null) { return; } var useFormValues = !String.IsNullOrEmpty(contextValues.FormValues); var bodyContents = useFormValues ? contextValues.FormValues : contextValues.BodyString; var bodyBytes = bodyContents != null ? Encoding.UTF8.GetBytes(bodyContents) : new byte[] { }; if (useFormValues && !contextValues.Headers.ContainsKey("Content-Type")) { contextValues.Headers["Content-Type"] = new[] { "application/x-www-form-urlencoded" }; } contextValues.Body = new MemoryStream(bodyBytes); } private HttpRequestMessage CreateRequest(HttpMethod method, string path, Action<BrowserContext> browserContext) { var context = new BrowserContext(); this.SetCookies(context); browserContext.Invoke(context); var contextValues = (IBrowserContextValues)context; BuildRequestBody(contextValues); var request = new HttpRequestMessage(); request.Method = method; request.RequestUri = new Uri(contextValues.Protocol + "://" + contextValues.UserHostAddress + path + contextValues.QueryString); request.Content = new StreamContent(contextValues.Body); foreach (var header in contextValues.Headers) { if (header.Key.StartsWith("Content") && !request.Content.Headers.Contains(header.Key)) { request.Content.Headers.Add(header.Key, header.Value); } else if (!header.Key.StartsWith("Content") && !request.Headers.Contains(header.Key)) { request.Headers.Add(header.Key, header.Value); } } return request; } public void Dispose() { if (_server != null) { _server.Dispose(); } } } }
// <copyright file="IntegrationTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.Integration; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.IntegrationTests { /// <summary> /// Integration tests. /// </summary> [TestFixture, Category("Integration")] public class IntegrationTest { /// <summary> /// Test Function: f(x) = exp(-x/5) (2 + sin(2 * x)) /// </summary> /// <param name="x">Input value.</param> /// <returns>Function result.</returns> private static double TargetFunctionA(double x) { return Math.Exp(-x / 5) * (2 + Math.Sin(2 * x)); } /// <summary> /// Test Function: f(x,y) = exp(-x/5) (2 + sin(x * y)) /// </summary> /// <param name="x">First input value.</param> /// <param name="y">Second input value.</param> /// <returns>Function result.</returns> private static double TargetFunctionB(double x, double y) { return Math.Exp(-x / 5) * (2 + Math.Sin(2 * y)); } /// <summary> /// Test Function Start point. /// </summary> private const double StartA = 0; /// <summary> /// Test Function Stop point. /// </summary> private const double StopA = 10; /// <summary> /// Test Function Start point. /// </summary> private const double StartB = 0; /// <summary> /// Test Function Stop point. /// </summary> private const double StopB = 1; /// <summary> /// Target area square. /// </summary> private const double TargetAreaA = 9.1082396073229965070; /// <summary> /// Target area. /// </summary> private const double TargetAreaB = 11.7078776759298776163; /// <summary> /// Test Integrate facade for simple use cases. /// </summary> [Test] public void TestIntegrateFacade() { Assert.AreEqual( TargetAreaA, Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA), 1e-5, "Interval"); Assert.AreEqual( TargetAreaA, Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA, 1e-10), 1e-10, "Interval, Target 1e-10"); Assert.AreEqual( Integrate.OnRectangle(TargetFunctionB, StartA, StopA, StartB, StopB), TargetAreaB, 1e-12, "Rectangle"); Assert.AreEqual( Integrate.OnRectangle(TargetFunctionB, StartA, StopA, StartB, StopB, 22), TargetAreaB, 1e-10, "Rectangle, Gauss-Legendre Order 22"); } /// <summary> /// Test double exponential transformation algorithm. /// </summary> /// <param name="targetRelativeError">Relative error.</param> [TestCase(1e-5)] [TestCase(1e-13)] public void TestDoubleExponentialTransformationAlgorithm(double targetRelativeError) { Assert.AreEqual( TargetAreaA, DoubleExponentialTransformation.Integrate(TargetFunctionA, StartA, StopA, targetRelativeError), targetRelativeError * TargetAreaA, "DET Adaptive {0}", targetRelativeError); } /// <summary> /// Trapezium rule supports two point integration. /// </summary> [Test] public void TrapeziumRuleSupportsTwoPointIntegration() { Assert.AreEqual( TargetAreaA, NewtonCotesTrapeziumRule.IntegrateTwoPoint(TargetFunctionA, StartA, StopA), 0.4 * TargetAreaA, "Direct (1 Partition)"); } /// <summary> /// Trapezium rule supports composite integration. /// </summary> /// <param name="partitions">Partitions count.</param> /// <param name="maxRelativeError">Maximum relative error.</param> [TestCase(1, 3.5e-1)] [TestCase(5, 1e-1)] [TestCase(10, 2e-2)] [TestCase(50, 6e-4)] [TestCase(1000, 1.5e-6)] public void TrapeziumRuleSupportsCompositeIntegration(int partitions, double maxRelativeError) { Assert.AreEqual( TargetAreaA, NewtonCotesTrapeziumRule.IntegrateComposite(TargetFunctionA, StartA, StopA, partitions), maxRelativeError * TargetAreaA, "Composite {0} Partitions", partitions); } /// <summary> /// Trapezium rule supports adaptive integration. /// </summary> /// <param name="targetRelativeError">Relative error</param> [TestCase(1e-1)] [TestCase(1e-5)] [TestCase(1e-10)] public void TrapeziumRuleSupportsAdaptiveIntegration(double targetRelativeError) { Assert.AreEqual( TargetAreaA, NewtonCotesTrapeziumRule.IntegrateAdaptive(TargetFunctionA, StartA, StopA, targetRelativeError), targetRelativeError * TargetAreaA, "Adaptive {0}", targetRelativeError); } /// <summary> /// Simpson rule supports three point integration. /// </summary> [Test] public void SimpsonRuleSupportsThreePointIntegration() { Assert.AreEqual( TargetAreaA, SimpsonRule.IntegrateThreePoint(TargetFunctionA, StartA, StopA), 0.2 * TargetAreaA, "Direct (2 Partitions)"); } /// <summary> /// Simpson rule supports composite integration. /// </summary> /// <param name="partitions">Partitions count.</param> /// <param name="maxRelativeError">Maximum relative error.</param> [TestCase(2, 1.7e-1)] [TestCase(6, 1.2e-1)] [TestCase(10, 8e-3)] [TestCase(50, 8e-6)] [TestCase(1000, 5e-11)] public void SimpsonRuleSupportsCompositeIntegration(int partitions, double maxRelativeError) { Assert.AreEqual( TargetAreaA, SimpsonRule.IntegrateComposite(TargetFunctionA, StartA, StopA, partitions), maxRelativeError * TargetAreaA, "Composite {0} Partitions", partitions); } /// <summary> /// Gauss-Legendre rule supports integration. /// </summary> /// <param name="order">Defines an Nth order Gauss-Legendre rule. The order also defines the number of abscissas and weights for the rule.</param> [TestCase(19)] [TestCase(20)] [TestCase(21)] [TestCase(22)] public void TestGaussLegendreRuleIntegration(int order) { double appoximateArea = GaussLegendreRule.Integrate(TargetFunctionA, StartA, StopA, order); double relativeError = Math.Abs(TargetAreaA - appoximateArea) / TargetAreaA; Assert.Less(relativeError, 5e-16); } /// <summary> /// Gauss-Legendre rule supports 2-dimensional integration over the rectangle. /// </summary> /// <param name="order">Defines an Nth order Gauss-Legendre rule. The order also defines the number of abscissas and weights for the rule.</param> [TestCase(19)] [TestCase(20)] [TestCase(21)] [TestCase(22)] public void TestGaussLegendreRuleIntegrate2D(int order) { double appoximateArea = GaussLegendreRule.Integrate(TargetFunctionB, StartA, StopA, StartB, StopB, order); double relativeError = Math.Abs(TargetAreaB - appoximateArea) / TargetAreaB; Assert.Less(relativeError, 1e-15); } /// <summary> /// Gauss-Legendre rule supports obtaining the ith abscissa/weight. In this case, they're used for integration. /// </summary> /// <param name="order">Defines an Nth order Gauss-Legendre rule. The order also defines the number of abscissas and weights for the rule.</param> [TestCase(19)] [TestCase(20)] [TestCase(21)] [TestCase(22)] public void TestGaussLegendreRuleGetAbscissaGetWeightOrderViaIntegration(int order) { GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order); double appoximateArea = 0; for (int i = 0; i < gaussLegendre.Order; i++) { appoximateArea += gaussLegendre.GetWeight(i) * TargetFunctionA(gaussLegendre.GetAbscissa(i)); } double relativeError = Math.Abs(TargetAreaA - appoximateArea) / TargetAreaA; Assert.Less(relativeError, 5e-16); } /// <summary> /// Gauss-Legendre rule supports obtaining array of abscissas/weights. /// </summary> [Test] public void TestGaussLegendreRuleAbscissasWeightsViaIntegration() { const int order = 19; GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order); double[] abscissa = gaussLegendre.Abscissas; double[] weight = gaussLegendre.Weights; for (int i = 0; i < gaussLegendre.Order; i++) { Assert.AreEqual(gaussLegendre.GetAbscissa(i),abscissa[i]); Assert.AreEqual(gaussLegendre.GetWeight(i), weight[i]); } } /// <summary> /// Gauss-Legendre rule supports obtaining IntervalBegin. /// </summary> [Test] public void TestGetGaussLegendreRuleIntervalBegin() { const int order = 19; GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order); Assert.AreEqual(gaussLegendre.IntervalBegin, StartA); } /// <summary> /// Gauss-Legendre rule supports obtaining IntervalEnd. /// </summary> [Test] public void TestGaussLegendreRuleIntervalEnd() { const int order = 19; GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order); Assert.AreEqual(gaussLegendre.IntervalEnd, StopA); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Tests for the ProjectUsingTaskElement class.</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Shared; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using Xunit; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> /// Tests for the ProjectUsingTaskElement class /// </summary> public class ProjectUsingTaskElement_Tests { /// <summary> /// Read project with no usingtasks /// </summary> [Fact] public void ReadNone() { ProjectRootElement project = ProjectRootElement.Create(); Assert.Equal(null, project.UsingTasks.GetEnumerator().Current); } /// <summary> /// Read usingtask with no task name attribute /// </summary> [Fact] public void ReadInvalidMissingTaskName() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask AssemblyFile='af'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with empty task name attribute /// </summary> [Fact] public void ReadInvalidEmptyTaskName() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='' AssemblyFile='af'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with unexpected attribute /// </summary> [Fact] public void ReadInvalidAttribute() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t' AssemblyFile='af' X='Y'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with neither AssemblyFile nor AssemblyName attributes /// </summary> [Fact] public void ReadInvalidMissingAssemblyFileAssemblyName() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with only empty AssemblyFile attribute /// </summary> [Fact] public void ReadInvalidEmptyAssemblyFile() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t' AssemblyFile=''/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with empty AssemblyFile attribute but AssemblyName present /// </summary> [Fact] public void ReadInvalidEmptyAssemblyFileAndAssemblyNameNotEmpty() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t' AssemblyFile='' AssemblyName='n'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with only empty AssemblyName attribute but AssemblyFile present /// </summary> [Fact] public void ReadInvalidEmptyAssemblyNameAndAssemblyFileNotEmpty() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t' AssemblyName='' AssemblyFile='f'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with both AssemblyName and AssemblyFile attributes /// </summary> [Fact] public void ReadInvalidBothAssemblyFileAssemblyName() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t' AssemblyName='an' AssemblyFile='af'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with both AssemblyName and AssemblyFile attributes but both are empty /// </summary> [Fact] public void ReadInvalidBothEmptyAssemblyFileEmptyAssemblyNameBoth() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t' AssemblyName='' AssemblyFile=''/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read usingtask with assembly file /// </summary> [Fact] public void ReadBasicUsingTaskAssemblyFile() { ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyFile(); Assert.Equal("t1", usingTask.TaskName); Assert.Equal("af", usingTask.AssemblyFile); Assert.Equal(String.Empty, usingTask.AssemblyName); Assert.Equal(String.Empty, usingTask.Condition); } /// <summary> /// Read usingtask with assembly name /// </summary> [Fact] public void ReadBasicUsingTaskAssemblyName() { ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyName(); Assert.Equal("t2", usingTask.TaskName); Assert.Equal(String.Empty, usingTask.AssemblyFile); Assert.Equal("an", usingTask.AssemblyName); Assert.Equal("c", usingTask.Condition); } /// <summary> /// Read usingtask with task factory, required runtime and required platform /// </summary> [Fact] public void ReadBasicUsingTaskFactoryRuntimeAndPlatform() { ProjectUsingTaskElement usingTask = GetUsingTaskFactoryRuntimeAndPlatform(); Assert.Equal("t2", usingTask.TaskName); Assert.Equal(String.Empty, usingTask.AssemblyFile); Assert.Equal("an", usingTask.AssemblyName); Assert.Equal("c", usingTask.Condition); Assert.Equal("AssemblyFactory", usingTask.TaskFactory); } /// <summary> /// Verify that passing in string.empty or null for TaskFactory will remove the element from the xml. /// </summary> [Fact] public void RemoveUsingTaskFactoryRuntimeAndPlatform() { ProjectUsingTaskElement usingTask = GetUsingTaskFactoryRuntimeAndPlatform(); string value = null; VerifyAttributesRemoved(usingTask, value); usingTask = GetUsingTaskFactoryRuntimeAndPlatform(); value = String.Empty; VerifyAttributesRemoved(usingTask, value); } /// <summary> /// Set assembly file on a usingtask that already has assembly file /// </summary> [Fact] public void SetUsingTaskAssemblyFileOnUsingTaskAssemblyFile() { ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyFile(); Helpers.ClearDirtyFlag(usingTask.ContainingProject); usingTask.AssemblyFile = "afb"; Assert.Equal("afb", usingTask.AssemblyFile); Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges); } /// <summary> /// Set assembly name on a usingtask that already has assembly name /// </summary> [Fact] public void SetUsingTaskAssemblyNameOnUsingTaskAssemblyName() { ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyName(); Helpers.ClearDirtyFlag(usingTask.ContainingProject); usingTask.AssemblyName = "anb"; Assert.Equal("anb", usingTask.AssemblyName); Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges); } /// <summary> /// Set assembly file on a usingtask that already has assembly name /// </summary> [Fact] public void SetUsingTaskAssemblyFileOnUsingTaskAssemblyName() { Assert.Throws<InvalidOperationException>(() => { ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyName(); usingTask.AssemblyFile = "afb"; } ); } /// <summary> /// Set assembly name on a usingtask that already has assembly file /// </summary> [Fact] public void SetUsingTaskAssemblyNameOnUsingTaskAssemblyFile() { Assert.Throws<InvalidOperationException>(() => { ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyFile(); usingTask.AssemblyName = "anb"; } ); } /// <summary> /// Set task name /// </summary> [Fact] public void SetTaskName() { ProjectRootElement project = ProjectRootElement.Create(); ProjectUsingTaskElement usingTask = project.AddUsingTask("t", "af", null); Helpers.ClearDirtyFlag(usingTask.ContainingProject); usingTask.TaskName = "tt"; Assert.Equal("tt", usingTask.TaskName); Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges); } /// <summary> /// Set condition /// </summary> [Fact] public void SetCondition() { ProjectRootElement project = ProjectRootElement.Create(); ProjectUsingTaskElement usingTask = project.AddUsingTask("t", "af", null); Helpers.ClearDirtyFlag(usingTask.ContainingProject); usingTask.Condition = "c"; Assert.Equal("c", usingTask.Condition); Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges); } /// <summary> /// Set task factory /// </summary> [Fact] public void SetTaskFactory() { ProjectRootElement project = ProjectRootElement.Create(); ProjectUsingTaskElement usingTask = project.AddUsingTask("t", "af", null); Helpers.ClearDirtyFlag(usingTask.ContainingProject); usingTask.TaskFactory = "AssemblyFactory"; Assert.Equal("AssemblyFactory", usingTask.TaskFactory); Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges); } /// <summary> /// Make sure there is an exception when there are multiple parameter groups in the using task tag. /// </summary> [Fact] public void DuplicateParameterGroup() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'> <ParameterGroup/> <ParameterGroup/> </UsingTask> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); } ); } /// <summary> /// Make sure there is an exception when there are multiple task groups in the using task tag. /// </summary> [Fact] public void DuplicateTaskGroup() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'> <Task/> <Task/> </UsingTask> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); } ); } /// <summary> /// Make sure there is an exception when there is an unknown child /// </summary> [Fact] public void UnknownChild() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'> <IAMUNKNOWN/> </UsingTask> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); } ); } /// <summary> /// Make sure there is an no exception when there are children in the using task /// </summary> [Fact] public void WorksWithChildren() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'> <ParameterGroup> <MyParameter/> </ParameterGroup> <Task> RANDOM GOO </Task> </UsingTask> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children); Assert.NotNull(usingTask); Assert.Equal(2, usingTask.Count); } /// <summary> /// Make sure there is an exception when a parameter group is added but no task factory attribute is on the using task /// </summary> [Fact] public void ExceptionWhenNoTaskFactoryAndHavePG() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c'> <ParameterGroup> <MyParameter/> </ParameterGroup> </UsingTask> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children); Assert.True(false); } ); } /// <summary> /// Make sure there is an exception when a parameter group is added but no task factory attribute is on the using task /// </summary> [Fact] public void ExceptionWhenNoTaskFactoryAndHaveTask() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c'> <Task/> </UsingTask> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children); Assert.True(false); } ); } /// <summary> /// Helper to get a ProjectUsingTaskElement with a task factory, required runtime and required platform /// </summary> private static ProjectUsingTaskElement GetUsingTaskFactoryRuntimeAndPlatform() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory' /> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children); return usingTask; } /// <summary> /// Helper to get a ProjectUsingTaskElement with an assembly file set /// </summary> private static ProjectUsingTaskElement GetUsingTaskAssemblyFile() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t1' AssemblyFile='af' /> <UsingTask TaskName='t2' AssemblyName='an' Condition='c'/> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children); return usingTask; } /// <summary> /// Helper to get a ProjectUsingTaskElement with an assembly name set /// </summary> private static ProjectUsingTaskElement GetUsingTaskAssemblyName() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <UsingTask TaskName='t2' AssemblyName='an' Condition='c'/> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children); return usingTask; } /// <summary> /// Verify the attributes are removed from the xml when string.empty and null are passed in /// </summary> private static void VerifyAttributesRemoved(ProjectUsingTaskElement usingTask, string value) { Assert.True(usingTask.ContainingProject.RawXml.Contains("TaskFactory")); usingTask.TaskFactory = value; Assert.False(usingTask.ContainingProject.RawXml.Contains("TaskFactory")); } } }
/* * 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 copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OMV = OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.PhysicsModules.SharedBase; namespace OpenSim.Region.PhysicsModule.BulletS { public sealed class BSCharacter : BSPhysObject { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS CHAR]"; // private bool _stopped; private bool _grabbed; private bool _selected; private float _mass; private float _avatarVolume; private float _collisionScore; private OMV.Vector3 _acceleration; private int _physicsActorType; private bool _isPhysical; private bool _flying; private bool _setAlwaysRun; private bool _throttleUpdates; private bool _floatOnWater; private bool _kinematic; private float _buoyancy; private OMV.Vector3 _size; private float _footOffset; private BSActorAvatarMove m_moveActor; private const string AvatarMoveActorName = "BSCharacter.AvatarMove"; private OMV.Vector3 _PIDTarget; private float _PIDTau; // public override OMV.Vector3 RawVelocity // { get { return base.RawVelocity; } // set { // if (value != base.RawVelocity) // Util.PrintCallStack(); // Console.WriteLine("Set rawvel to {0}", value); // base.RawVelocity = value; } // } // Avatars are always complete (in the physics engine sense) public override bool IsIncomplete { get { return false; } } public BSCharacter( uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 vel, OMV.Vector3 size, float footOffset, bool isFlying) : base(parent_scene, localID, avName, "BSCharacter") { _physicsActorType = (int)ActorTypes.Agent; RawPosition = pos; _flying = isFlying; RawOrientation = OMV.Quaternion.Identity; RawVelocity = vel; _buoyancy = ComputeBuoyancyFromFlying(isFlying); Friction = BSParam.AvatarStandingFriction; Density = BSParam.AvatarDensity; _isPhysical = true; _footOffset = footOffset; // Adjustments for zero X and Y made in Size() // This also computes avatar scale, volume, and mass SetAvatarSize(size, footOffset, true /* initializing */); DetailLog( "{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6},vel={7}", LocalID, Size, Scale, Density, _avatarVolume, RawMass, pos, vel); // do actual creation in taint time PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); // New body and shape into PhysBody and PhysShape PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this); // The avatar's movement is controlled by this motor that speeds up and slows down // the avatar seeking to reach the motor's target speed. // This motor runs as a prestep action for the avatar so it will keep the avatar // standing as well as moving. Destruction of the avatar will destroy the pre-step action. m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName); PhysicalActors.Add(AvatarMoveActorName, m_moveActor); SetPhysicalProperties(); IsInitialized = true; }); return; } // called when this character is being destroyed and the resources should be released public override void Destroy() { IsInitialized = false; base.Destroy(); DetailLog("{0},BSCharacter.Destroy", LocalID); PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate() { PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */); PhysBody.Clear(); PhysShape.Dereference(PhysScene); PhysShape = new BSShapeNull(); }); } private void SetPhysicalProperties() { PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody); ForcePosition = RawPosition; // Set the velocity if (m_moveActor != null) m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false); ForceVelocity = RawVelocity; TargetVelocity = RawVelocity; // This will enable or disable the flying buoyancy of the avatar. // Needs to be reset especially when an avatar is recreated after crossing a region boundry. Flying = _flying; PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution); PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin); PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); if (BSParam.CcdMotionThreshold > 0f) { PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); } UpdatePhysicalMassProperties(RawMass, false); // Make so capsule does not fall over PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero); // The avatar mover sets some parameters. PhysicalActors.Refresh(); PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT); PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody); // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG); PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION); PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody); // Do this after the object has been added to the world if (BSParam.AvatarToAvatarCollisionsByDefault) PhysBody.collisionType = CollisionType.Avatar; else PhysBody.collisionType = CollisionType.PhantomToOthersAvatar; PhysBody.ApplyCollisionMask(PhysScene); } public override void RequestPhysicsterseUpdate() { base.RequestPhysicsterseUpdate(); } // No one calls this method so I don't know what it could possibly mean public override bool Stopped { get { return false; } } public override OMV.Vector3 Size { get { return _size; } set { setAvatarSize(value, _footOffset); } } // OpenSim 0.9 introduces a common avatar size computation public override void setAvatarSize(OMV.Vector3 size, float feetOffset) { SetAvatarSize(size, feetOffset, false /* initializing */); } // Internal version that, if initializing, doesn't do all the updating of the physics engine public void SetAvatarSize(OMV.Vector3 size, float feetOffset, bool initializing) { OMV.Vector3 newSize = size; if (newSize.IsFinite()) { // Old versions of ScenePresence passed only the height. If width and/or depth are zero, // replace with the default values. if (newSize.X == 0f) newSize.X = BSParam.AvatarCapsuleDepth; if (newSize.Y == 0f) newSize.Y = BSParam.AvatarCapsuleWidth; if (newSize.X < 0.01f) newSize.X = 0.01f; if (newSize.Y < 0.01f) newSize.Y = 0.01f; if (newSize.Z < 0.01f) newSize.Z = BSParam.AvatarCapsuleHeight; } else { newSize = new OMV.Vector3(BSParam.AvatarCapsuleDepth, BSParam.AvatarCapsuleWidth, BSParam.AvatarCapsuleHeight); } // This is how much the avatar size is changing. Positive means getting bigger. // The avatar altitude must be adjusted for this change. float heightChange = newSize.Z - Size.Z; _size = newSize; Scale = ComputeAvatarScale(Size); ComputeAvatarVolumeAndMass(); DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}", LocalID, _size, Scale, Density, _avatarVolume, RawMass); PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate() { if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape) { PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); UpdatePhysicalMassProperties(RawMass, true); // Adjust the avatar's position to account for the increase/decrease in size ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f); // Make sure this change appears as a property update event PhysScene.PE.PushUpdate(PhysBody); } }); } public override PrimitiveBaseShape Shape { set { BaseShape = value; } } public override bool Grabbed { set { _grabbed = value; } } public override bool Selected { set { _selected = value; } } public override bool IsSelected { get { return _selected; } } public override void CrossingFailure() { return; } public override void link(PhysicsActor obj) { return; } public override void delink() { return; } // Set motion values to zero. // Do it to the properties so the values get set in the physics engine. // Push the setting of the values to the viewer. // Called at taint time! public override void ZeroMotion(bool inTaintTime) { RawVelocity = OMV.Vector3.Zero; _acceleration = OMV.Vector3.Zero; RawRotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) PhysScene.PE.ClearAllForces(PhysBody); }); } public override void ZeroAngularMotion(bool inTaintTime) { RawRotationalVelocity = OMV.Vector3.Zero; PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) { PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero); PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero); // The next also get rid of applied linear force but the linear velocity is untouched. PhysScene.PE.ClearForces(PhysBody); } }); } public override void LockAngularMotion(byte axislocks) { return; } public override OMV.Vector3 Position { get { // Don't refetch the position because this function is called a zillion times // RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID); return RawPosition; } set { RawPosition = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); PositionSanityCheck(); ForcePosition = RawPosition; }); } } public override OMV.Vector3 ForcePosition { get { RawPosition = PhysScene.PE.GetPosition(PhysBody); return RawPosition; } set { RawPosition = value; if (PhysBody.HasPhysicalBody) { PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); } } } // Check that the current position is sane and, if not, modify the position to make it so. // Check for being below terrain or on water. // Returns 'true' of the position was made sane by some action. private bool PositionSanityCheck() { bool ret = false; // TODO: check for out of bounds if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition)) { // The character is out of the known/simulated area. // Force the avatar position to be within known. ScenePresence will use the position // plus the velocity to decide if the avatar is moving out of the region. RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition); DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition); return true; } // If below the ground, move the avatar up float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); if (Position.Z < terrainHeight) { DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight); RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters); ret = true; } if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition); if (Position.Z < waterHeight) { RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight); ret = true; } } return ret; } // A version of the sanity check that also makes sure a new position value is // pushed back to the physics engine. This routine would be used by anyone // who is not already pushing the value. private bool PositionSanityCheck(bool inTaintTime) { bool ret = false; if (PositionSanityCheck()) { // The new position value must be pushed into the physics engine but we can't // just assign to "Position" because of potential call loops. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); ForcePosition = RawPosition; }); ret = true; } return ret; } public override float Mass { get { return _mass; } } // used when we only want this prim's mass and not the linkset thing public override float RawMass { get {return _mass; } } public override void UpdatePhysicalMassProperties(float physMass, bool inWorld) { OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia); } public override OMV.Vector3 Force { get { return RawForce; } set { RawForce = value; // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force); PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate() { DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce); if (PhysBody.HasPhysicalBody) PhysScene.PE.SetObjectForce(PhysBody, RawForce); }); } } // Avatars don't do vehicles public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, OMV.Vector3 value) {} public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { } public override void VehicleFlags(int param, bool remove) { } // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more public override void SetVolumeDetect(int param) { return; } public override bool IsVolumeDetect { get { return false; } } public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } } public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } } // PhysicsActor.TargetVelocity // Sets the target in the motor. This starts the changing of the avatar's velocity. public override OMV.Vector3 TargetVelocity { get { return base.m_targetVelocity; } set { DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value); OMV.Vector3 targetVel = value; if (!_flying) { if (_setAlwaysRun) targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f); else if (BSParam.AvatarWalkVelocityFactor != 1f) targetVel *= new OMV.Vector3(BSParam.AvatarWalkVelocityFactor, BSParam.AvatarWalkVelocityFactor, 1f); } base.m_targetVelocity = targetVel; if (m_moveActor != null) m_moveActor.SetVelocityAndTarget(RawVelocity, base.m_targetVelocity, false /* inTaintTime */); } } // Directly setting velocity means this is what the user really wants now. public override OMV.Vector3 Velocity { get { return RawVelocity; } set { if (m_moveActor != null) { // m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */); m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */); } base.Velocity = value; } } // SetMomentum just sets the velocity without a target. We need to stop the movement actor if a character. public override void SetMomentum(OMV.Vector3 momentum) { if (m_moveActor != null) { // m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */); m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */); } base.SetMomentum(momentum); } public override OMV.Vector3 ForceVelocity { get { return RawVelocity; } set { DetailLog("{0},BSCharacter.ForceVelocity.set={1}", LocalID, value); RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity); PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity); PhysScene.PE.Activate(PhysBody, true); } } public override OMV.Vector3 Torque { get { return RawTorque; } set { RawTorque = value; } } public override float CollisionScore { get { return _collisionScore; } set { _collisionScore = value; } } public override OMV.Vector3 Acceleration { get { return _acceleration; } set { _acceleration = value; } } public override OMV.Quaternion Orientation { get { return RawOrientation; } set { // Orientation is set zillions of times when an avatar is walking. It's like // the viewer doesn't trust us. if (RawOrientation != value) { RawOrientation = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate() { // Bullet assumes we know what we are doing when forcing orientation // so it lets us go against all the rules and just compensates for them later. // This forces rotation to be only around the Z axis and doesn't change any of the other axis. // This keeps us from flipping the capsule over which the veiwer does not understand. float oRoll, oPitch, oYaw; RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw); OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw); // DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}", // LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation, // trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation); ForceOrientation = trimmedOrientation; }); } } } // Go directly to Bullet to get/set the value. public override OMV.Quaternion ForceOrientation { get { RawOrientation = PhysScene.PE.GetOrientation(PhysBody); return RawOrientation; } set { RawOrientation = value; if (PhysBody.HasPhysicalBody) { // RawPosition = PhysicsScene.PE.GetPosition(BSBody); PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); } } } public override int PhysicsActorType { get { return _physicsActorType; } set { _physicsActorType = value; } } public override bool IsPhysical { get { return _isPhysical; } set { _isPhysical = value; } } public override bool IsSolid { get { return true; } } public override bool IsStatic { get { return false; } } public override bool IsPhysicallyActive { get { return true; } } public override bool Flying { get { return _flying; } set { _flying = value; // simulate flying by changing the effect of gravity Buoyancy = ComputeBuoyancyFromFlying(_flying); } } // Flying is implimented by changing the avatar's buoyancy. // Would this be done better with a vehicle type? private float ComputeBuoyancyFromFlying(bool ifFlying) { return ifFlying ? 1f : 0f; } public override bool SetAlwaysRun { get { return _setAlwaysRun; } set { _setAlwaysRun = value; } } public override bool ThrottleUpdates { get { return _throttleUpdates; } set { _throttleUpdates = value; } } public override bool FloatOnWater { set { _floatOnWater = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate() { if (PhysBody.HasPhysicalBody) { if (_floatOnWater) CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); else CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); } }); } } public override bool Kinematic { get { return _kinematic; } set { _kinematic = value; } } // neg=fall quickly, 0=1g, 1=0g, pos=float up public override float Buoyancy { get { return _buoyancy; } set { _buoyancy = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); ForceBuoyancy = _buoyancy; }); } } public override float ForceBuoyancy { get { return _buoyancy; } set { _buoyancy = value; DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); // Buoyancy is faked by changing the gravity applied to the object float grav = BSParam.Gravity * (1f - _buoyancy); Gravity = new OMV.Vector3(0f, 0f, grav); if (PhysBody.HasPhysicalBody) PhysScene.PE.SetGravity(PhysBody, Gravity); } } // Used for MoveTo public override OMV.Vector3 PIDTarget { set { _PIDTarget = value; } } public override bool PIDActive { get; set; } public override float PIDTau { set { _PIDTau = value; } } public override void AddForce(OMV.Vector3 force, bool pushforce) { // Since this force is being applied in only one step, make this a force per second. OMV.Vector3 addForce = force; // The interaction of this force with the simulator rate and collision occurance is tricky. // ODE multiplies the force by 100 // ubODE multiplies the force by 5.3 // BulletSim, after much in-world testing, thinks it gets a similar effect by multiplying mass*0.315f // This number could be a feature of friction or timing, but it seems to move avatars the same as ubODE addForce *= Mass * BSParam.AvatarAddForcePushFactor; DetailLog("{0},BSCharacter.addForce,call,force={1},addForce={2},push={3},mass={4}", LocalID, force, addForce, pushforce, Mass); AddForce(false, addForce); } public override void AddForce(bool inTaintTime, OMV.Vector3 force) { if (force.IsFinite()) { OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude); // DetailLog("{0},BSCharacter.addForce,call,force={1},push={2},inTaint={3}", LocalID, addForce, pushforce, inTaintTime); PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate() { // Bullet adds this central force to the total force for this tick // DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce); if (PhysBody.HasPhysicalBody) { // Bullet adds this central force to the total force for this tick. // Deep down in Bullet: // linearVelocity += totalForce / mass * timeStep; PhysScene.PE.ApplyCentralForce(PhysBody, addForce); PhysScene.PE.Activate(PhysBody, true); } if (m_moveActor != null) { m_moveActor.SuppressStationayCheckUntilLowVelocity(); } }); } else { m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID); return; } } public override void AddAngularForce(bool inTaintTime, OMV.Vector3 force) { } // The avatar's physical shape (whether capsule or cube) is unit sized. BulletSim sets // the scale of that unit shape to create the avatars full size. private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size) { OMV.Vector3 newScale = size; if (BSParam.AvatarUseBefore09SizeComputation) { // Bullet's capsule total height is the "passed height + radius * 2"; // The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1) // The number we pass in for 'scaling' is the multiplier to get that base // shape to be the size desired. // So, when creating the scale for the avatar height, we take the passed height // (size.Z) and remove the caps. // An oddity of the Bullet capsule implementation is that it presumes the Y // dimension is the radius of the capsule. Even though some of the code allows // for a asymmetrical capsule, other parts of the code presume it is cylindrical. // Scale is multiplier of radius with one of "0.5" float heightAdjust = BSParam.AvatarHeightMidFudge; if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f) { const float AVATAR_LOW = 1.1f; const float AVATAR_MID = 1.775f; // 1.87f const float AVATAR_HI = 2.45f; // An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m. float midHeightOffset = size.Z - AVATAR_MID; if (midHeightOffset < 0f) { // Small avatar. Add the adjustment based on the distance from midheight heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge; } else { // Large avatar. Add the adjustment based on the distance from midheight heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge; } } if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule) { newScale.X = size.X / 2f; newScale.Y = size.Y / 2f; // The total scale height is the central cylindar plus the caps on the two ends. newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f; } else { newScale.Z = size.Z + heightAdjust; } // m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale); // If smaller than the endcaps, just fake like we're almost that small if (newScale.Z < 0) newScale.Z = 0.1f; DetailLog("{0},BSCharacter.ComputeAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}", LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale); } else { newScale.Z = size.Z + _footOffset; DetailLog("{0},BSCharacter.ComputeAvatarScale,using newScale={1}, footOffset={2}", LocalID, newScale, _footOffset); } return newScale; } // set _avatarVolume and _mass based on capsule size, _density and Scale private void ComputeAvatarVolumeAndMass() { if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule) { _avatarVolume = (float)( Math.PI * Size.X / 2f * Size.Y / 2f // the area of capsule cylinder * Size.Z // times height of capsule cylinder + 1.33333333f * Math.PI * Size.X / 2f * Math.Min(Size.X, Size.Y) / 2 * Size.Y / 2f // plus the volume of the capsule end caps ); } else { _avatarVolume = Size.X * Size.Y * Size.Z; } _mass = Density * BSParam.DensityScaleFactor * _avatarVolume; } // The physics engine says that properties have updated. Update same and inform // the world that things have changed. public override void UpdateProperties(EntityProperties entprop) { // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator. TriggerPreUpdatePropertyAction(ref entprop); RawPosition = entprop.Position; RawOrientation = entprop.Rotation; // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar // and will send agent updates to the clients if velocity changes by more than // 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many // extra updates. // // XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to // avatar movement rather than removes it. The larger the threshold, the bigger the jitter. // This is most noticeable in level flight and can be seen with // the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower // bound and an upper bound, where the difference between the two is enough to trigger a large delta v update // and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?) // has not yet been identified. // // If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra // updates are not triggered in ScenePresence.SendTerseUpdateToAllClients(). // if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f)) RawVelocity = entprop.Velocity; _acceleration = entprop.Acceleration; RawRotationalVelocity = entprop.RotationalVelocity; // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. if (PositionSanityCheck(true)) { DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition); entprop.Position = RawPosition; } // remember the current and last set values LastEntityProperties = CurrentEntityProperties; CurrentEntityProperties = entprop; // Tell the linkset about value changes // Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. // PhysScene.PostUpdate(this); DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, RawRotationalVelocity); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Compute.Tests { public class VMScaleSetScenarioTests : VMScaleSetVMTestsBase { /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet with extension /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations")] public void TestVMScaleSetScenarioOperations() { using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context); } } /// <summary> /// Covers following Operations for ManagedDisks: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet with extension /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ManagedDisks")] public void TestVMScaleSetScenarioOperations_ManagedDisks_PirImage() { using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false); } } /// <summary> /// To record this test case, you need to run it again zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_SingleZone")] public void TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_SingleZone() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, zones: new List<string> { "1" }); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support local diff disks. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_DiffDisks")] public void TestVMScaleSetScenarioOperations_DiffDisks() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardDS5V2, hasManagedDisks: true, hasDiffDisks: true); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support encryption at host /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_EncryptionAtHost")] public void TestVMScaleSetScenarioOperations_EncryptionAtHost() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardDS1V2, hasManagedDisks: true, encryptionAtHostEnabled: true); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support DiskEncryptionSet resource for the Disks /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_With_DiskEncryptionSet")] public void TestVMScaleSetScenarioOperations_With_DiskEncryptionSet() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { string diskEncryptionSetId = getDefaultDiskEncryptionSetId(); Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardA1V2, hasManagedDisks: true, osDiskSizeInGB: 175, diskEncryptionSetId: diskEncryptionSetId); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_UltraSSD")] public void TestVMScaleSetScenarioOperations_UltraSSD() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardE4sV3, hasManagedDisks: true, useVmssExtension: false, zones: new List<string> { "1" }, enableUltraSSD: true, osDiskSizeInGB: 175); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it again zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_Zones")] public void TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_Zones() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal( context, hasManagedDisks: true, useVmssExtension: false, zones: new List<string> { "1", "3" }, osDiskSizeInGB: 175); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it again zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_PpgScenario")] public void TestVMScaleSetScenarioOperations_PpgScenario() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, isPpgScenario: true); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_AutomaticPlacementOnDedicatedHostGroup")] public void TestVMScaleSetScenarioOperations_AutomaticPlacementOnDedicatedHostGroup() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); // This test was recorded in WestUSValidation, where the platform image typically used for recording is not available. // Hence the following custom image was used. //ImageReference imageReference = new ImageReference //{ // Publisher = "AzureRT.PIRCore.TestWAStage", // Offer = "TestUbuntuServer", // Sku = "16.04", // Version = "latest" //}; //using (MockContext context = MockContext.Start(this.GetType())) //{ // TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, isAutomaticPlacementOnDedicatedHostGroupScenario: true, // vmSize: VirtualMachineSizeTypes.StandardD2sV3, faultDomainCount: 1, capacity: 1, shouldOverProvision: false, // validateVmssVMInstanceView: true, imageReference: imageReference, validateListSku: false, deleteAsPartOfTest: false); //} using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, isAutomaticPlacementOnDedicatedHostGroupScenario: true, vmSize: VirtualMachineSizeTypes.StandardD2sV3, faultDomainCount: 1, capacity: 1, shouldOverProvision: false, validateVmssVMInstanceView: true, validateListSku: false, deleteAsPartOfTest: false); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ScheduledEvents")] public void TestVMScaleSetScenarioOperations_ScheduledEvents() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, vmScaleSetCustomizer: vmScaleSet => { vmScaleSet.VirtualMachineProfile.ScheduledEventsProfile = new ScheduledEventsProfile { TerminateNotificationProfile = new TerminateNotificationProfile { Enable = true, NotBeforeTimeout = "PT6M", } }; }, vmScaleSetValidator: vmScaleSet => { Assert.True(true == vmScaleSet.VirtualMachineProfile.ScheduledEventsProfile?.TerminateNotificationProfile?.Enable); Assert.True("PT6M" == vmScaleSet.VirtualMachineProfile.ScheduledEventsProfile?.TerminateNotificationProfile?.NotBeforeTimeout); }); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_AutomaticRepairsPolicyTest")] public void TestVMScaleSetScenarioOperations_AutomaticRepairsPolicyTest() { string environmentVariable = "AZURE_VM_TEST_LOCATION"; string region = "eastus"; string originalTestLocation = Environment.GetEnvironmentVariable(environmentVariable); try { using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable(environmentVariable, region); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // Set Automatic Repairs to true inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = true }; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(getResponse.AutomaticRepairsPolicy); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // Update Automatic Repairs default values inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = true, GracePeriod = "PT35M" }; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(getResponse.AutomaticRepairsPolicy); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // Set automatic repairs to null inputVMScaleSet.AutomaticRepairsPolicy = null; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); Assert.NotNull(getResponse.AutomaticRepairsPolicy); Assert.True(getResponse.AutomaticRepairsPolicy.Enabled == true); Assert.Equal("PT35M", getResponse.AutomaticRepairsPolicy.GracePeriod, ignoreCase: true); // Disable Automatic Repairs inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = false }; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(getResponse.AutomaticRepairsPolicy); Assert.True(getResponse.AutomaticRepairsPolicy.Enabled == false); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_OrchestrationService")] public void TestVMScaleSetScenarioOperations_OrchestrationService() { string environmentVariable = "AZURE_VM_TEST_LOCATION"; string region = "eastus"; string originalTestLocation = Environment.GetEnvironmentVariable(environmentVariable); try { using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable(environmentVariable, region); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); AutomaticRepairsPolicy automaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = true }; var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true, automaticRepairsPolicy: automaticRepairsPolicy); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.True(getInstanceViewResponse.OrchestrationServices.Count == 1); Assert.Equal("Running", getInstanceViewResponse.OrchestrationServices[0].ServiceState); Assert.Equal("AutomaticRepairs", getInstanceViewResponse.OrchestrationServices[0].ServiceName); OrchestrationServiceStateInput orchestrationServiceStateInput = new OrchestrationServiceStateInput() { ServiceName = OrchestrationServiceNames.AutomaticRepairs, Action = OrchestrationServiceStateAction.Suspend }; m_CrpClient.VirtualMachineScaleSets.SetOrchestrationServiceState(rgName, vmssName, orchestrationServiceStateInput); getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.Equal(OrchestrationServiceState.Suspended.ToString(), getInstanceViewResponse.OrchestrationServices[0].ServiceState); orchestrationServiceStateInput.Action = OrchestrationServiceStateAction.Resume; m_CrpClient.VirtualMachineScaleSets.SetOrchestrationServiceState(rgName, vmssName, orchestrationServiceStateInput); getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.Equal(OrchestrationServiceState.Running.ToString(), getInstanceViewResponse.OrchestrationServices[0].ServiceState); //m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } private void TestScaleSetOperationsInternal(MockContext context, string vmSize = null, bool hasManagedDisks = false, bool useVmssExtension = true, bool hasDiffDisks = false, IList<string> zones = null, int? osDiskSizeInGB = null, bool isPpgScenario = false, bool? enableUltraSSD = false, Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null, Action<VirtualMachineScaleSet> vmScaleSetValidator = null, string diskEncryptionSetId = null, bool? encryptionAtHostEnabled = null, bool isAutomaticPlacementOnDedicatedHostGroupScenario = false, int? faultDomainCount = null, int? capacity = null, bool shouldOverProvision = true, bool validateVmssVMInstanceView = false, ImageReference imageReference = null, bool validateListSku = true, bool deleteAsPartOfTest = true) { EnsureClientsInitialized(context); ImageReference imageRef = imageReference ?? GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { GetTestVMSSVMExtension(autoUpdateMinorVersion:false), } }; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); string ppgId = null; string ppgName = null; if (isPpgScenario) { ppgName = ComputeManagementTestUtilities.GenerateName("ppgtest"); ppgId = CreateProximityPlacementGroup(rgName, ppgName); } string dedicatedHostGroupName = null, dedicatedHostName = null, dedicatedHostGroupReferenceId = null, dedicatedHostReferenceId = null; if (isAutomaticPlacementOnDedicatedHostGroupScenario) { dedicatedHostGroupName = ComputeManagementTestUtilities.GenerateName("dhgtest"); dedicatedHostName = ComputeManagementTestUtilities.GenerateName("dhtest"); dedicatedHostGroupReferenceId = Helpers.GetDedicatedHostGroupRef(m_subId, rgName, dedicatedHostGroupName); dedicatedHostReferenceId = Helpers.GetDedicatedHostRef(m_subId, rgName, dedicatedHostGroupName, dedicatedHostName); } VirtualMachineScaleSet getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, useVmssExtension ? extensionProfile : null, (vmScaleSet) => { vmScaleSet.Overprovision = shouldOverProvision; if (!String.IsNullOrEmpty(vmSize)) { vmScaleSet.Sku.Name = vmSize; } vmScaleSetCustomizer?.Invoke(vmScaleSet); }, createWithManagedDisks: hasManagedDisks, hasDiffDisks : hasDiffDisks, zones: zones, osDiskSizeInGB: osDiskSizeInGB, ppgId: ppgId, enableUltraSSD: enableUltraSSD, diskEncryptionSetId: diskEncryptionSetId, encryptionAtHostEnabled: encryptionAtHostEnabled, faultDomainCount: faultDomainCount, capacity: capacity, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId, dedicatedHostGroupName: dedicatedHostGroupName, dedicatedHostName: dedicatedHostName); if (diskEncryptionSetId != null) { Assert.True(getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != null, "OsDisk.ManagedDisk.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "OsDisk.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource"); Assert.Equal(1, getResponse.VirtualMachineProfile.StorageProfile.DataDisks.Count); Assert.True(getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet != null, ".DataDisks.ManagedDisk.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "DataDisks.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource"); } if (encryptionAtHostEnabled != null) { Assert.True(getResponse.VirtualMachineProfile.SecurityProfile.EncryptionAtHost == encryptionAtHostEnabled.Value, "SecurityProfile.EncryptionAtHost is not same as expected"); } ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks, ppgId: ppgId, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.NotNull(getInstanceViewResponse); ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse); if (isPpgScenario) { ProximityPlacementGroup outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(rgName, ppgName); Assert.Equal(1, outProximityPlacementGroup.VirtualMachineScaleSets.Count); string expectedVmssReferenceId = Helpers.GetVMScaleSetReferenceId(m_subId, rgName, vmssName); Assert.Equal(expectedVmssReferenceId, outProximityPlacementGroup.VirtualMachineScaleSets.First().Id, StringComparer.OrdinalIgnoreCase); } var listResponse = m_CrpClient.VirtualMachineScaleSets.List(rgName); ValidateVMScaleSet(inputVMScaleSet, listResponse.FirstOrDefault(x => x.Name == vmssName), hasManagedDisks); if (validateListSku) { var listSkusResponse = m_CrpClient.VirtualMachineScaleSets.ListSkus(rgName, vmssName); Assert.NotNull(listSkusResponse); Assert.False(listSkusResponse.Count() == 0); } if (zones != null) { var query = new Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineScaleSetVM>(); query.SetFilter(vm => vm.LatestModelApplied == true); var listVMsResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query); Assert.False(listVMsResponse == null, "VMScaleSetVMs not returned"); Assert.True(listVMsResponse.Count() == inputVMScaleSet.Sku.Capacity); foreach (var vmScaleSetVM in listVMsResponse) { string instanceId = vmScaleSetVM.InstanceId; var getVMResponse = m_CrpClient.VirtualMachineScaleSetVMs.Get(rgName, vmssName, instanceId); ValidateVMScaleSetVM(inputVMScaleSet, instanceId, getVMResponse, hasManagedDisks); } } if (validateVmssVMInstanceView) { VirtualMachineScaleSetVMInstanceView vmssVMInstanceView = m_CrpClient.VirtualMachineScaleSetVMs.GetInstanceView(rgName, vmssName, "0"); ValidateVMScaleSetVMInstanceView(vmssVMInstanceView, hasManagedDisks, dedicatedHostReferenceId); } vmScaleSetValidator?.Invoke(getResponse); if (deleteAsPartOfTest) { m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName); } } finally { if (deleteAsPartOfTest) { m_ResourcesClient.ResourceGroups.Delete(rgName); } else { // Fire and forget. No need to wait for RG deletion completion m_ResourcesClient.ResourceGroups.BeginDelete(rgName); } } } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Text; using MLifter.DAL.Interfaces.DB; using MLifter.DAL.Interfaces; using MLifter.DAL.Tools; using MLifter.Generics; using NpgsqlTypes; using Npgsql; using System.IO; namespace MLifter.DAL.DB.PostgreSQL { /// <summary> /// /// </summary> /// <remarks>Documented by Dev08, 2009-07-02</remarks> public class PgSqlExtensionConnector : IDbExtensionConnector { private static Dictionary<ConnectionStringStruct, PgSqlExtensionConnector> instances = new Dictionary<ConnectionStringStruct, PgSqlExtensionConnector>(); /// <summary> /// Gets the instance. /// </summary> /// <param name="parentClass">The parent class.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2009-07-02</remarks> public static PgSqlExtensionConnector GetInstance(ParentClass parentClass) { ConnectionStringStruct connection = parentClass.CurrentUser.ConnectionString; if (!instances.ContainsKey(connection)) instances.Add(connection, new PgSqlExtensionConnector(parentClass)); return instances[connection]; } private ParentClass Parent; private PgSqlExtensionConnector(ParentClass parentClass) { Parent = parentClass; Parent.DictionaryClosed += new EventHandler(Parent_DictionaryClosed); } private void Parent_DictionaryClosed(object sender, EventArgs e) { IParent parent = sender as IParent; instances.Remove(parent.Parent.CurrentUser.ConnectionString); } /// <summary> /// The size of chunks to read from the db at once. /// </summary> private readonly int chunkSize = 204800; //200 KB /// <summary> /// Writes the content of a buffer into a LargeObject. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="largeObject">The large object.</param> /// <remarks>Documented by Dev02, 2008-08-08</remarks> private void BufferToLargeObject(byte[] buffer, LargeObject largeObject) { largeObject.Seek(0); int offset = 0; int size = buffer.Length; while (offset < size) { largeObject.Write(buffer, offset, Math.Min(chunkSize, size - offset)); offset += chunkSize; } } /// <summary> /// Writes the content of a buffer into a LargeObject. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="largeObject">The large object.</param> /// <param name="rpu">The rpu.</param> /// <param name="caller">The calling object.</param> /// <remarks>Documented by Dev02, 2008-08-08</remarks> private void BufferToLargeObject(byte[] buffer, LargeObject largeObject, StatusMessageReportProgress rpu, object caller) { largeObject.Seek(0); int offset = 0; int size = buffer.Length; StatusMessageEventArgs args = new StatusMessageEventArgs(StatusMessageType.CreateMediaProgress, buffer.Length); while (offset < size) { largeObject.Write(buffer, offset, Math.Min(chunkSize, size - offset)); offset += chunkSize; args.Progress = offset; if (rpu != null) rpu(args, caller); } } /// <summary> /// Gets the contents of a LargeObject into a buffer. /// </summary> /// <param name="largeObject">The large object.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-08-08</remarks> private byte[] LargeObjectToBuffer(LargeObject largeObject) { largeObject.Seek(0); int size = largeObject.Size(); byte[] buffer = new byte[size]; int offset = 0; while (offset < size) { largeObject.Read(buffer, offset, Math.Min(chunkSize, size - offset)); offset += chunkSize; } return buffer; } #region IDbExtensionConnector Members /// <summary> /// Adds the new extension. /// </summary> /// <returns></returns> public Guid AddNewExtension() { Guid newGuid = Guid.NewGuid(); return AddNewExtension(newGuid); } /// <summary> /// Adds the new extension. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public Guid AddNewExtension(Guid guid) { DeleteExtension(guid); using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "INSERT INTO \"Extensions\" (guid, name, version, type, data) VALUES (:guid, '', '', :type, 0)"; cmd.Parameters.Add("guid", guid.ToString()); cmd.Parameters.Add("type", ExtensionType.Unknown.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); return guid; } } } /// <summary> /// Sets the extension LM. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="lmid">The lmid.</param> public void SetExtensionLM(Guid guid, int lmid) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"Extensions\" SET lm_id=:lmid WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); cmd.Parameters.Add("lmid", lmid); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } } } /// <summary> /// Deletes the extension. /// </summary> /// <param name="guid">The GUID.</param> public void DeleteExtension(Guid guid) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "DELETE FROM \"Extensions\" WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } } } /// <summary> /// Gets the name of the extension. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public string GetExtensionName(Guid guid) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT name FROM \"Extensions\" WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); return PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser).ToString(); } } } /// <summary> /// Sets the name of the extension. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="extensionName">Name of the extension.</param> public void SetExtensionName(Guid guid, string extensionName) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"Extensions\" SET name=:name WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); cmd.Parameters.Add("name", extensionName); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } } } /// <summary> /// Gets the extension version. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public Version GetExtensionVersion(Guid guid) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT version FROM \"Extensions\" WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); return new Version(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser).ToString()); } } } /// <summary> /// Sets the extension version. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="versionName">Name of the version.</param> public void SetExtensionVersion(Guid guid, Version versionName) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"Extensions\" SET version=:version WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); cmd.Parameters.Add("version", versionName.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } } } /// <summary> /// Gets the type of the extension. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public ExtensionType GetExtensionType(Guid guid) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT type FROM \"Extensions\" WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); try { return (ExtensionType)Enum.Parse(typeof(ExtensionType), PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser).ToString()); } catch (ArgumentException) { return ExtensionType.Unknown; } } } } /// <summary> /// Sets the type of the extension. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="extensionType">Type of the extension.</param> public void SetExtensionType(Guid guid, ExtensionType extensionType) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"Extensions\" SET type=:type WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); cmd.Parameters.Add("type", extensionType.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } } } /// <summary> /// Gets the extension start file. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public string GetExtensionStartFile(Guid guid) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT startfile FROM \"Extensions\" WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); return PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser).ToString(); } } } /// <summary> /// Sets the extension start file. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="startFile">The start file.</param> public void SetExtensionStartFile(Guid guid, string startFile) { if (startFile == null) startFile = string.Empty; using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"Extensions\" SET startfile=:startfile WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); cmd.Parameters.Add("startfile", startFile); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } } } /// <summary> /// Gets the extension stream. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public Stream GetExtensionStream(Guid guid) { MemoryStream stream = null; using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { int noid = 0; using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT data FROM \"Extensions\" WHERE guid=:guid;"; cmd.Parameters.Add("guid", guid.ToString()); object obj = PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser); if (obj == null || obj == DBNull.Value || !(obj as long?).HasValue) return stream; noid = Convert.ToInt32((obj as long?).Value); } NpgsqlTransaction tran = con.BeginTransaction(); try { LargeObjectManager lbm = new LargeObjectManager(con); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); byte[] buffer = LargeObjectToBuffer(largeObject); stream = new MemoryStream(buffer); largeObject.Close(); } catch { } finally { tran.Commit(); } } return stream; } /// <summary> /// Sets the extension stream. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="extensionStream">The extension stream.</param> public void SetExtensionStream(Guid guid, Stream extensionStream) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { NpgsqlTransaction tran = con.BeginTransaction(); LargeObjectManager lbm = new LargeObjectManager(con); int noid = lbm.Create(LargeObjectManager.READWRITE); LargeObject largeObject = lbm.Open(noid, LargeObjectManager.READWRITE); byte[] buffer = new byte[extensionStream.Length]; extensionStream.Read(buffer, 0, (int)extensionStream.Length); BufferToLargeObject(buffer, largeObject); largeObject.Close(); using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"Extensions\" SET data=:data WHERE guid=:guid"; cmd.Parameters.Add("data", noid); cmd.Parameters.Add("guid", guid.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } tran.Commit(); } } /// <summary> /// Determines whether the stream is available. /// </summary> /// <param name="guid">The GUID.</param> /// <returns> /// <c>true</c> if stream is available; otherwise, <c>false</c>. /// </returns> public bool IsStreamAvailable(Guid guid) { return true; } /// <summary> /// Gets the extension actions. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public IList<ExtensionAction> GetExtensionActions(Guid guid) { List<ExtensionAction> actions = new List<ExtensionAction>(); using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT action, execution FROM \"ExtensionActions\" WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser); while (reader.Read()) { ExtensionAction action = new ExtensionAction(); action.Kind = (ExtensionActionKind)Enum.Parse(typeof(ExtensionActionKind), Convert.ToString(reader["action"])); action.Execution = (ExtensionActionExecution)Enum.Parse(typeof(ExtensionActionExecution), Convert.ToString(reader["execution"])); actions.Add(action); } } } return actions; } /// <summary> /// Sets the extension actions. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="extensionActions">The extension actions.</param> public void SetExtensionActions(Guid guid, IList<ExtensionAction> extensionActions) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { NpgsqlTransaction tran = con.BeginTransaction(); using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "DELETE FROM \"ExtensionActions\" WHERE guid=:guid"; cmd.Parameters.Add("guid", guid.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } foreach (ExtensionAction action in extensionActions) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "INSERT INTO \"ExtensionActions\" (guid, action, execution) VALUES (:guid, :action, :execution)"; cmd.Parameters.Add("guid", guid.ToString()); cmd.Parameters.Add("action", action.Kind.ToString()); cmd.Parameters.Add("execution", action.Execution.ToString()); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); } } tran.Commit(); } } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Audit Data Changes Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class QSADDataSet : EduHubDataSet<QSAD> { /// <inheritdoc /> public override string Name { get { return "QSAD"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal QSADDataSet(EduHubContext Context) : base(Context) { Index_QSADKEY = new Lazy<Dictionary<int, QSAD>>(() => this.ToDictionary(i => i.QSADKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="QSAD" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="QSAD" /> fields for each CSV column header</returns> internal override Action<QSAD, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<QSAD, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "QSADKEY": mapper[i] = (e, v) => e.QSADKEY = int.Parse(v); break; case "TABLE_NAME": mapper[i] = (e, v) => e.TABLE_NAME = v; break; case "COLUMN_NAME": mapper[i] = (e, v) => e.COLUMN_NAME = v; break; case "CHANGE_TYPE": mapper[i] = (e, v) => e.CHANGE_TYPE = v; break; case "RECORD_KEY_VALUE": mapper[i] = (e, v) => e.RECORD_KEY_VALUE = v; break; case "RECORD_DESCRIPTION": mapper[i] = (e, v) => e.RECORD_DESCRIPTION = v; break; case "BEFORE_VALUE": mapper[i] = (e, v) => e.BEFORE_VALUE = v; break; case "AFTER_VALUE": mapper[i] = (e, v) => e.AFTER_VALUE = v; break; case "USER_NAME": mapper[i] = (e, v) => e.USER_NAME = v; break; case "CHANGE_TIMESTAMP": mapper[i] = (e, v) => e.CHANGE_TIMESTAMP = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="QSAD" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="QSAD" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="QSAD" /> entities</param> /// <returns>A merged <see cref="IEnumerable{QSAD}"/> of entities</returns> internal override IEnumerable<QSAD> ApplyDeltaEntities(IEnumerable<QSAD> Entities, List<QSAD> DeltaEntities) { HashSet<int> Index_QSADKEY = new HashSet<int>(DeltaEntities.Select(i => i.QSADKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.QSADKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_QSADKEY.Remove(entity.QSADKEY); if (entity.QSADKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, QSAD>> Index_QSADKEY; #endregion #region Index Methods /// <summary> /// Find QSAD by QSADKEY field /// </summary> /// <param name="QSADKEY">QSADKEY value used to find QSAD</param> /// <returns>Related QSAD entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public QSAD FindByQSADKEY(int QSADKEY) { return Index_QSADKEY.Value[QSADKEY]; } /// <summary> /// Attempt to find QSAD by QSADKEY field /// </summary> /// <param name="QSADKEY">QSADKEY value used to find QSAD</param> /// <param name="Value">Related QSAD entity</param> /// <returns>True if the related QSAD entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByQSADKEY(int QSADKEY, out QSAD Value) { return Index_QSADKEY.Value.TryGetValue(QSADKEY, out Value); } /// <summary> /// Attempt to find QSAD by QSADKEY field /// </summary> /// <param name="QSADKEY">QSADKEY value used to find QSAD</param> /// <returns>Related QSAD entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public QSAD TryFindByQSADKEY(int QSADKEY) { QSAD value; if (Index_QSADKEY.Value.TryGetValue(QSADKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a QSAD table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QSAD]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[QSAD]( [QSADKEY] int IDENTITY NOT NULL, [TABLE_NAME] varchar(10) NULL, [COLUMN_NAME] varchar(32) NULL, [CHANGE_TYPE] varchar(1) NULL, [RECORD_KEY_VALUE] varchar(20) NULL, [RECORD_DESCRIPTION] varchar(60) NULL, [BEFORE_VALUE] varchar(255) NULL, [AFTER_VALUE] varchar(255) NULL, [USER_NAME] varchar(128) NULL, [CHANGE_TIMESTAMP] datetime NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [QSAD_Index_QSADKEY] PRIMARY KEY CLUSTERED ( [QSADKEY] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="QSADDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="QSADDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="QSAD"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="QSAD"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<QSAD> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_QSADKEY = new List<int>(); foreach (var entity in Entities) { Index_QSADKEY.Add(entity.QSADKEY); } builder.AppendLine("DELETE [dbo].[QSAD] WHERE"); // Index_QSADKEY builder.Append("[QSADKEY] IN ("); for (int index = 0; index < Index_QSADKEY.Count; index++) { if (index != 0) builder.Append(", "); // QSADKEY var parameterQSADKEY = $"@p{parameterIndex++}"; builder.Append(parameterQSADKEY); command.Parameters.Add(parameterQSADKEY, SqlDbType.Int).Value = Index_QSADKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the QSAD data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the QSAD data set</returns> public override EduHubDataSetDataReader<QSAD> GetDataSetDataReader() { return new QSADDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the QSAD data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the QSAD data set</returns> public override EduHubDataSetDataReader<QSAD> GetDataSetDataReader(List<QSAD> Entities) { return new QSADDataReader(new EduHubDataSetLoadedReader<QSAD>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class QSADDataReader : EduHubDataSetDataReader<QSAD> { public QSADDataReader(IEduHubDataSetReader<QSAD> Reader) : base (Reader) { } public override int FieldCount { get { return 13; } } public override object GetValue(int i) { switch (i) { case 0: // QSADKEY return Current.QSADKEY; case 1: // TABLE_NAME return Current.TABLE_NAME; case 2: // COLUMN_NAME return Current.COLUMN_NAME; case 3: // CHANGE_TYPE return Current.CHANGE_TYPE; case 4: // RECORD_KEY_VALUE return Current.RECORD_KEY_VALUE; case 5: // RECORD_DESCRIPTION return Current.RECORD_DESCRIPTION; case 6: // BEFORE_VALUE return Current.BEFORE_VALUE; case 7: // AFTER_VALUE return Current.AFTER_VALUE; case 8: // USER_NAME return Current.USER_NAME; case 9: // CHANGE_TIMESTAMP return Current.CHANGE_TIMESTAMP; case 10: // LW_DATE return Current.LW_DATE; case 11: // LW_TIME return Current.LW_TIME; case 12: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // TABLE_NAME return Current.TABLE_NAME == null; case 2: // COLUMN_NAME return Current.COLUMN_NAME == null; case 3: // CHANGE_TYPE return Current.CHANGE_TYPE == null; case 4: // RECORD_KEY_VALUE return Current.RECORD_KEY_VALUE == null; case 5: // RECORD_DESCRIPTION return Current.RECORD_DESCRIPTION == null; case 6: // BEFORE_VALUE return Current.BEFORE_VALUE == null; case 7: // AFTER_VALUE return Current.AFTER_VALUE == null; case 8: // USER_NAME return Current.USER_NAME == null; case 9: // CHANGE_TIMESTAMP return Current.CHANGE_TIMESTAMP == null; case 10: // LW_DATE return Current.LW_DATE == null; case 11: // LW_TIME return Current.LW_TIME == null; case 12: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // QSADKEY return "QSADKEY"; case 1: // TABLE_NAME return "TABLE_NAME"; case 2: // COLUMN_NAME return "COLUMN_NAME"; case 3: // CHANGE_TYPE return "CHANGE_TYPE"; case 4: // RECORD_KEY_VALUE return "RECORD_KEY_VALUE"; case 5: // RECORD_DESCRIPTION return "RECORD_DESCRIPTION"; case 6: // BEFORE_VALUE return "BEFORE_VALUE"; case 7: // AFTER_VALUE return "AFTER_VALUE"; case 8: // USER_NAME return "USER_NAME"; case 9: // CHANGE_TIMESTAMP return "CHANGE_TIMESTAMP"; case 10: // LW_DATE return "LW_DATE"; case 11: // LW_TIME return "LW_TIME"; case 12: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "QSADKEY": return 0; case "TABLE_NAME": return 1; case "COLUMN_NAME": return 2; case "CHANGE_TYPE": return 3; case "RECORD_KEY_VALUE": return 4; case "RECORD_DESCRIPTION": return 5; case "BEFORE_VALUE": return 6; case "AFTER_VALUE": return 7; case "USER_NAME": return 8; case "CHANGE_TIMESTAMP": return 9; case "LW_DATE": return 10; case "LW_TIME": return 11; case "LW_USER": return 12; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using OxyPlot.Xamarin.Android; using OxyPlot; using OxyPlot.Axes; using OxyPlot.Series; namespace AndroidApp { public interface IGraphFactory { PlotModel createGraph(GraphType graphType, GraphEffect graphEffect, GraphData graphData); } public class TupleCompareClass : IComparer<Tuple<string, float>> { public int Compare(Tuple<string, float> x, Tuple<string, float> y) { if (x.Item2 < y.Item2) { return 1; } else if (x.Item2 == y.Item2) { return 0; } else { return -1; } } } public class GraphData { public string graphTitle; public string xTitle; public string yTitle; public List<Tuple<string, float>> dataCollection; public GraphData(string GraphTitle, string XTitle, string YTitle, List<Tuple<string, float>> DataCollection) { this.graphTitle = GraphTitle; this.xTitle = XTitle; this.yTitle = YTitle; this.dataCollection = DataCollection; } } public enum GraphType { Bar, Line, Pie } public class GraphEffect { } public abstract class Graph { public GraphType graphType; public GraphEffect graphEffect; public GraphData graphData; protected Graph(GraphType GraphType, GraphEffect GraphEffect, GraphData GraphData) { this.graphType = GraphType; this.graphEffect = GraphEffect; this.graphData = GraphData; } public abstract PlotModel createChart(); } public class BarChart : Graph { public BarChart(GraphType GraphType, GraphEffect GraphEffect, GraphData GraphData) : base(GraphType, GraphEffect, GraphData) { this.createChart(); } public override PlotModel createChart() { var model = new PlotModel { Title = base.graphData.graphTitle, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter, LegendOrientation = LegendOrientation.Horizontal, LegendBorderThickness = 0 }; var s1 = new BarSeries { Title = base.graphData.graphTitle, StrokeColor = OxyColors.Black, StrokeThickness = 1 }; var categoryAxis = new CategoryAxis { Position = AxisPosition.Left }; graphData.dataCollection.Sort(new TupleCompareClass().Compare); for (int i = 0; i < 5; i++) { s1.Items.Add(new BarItem { Value = graphData.dataCollection.ElementAt(i).Item2 }); categoryAxis.Labels.Add(graphData.dataCollection.ElementAt(i).Item1); } var valueAxis = new LinearAxis { Position = AxisPosition.Bottom, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0 }; model.Series.Add(s1); model.Axes.Add(categoryAxis); model.Axes.Add(valueAxis); return model; } } public class LineChart : Graph { public LineChart(GraphType GraphType, GraphEffect GraphEffect, GraphData GraphData) : base(GraphType, GraphEffect, GraphData) { this.createChart(); } public override PlotModel createChart() { var plotModel = new PlotModel { Title = "OxyPlot Demo" }; plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Maximum = 10, Minimum = 0 }); var series1 = new LineSeries { MarkerType = MarkerType.Circle, MarkerSize = 4, MarkerStroke = OxyColors.White }; series1.Points.Add(new DataPoint(0.0, 6.0)); series1.Points.Add(new DataPoint(0.2, 6.0)); series1.Points.Add(new DataPoint(0.3, 6.0)); series1.Points.Add(new DataPoint(0.4, 6.0)); series1.Points.Add(new DataPoint(0.5, 6.0)); series1.Points.Add(new DataPoint(0.6, 6.0)); series1.Points.Add(new DataPoint(0.7, 6.0)); series1.Points.Add(new DataPoint(0.8, 6.0)); series1.Points.Add(new DataPoint(0.9, 6.0)); series1.Points.Add(new DataPoint(1.0, 6.0)); series1.Points.Add(new DataPoint(1.4, 2.1)); series1.Points.Add(new DataPoint(2.0, 4.2)); series1.Points.Add(new DataPoint(3.3, 2.3)); series1.Points.Add(new DataPoint(4.7, 7.4)); series1.Points.Add(new DataPoint(6.0, 6.2)); series1.Points.Add(new DataPoint(8.9, 8.9)); plotModel.Series.Add(series1); return plotModel; } } public class PieChart : Graph { public PieChart(GraphType GraphType, GraphEffect GraphEffect, GraphData GraphData) : base(GraphType, GraphEffect, GraphData) { this.createChart(); } public override PlotModel createChart() { PlotModel model = new PlotModel { Title = "Pie Sample1" }; var seriesP1 = new PieSeries { StrokeThickness = 2.0, InsideLabelPosition = 0.8, AngleSpan = 360, StartAngle = 0 }; seriesP1.Slices.Add(new PieSlice("Africa", 1030) { IsExploded = false, Fill = OxyColors.PaleVioletRed }); seriesP1.Slices.Add(new PieSlice("Americas", 929) { IsExploded = true }); seriesP1.Slices.Add(new PieSlice("Asia", 4157) { IsExploded = true }); seriesP1.Slices.Add(new PieSlice("Europe", 739) { IsExploded = true }); seriesP1.Slices.Add(new PieSlice("Oceania", 35) { IsExploded = true }); model.Series.Add(seriesP1); return model; } } public class GraphFactory : IGraphFactory { Graph Chart; public PlotModel createGraph(GraphType graphType, GraphEffect graphEffect, GraphData graphData) { switch (graphType) { case GraphType.Line: Chart = new LineChart(graphType, graphEffect, graphData); break; case GraphType.Pie: Chart = new PieChart(graphType, graphEffect, graphData); break; default: Chart = new BarChart(graphType, graphEffect, graphData); break; } return Chart.createChart(); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Moq; using Newtonsoft.Json; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.PropertyEditors { [TestFixture] public class BlockEditorComponentTests { private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, }; private const string ContentGuid1 = "036ce82586a64dfba2d523a99ed80f58"; private const string ContentGuid2 = "48288c21a38a40ef82deb3eda90a58f6"; private const string SettingsGuid1 = "ffd35c4e2eea4900abfa5611b67b2492"; private const string SubContentGuid1 = "4c44ce6b3a5c4f5f8f15e3dc24819a9e"; private const string SubContentGuid2 = "a062c06d6b0b44ac892b35d90309c7f8"; private const string SubSettingsGuid1 = "4d998d980ffa4eee8afdc23c4abd6d29"; private static readonly ILogger<BlockEditorPropertyHandler> s_logger = Mock.Of<ILogger<BlockEditorPropertyHandler>>(); [Test] public void Cannot_Have_Null_Udi() { var component = new BlockEditorPropertyHandler(s_logger); var json = GetBlockListJson(null, string.Empty); Assert.Throws<FormatException>(() => component.ReplaceBlockListUdis(json)); } [Test] public void No_Nesting() { var guids = Enumerable.Range(0, 3).Select(x => Guid.NewGuid()).ToList(); var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; var json = GetBlockListJson(null); var expected = ReplaceGuids(json, guids, ContentGuid1, ContentGuid2, SettingsGuid1); var component = new BlockEditorPropertyHandler(s_logger); var result = component.ReplaceBlockListUdis(json, GuidFactory); var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings); var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings); Console.WriteLine(expectedJson); Console.WriteLine(resultJson); Assert.AreEqual(expectedJson, resultJson); } [Test] public void One_Level_Nesting_Escaped() { var guids = Enumerable.Range(0, 6).Select(x => Guid.NewGuid()).ToList(); var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; var innerJson = GetBlockListJson(null, SubContentGuid1, SubContentGuid2, SubSettingsGuid1); // we need to ensure the escaped json is consistent with how it will be re-escaped after parsing // and this is how to do that, the result will also include quotes around it. var innerJsonEscaped = JsonConvert.ToString(innerJson); // get the json with the subFeatures as escaped var json = GetBlockListJson(innerJsonEscaped); var component = new BlockEditorPropertyHandler(s_logger); var result = component.ReplaceBlockListUdis(json, GuidFactory); // the expected result is that the subFeatures data is no longer escaped var expected = ReplaceGuids( GetBlockListJson(innerJson), guids, ContentGuid1, ContentGuid2, SettingsGuid1, SubContentGuid1, SubContentGuid2, SubSettingsGuid1); var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings); var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings); Console.WriteLine(expectedJson); Console.WriteLine(resultJson); Assert.AreEqual(expectedJson, resultJson); } [Test] public void One_Level_Nesting_Unescaped() { var guids = Enumerable.Range(0, 6).Select(x => Guid.NewGuid()).ToList(); var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; // nested blocks without property value escaping used in the conversion var innerJson = GetBlockListJson(null, SubContentGuid1, SubContentGuid2, SubSettingsGuid1); // get the json with the subFeatures as unescaped var json = GetBlockListJson(innerJson); var expected = ReplaceGuids( GetBlockListJson(innerJson), guids, ContentGuid1, ContentGuid2, SettingsGuid1, SubContentGuid1, SubContentGuid2, SubSettingsGuid1); var component = new BlockEditorPropertyHandler(s_logger); var result = component.ReplaceBlockListUdis(json, GuidFactory); var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings); var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings); Console.WriteLine(expectedJson); Console.WriteLine(resultJson); Assert.AreEqual(expectedJson, resultJson); } [Test] public void Nested_In_Complex_Editor_Escaped() { var guids = Enumerable.Range(0, 6).Select(x => Guid.NewGuid()).ToList(); var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; var innerJson = GetBlockListJson(null, SubContentGuid1, SubContentGuid2, SubSettingsGuid1); // we need to ensure the escaped json is consistent with how it will be re-escaped after parsing // and this is how to do that, the result will also include quotes around it. var innerJsonEscaped = JsonConvert.ToString(innerJson); // Complex editor such as the grid var complexEditorJsonEscaped = GetGridJson(innerJsonEscaped); var json = GetBlockListJson(complexEditorJsonEscaped); var component = new BlockEditorPropertyHandler(s_logger); var result = component.ReplaceBlockListUdis(json, GuidFactory); // the expected result is that the subFeatures data is no longer escaped var expected = ReplaceGuids( GetBlockListJson(GetGridJson(innerJson)), guids, ContentGuid1, ContentGuid2, SettingsGuid1, SubContentGuid1, SubContentGuid2, SubSettingsGuid1); var expectedJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(expected, _serializerSettings), _serializerSettings); var resultJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(result, _serializerSettings), _serializerSettings); Console.WriteLine(expectedJson); Console.WriteLine(resultJson); Assert.AreEqual(expectedJson, resultJson); } private string GetBlockListJson( string subFeatures, string contentGuid1 = ContentGuid1, string contentGuid2 = ContentGuid2, string settingsGuid1 = SettingsGuid1) { return @"{ ""layout"": { ""Umbraco.BlockList"": [ { ""contentUdi"": """ + (contentGuid1.IsNullOrWhiteSpace() ? string.Empty : GuidUdi.Create(Constants.UdiEntityType.Element, Guid.Parse(contentGuid1)).ToString()) + @""" }, { ""contentUdi"": ""umb://element/" + contentGuid2 + @""", ""settingsUdi"": ""umb://element/" + settingsGuid1 + @""" } ] }, ""contentData"": [ { ""contentTypeKey"": ""d6ce4a86-91a2-45b3-a99c-8691fc1fb020"", ""udi"": """ + (contentGuid1.IsNullOrWhiteSpace() ? string.Empty : GuidUdi.Create(Constants.UdiEntityType.Element, Guid.Parse(contentGuid1)).ToString()) + @""", ""featureName"": ""Hello"", ""featureDetails"": ""World"" }, { ""contentTypeKey"": ""d6ce4a86-91a2-45b3-a99c-8691fc1fb020"", ""udi"": ""umb://element/" + contentGuid2 + @""", ""featureName"": ""Another"", ""featureDetails"": ""Feature""" + (subFeatures == null ? string.Empty : (@", ""subFeatures"": " + subFeatures)) + @" } ], ""settingsData"": [ { ""contentTypeKey"": ""d6ce4a86-91a2-45b3-a99c-8691fc1fb020"", ""udi"": ""umb://element/" + settingsGuid1 + @""", ""featureName"": ""Setting 1"", ""featureDetails"": ""Setting 2"" }, ] }"; } private string GetGridJson(string subBlockList) { return @"{ ""name"": ""1 column layout"", ""sections"": [ { ""grid"": ""12"", ""rows"": [ { ""name"": ""Article"", ""id"": ""b4f6f651-0de3-ef46-e66a-464f4aaa9c57"", ""areas"": [ { ""grid"": ""4"", ""controls"": [ { ""value"": ""I am quote"", ""editor"": { ""alias"": ""quote"", ""view"": ""textstring"" }, ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }, { ""grid"": ""8"", ""controls"": [ { ""value"": ""Header"", ""editor"": { ""alias"": ""headline"", ""view"": ""textstring"" }, ""styles"": null, ""config"": null }, { ""value"": " + subBlockList + @", ""editor"": { ""alias"": ""madeUpNestedContent"", ""view"": ""madeUpNestedContentInGrid"" }, ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }] }] }"; } private string ReplaceGuids(string json, List<Guid> newGuids, params string[] oldGuids) { for (var i = 0; i < oldGuids.Length; i++) { var old = oldGuids[i]; json = json.Replace(old, newGuids[i].ToString("N")); } return json; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Text; internal partial class Interop { internal partial class WinHttp { [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, int flags); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpCloseHandle( IntPtr handle); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved); // NOTE: except for the return type, this refers to the same function as WinHttpConnect. [DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpConnect", CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandleWithCallback WinHttpConnectWithCallback( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags); // NOTE: except for the return type, this refers to the same function as WinHttpOpenRequest. [DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpOpenRequest", CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandleWithCallback WinHttpOpenRequestWithCallback( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, [In] StringBuilder headers, uint headersLength, uint modifiers); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, [In] StringBuilder headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReceiveResponse( SafeWinHttpHandle requestHandle, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, out uint bytesAvailable); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, out uint bytesRead); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, IntPtr buffer, ref uint bufferLength, ref uint index); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, [Out] StringBuilder buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, out uint bytesWritten); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr parameterIgnoredAndShouldBeNullForAsync); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, string optionData, uint optionLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpGetIEProxyConfigForCurrentUser( out WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out WINHTTP_PROXY_INFO proxyInfo); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeWinHttpHandleWithCallback WinHttpWebSocketCompleteUpgrade( SafeWinHttpHandle requestHandle, IntPtr context); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketSend( SafeWinHttpHandle webSocketHandle, WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType, IntPtr buffer, uint bufferLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketReceive( SafeWinHttpHandle webSocketHandle, IntPtr buffer, uint bufferLength, out uint bytesRead, out WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketShutdown( SafeWinHttpHandle webSocketHandle, ushort status, byte[] reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketShutdown( SafeWinHttpHandle webSocketHandle, ushort status, IntPtr reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketClose( SafeWinHttpHandle webSocketHandle, ushort status, byte[] reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketClose( SafeWinHttpHandle webSocketHandle, ushort status, IntPtr reason, uint reasonLength); [DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)] public static extern uint WinHttpWebSocketQueryCloseStatus( SafeWinHttpHandle webSocketHandle, out ushort status, byte[] reason, uint reasonLength, out uint reasonLengthConsumed); } }
// 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. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Activator is an object that contains the Activation (CreateInstance/New) // methods for late bound support. // // // // namespace System { using System; using System.Reflection; using System.Runtime.Remoting; #if FEATURE_REMOTING using System.Runtime.Remoting.Activation; using Message = System.Runtime.Remoting.Messaging.Message; #endif using System.Security; using CultureInfo = System.Globalization.CultureInfo; using Evidence = System.Security.Policy.Evidence; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security.Permissions; using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // Only statics, does not need to be marked with the serializable attribute [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Activator))] [System.Runtime.InteropServices.ComVisible(true)] public sealed class Activator : _Activator { internal const int LookupMask = 0x000000FF; internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public); internal const BindingFlags ConstructorDefault= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; // This class only contains statics, so hide the worthless constructor private Activator() { } // CreateInstance // The following methods will create a new instance of an Object // Full Binding Support // For all of these methods we need to get the underlying RuntimeType and // call the Impl version. static public Object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) { return CreateInstance(type, bindingAttr, binder, args, culture, null); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public Object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) { if ((object)type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); if (type is System.Reflection.Emit.TypeBuilder) throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder")); // If they didn't specify a lookup, then we will provide the default lookup. if ((bindingAttr & (BindingFlags) LookupMask) == 0) bindingAttr |= Activator.ConstructorDefault; if (activationAttributes != null && activationAttributes.Length > 0){ // If type does not derive from MBR // throw notsupportedexception #if FEATURE_REMOTING if(type.IsMarshalByRef){ // The fix below is preventative. // if(!(type.IsContextful)){ if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute)) throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR")); } } else #endif throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" )); } RuntimeType rt = type.UnderlyingSystemType as RuntimeType; if (rt == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes, ref stackMark); } static public Object CreateInstance(Type type, params Object[] args) { return CreateInstance(type, Activator.ConstructorDefault, null, args, null, null); } static public Object CreateInstance(Type type, Object[] args, Object[] activationAttributes) { return CreateInstance(type, Activator.ConstructorDefault, null, args, null, activationAttributes); } static public Object CreateInstance(Type type) { return Activator.CreateInstance(type, false); } /* * Create an instance using the name of type and the assembly where it exists. This allows * types to be created remotely without having to load the type locally. */ [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public ObjectHandle CreateInstance(String assemblyName, String typeName) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, false, Activator.ConstructorDefault, null, null, null, null, null, ref stackMark); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public ObjectHandle CreateInstance(String assemblyName, String typeName, Object[] activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, false, Activator.ConstructorDefault, null, null, null, activationAttributes, null, ref stackMark); } [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public Object CreateInstance(Type type, bool nonPublic) { if ((object)type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); RuntimeType rt = type.UnderlyingSystemType as RuntimeType; if (rt == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark); } [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public T CreateInstance<T>() { RuntimeType rt = typeof(T) as RuntimeType; // This is a workaround to maintain compatibility with V2. Without this we would throw a NotSupportedException for void[]. // Array, Ref, and Pointer types don't have default constructors. if (rt.HasElementType) throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor")); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions). return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark); } static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName) { return CreateInstanceFrom(assemblyFile, typeName, null); } static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName, Object[] activationAttributes) { return CreateInstanceFrom(assemblyFile, typeName, false, Activator.ConstructorDefault, null, null, null, activationAttributes); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] static public ObjectHandle CreateInstance(String assemblyName, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo, ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null, ref stackMark); } [System.Security.SecurityCritical] // auto-generated static internal ObjectHandle CreateInstance(String assemblyString, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, ref StackCrawlMark stackMark) { #if FEATURE_CAS_POLICY if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY Type type = null; Assembly assembly = null; if (assemblyString == null) { assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark); } else { RuntimeAssembly assemblyFromResolveEvent; AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent); if (assemblyFromResolveEvent != null) { // Assembly was resolved via AssemblyResolve event assembly = assemblyFromResolveEvent; } else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) { // WinRT type - we have to use Type.GetType type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase); } else { // Classic managed type assembly = RuntimeAssembly.InternalLoadAssemblyName( assemblyName, securityInfo, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/); } } if (type == null) { // It's classic managed type (not WinRT type) Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString); if(assembly == null) return null; type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase); } Object o = Activator.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); if(o == null) return null; else { ObjectHandle Handle = new ObjectHandle(o); return Handle; } } [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo) { #if FEATURE_CAS_POLICY if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY return CreateInstanceFromInternal(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo); } public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { return CreateInstanceFromInternal(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null); } private static ObjectHandle CreateInstanceFromInternal(String assemblyFile, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo) { #if FEATURE_CAS_POLICY Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null); #endif // FEATURE_CAS_POLICY #pragma warning disable 618 Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo); #pragma warning restore 618 Type t = assembly.GetType(typeName, true, ignoreCase); Object o = Activator.CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes); Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); if(o == null) return null; else { ObjectHandle Handle = new ObjectHandle(o); return Handle; } } // // This API is designed to be used when a host needs to execute code in an AppDomain // with restricted security permissions. In that case, we demand in the client domain // and assert in the server domain because the server domain might not be trusted enough // to pass the security checks when activating the type. // [System.Security.SecurityCritical] // auto-generated_required public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName); } [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); #if FEATURE_CAS_POLICY if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes); } [SecurityCritical] public static ObjectHandle CreateInstance(AppDomain domain, string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null); } // // This API is designed to be used when a host needs to execute code in an AppDomain // with restricted security permissions. In that case, we demand in the client domain // and assert in the server domain because the server domain might not be trusted enough // to pass the security checks when activating the type. // [System.Security.SecurityCritical] // auto-generated_required public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName); } [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Methods which use Evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); #if FEATURE_CAS_POLICY if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes); } [SecurityCritical] public static ObjectHandle CreateInstanceFrom(AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null); } #if FEATURE_COMINTEROP #if FEATURE_CLICKONCE [System.Security.SecuritySafeCritical] // auto-generated public static ObjectHandle CreateInstance (ActivationContext activationContext) { AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager; if (domainManager == null) domainManager = new AppDomainManager(); return domainManager.ApplicationActivator.CreateInstance(activationContext); } [System.Security.SecuritySafeCritical] // auto-generated public static ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData) { AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager; if (domainManager == null) domainManager = new AppDomainManager(); return domainManager.ApplicationActivator.CreateInstance(activationContext, activationCustomData); } #endif // FEATURE_CLICKONCE public static ObjectHandle CreateComInstanceFrom(String assemblyName, String typeName) { return CreateComInstanceFrom(assemblyName, typeName, null, AssemblyHashAlgorithm.None); } public static ObjectHandle CreateComInstanceFrom(String assemblyName, String typeName, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) { Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm); Type t = assembly.GetType(typeName, true, false); Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute),false); if (Attr.Length > 0) { if (((ComVisibleAttribute)Attr[0]).Value == false) throw new TypeLoadException(Environment.GetResourceString( "Argument_TypeMustBeVisibleFromCom" )); } Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName); if(assembly == null) return null; Object o = Activator.CreateInstance(t, Activator.ConstructorDefault, null, null, null, null); Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); if(o == null) return null; else { ObjectHandle Handle = new ObjectHandle(o); return Handle; } } #endif // FEATURE_COMINTEROP #if FEATURE_REMOTING // This method is a helper method and delegates to the remoting // services to do the actual work. [System.Security.SecurityCritical] // auto-generated_required static public Object GetObject(Type type, String url) { return GetObject(type, url, null); } // This method is a helper method and delegates to the remoting // services to do the actual work. [System.Security.SecurityCritical] // auto-generated_required static public Object GetObject(Type type, String url, Object state) { if (type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); return RemotingServices.Connect(type, url, state); } #endif [System.Diagnostics.Conditional("_DEBUG")] private static void Log(bool test, string title, string success, string failure) { #if FEATURE_REMOTING if(test) BCLDebug.Trace("REMOTE", "{0}{1}", title, success); else BCLDebug.Trace("REMOTE", "{0}{1}", title, failure); #endif } #if !FEATURE_CORECLR void _Activator.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _Activator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _Activator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _Activator.Invoke in VM\DangerousAPIs.h and // include _Activator in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _Activator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if !CLR2 #else using Microsoft.Scripting.Ast; #endif using System.Reflection; using System.Runtime.CompilerServices; using System.Collections.Generic; namespace System.Management.Automation.Interpreter { #nullable enable internal interface IBoxableInstruction { Instruction? BoxIfIndexMatches(int index); } #nullable restore internal abstract class LocalAccessInstruction : Instruction { internal readonly int _index; protected LocalAccessInstruction(int index) { _index = index; } public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { return cookie == null ? InstructionName + "(" + _index + ")" : InstructionName + "(" + cookie + ": " + _index + ")"; } } #region Load internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal LoadLocalInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex++] = frame.Data[_index]; // frame.Push(frame.Data[_index]); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.LoadLocalBoxed(index) : null; } } internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction { internal LoadLocalBoxedInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = (StrongBox<object>)frame.Data[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction { internal LoadLocalFromClosureInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction { internal LoadLocalFromClosureBoxedInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box; return +1; } } #endregion #region Store, Assign internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal AssignLocalInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { frame.Data[_index] = frame.Peek(); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.AssignLocalBoxed(index) : null; } } internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal StoreLocalInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { frame.Data[_index] = frame.Data[--frame.StackIndex]; // frame.Data[_index] = frame.Pop(); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.StoreLocalBoxed(index) : null; } } internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction { internal AssignLocalBoxedInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = (StrongBox<object>)frame.Data[_index]; box.Value = frame.Peek(); return +1; } } internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction { internal StoreLocalBoxedInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 0; } } public override int Run(InterpretedFrame frame) { var box = (StrongBox<object>)frame.Data[_index]; box.Value = frame.Data[--frame.StackIndex]; return +1; } } internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction { internal AssignLocalToClosureInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; box.Value = frame.Peek(); return +1; } } #endregion #region Initialize [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors")] internal abstract class InitializeLocalInstruction : LocalAccessInstruction { internal InitializeLocalInstruction(int index) : base(index) { } internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction { internal Reference(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = null; return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.InitImmutableRefBox(index) : null; } public override string InstructionName { get { return "InitRef"; } } } internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction { private readonly object _defaultValue; internal ImmutableValue(int index, object defaultValue) : base(index) { _defaultValue = defaultValue; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = _defaultValue; return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? new ImmutableBox(index, _defaultValue) : null; } public override string InstructionName { get { return "InitImmutableValue"; } } } internal sealed class ImmutableBox : InitializeLocalInstruction { // immutable value: private readonly object _defaultValue; internal ImmutableBox(int index, object defaultValue) : base(index) { _defaultValue = defaultValue; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new StrongBox<object>(_defaultValue); return 1; } public override string InstructionName { get { return "InitImmutableBox"; } } } internal sealed class ParameterBox : InitializeLocalInstruction { public ParameterBox(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new StrongBox<object>(frame.Data[_index]); return 1; } } internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction { internal Parameter(int index) : base(index) { } public override int Run(InterpretedFrame frame) { // nop return 1; } public Instruction BoxIfIndexMatches(int index) { if (index == _index) { return InstructionList.ParameterBox(index); } return null; } public override string InstructionName { get { return "InitParameter"; } } } internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction { private readonly Type _type; internal MutableValue(int index, Type type) : base(index) { _type = type; } public override int Run(InterpretedFrame frame) { try { frame.Data[_index] = Activator.CreateInstance(_type); } catch (TargetInvocationException e) { ExceptionHelpers.UpdateForRethrow(e.InnerException); throw e.InnerException; } return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? new MutableBox(index, _type) : null; } public override string InstructionName { get { return "InitMutableValue"; } } } internal sealed class MutableBox : InitializeLocalInstruction { private readonly Type _type; internal MutableBox(int index, Type type) : base(index) { _type = type; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new StrongBox<object>(Activator.CreateInstance(_type)); return 1; } public override string InstructionName { get { return "InitMutableBox"; } } } } #endregion #region RuntimeVariables internal sealed class RuntimeVariablesInstruction : Instruction { private readonly int _count; public RuntimeVariablesInstruction(int count) { _count = count; } public override int ProducedStack { get { return 1; } } public override int ConsumedStack { get { return _count; } } public override int Run(InterpretedFrame frame) { var ret = new IStrongBox[_count]; for (int i = ret.Length - 1; i >= 0; i--) { ret[i] = (IStrongBox)frame.Pop(); } frame.Push(RuntimeVariables.Create(ret)); return +1; } public override string ToString() { return "GetRuntimeVariables()"; } } #endregion }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class OfferOperationsExtensions { /// <summary> /// Gets an offer given its Id. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='offerId'> /// Required. The full offer Id in format /// /delegatedProviders/{providerId}/offers/{offerName} /// </param> /// <returns> /// The offer get result. /// </returns> public static OfferGetResult Get(this IOfferOperations operations, string offerId) { return Task.Factory.StartNew((object s) => { return ((IOfferOperations)s).GetAsync(offerId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets an offer given its Id. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='offerId'> /// Required. The full offer Id in format /// /delegatedProviders/{providerId}/offers/{offerName} /// </param> /// <returns> /// The offer get result. /// </returns> public static Task<OfferGetResult> GetAsync(this IOfferOperations operations, string offerId) { return operations.GetAsync(offerId, CancellationToken.None); } /// <summary> /// Gets the price of the offer. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='offerId'> /// Required. the full offer ID /// /delegatedProviders/{providerId}/offers/{offerId}. /// </param> /// <returns> /// Offer price result. /// </returns> public static OfferGetPriceResult GetPrice(this IOfferOperations operations, string offerId) { return Task.Factory.StartNew((object s) => { return ((IOfferOperations)s).GetPriceAsync(offerId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the price of the offer. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='offerId'> /// Required. the full offer ID /// /delegatedProviders/{providerId}/offers/{offerId}. /// </param> /// <returns> /// Offer price result. /// </returns> public static Task<OfferGetPriceResult> GetPriceAsync(this IOfferOperations operations, string offerId) { return operations.GetPriceAsync(offerId, CancellationToken.None); } /// <summary> /// Gets the public offers under the provider which has the given /// provider identifier /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='providerIdentifier'> /// Required. The provider identifier, we get the public offers under /// that provider. /// </param> /// <returns> /// Result of the offer /// </returns> public static OfferListResult List(this IOfferOperations operations, string providerIdentifier) { return Task.Factory.StartNew((object s) => { return ((IOfferOperations)s).ListAsync(providerIdentifier); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the public offers under the provider which has the given /// provider identifier /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='providerIdentifier'> /// Required. The provider identifier, we get the public offers under /// that provider. /// </param> /// <returns> /// Result of the offer /// </returns> public static Task<OfferListResult> ListAsync(this IOfferOperations operations, string providerIdentifier) { return operations.ListAsync(providerIdentifier, CancellationToken.None); } /// <summary> /// Lists the offer with the next link /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='nextLink'> /// Required. The URL to get the next set of offers /// </param> /// <returns> /// Result of the offer /// </returns> public static OfferListResult ListNext(this IOfferOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IOfferOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the offer with the next link /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <param name='nextLink'> /// Required. The URL to get the next set of offers /// </param> /// <returns> /// Result of the offer /// </returns> public static Task<OfferListResult> ListNextAsync(this IOfferOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Gets the public offers under the zero day (root) provider /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <returns> /// Result of the offer /// </returns> public static OfferListResult ListUnderRootProvider(this IOfferOperations operations) { return Task.Factory.StartNew((object s) => { return ((IOfferOperations)s).ListUnderRootProviderAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the public offers under the zero day (root) provider /// </summary> /// <param name='operations'> /// Reference to the Microsoft.AzureStack.Management.IOfferOperations. /// </param> /// <returns> /// Result of the offer /// </returns> public static Task<OfferListResult> ListUnderRootProviderAsync(this IOfferOperations operations) { return operations.ListUnderRootProviderAsync(CancellationToken.None); } } }
// 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.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Net.Test.Common; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { public sealed class SocketsHttpHandler_HttpClientHandler_Asynchrony_Test : HttpClientHandler_Asynchrony_Test { protected override bool UseSocketsHttpHandler => true; [OuterLoop("Relies on finalization")] [Fact] public async Task ExecutionContext_HttpConnectionLifetimeDoesntKeepContextAlive() { var clientCompleted = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); await LoopbackServer.CreateClientAndServerAsync(async uri => { try { using (HttpClient client = CreateHttpClient()) { (Task completedWhenFinalized, Task getRequest) = MakeHttpRequestWithTcsSetOnFinalizationInAsyncLocal(client, uri); await getRequest; for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } await completedWhenFinalized.TimeoutAfter(TestHelper.PassingTestTimeoutMilliseconds); } } finally { clientCompleted.SetResult(true); } }, async server => { await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAndSendResponseAsync(); await clientCompleted.Task; }); }); } [MethodImpl(MethodImplOptions.NoInlining)] // avoid JIT extending lifetime of the finalizable object private static (Task completedOnFinalized, Task getRequest) MakeHttpRequestWithTcsSetOnFinalizationInAsyncLocal(HttpClient client, Uri uri) { var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); // Put something in ExecutionContext, start the HTTP request, then undo the EC change. var al = new AsyncLocal<object>() { Value = new SetOnFinalized() { _completedWhenFinalized = tcs } }; Task t = client.GetStringAsync(uri); al.Value = null; // Return a task that will complete when the SetOnFinalized is finalized, // as well as a task to wait on for the get request; for the get request, // we return a continuation to avoid any test-altering issues related to // the state machine holding onto stuff. t = t.ContinueWith(p => p.GetAwaiter().GetResult()); return (tcs.Task, t); } private sealed class SetOnFinalized { internal TaskCompletionSource<bool> _completedWhenFinalized; ~SetOnFinalized() => _completedWhenFinalized.SetResult(true); } } public sealed class SocketsHttpHandler_HttpProtocolTests : HttpProtocolTests { protected override bool UseSocketsHttpHandler => true; [Theory] [InlineData("delete", "DELETE")] [InlineData("options", "OPTIONS")] [InlineData("trace", "TRACE")] [InlineData("patch", "PATCH")] public Task CustomMethod_SentUppercasedIfKnown_Additional(string specifiedMethod, string expectedMethod) => CustomMethod_SentUppercasedIfKnown(specifiedMethod, expectedMethod); } public sealed class SocketsHttpHandler_HttpProtocolTests_Dribble : HttpProtocolTests_Dribble { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_DiagnosticsTest : DiagnosticsTest { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClient_SelectedSites_Test : HttpClient_SelectedSites_Test { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientEKUTest : HttpClientEKUTest { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_Decompression_Tests : HttpClientHandler_Decompression_Test { public SocketsHttpHandler_HttpClientHandler_Decompression_Tests(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test { public SocketsHttpHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test { protected override bool UseSocketsHttpHandler => true; [OuterLoop("Incurs a small delay")] [Theory] [InlineData(0)] [InlineData(1)] public async Task SmallConnectionLifetimeWithMaxConnections_PendingRequestUsesDifferentConnection(int lifetimeMilliseconds) { using (var handler = new SocketsHttpHandler()) { handler.PooledConnectionLifetime = TimeSpan.FromMilliseconds(lifetimeMilliseconds); handler.MaxConnectionsPerServer = 1; using (HttpClient client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (server, uri) => { Task<string> request1 = client.GetStringAsync(uri); Task<string> request2 = client.GetStringAsync(uri); await server.AcceptConnectionAsync(async connection => { Task secondResponse = server.AcceptConnectionAsync(connection2 => connection2.ReadRequestHeaderAndSendCustomResponseAsync(LoopbackServer.GetConnectionCloseResponse())); // Wait a small amount of time before sending the first response, so the connection lifetime will expire. Debug.Assert(lifetimeMilliseconds < 100); await Task.Delay(100); // Second request should not have completed yet, as we haven't completed the first yet. Assert.False(request2.IsCompleted); Assert.False(secondResponse.IsCompleted); // Send the first response and wait for the first request to complete. await connection.ReadRequestHeaderAndSendResponseAsync(); await request1; // Now the second request should complete. await secondResponse.TimeoutAfter(TestHelper.PassingTestTimeoutMilliseconds); }); }); } } } } public sealed class SocketsHttpHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_ResponseDrain_Test : HttpClientHandler_ResponseDrain_Test { protected override bool UseSocketsHttpHandler => true; protected override void SetResponseDrainTimeout(HttpClientHandler handler, TimeSpan time) { SocketsHttpHandler s = (SocketsHttpHandler)GetUnderlyingSocketsHttpHandler(handler); Assert.NotNull(s); s.ResponseDrainTimeout = time; } [Fact] public void MaxResponseDrainSize_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(1024 * 1024, handler.MaxResponseDrainSize); handler.MaxResponseDrainSize = 0; Assert.Equal(0, handler.MaxResponseDrainSize); handler.MaxResponseDrainSize = int.MaxValue; Assert.Equal(int.MaxValue, handler.MaxResponseDrainSize); } } [Fact] public void MaxResponseDrainSize_InvalidArgument_Throws() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(1024 * 1024, handler.MaxResponseDrainSize); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseDrainSize = -1); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseDrainSize = int.MinValue); Assert.Equal(1024 * 1024, handler.MaxResponseDrainSize); } } [Fact] public void MaxResponseDrainSize_SetAfterUse_Throws() { using (var handler = new SocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.MaxResponseDrainSize = 1; client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure Assert.Equal(1, handler.MaxResponseDrainSize); Assert.Throws<InvalidOperationException>(() => handler.MaxResponseDrainSize = 1); } } [Fact] public void ResponseDrainTimeout_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(TimeSpan.FromSeconds(2), handler.ResponseDrainTimeout); handler.ResponseDrainTimeout = TimeSpan.Zero; Assert.Equal(TimeSpan.Zero, handler.ResponseDrainTimeout); handler.ResponseDrainTimeout = TimeSpan.FromTicks(int.MaxValue); Assert.Equal(TimeSpan.FromTicks(int.MaxValue), handler.ResponseDrainTimeout); } } [Fact] public void MaxResponseDraiTime_InvalidArgument_Throws() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(TimeSpan.FromSeconds(2), handler.ResponseDrainTimeout); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ResponseDrainTimeout = TimeSpan.FromSeconds(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ResponseDrainTimeout = TimeSpan.MaxValue); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ResponseDrainTimeout = TimeSpan.FromSeconds(int.MaxValue)); Assert.Equal(TimeSpan.FromSeconds(2), handler.ResponseDrainTimeout); } } [Fact] public void ResponseDrainTimeout_SetAfterUse_Throws() { using (var handler = new SocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.ResponseDrainTimeout = TimeSpan.FromSeconds(42); client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure Assert.Equal(TimeSpan.FromSeconds(42), handler.ResponseDrainTimeout); Assert.Throws<InvalidOperationException>(() => handler.ResponseDrainTimeout = TimeSpan.FromSeconds(42)); } } [OuterLoop] [Theory] [InlineData(1024 * 1024 * 2, 9_500, 1024 * 1024 * 3, LoopbackServer.ContentMode.ContentLength)] [InlineData(1024 * 1024 * 2, 9_500, 1024 * 1024 * 3, LoopbackServer.ContentMode.SingleChunk)] [InlineData(1024 * 1024 * 2, 9_500, 1024 * 1024 * 13, LoopbackServer.ContentMode.BytePerChunk)] public async Task GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsUnderMaxDrainSizeAndReusesConnection(int totalSize, int readSize, int maxDrainSize, LoopbackServer.ContentMode mode) { await LoopbackServer.CreateClientAndServerAsync( async url => { var handler = new SocketsHttpHandler(); handler.MaxResponseDrainSize = maxDrainSize; handler.ResponseDrainTimeout = Timeout.InfiniteTimeSpan; // Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to) handler.MaxConnectionsPerServer = 1; using (var client = new HttpClient(handler)) { HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); ValidateResponseHeaders(response1, totalSize, mode); // Read part but not all of response Stream responseStream = await response1.Content.ReadAsStreamAsync(); await ReadToByteCount(responseStream, readSize); response1.Dispose(); // Issue another request. We'll confirm that it comes on the same connection. HttpResponseMessage response2 = await client.GetAsync(url); ValidateResponseHeaders(response2, totalSize, mode); Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length); } }, async server => { string content = new string('a', totalSize); string response = LoopbackServer.GetContentModeResponse(mode, content); await server.AcceptConnectionAsync(async connection => { server.ListenSocket.Close(); // Shut down the listen socket so attempts at additional connections would fail on the client await connection.ReadRequestHeaderAndSendCustomResponseAsync(response); await connection.ReadRequestHeaderAndSendCustomResponseAsync(response); }); }); } [OuterLoop] [Theory] [InlineData(100_000, 0, LoopbackServer.ContentMode.ContentLength)] [InlineData(100_000, 0, LoopbackServer.ContentMode.SingleChunk)] [InlineData(100_000, 0, LoopbackServer.ContentMode.BytePerChunk)] public async Task GetAsyncWithMaxConnections_DisposeLargerThanMaxDrainSize_KillsConnection(int totalSize, int maxDrainSize, LoopbackServer.ContentMode mode) { await LoopbackServer.CreateClientAndServerAsync( async url => { var handler = new SocketsHttpHandler(); handler.MaxResponseDrainSize = maxDrainSize; handler.ResponseDrainTimeout = Timeout.InfiniteTimeSpan; // Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to) handler.MaxConnectionsPerServer = 1; using (var client = new HttpClient(handler)) { HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); ValidateResponseHeaders(response1, totalSize, mode); response1.Dispose(); // Issue another request. We'll confirm that it comes on a new connection. HttpResponseMessage response2 = await client.GetAsync(url); ValidateResponseHeaders(response2, totalSize, mode); Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length); } }, async server => { string content = new string('a', totalSize); await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAsync(); try { await connection.Writer.WriteAsync(LoopbackServer.GetContentModeResponse(mode, content, connectionClose: false)); } catch (Exception) { } // Eat errors from client disconnect. await server.AcceptConnectionSendCustomResponseAndCloseAsync(LoopbackServer.GetContentModeResponse(mode, content, connectionClose: true)); }); }); } [OuterLoop] [Theory] [InlineData(LoopbackServer.ContentMode.ContentLength)] [InlineData(LoopbackServer.ContentMode.SingleChunk)] [InlineData(LoopbackServer.ContentMode.BytePerChunk)] public async Task GetAsyncWithMaxConnections_DrainTakesLongerThanTimeout_KillsConnection(LoopbackServer.ContentMode mode) { const int ContentLength = 10_000; await LoopbackServer.CreateClientAndServerAsync( async url => { var handler = new SocketsHttpHandler(); handler.MaxResponseDrainSize = int.MaxValue; handler.ResponseDrainTimeout = TimeSpan.FromMilliseconds(1); // Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to) handler.MaxConnectionsPerServer = 1; using (var client = new HttpClient(handler)) { client.Timeout = Timeout.InfiniteTimeSpan; HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); ValidateResponseHeaders(response1, ContentLength, mode); response1.Dispose(); // Issue another request. We'll confirm that it comes on a new connection. HttpResponseMessage response2 = await client.GetAsync(url); ValidateResponseHeaders(response2, ContentLength, mode); Assert.Equal(ContentLength, (await response2.Content.ReadAsStringAsync()).Length); } }, async server => { string content = new string('a', ContentLength); await server.AcceptConnectionAsync(async connection => { string response = LoopbackServer.GetContentModeResponse(mode, content, connectionClose: false); await connection.ReadRequestHeaderAsync(); try { // Write out only part of the response await connection.Writer.WriteAsync(response.Substring(0, response.Length / 2)); } catch (Exception) { } // Eat errors from client disconnect. response = LoopbackServer.GetContentModeResponse(mode, content, connectionClose: true); await server.AcceptConnectionSendCustomResponseAndCloseAsync(response); }); }); } } public sealed class SocketsHttpHandler_PostScenarioTest : PostScenarioTest { public SocketsHttpHandler_PostScenarioTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_ResponseStreamTest : ResponseStreamTest { public SocketsHttpHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_Proxy_Test : HttpClientHandler_Proxy_Test { public SocketsHttpHandler_HttpClientHandler_Proxy_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_TrailingHeaders_Test : HttpClientHandlerTest_TrailingHeaders_Test { // PlatformHandlers don't support trailers. protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest { public SocketsHttpHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientMiniStress : HttpClientMiniStress { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandlerTest : HttpClientHandlerTest { public SocketsHttpHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandlerTest_AutoRedirect : HttpClientHandlerTest_AutoRedirect { public SocketsHttpHandlerTest_AutoRedirect(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_DefaultCredentialsTest : DefaultCredentialsTest { public SocketsHttpHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_IdnaProtocolTests : IdnaProtocolTests { protected override bool UseSocketsHttpHandler => true; protected override bool SupportsIdna => true; } public sealed class SocketsHttpHandler_HttpRetryProtocolTests : HttpRetryProtocolTests { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandlerTest_Cookies : HttpClientHandlerTest_Cookies { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandlerTest_Cookies_Http11 : HttpClientHandlerTest_Cookies_Http11 { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_Cancellation_Test : HttpClientHandler_Cancellation_Test { protected override bool UseSocketsHttpHandler => true; [Fact] public void ConnectTimeout_Default() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(Timeout.InfiniteTimeSpan, handler.ConnectTimeout); } } [Theory] [InlineData(0)] [InlineData(-2)] [InlineData(int.MaxValue + 1L)] public void ConnectTimeout_InvalidValues(long ms) { using (var handler = new SocketsHttpHandler()) { Assert.Throws<ArgumentOutOfRangeException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms)); } } [Theory] [InlineData(-1)] [InlineData(1)] [InlineData(int.MaxValue - 1)] [InlineData(int.MaxValue)] public void ConnectTimeout_ValidValues_Roundtrip(long ms) { using (var handler = new SocketsHttpHandler()) { handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms); Assert.Equal(TimeSpan.FromMilliseconds(ms), handler.ConnectTimeout); } } [Fact] public void ConnectTimeout_SetAfterUse_Throws() { using (var handler = new SocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.ConnectTimeout = TimeSpan.FromMilliseconds(int.MaxValue); client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure Assert.Equal(TimeSpan.FromMilliseconds(int.MaxValue), handler.ConnectTimeout); Assert.Throws<InvalidOperationException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(1)); } } [OuterLoop] [Fact] [ActiveIssue(30032)] public async Task ConnectTimeout_TimesOutSSLAuth_Throws() { var releaseServer = new TaskCompletionSource<bool>(); await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var handler = new SocketsHttpHandler()) using (var invoker = new HttpMessageInvoker(handler)) { handler.ConnectTimeout = TimeSpan.FromSeconds(1); var sw = Stopwatch.StartNew(); await Assert.ThrowsAsync<TaskCanceledException>(() => invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, new UriBuilder(uri) { Scheme = "https" }.ToString()), default)); sw.Stop(); Assert.InRange(sw.ElapsedMilliseconds, 500, 60_000); releaseServer.SetResult(true); } }, server => releaseServer.Task); // doesn't establish SSL connection } [Fact] public void Expect100ContinueTimeout_Default() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(TimeSpan.FromSeconds(1), handler.Expect100ContinueTimeout); } } [Theory] [InlineData(-2)] [InlineData(int.MaxValue + 1L)] public void Expect100ContinueTimeout_InvalidValues(long ms) { using (var handler = new SocketsHttpHandler()) { Assert.Throws<ArgumentOutOfRangeException>(() => handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(ms)); } } [Theory] [InlineData(-1)] [InlineData(1)] [InlineData(int.MaxValue - 1)] [InlineData(int.MaxValue)] public void Expect100ContinueTimeout_ValidValues_Roundtrip(long ms) { using (var handler = new SocketsHttpHandler()) { handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(ms); Assert.Equal(TimeSpan.FromMilliseconds(ms), handler.Expect100ContinueTimeout); } } [Fact] public void Expect100ContinueTimeout_SetAfterUse_Throws() { using (var handler = new SocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(int.MaxValue); client.GetAsync("http://" + Guid.NewGuid().ToString("N")); // ignoring failure Assert.Equal(TimeSpan.FromMilliseconds(int.MaxValue), handler.Expect100ContinueTimeout); Assert.Throws<InvalidOperationException>(() => handler.Expect100ContinueTimeout = TimeSpan.FromMilliseconds(1)); } } [OuterLoop("Incurs significant delay")] [Fact] public async Task Expect100Continue_WaitsExpectedPeriodOfTimeBeforeSendingContent() { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var handler = new SocketsHttpHandler()) using (var invoker = new HttpMessageInvoker(handler)) { TimeSpan delay = TimeSpan.FromSeconds(3); handler.Expect100ContinueTimeout = delay; var tcs = new TaskCompletionSource<bool>(); var content = new SetTcsContent(new MemoryStream(new byte[1]), tcs); var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = content }; request.Headers.ExpectContinue = true; var sw = Stopwatch.StartNew(); (await invoker.SendAsync(request, default)).Dispose(); sw.Stop(); Assert.InRange(sw.Elapsed, delay - TimeSpan.FromSeconds(.5), delay * 10); // arbitrary wiggle room } }, async server => { await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAsync(); await connection.Reader.ReadAsync(new char[1]); await connection.SendResponseAsync(); }); }); } private sealed class SetTcsContent : StreamContent { private readonly TaskCompletionSource<bool> _tcs; public SetTcsContent(Stream stream, TaskCompletionSource<bool> tcs) : base(stream) => _tcs = tcs; protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { _tcs.SetResult(true); return base.SerializeToStreamAsync(stream, context); } } } public sealed class SocketsHttpHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test { protected override bool UseSocketsHttpHandler => true; } public sealed class SocketsHttpHandler_HttpClientHandler_Authentication_Test : HttpClientHandler_Authentication_Test { public SocketsHttpHandler_HttpClientHandler_Authentication_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => true; [Theory] [MemberData(nameof(Authentication_SocketsHttpHandler_TestData))] public async void SocketsHttpHandler_Authentication_Succeeds(string authenticateHeader, bool result) { await HttpClientHandler_Authentication_Succeeds(authenticateHeader, result); } public static IEnumerable<object[]> Authentication_SocketsHttpHandler_TestData() { // These test cases successfully authenticate on SocketsHttpHandler but fail on the other handlers. // These are legal as per the the RFC, so authenticating is the expected behavior. See #28521 for details. yield return new object[] { "Basic realm=\"testrealm1\" basic realm=\"testrealm1\"", true }; yield return new object[] { "Basic something digest something", true }; yield return new object[] { "Digest realm=\"api@example.org\", qop=\"auth\", algorithm=MD5-sess, nonce=\"5TsQWLVdgBdmrQ0XsxbDODV+57QdFR34I9HAbC/RVvkK\", " + "opaque=\"HRPCssKJSGjCrkzDg8OhwpzCiGPChXYjwrI2QmXDnsOS\", charset=UTF-8, userhash=true", true }; yield return new object[] { "dIgEsT realm=\"api@example.org\", qop=\"auth\", algorithm=MD5-sess, nonce=\"5TsQWLVdgBdmrQ0XsxbDODV+57QdFR34I9HAbC/RVvkK\", " + "opaque=\"HRPCssKJSGjCrkzDg8OhwpzCiGPChXYjwrI2QmXDnsOS\", charset=UTF-8, userhash=true", true }; // These cases fail on WinHttpHandler because of a behavior in WinHttp that causes requests to be duplicated // when the digest header has certain parameters. See #28522 for details. yield return new object[] { "Digest ", false }; yield return new object[] { "Digest realm=\"testrealm\", nonce=\"testnonce\", algorithm=\"myown\"", false }; // These cases fail to authenticate on SocketsHttpHandler, but succeed on the other handlers. // they are all invalid as per the RFC, so failing is the expected behavior. See #28523 for details. yield return new object[] { "Digest realm=withoutquotes, nonce=withoutquotes", false }; yield return new object[] { "Digest realm=\"testrealm\" nonce=\"testnonce\"", false }; yield return new object[] { "Digest realm=\"testrealm1\", nonce=\"testnonce1\" Digest realm=\"testrealm2\", nonce=\"testnonce2\"", false }; // These tests check that the algorithm parameter is treated in case insensitive way. // WinHTTP only supports plain MD5, so other algorithms are included here. yield return new object[] { $"Digest realm=\"testrealm\", algorithm=md5-Sess, nonce=\"testnonce\"", true }; yield return new object[] { $"Digest realm=\"testrealm\", algorithm=sha-256, nonce=\"testnonce\"", true }; yield return new object[] { $"Digest realm=\"testrealm\", algorithm=sha-256-SESS, nonce=\"testnonce\"", true }; } } public sealed class SocketsHttpHandler_ConnectionUpgrade_Test : HttpClientHandlerTestBase { protected override bool UseSocketsHttpHandler => true; [Fact] public async Task UpgradeConnection_ReturnsReadableAndWritableStream() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { // We need to use ResponseHeadersRead here, otherwise we will hang trying to buffer the response body. Task<HttpResponseMessage> getResponseTask = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); await server.AcceptConnectionAsync(async connection => { Task<List<string>> serverTask = connection.ReadRequestHeaderAndSendCustomResponseAsync($"HTTP/1.1 101 Switching Protocols\r\nDate: {DateTimeOffset.UtcNow:R}\r\n\r\n"); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); using (Stream clientStream = await (await getResponseTask).Content.ReadAsStreamAsync()) { // Boolean properties returning correct values Assert.True(clientStream.CanWrite); Assert.True(clientStream.CanRead); Assert.False(clientStream.CanSeek); // Not supported operations Assert.Throws<NotSupportedException>(() => clientStream.Length); Assert.Throws<NotSupportedException>(() => clientStream.Position); Assert.Throws<NotSupportedException>(() => clientStream.Position = 0); Assert.Throws<NotSupportedException>(() => clientStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => clientStream.SetLength(0)); // Invalid arguments var nonWritableStream = new MemoryStream(new byte[1], false); var disposedStream = new MemoryStream(); disposedStream.Dispose(); Assert.Throws<ArgumentNullException>(() => clientStream.CopyTo(null)); Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.CopyTo(Stream.Null, 0)); Assert.Throws<ArgumentNullException>(() => { clientStream.CopyToAsync(null, 100, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.CopyToAsync(Stream.Null, 0, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.CopyToAsync(Stream.Null, -1, default); }); Assert.Throws<NotSupportedException>(() => { clientStream.CopyToAsync(nonWritableStream, 100, default); }); Assert.Throws<ObjectDisposedException>(() => { clientStream.CopyToAsync(disposedStream, 100, default); }); Assert.Throws<ArgumentNullException>(() => clientStream.Read(null, 0, 100)); Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.Read(new byte[1], -1, 1)); Assert.ThrowsAny<ArgumentException>(() => clientStream.Read(new byte[1], 2, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.Read(new byte[1], 0, -1)); Assert.ThrowsAny<ArgumentException>(() => clientStream.Read(new byte[1], 0, 2)); Assert.Throws<ArgumentNullException>(() => clientStream.BeginRead(null, 0, 100, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.BeginRead(new byte[1], -1, 1, null, null)); Assert.ThrowsAny<ArgumentException>(() => clientStream.BeginRead(new byte[1], 2, 1, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => clientStream.BeginRead(new byte[1], 0, -1, null, null)); Assert.ThrowsAny<ArgumentException>(() => clientStream.BeginRead(new byte[1], 0, 2, null, null)); Assert.Throws<ArgumentNullException>(() => clientStream.EndRead(null)); Assert.Throws<ArgumentNullException>(() => { clientStream.ReadAsync(null, 0, 100, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.ReadAsync(new byte[1], -1, 1, default); }); Assert.ThrowsAny<ArgumentException>(() => { clientStream.ReadAsync(new byte[1], 2, 1, default); }); Assert.Throws<ArgumentOutOfRangeException>(() => { clientStream.ReadAsync(new byte[1], 0, -1, default); }); Assert.ThrowsAny<ArgumentException>(() => { clientStream.ReadAsync(new byte[1], 0, 2, default); }); // Validate writing APIs on clientStream clientStream.WriteByte((byte)'!'); clientStream.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2); Assert.Equal("!", await connection.Reader.ReadLineAsync()); clientStream.Write(new Span<byte>(new byte[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\r', (byte)'\n' })); Assert.Equal("hello", await connection.Reader.ReadLineAsync()); await clientStream.WriteAsync(new byte[] { (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 7); Assert.Equal("world", await connection.Reader.ReadLineAsync()); await clientStream.WriteAsync(new Memory<byte>(new byte[] { (byte)'a', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 5)); Assert.Equal("and", await connection.Reader.ReadLineAsync()); await Task.Factory.FromAsync(clientStream.BeginWrite, clientStream.EndWrite, new byte[] { (byte)'b', (byte)'e', (byte)'y', (byte)'o', (byte)'n', (byte)'d', (byte)'\r', (byte)'\n' }, 0, 8, null); Assert.Equal("beyond", await connection.Reader.ReadLineAsync()); clientStream.Flush(); await clientStream.FlushAsync(); // Validate reading APIs on clientStream await connection.Stream.WriteAsync(Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz")); var buffer = new byte[1]; Assert.Equal('a', clientStream.ReadByte()); Assert.Equal(1, clientStream.Read(buffer, 0, 1)); Assert.Equal((byte)'b', buffer[0]); Assert.Equal(1, clientStream.Read(new Span<byte>(buffer, 0, 1))); Assert.Equal((byte)'c', buffer[0]); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal((byte)'d', buffer[0]); Assert.Equal(1, await clientStream.ReadAsync(new Memory<byte>(buffer, 0, 1))); Assert.Equal((byte)'e', buffer[0]); Assert.Equal(1, await Task.Factory.FromAsync(clientStream.BeginRead, clientStream.EndRead, buffer, 0, 1, null)); Assert.Equal((byte)'f', buffer[0]); var ms = new MemoryStream(); Task copyTask = clientStream.CopyToAsync(ms); string bigString = string.Concat(Enumerable.Repeat("abcdefghijklmnopqrstuvwxyz", 1000)); Task lotsOfDataSent = connection.Socket.SendAsync(Encoding.ASCII.GetBytes(bigString), SocketFlags.None); connection.Socket.Shutdown(SocketShutdown.Send); await copyTask; await lotsOfDataSent; Assert.Equal("ghijklmnopqrstuvwxyz" + bigString, Encoding.ASCII.GetString(ms.ToArray())); } }); } }); } } public sealed class SocketsHttpHandler_Connect_Test : HttpClientHandlerTestBase { protected override bool UseSocketsHttpHandler => true; [Fact] public async Task ConnectMethod_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("CONNECT"), url); request.Headers.Host = "foo.com:345"; // We need to use ResponseHeadersRead here, otherwise we will hang trying to buffer the response body. Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); await server.AcceptConnectionAsync(async connection => { // Verify that Host header exist and has same value and URI authority. List<string> lines = await connection.ReadRequestHeaderAsync().ConfigureAwait(false); string authority = lines[0].Split()[1]; foreach (string line in lines) { if (line.StartsWith("Host:",StringComparison.InvariantCultureIgnoreCase)) { Assert.Equal(line, "Host: foo.com:345"); break; } } Task serverTask = connection.SendResponseAsync(HttpStatusCode.OK); await TestHelper.WhenAllCompletedOrAnyFailed(responseTask, serverTask).ConfigureAwait(false); using (Stream clientStream = await (await responseTask).Content.ReadAsStreamAsync()) { Assert.True(clientStream.CanWrite); Assert.True(clientStream.CanRead); Assert.False(clientStream.CanSeek); TextReader clientReader = new StreamReader(clientStream); TextWriter clientWriter = new StreamWriter(clientStream) { AutoFlush = true }; TextReader serverReader = connection.Reader; TextWriter serverWriter = connection.Writer; const string helloServer = "hello server"; const string helloClient = "hello client"; const string goodbyeServer = "goodbye server"; const string goodbyeClient = "goodbye client"; clientWriter.WriteLine(helloServer); Assert.Equal(helloServer, serverReader.ReadLine()); serverWriter.WriteLine(helloClient); Assert.Equal(helloClient, clientReader.ReadLine()); clientWriter.WriteLine(goodbyeServer); Assert.Equal(goodbyeServer, serverReader.ReadLine()); serverWriter.WriteLine(goodbyeClient); Assert.Equal(goodbyeClient, clientReader.ReadLine()); } }); } }); } [Fact] public async Task ConnectMethod_Fails() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("CONNECT"), url); request.Headers.Host = "foo.com:345"; // We need to use ResponseHeadersRead here, otherwise we will hang trying to buffer the response body. Task<HttpResponseMessage> responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); await server.AcceptConnectionAsync(async connection => { Task<List<string>> serverTask = connection.ReadRequestHeaderAndSendResponseAsync(HttpStatusCode.Forbidden, content: "error"); await TestHelper.WhenAllCompletedOrAnyFailed(responseTask, serverTask); HttpResponseMessage response = await responseTask; Assert.True(response.StatusCode == HttpStatusCode.Forbidden); }); } }); } } public sealed class SocketsHttpHandler_HttpClientHandler_ConnectionPooling_Test : HttpClientHandlerTestBase { protected override bool UseSocketsHttpHandler => true; [Fact] public async Task MultipleIterativeRequests_SameConnectionReused() { using (HttpClient client = CreateHttpClient()) using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var ep = (IPEndPoint)listener.LocalEndPoint; var uri = new Uri($"http://{ep.Address}:{ep.Port}/"); string responseBody = "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "\r\n"; Task<string> firstRequest = client.GetStringAsync(uri); using (Socket server = await listener.AcceptAsync()) using (var serverStream = new NetworkStream(server, ownsSocket: false)) using (var serverReader = new StreamReader(serverStream)) { while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync())); await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None); await firstRequest; Task<Socket> secondAccept = listener.AcceptAsync(); // shouldn't complete Task<string> additionalRequest = client.GetStringAsync(uri); while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync())); await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None); await additionalRequest; Assert.False(secondAccept.IsCompleted, $"Second accept should never complete"); } } } [OuterLoop("Incurs a delay")] [Fact] public async Task ServerDisconnectsAfterInitialRequest_SubsequentRequestUsesDifferentConnection() { using (HttpClient client = CreateHttpClient()) { await LoopbackServer.CreateServerAsync(async (server, uri) => { // Make multiple requests iteratively. for (int i = 0; i < 2; i++) { Task<string> request = client.GetStringAsync(uri); await server.AcceptConnectionSendResponseAndCloseAsync(); await request; if (i == 0) { await Task.Delay(2000); // give client time to see the closing before next connect } } }); } } [Fact] public async Task ServerSendsGarbageAfterInitialRequest_SubsequentRequestUsesDifferentConnection() { using (HttpClient client = CreateHttpClient()) { await LoopbackServer.CreateServerAsync(async (server, uri) => { var releaseServer = new TaskCompletionSource<bool>(); // Make multiple requests iteratively. Task serverTask1 = server.AcceptConnectionAsync(async connection => { await connection.Writer.WriteAsync(LoopbackServer.GetHttpResponse(connectionClose: false) + "here is a bunch of garbage"); await releaseServer.Task; // keep connection alive on the server side }); await client.GetStringAsync(uri); Task serverTask2 = server.AcceptConnectionSendCustomResponseAndCloseAsync(LoopbackServer.GetHttpResponse(connectionClose: true)); await new[] { client.GetStringAsync(uri), serverTask2 }.WhenAllOrAnyFailed(); releaseServer.SetResult(true); await serverTask1; }); } } [Fact] public async Task ServerSendsConnectionClose_SubsequentRequestUsesDifferentConnection() { using (HttpClient client = CreateHttpClient()) { await LoopbackServer.CreateServerAsync(async (server, uri) => { string responseBody = "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; // Make first request. Task<string> request1 = client.GetStringAsync(uri); await server.AcceptConnectionAsync(async connection1 => { await connection1.ReadRequestHeaderAndSendCustomResponseAsync(responseBody); await request1; // Make second request and expect it to be served from a different connection. Task<string> request2 = client.GetStringAsync(uri); await server.AcceptConnectionAsync(async connection2 => { await connection2.ReadRequestHeaderAndSendCustomResponseAsync(responseBody); await request2; }); }); }); } } [Theory] [InlineData("PooledConnectionLifetime")] [InlineData("PooledConnectionIdleTimeout")] public async Task SmallConnectionTimeout_SubsequentRequestUsesDifferentConnection(string timeoutPropertyName) { using (var handler = new SocketsHttpHandler()) { switch (timeoutPropertyName) { case "PooledConnectionLifetime": handler.PooledConnectionLifetime = TimeSpan.FromMilliseconds(1); break; case "PooledConnectionIdleTimeout": handler.PooledConnectionLifetime = TimeSpan.FromMilliseconds(1); break; default: throw new ArgumentOutOfRangeException(nameof(timeoutPropertyName)); } using (HttpClient client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (server, uri) => { // Make first request. Task<string> request1 = client.GetStringAsync(uri); await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAndSendResponseAsync(); await request1; // Wait a small amount of time before making the second request, to give the first request time to timeout. await Task.Delay(100); // Make second request and expect it to be served from a different connection. Task<string> request2 = client.GetStringAsync(uri); await server.AcceptConnectionAsync(async connection2 => { await connection2.ReadRequestHeaderAndSendResponseAsync(); await request2; }); }); }); } } } [OuterLoop] [Theory] [InlineData(false)] [InlineData(true)] public void ConnectionsPooledThenDisposed_NoUnobservedTaskExceptions(bool secure) { RemoteInvoke(async secureString => { var releaseServer = new TaskCompletionSource<bool>(); await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var handler = new SocketsHttpHandler()) using (var client = new HttpClient(handler)) { handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; }; handler.PooledConnectionLifetime = TimeSpan.FromMilliseconds(1); var exceptions = new List<Exception>(); TaskScheduler.UnobservedTaskException += (s, e) => exceptions.Add(e.Exception); await client.GetStringAsync(uri); await Task.Delay(10); // any value >= the lifetime Task ignored = client.GetStringAsync(uri); // force the pool to look for the previous connection and find it's too old await Task.Delay(100); // give some time for the connection close to fail pending reads GC.Collect(); GC.WaitForPendingFinalizers(); // Note that there are race conditions here such that we may not catch every failure, // and thus could have some false negatives, but there won't be any false positives. Assert.True(exceptions.Count == 0, string.Concat(exceptions)); releaseServer.SetResult(true); } }, server => server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAndSendResponseAsync(content: "hello world"); await releaseServer.Task; }), new LoopbackServer.Options { UseSsl = bool.Parse(secureString) }); return SuccessExitCode; }, secure.ToString()).Dispose(); } [OuterLoop] [Fact] public void HandlerDroppedWithoutDisposal_NotKeptAlive() { var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); HandlerDroppedWithoutDisposal_NotKeptAliveCore(tcs); for (int i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Assert.True(tcs.Task.IsCompleted); } [MethodImpl(MethodImplOptions.NoInlining)] private void HandlerDroppedWithoutDisposal_NotKeptAliveCore(TaskCompletionSource<bool> setOnFinalized) { // This relies on knowing that in order for the connection pool to operate, it needs // to maintain a reference to the supplied IWebProxy. As such, we provide a proxy // that when finalized will set our event, so that we can determine the state associated // with a handler has gone away. IWebProxy p = new PassthroughProxyWithFinalizerCallback(() => setOnFinalized.TrySetResult(true)); // Make a bunch of requests and drop the associated HttpClient instances after making them, without disposal. Task.WaitAll((from i in Enumerable.Range(0, 10) select LoopbackServer.CreateClientAndServerAsync( url => new HttpClient(new SocketsHttpHandler { Proxy = p }).GetStringAsync(url), server => server.AcceptConnectionSendResponseAndCloseAsync())).ToArray()); } private sealed class PassthroughProxyWithFinalizerCallback : IWebProxy { private readonly Action _callback; public PassthroughProxyWithFinalizerCallback(Action callback) => _callback = callback; ~PassthroughProxyWithFinalizerCallback() => _callback(); public ICredentials Credentials { get; set; } public Uri GetProxy(Uri destination) => destination; public bool IsBypassed(Uri host) => true; } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not support custom proxies.")] [Fact] public async Task ProxyAuth_SameConnection_Succeeds() { Task serverTask = LoopbackServer.CreateServerAsync(async (proxyServer, proxyUrl) => { string responseBody = "HTTP/1.1 407 Proxy Auth Required\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Proxy-Authenticate: Basic\r\n" + "Content-Length: 0\r\n" + "\r\n"; using (var handler = new HttpClientHandler()) { handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, new NetworkCredential("abc", "def")); using (var client = new HttpClient(handler)) { Task<string> request = client.GetStringAsync($"http://notarealserver.com/"); await proxyServer.AcceptConnectionAsync(async connection => { // Get first request, no body for GET. await connection.ReadRequestHeaderAndSendCustomResponseAsync(responseBody).ConfigureAwait(false); // Client should send another request after being rejected with 407. await connection.ReadRequestHeaderAndSendResponseAsync(content:"OK").ConfigureAwait(false); }); string response = await request; Assert.Equal("OK", response); } } }); await serverTask.TimeoutAfter(TestHelper.PassingTestTimeoutMilliseconds); } } public sealed class SocketsHttpHandler_PublicAPIBehavior_Test { private static async Task IssueRequestAsync(HttpMessageHandler handler) { using (var c = new HttpMessageInvoker(handler, disposeHandler: false)) await Assert.ThrowsAnyAsync<Exception>(() => c.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("/shouldquicklyfail", UriKind.Relative)), default)); } [Fact] public void AllowAutoRedirect_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.True(handler.AllowAutoRedirect); handler.AllowAutoRedirect = true; Assert.True(handler.AllowAutoRedirect); handler.AllowAutoRedirect = false; Assert.False(handler.AllowAutoRedirect); } } [Fact] public void AutomaticDecompression_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression); handler.AutomaticDecompression = DecompressionMethods.GZip; Assert.Equal(DecompressionMethods.GZip, handler.AutomaticDecompression); handler.AutomaticDecompression = DecompressionMethods.Deflate; Assert.Equal(DecompressionMethods.Deflate, handler.AutomaticDecompression); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression); } } [Fact] public void CookieContainer_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { CookieContainer container = handler.CookieContainer; Assert.Same(container, handler.CookieContainer); var newContainer = new CookieContainer(); handler.CookieContainer = newContainer; Assert.Same(newContainer, handler.CookieContainer); } } [Fact] public void Credentials_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Null(handler.Credentials); var newCredentials = new NetworkCredential("username", "password"); handler.Credentials = newCredentials; Assert.Same(newCredentials, handler.Credentials); } } [Fact] public void DefaultProxyCredentials_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Null(handler.DefaultProxyCredentials); var newCredentials = new NetworkCredential("username", "password"); handler.DefaultProxyCredentials = newCredentials; Assert.Same(newCredentials, handler.DefaultProxyCredentials); } } [Fact] public void MaxAutomaticRedirections_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(50, handler.MaxAutomaticRedirections); handler.MaxAutomaticRedirections = int.MaxValue; Assert.Equal(int.MaxValue, handler.MaxAutomaticRedirections); handler.MaxAutomaticRedirections = 1; Assert.Equal(1, handler.MaxAutomaticRedirections); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxAutomaticRedirections = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxAutomaticRedirections = -1); } } [Fact] public void MaxConnectionsPerServer_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer); handler.MaxConnectionsPerServer = int.MaxValue; Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer); handler.MaxConnectionsPerServer = 1; Assert.Equal(1, handler.MaxConnectionsPerServer); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxConnectionsPerServer = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxConnectionsPerServer = -1); } } [Fact] public void MaxResponseHeadersLength_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(64, handler.MaxResponseHeadersLength); handler.MaxResponseHeadersLength = int.MaxValue; Assert.Equal(int.MaxValue, handler.MaxResponseHeadersLength); handler.MaxResponseHeadersLength = 1; Assert.Equal(1, handler.MaxResponseHeadersLength); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = -1); } } [Fact] public void PreAuthenticate_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.False(handler.PreAuthenticate); handler.PreAuthenticate = false; Assert.False(handler.PreAuthenticate); handler.PreAuthenticate = true; Assert.True(handler.PreAuthenticate); } } [Fact] public void PooledConnectionIdleTimeout_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(TimeSpan.FromMinutes(2), handler.PooledConnectionIdleTimeout); handler.PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan; Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionIdleTimeout); handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(0); Assert.Equal(TimeSpan.FromSeconds(0), handler.PooledConnectionIdleTimeout); handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(1); Assert.Equal(TimeSpan.FromSeconds(1), handler.PooledConnectionIdleTimeout); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(-2)); } } [Fact] public void PooledConnectionLifetime_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionLifetime); handler.PooledConnectionLifetime = Timeout.InfiniteTimeSpan; Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionLifetime); handler.PooledConnectionLifetime = TimeSpan.FromSeconds(0); Assert.Equal(TimeSpan.FromSeconds(0), handler.PooledConnectionLifetime); handler.PooledConnectionLifetime = TimeSpan.FromSeconds(1); Assert.Equal(TimeSpan.FromSeconds(1), handler.PooledConnectionLifetime); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.PooledConnectionLifetime = TimeSpan.FromSeconds(-2)); } } [Fact] public void Properties_Roundtrips() { using (var handler = new SocketsHttpHandler()) { IDictionary<string, object> props = handler.Properties; Assert.NotNull(props); Assert.Empty(props); props.Add("hello", "world"); Assert.Equal(1, props.Count); Assert.Equal("world", props["hello"]); } } [Fact] public void Proxy_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.Null(handler.Proxy); var proxy = new WebProxy(); handler.Proxy = proxy; Assert.Same(proxy, handler.Proxy); } } [Fact] public void SslOptions_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { SslClientAuthenticationOptions options = handler.SslOptions; Assert.NotNull(options); Assert.True(options.AllowRenegotiation); Assert.Null(options.ApplicationProtocols); Assert.Equal(X509RevocationMode.NoCheck, options.CertificateRevocationCheckMode); Assert.Null(options.ClientCertificates); Assert.Equal(SslProtocols.None, options.EnabledSslProtocols); Assert.Equal(EncryptionPolicy.RequireEncryption, options.EncryptionPolicy); Assert.Null(options.LocalCertificateSelectionCallback); Assert.Null(options.RemoteCertificateValidationCallback); Assert.Null(options.TargetHost); Assert.Same(options, handler.SslOptions); var newOptions = new SslClientAuthenticationOptions(); handler.SslOptions = newOptions; Assert.Same(newOptions, handler.SslOptions); } } [Fact] public void UseCookies_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.True(handler.UseCookies); handler.UseCookies = true; Assert.True(handler.UseCookies); handler.UseCookies = false; Assert.False(handler.UseCookies); } } [Fact] public void UseProxy_GetSet_Roundtrips() { using (var handler = new SocketsHttpHandler()) { Assert.True(handler.UseProxy); handler.UseProxy = false; Assert.False(handler.UseProxy); handler.UseProxy = true; Assert.True(handler.UseProxy); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task AfterDisposeSendAsync_GettersUsable_SettersThrow(bool dispose) { using (var handler = new SocketsHttpHandler()) { Type expectedExceptionType; if (dispose) { handler.Dispose(); expectedExceptionType = typeof(ObjectDisposedException); } else { await IssueRequestAsync(handler); expectedExceptionType = typeof(InvalidOperationException); } Assert.True(handler.AllowAutoRedirect); Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression); Assert.NotNull(handler.CookieContainer); Assert.Null(handler.Credentials); Assert.Null(handler.DefaultProxyCredentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer); Assert.Equal(64, handler.MaxResponseHeadersLength); Assert.False(handler.PreAuthenticate); Assert.Equal(TimeSpan.FromMinutes(2), handler.PooledConnectionIdleTimeout); Assert.Equal(Timeout.InfiniteTimeSpan, handler.PooledConnectionLifetime); Assert.NotNull(handler.Properties); Assert.Null(handler.Proxy); Assert.NotNull(handler.SslOptions); Assert.True(handler.UseCookies); Assert.True(handler.UseProxy); Assert.Throws(expectedExceptionType, () => handler.AllowAutoRedirect = false); Assert.Throws(expectedExceptionType, () => handler.AutomaticDecompression = DecompressionMethods.GZip); Assert.Throws(expectedExceptionType, () => handler.CookieContainer = new CookieContainer()); Assert.Throws(expectedExceptionType, () => handler.Credentials = new NetworkCredential("anotheruser", "anotherpassword")); Assert.Throws(expectedExceptionType, () => handler.DefaultProxyCredentials = new NetworkCredential("anotheruser", "anotherpassword")); Assert.Throws(expectedExceptionType, () => handler.MaxAutomaticRedirections = 2); Assert.Throws(expectedExceptionType, () => handler.MaxConnectionsPerServer = 2); Assert.Throws(expectedExceptionType, () => handler.MaxResponseHeadersLength = 2); Assert.Throws(expectedExceptionType, () => handler.PreAuthenticate = false); Assert.Throws(expectedExceptionType, () => handler.PooledConnectionIdleTimeout = TimeSpan.FromSeconds(2)); Assert.Throws(expectedExceptionType, () => handler.PooledConnectionLifetime = TimeSpan.FromSeconds(2)); Assert.Throws(expectedExceptionType, () => handler.Proxy = new WebProxy()); Assert.Throws(expectedExceptionType, () => handler.SslOptions = new SslClientAuthenticationOptions()); Assert.Throws(expectedExceptionType, () => handler.UseCookies = false); Assert.Throws(expectedExceptionType, () => handler.UseProxy = false); } } } public sealed class SocketsHttpHandler_ExternalConfiguration_Test : HttpClientHandlerTestBase { private const string EnvironmentVariableSettingName = "DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER"; private const string AppContextSettingName = "System.Net.Http.UseSocketsHttpHandler"; private static bool UseSocketsHttpHandlerEnvironmentVariableIsNotSet => string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariableSettingName)); [ConditionalTheory(nameof(UseSocketsHttpHandlerEnvironmentVariableIsNotSet))] [InlineData("true", true)] [InlineData("TRUE", true)] [InlineData("tRuE", true)] [InlineData("1", true)] [InlineData("0", false)] [InlineData("false", false)] [InlineData("helloworld", true)] [InlineData("", true)] public void HttpClientHandler_SettingEnvironmentVariableChangesDefault(string envVarValue, bool expectedUseSocketsHandler) { RemoteInvoke((innerEnvVarValue, innerExpectedUseSocketsHandler) => { Environment.SetEnvironmentVariable(EnvironmentVariableSettingName, innerEnvVarValue); using (var handler = new HttpClientHandler()) { Assert.Equal(bool.Parse(innerExpectedUseSocketsHandler), IsSocketsHttpHandler(handler)); } return SuccessExitCode; }, envVarValue, expectedUseSocketsHandler.ToString()).Dispose(); } [Fact] public void HttpClientHandler_SettingAppContextChangesDefault() { RemoteInvoke(() => { AppContext.SetSwitch(AppContextSettingName, isEnabled: true); using (var handler = new HttpClientHandler()) { Assert.True(IsSocketsHttpHandler(handler)); } AppContext.SetSwitch(AppContextSettingName, isEnabled: false); using (var handler = new HttpClientHandler()) { Assert.False(IsSocketsHttpHandler(handler)); } return SuccessExitCode; }).Dispose(); } [Fact] public void HttpClientHandler_AppContextOverridesEnvironmentVariable() { RemoteInvoke(() => { Environment.SetEnvironmentVariable(EnvironmentVariableSettingName, "true"); using (var handler = new HttpClientHandler()) { Assert.True(IsSocketsHttpHandler(handler)); } AppContext.SetSwitch(AppContextSettingName, isEnabled: false); using (var handler = new HttpClientHandler()) { Assert.False(IsSocketsHttpHandler(handler)); } AppContext.SetSwitch(AppContextSettingName, isEnabled: true); Environment.SetEnvironmentVariable(EnvironmentVariableSettingName, null); using (var handler = new HttpClientHandler()) { Assert.True(IsSocketsHttpHandler(handler)); } return SuccessExitCode; }).Dispose(); } } public sealed class SocketsHttpHandlerTest_Http2 : HttpClientHandlerTest_Http2 { protected override bool UseSocketsHttpHandler => true; } [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.SupportsAlpn))] public sealed class SocketsHttpHandlerTest_Cookies_Http2 : HttpClientHandlerTest_Cookies { protected override bool UseSocketsHttpHandler => true; protected override bool UseHttp2LoopbackServer => true; } }
using System; namespace SharpLua.LASM { public class Disassembler { static string Reverse(string s) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } static int index = 0; //static bool big = false; static LuaFile file = new LuaFile(); static Func<string, double> loadNumber = null; static string chunk = ""; static string Read(int len) { string c = chunk.Substring(index, len); index += len; if (file.BigEndian) { c = Reverse(c); } return c; } static int ReadInt8() { return (int)Read(1)[0]; } static double ReadNumber() { return loadNumber(Read(file.NumberSize)); } static string GetString(int len) { return Read(len); } static int ReadInt32() { if (file.IntegerSize > file.SizeT) throw new Exception("IntegerSize cannot be greater than SizeT"); string x = Read(file.SizeT); if (x == null || x.Length == 0) throw new Exception("Could not load integer"); else { long sum = 0; for (int i = file.IntegerSize - 1; i >= 0; i--) { sum = (sum * 256) + (int)x[i]; } // check for negative number if (x[file.IntegerSize - 1] > 127) sum = sum - (long)Bit.ldexp(1, 8 * file.IntegerSize); return (int)sum; } } static string ReadString() { int len = (int)ReadInt32(); string s = GetString(len); // Strip last '\0': return s.Length > 0 ? s.Substring(0, s.Length - 1) : s; } static Chunk ReadFunction() { Chunk c = new Chunk(); c.Name = ReadString(); c.FirstLine = (uint)ReadInt32(); c.LastLine = (ulong)ReadInt32(); c.UpvalueCount = ReadInt8(); // Upvalues c.ArgumentCount = ReadInt8(); c.Vararg = ReadInt8(); c.MaxStackSize = (uint)ReadInt8(); // Instructions long count = ReadInt32(); for (int i = 0; i < count; i++) { uint op = (uint)ReadInt32(); int opcode = (int)Lua.GET_OPCODE(op); //(int)Bit.Get(op, 1, 6); Instruction instr = Instruction.From(op); instr.Number = i; c.Instructions.Add(instr); } // Constants count = ReadInt32(); for (int i = 0; i < count; i++) { Constant cnst = new Constant(0, null); int t = ReadInt8(); cnst.Number = i; if (t == 0) { cnst.Type = ConstantType.Nil; cnst.Value = null; } else if (t == 1) { cnst.Type = ConstantType.Bool; cnst.Value = ReadInt8() != 0; } else if (t == 3) { cnst.Type = ConstantType.Number; cnst.Value = ReadNumber(); } else if (t == 4) { cnst.Type = ConstantType.String; cnst.Value = ReadString(); } c.Constants.Add(cnst); } // Protos count = ReadInt32(); for (int i = 0; i < count; i++) c.Protos.Add(ReadFunction()); // Line numbers count = ReadInt32(); for (int i = 0; i < count; i++) c.Instructions[i].LineNumber = ReadInt32(); // Locals count = ReadInt32(); for (int i = 0; i < count; i++) c.Locals.Add(new Local(ReadString(), ReadInt32(), ReadInt32())); // Upvalues count = ReadInt32(); for (int i = 0; i < count; i++) c.Upvalues.Add(new Upvalue(ReadString())); return c; } /// <summary> /// Returns a disassembled LuaFile /// </summary> /// <param name="c"></param> /// <returns></returns> public static LuaFile Disassemble(string c) { chunk = c; index = 0; file = new LuaFile(); Disassembler.loadNumber = null; if (StringExt.IsNullOrWhiteSpace(chunk)) throw new Exception("chunk is empty"); file.Identifier = GetString(4); // \027Lua if (file.Identifier != (char)27 + "Lua") throw new Exception("Not a valid Lua bytecode chunk"); file.Version = ReadInt8(); // 0x51 if (file.Version != 0x51) throw new Exception(string.Format("Invalid bytecode version, 0x51 expected, got 0x{0:X}", file.Version)); int fmt = ReadInt8(); file.Format = fmt == 0 ? Format.Official : Format.Unofficial; file.FormatNumber = fmt; if (file.Format == Format.Unofficial) throw new Exception("Unknown binary chunk format"); file.BigEndian = ReadInt8() == 0; file.IntegerSize = ReadInt8(); file.SizeT = ReadInt8(); file.InstructionSize = ReadInt8(); file.NumberSize = ReadInt8(); file.IsFloatingPointNumbers = ReadInt8() == 0; loadNumber = PlatformConfig.GetNumberTypeConvertFrom(file); if (file.InstructionSize != 4) throw new Exception("Unsupported instruction size '" + file.InstructionSize + "', expected '4'"); file.Main = ReadFunction(); return file; } /// <summary> /// Returns a decompiled chunk, with info based upon a default LuaFile /// </summary> /// <param name="chunk"></param> /// <returns></returns> public static Chunk DisassembleChunk(string c) { chunk = c; index = 0; file = new LuaFile(); loadNumber = PlatformConfig.GetNumberTypeConvertFrom(file); if (StringExt.IsNullOrWhiteSpace(chunk)) throw new Exception("chunk is empty"); return ReadFunction(); } } }
// 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.Xml; using System.Text; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Shared; using Microsoft.Build.Collections; using Microsoft.Build.Execution; using Microsoft.Build.Evaluation; using Microsoft.Build.Unittest; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using System.Threading.Tasks; public class RequestBuilder_Tests : IDisposable { private AutoResetEvent _newBuildRequestsEvent; private BuildRequestEntry _newBuildRequests_Entry; private FullyQualifiedBuildRequest[] _newBuildRequests_FQRequests; private BuildRequest[] _newBuildRequests_BuildRequests; private AutoResetEvent _buildRequestCompletedEvent; private BuildRequestEntry _buildRequestCompleted_Entry; private MockHost _host; private IRequestBuilder _requestBuilder; private int _nodeRequestId; private string _originalWorkingDirectory; #pragma warning disable xUnit1013 public void LoggingException(Exception e) { } #pragma warning restore xUnit1013 public RequestBuilder_Tests() { _originalWorkingDirectory = Directory.GetCurrentDirectory(); _nodeRequestId = 1; _host = new MockHost(); _host.RequestBuilder = new RequestBuilder(); ((IBuildComponent)_host.RequestBuilder).InitializeComponent(_host); _host.OnLoggingThreadException += this.LoggingException; _newBuildRequestsEvent = new AutoResetEvent(false); _buildRequestCompletedEvent = new AutoResetEvent(false); _requestBuilder = (IRequestBuilder)_host.GetComponent(BuildComponentType.RequestBuilder); _requestBuilder.OnBuildRequestCompleted += this.BuildRequestCompletedCallback; _requestBuilder.OnNewBuildRequests += this.NewBuildRequestsCallback; } public void Dispose() { ((IBuildComponent)_requestBuilder).ShutdownComponent(); _host = null; // Normally, RequestBuilder ensures that this gets reset before completing // requests, but we call it in odd ways here so restore it manually // to keep the overall test invariant happy. Directory.SetCurrentDirectory(_originalWorkingDirectory); } [Fact] public void TestSimpleBuildRequest() { BuildRequestConfiguration configuration = CreateTestProject(1); try { TestTargetBuilder targetBuilder = (TestTargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache configCache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); configCache.AddConfiguration(configuration); BuildRequest request = CreateNewBuildRequest(1, new string[1] { "target1" }); BuildRequestEntry entry = new BuildRequestEntry(request, configuration); BuildResult result = new BuildResult(request); result.AddResultsForTarget("target1", GetEmptySuccessfulTargetResult()); targetBuilder.SetResultsToReturn(result); _requestBuilder.BuildRequest(GetNodeLoggingContext(), entry); WaitForEvent(_buildRequestCompletedEvent, "Build Request Completed"); Assert.Equal(BuildRequestEntryState.Complete, entry.State); Assert.Equal(entry, _buildRequestCompleted_Entry); Assert.Equal(BuildResultCode.Success, _buildRequestCompleted_Entry.Result.OverallResult); } finally { DeleteTestProject(configuration); } } [Fact] public void TestSimpleBuildRequestCancelled() { BuildRequestConfiguration configuration = CreateTestProject(1); try { TestTargetBuilder targetBuilder = (TestTargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache configCache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); configCache.AddConfiguration(configuration); BuildRequest request = CreateNewBuildRequest(1, new string[1] { "target1" }); BuildRequestEntry entry = new BuildRequestEntry(request, configuration); BuildResult result = new BuildResult(request); result.AddResultsForTarget("target1", GetEmptySuccessfulTargetResult()); targetBuilder.SetResultsToReturn(result); _requestBuilder.BuildRequest(GetNodeLoggingContext(), entry); Thread.Sleep(500); _requestBuilder.CancelRequest(); WaitForEvent(_buildRequestCompletedEvent, "Build Request Completed"); Assert.Equal(BuildRequestEntryState.Complete, entry.State); Assert.Equal(entry, _buildRequestCompleted_Entry); Assert.Equal(BuildResultCode.Failure, _buildRequestCompleted_Entry.Result.OverallResult); } finally { DeleteTestProject(configuration); } } [Fact] public void TestRequestWithReference() { BuildRequestConfiguration configuration = CreateTestProject(1); try { TestTargetBuilder targetBuilder = (TestTargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache configCache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); FullyQualifiedBuildRequest[] newRequest = new FullyQualifiedBuildRequest[1] { new FullyQualifiedBuildRequest(configuration, new string[1] { "testTarget2" }, true) }; targetBuilder.SetNewBuildRequests(newRequest); configCache.AddConfiguration(configuration); BuildRequest request = CreateNewBuildRequest(1, new string[1] { "target1" }); BuildRequestEntry entry = new BuildRequestEntry(request, configuration); BuildResult result = new BuildResult(request); result.AddResultsForTarget("target1", GetEmptySuccessfulTargetResult()); targetBuilder.SetResultsToReturn(result); _requestBuilder.BuildRequest(GetNodeLoggingContext(), entry); WaitForEvent(_newBuildRequestsEvent, "New Build Requests"); Assert.Equal(_newBuildRequests_Entry, entry); ObjectModelHelpers.AssertArrayContentsMatch(_newBuildRequests_FQRequests, newRequest); BuildResult newResult = new BuildResult(_newBuildRequests_BuildRequests[0]); newResult.AddResultsForTarget("testTarget2", GetEmptySuccessfulTargetResult()); entry.ReportResult(newResult); _requestBuilder.ContinueRequest(); WaitForEvent(_buildRequestCompletedEvent, "Build Request Completed"); Assert.Equal(BuildRequestEntryState.Complete, entry.State); Assert.Equal(entry, _buildRequestCompleted_Entry); Assert.Equal(BuildResultCode.Success, _buildRequestCompleted_Entry.Result.OverallResult); } finally { DeleteTestProject(configuration); } } [Fact] public void TestRequestWithReferenceCancelled() { BuildRequestConfiguration configuration = CreateTestProject(1); try { TestTargetBuilder targetBuilder = (TestTargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache configCache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); FullyQualifiedBuildRequest[] newRequest = new FullyQualifiedBuildRequest[1] { new FullyQualifiedBuildRequest(configuration, new string[1] { "testTarget2" }, true) }; targetBuilder.SetNewBuildRequests(newRequest); configCache.AddConfiguration(configuration); BuildRequest request = CreateNewBuildRequest(1, new string[1] { "target1" }); BuildRequestEntry entry = new BuildRequestEntry(request, configuration); BuildResult result = new BuildResult(request); result.AddResultsForTarget("target1", GetEmptySuccessfulTargetResult()); targetBuilder.SetResultsToReturn(result); _requestBuilder.BuildRequest(GetNodeLoggingContext(), entry); WaitForEvent(_newBuildRequestsEvent, "New Build Requests"); Assert.Equal(_newBuildRequests_Entry, entry); ObjectModelHelpers.AssertArrayContentsMatch(_newBuildRequests_FQRequests, newRequest); BuildResult newResult = new BuildResult(_newBuildRequests_BuildRequests[0]); newResult.AddResultsForTarget("testTarget2", GetEmptySuccessfulTargetResult()); entry.ReportResult(newResult); _requestBuilder.ContinueRequest(); Thread.Sleep(500); _requestBuilder.CancelRequest(); WaitForEvent(_buildRequestCompletedEvent, "Build Request Completed"); Assert.Equal(BuildRequestEntryState.Complete, entry.State); Assert.Equal(entry, _buildRequestCompleted_Entry); Assert.Equal(BuildResultCode.Failure, _buildRequestCompleted_Entry.Result.OverallResult); } finally { DeleteTestProject(configuration); } } [Fact] public void TestMissingProjectFile() { TestTargetBuilder targetBuilder = (TestTargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache configCache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestConfiguration configuration = new BuildRequestConfiguration(1, new BuildRequestData("testName", new Dictionary<string, string>(), "3.5", new string[0], null), "2.0"); configCache.AddConfiguration(configuration); BuildRequest request = CreateNewBuildRequest(1, new string[1] { "target1" }); BuildRequestEntry entry = new BuildRequestEntry(request, configuration); _requestBuilder.BuildRequest(GetNodeLoggingContext(), entry); WaitForEvent(_buildRequestCompletedEvent, "Build Request Completed"); Assert.Equal(BuildRequestEntryState.Complete, entry.State); Assert.Equal(entry, _buildRequestCompleted_Entry); Assert.Equal(BuildResultCode.Failure, _buildRequestCompleted_Entry.Result.OverallResult); Assert.Equal(typeof(InvalidProjectFileException), _buildRequestCompleted_Entry.Result.Exception.GetType()); } private BuildRequestConfiguration CreateTestProject(int configId) { string projectFileContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <ItemGroup> <Compile Include=`b.cs` /> <Compile Include=`c.cs` /> </ItemGroup> <ItemGroup> <Reference Include=`System` /> </ItemGroup> <Target Name=`Build` /> </Project> "; string projectFile = GetTestProjectFile(configId); File.WriteAllText(projectFile, projectFileContents.Replace('`', '"')); string defaultToolsVersion = null; defaultToolsVersion = FrameworkLocationHelper.PathToDotNetFrameworkV20 == null ? ObjectModelHelpers.MSBuildDefaultToolsVersion : "2.0"; BuildRequestConfiguration config = new BuildRequestConfiguration( configId, new BuildRequestData( projectFile, new Dictionary<string, string>(), ObjectModelHelpers.MSBuildDefaultToolsVersion, new string[0], null), defaultToolsVersion); return config; } private void DeleteTestProject(BuildRequestConfiguration config) { string fileName = GetTestProjectFile(config.ConfigurationId); if (File.Exists(fileName)) { File.Delete(fileName); } } private string GetTestProjectFile(int configId) { return Path.GetTempPath() + "testProject" + configId + ".proj"; } private void NewBuildRequestsCallback(BuildRequestEntry entry, FullyQualifiedBuildRequest[] requests) { _newBuildRequests_FQRequests = requests; _newBuildRequests_BuildRequests = new BuildRequest[requests.Length]; _newBuildRequests_Entry = entry; int index = 0; foreach (FullyQualifiedBuildRequest request in requests) { IConfigCache configCache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestConfiguration matchingConfig = configCache.GetMatchingConfiguration(request.Config); BuildRequest newRequest = CreateNewBuildRequest(matchingConfig.ConfigurationId, request.Targets); entry.WaitForResult(newRequest); _newBuildRequests_BuildRequests[index++] = newRequest; } _newBuildRequestsEvent.Set(); } private void BuildRequestCompletedCallback(BuildRequestEntry entry) { _buildRequestCompleted_Entry = entry; _buildRequestCompletedEvent.Set(); } private BuildRequest CreateNewBuildRequest(int configurationId, string[] targets) { return new BuildRequest(1 /* submissionId */, _nodeRequestId++, configurationId, targets, null, BuildEventContext.Invalid, null); } private TargetResult GetEmptySuccessfulTargetResult() { return new TargetResult(new TaskItem[0] { }, new WorkUnitResult(WorkUnitResultCode.Success, WorkUnitActionCode.Continue, null)); } private void WaitForEvent(WaitHandle evt, string eventName) { if (!evt.WaitOne(5000)) { Assert.True(false, "Did not receive " + eventName + " callback before the timeout expired."); } } private NodeLoggingContext GetNodeLoggingContext() { return new NodeLoggingContext(_host, 1, false); } } internal class TestTargetBuilder : ITargetBuilder, IBuildComponent { private IBuildComponentHost _host; private IResultsCache _cache; private FullyQualifiedBuildRequest[] _newRequests; private IRequestBuilderCallback _requestBuilderCallback; internal void SetResultsToReturn(BuildResult result) { _cache.AddResult(result); } internal void SetNewBuildRequests(FullyQualifiedBuildRequest[] requests) { _newRequests = requests; } #region ITargetBuilder Members public Task<BuildResult> BuildTargets(ProjectLoggingContext loggingContext, BuildRequestEntry entry, IRequestBuilderCallback callback, string[] targets, Lookup baseLookup, CancellationToken cancellationToken) { _requestBuilderCallback = callback; if (cancellationToken.WaitHandle.WaitOne(1500)) { BuildResult result = new BuildResult(entry.Request); foreach (string target in targets) { result.AddResultsForTarget(target, BuildResultUtilities.GetEmptyFailingTargetResult()); } return Task<BuildResult>.FromResult(result); } if (null != _newRequests) { string[] projectFiles = new string[_newRequests.Length]; PropertyDictionary<ProjectPropertyInstance>[] properties = new PropertyDictionary<ProjectPropertyInstance>[_newRequests.Length]; string[] toolsVersions = new string[_newRequests.Length]; for (int i = 0; i < projectFiles.Length; ++i) { projectFiles[i] = _newRequests[i].Config.ProjectFullPath; properties[i] = new PropertyDictionary<ProjectPropertyInstance>(_newRequests[i].Config.GlobalProperties); toolsVersions[i] = _newRequests[i].Config.ToolsVersion; } _requestBuilderCallback.BuildProjects(projectFiles, properties, toolsVersions, _newRequests[0].Targets, _newRequests[0].ResultsNeeded); if (cancellationToken.WaitHandle.WaitOne(1500)) { BuildResult result = new BuildResult(entry.Request); foreach (string target in targets) { result.AddResultsForTarget(target, BuildResultUtilities.GetEmptyFailingTargetResult()); } return Task<BuildResult>.FromResult(result); } } return Task<BuildResult>.FromResult(_cache.GetResultForRequest(entry.Request)); } #endregion #region IBuildComponent Members public void InitializeComponent(IBuildComponentHost host) { _host = host; _cache = new ResultsCache(); } public void ShutdownComponent() { _host = null; _cache = null; } #endregion } }
using System; using System.Collections.Generic; using De.Osthus.Ambeth.Collections; using De.Osthus.Ambeth.Ioc.Extendable; using De.Osthus.Ambeth.Ioc.Threadlocal; using De.Osthus.Ambeth.Log; using System.Threading; namespace De.Osthus.Ambeth.Util { public class ClassTupleEntry<V> : HashMap<ConversionKey, Object> { public readonly HashMap<ConversionKey, Object> typeToDefEntryMap = new HashMap<ConversionKey, Object>(0.5f); public readonly HashMap<Strong2Key<V>, List<Def2Entry<V>>> definitionReverseMap = new HashMap<Strong2Key<V>, List<Def2Entry<V>>>(0.5f); public ClassTupleEntry() : base(0.5f) { // Intended blank } } public class ClassTupleExtendableContainer<V> : MapExtendableContainer<ConversionKey, V> { protected static readonly Object alreadyHandled = new Object(); protected volatile ClassTupleEntry<V> classEntry = new ClassTupleEntry<V>(); public ClassTupleExtendableContainer(String message, String keyMessage) : base(message, keyMessage) { // Intended blank } public ClassTupleExtendableContainer(String message, String keyMessage, bool multiValue) : base(message, keyMessage, multiValue) { // Intended blank } public V GetExtension(Type sourceType, Type targetType) { return GetExtension(new ConversionKey(sourceType, targetType)); } public override V GetExtension(ConversionKey key) { Object extension = this.classEntry.Get(key); if (extension == null) { Object writeLock = GetWriteLock(); lock (writeLock) { extension = this.classEntry.Get(key); if (extension == null) { ClassTupleEntry<V> classEntry = CopyStructure(); classEntry.Put(key, alreadyHandled); classEntry.typeToDefEntryMap.Put(key, alreadyHandled); CheckToWeakRegisterExistingExtensions(key, classEntry); this.classEntry = classEntry; extension = classEntry.Get(key); if (extension == null) { return default(V); } } } } if (Object.ReferenceEquals(extension, alreadyHandled)) { // Already tried return default(V); } return (V)extension; } protected ClassTupleEntry<V> CopyStructure() { ClassTupleEntry<V> newClassEntry = new ClassTupleEntry<V>(); HashMap<ConversionKey, Object> newTypeToDefEntryMap = newClassEntry.typeToDefEntryMap; HashMap<Strong2Key<V>, List<Def2Entry<V>>> newDefinitionReverseMap = newClassEntry.definitionReverseMap; IdentityHashMap<Def2Entry<V>, Def2Entry<V>> originalToCopyMap = new IdentityHashMap<Def2Entry<V>, Def2Entry<V>>(); foreach (Entry<ConversionKey, Object> entry in classEntry.typeToDefEntryMap) { ConversionKey key = entry.Key; Object value = entry.Value; if (Object.ReferenceEquals(value, alreadyHandled)) { newTypeToDefEntryMap.Put(key, alreadyHandled); } else { InterfaceFastList<Def2Entry<V>> list = (InterfaceFastList<Def2Entry<V>>)value; InterfaceFastList<Def2Entry<V>> newList = new InterfaceFastList<Def2Entry<V>>(); IListElem<Def2Entry<V>> pointer = list.First; while (pointer != null) { Def2Entry<V> defEntry = pointer.ElemValue; Def2Entry<V> newDefEntry = new Def2Entry<V>(defEntry.extension, defEntry.sourceType, defEntry.targetType, defEntry.sourceDistance, defEntry.targetDistance); originalToCopyMap.Put(defEntry, newDefEntry); newList.PushLast(newDefEntry); pointer = pointer.Next; } newTypeToDefEntryMap.Put(key, newList); } TypeToDefEntryMapChanged(newClassEntry, key); } foreach (Entry<Strong2Key<V>, List<Def2Entry<V>>> entry in classEntry.definitionReverseMap) { List<Def2Entry<V>> defEntries = entry.Value; List<Def2Entry<V>> newDefEntries = new List<Def2Entry<V>>(defEntries.Count); for (int a = 0, size = defEntries.Count; a < size; a++) { Def2Entry<V> newDefEntry = originalToCopyMap.Get(defEntries[a]); if (newDefEntry == null) { throw new Exception("Must never happen"); } newDefEntries.Add(newDefEntry); } newDefinitionReverseMap.Put(entry.Key, newDefEntries); } return newClassEntry; } protected bool CheckToWeakRegisterExistingExtensions(ConversionKey conversionKey, ClassTupleEntry<V> classEntry) { bool changesHappened = false; foreach (Entry<Strong2Key<V>, List<Def2Entry<V>>> entry in classEntry.definitionReverseMap) { Strong2Key<V> strongKey = entry.Key; ConversionKey registeredStrongKey = strongKey.key; int sourceDistance = ClassExtendableContainer<V>.GetDistanceForType(conversionKey.SourceType, registeredStrongKey.SourceType); if (sourceDistance == ClassExtendableContainer<V>.NO_VALID_DISTANCE) { continue; } int targetDistance = ClassExtendableContainer<V>.GetDistanceForType(registeredStrongKey.TargetType, conversionKey.TargetType); if (targetDistance == ClassExtendableContainer<V>.NO_VALID_DISTANCE) { continue; } List<Def2Entry<V>> defEntries = entry.Value; for (int a = defEntries.Count; a-- > 0; ) { Def2Entry<V> defEntry = defEntries[a]; changesHappened |= AppendRegistration(registeredStrongKey, conversionKey, defEntry.extension, sourceDistance, targetDistance, classEntry); } } return changesHappened; } protected bool CheckToWeakRegisterExistingTypes(ConversionKey key, V extension, ClassTupleEntry<V> classEntry) { bool changesHappened = false; foreach (Entry<ConversionKey, Object> entry in classEntry.typeToDefEntryMap) { ConversionKey existingRequestedKey = entry.Key; int sourceDistance = ClassExtendableContainer<V>.GetDistanceForType(existingRequestedKey.SourceType, key.SourceType); if (sourceDistance == ClassExtendableContainer<V>.NO_VALID_DISTANCE) { continue; } int targetDistance = ClassExtendableContainer<V>.GetDistanceForType(key.TargetType, existingRequestedKey.TargetType); if (targetDistance == ClassExtendableContainer<V>.NO_VALID_DISTANCE) { continue; } changesHappened |= AppendRegistration(key, existingRequestedKey, extension, sourceDistance, targetDistance, classEntry); } return changesHappened; } public void Register(V extension, Type sourceType, Type targetType) { ParamChecker.AssertParamNotNull(sourceType, "sourceType"); ParamChecker.AssertParamNotNull(targetType, "targetType"); Register(extension, new ConversionKey(sourceType, targetType)); } public override void Register(V extension, ConversionKey key) { ParamChecker.AssertParamNotNull(extension, "extension"); ParamChecker.AssertParamNotNull(key, "key"); Object writeLock = GetWriteLock(); lock (writeLock) { base.Register(extension, key); ClassTupleEntry<V> classEntry = CopyStructure(); AppendRegistration(key, key, extension, 0, 0, classEntry); CheckToWeakRegisterExistingTypes(key, extension, classEntry); CheckToWeakRegisterExistingExtensions(key, classEntry); this.classEntry = classEntry; } } public void Unregister(V extension, Type sourceType, Type targetType) { ParamChecker.AssertParamNotNull(sourceType, "sourceType"); ParamChecker.AssertParamNotNull(targetType, "targetType"); Unregister(extension, new ConversionKey(sourceType, targetType)); } public override void Unregister(V extension, ConversionKey key) { ParamChecker.AssertParamNotNull(extension, "extension"); ParamChecker.AssertParamNotNull(key, "key"); Object writeLock = GetWriteLock(); lock (writeLock) { base.Unregister(extension, key); ClassTupleEntry<V> classEntry = CopyStructure(); HashMap<Strong2Key<V>, List<Def2Entry<V>>> definitionReverseMap = classEntry.definitionReverseMap; List<Def2Entry<V>> weakEntriesOfStrongType = definitionReverseMap.Remove(new Strong2Key<V>(extension, key)); if (weakEntriesOfStrongType == null) { return; } HashMap<ConversionKey, Object> typeToDefEntryMap = classEntry.typeToDefEntryMap; for (int a = weakEntriesOfStrongType.Count; a-- > 0; ) { Def2Entry<V> defEntry = weakEntriesOfStrongType[a]; ConversionKey registeredKey = new ConversionKey(defEntry.sourceType, defEntry.targetType); Object value = typeToDefEntryMap.Get(registeredKey); InterfaceFastList<Def2Entry<V>> list = (InterfaceFastList<Def2Entry<V>>)value; list.Remove(defEntry); if (list.Count == 0) { typeToDefEntryMap.Remove(registeredKey); } TypeToDefEntryMapChanged(classEntry, registeredKey); } this.classEntry = classEntry; } } protected void TypeToDefEntryMapChanged(ClassTupleEntry<V> classEntry, ConversionKey key) { Object obj = classEntry.typeToDefEntryMap.Get(key); if (obj == null) { classEntry.Remove(key); return; } if (obj == alreadyHandled) { classEntry.Put(key, alreadyHandled); return; } if (obj is Def2Entry<V>) { classEntry.Put(key, ((Def2Entry<V>) obj).extension); return; } Def2Entry<V> firstDefEntry = ((InterfaceFastList<Def2Entry<V>>) obj).First.ElemValue; classEntry.Put(key, firstDefEntry.extension); } protected bool AppendRegistration(ConversionKey strongTypeKey, ConversionKey key, V extension, int sourceDistance, int targetDistance, ClassTupleEntry<V> classEntry) { HashMap<ConversionKey, Object> typeToDefEntryMap = classEntry.typeToDefEntryMap; Object fastList = typeToDefEntryMap.Get(key); if (fastList != null && fastList != alreadyHandled) { IListElem<Def2Entry<V>> pointer = ((InterfaceFastList<Def2Entry<V>>)fastList).First; while (pointer != null) { Def2Entry<V> existingDefEntry = pointer.ElemValue; if (Object.ReferenceEquals(existingDefEntry.extension, extension) && existingDefEntry.sourceDistance == sourceDistance && existingDefEntry.targetDistance == targetDistance) { // DefEntry already exists with same distance return false; } pointer = pointer.Next; } } if (fastList == null || Object.ReferenceEquals(fastList, alreadyHandled)) { fastList = new InterfaceFastList<Def2Entry<V>>(); typeToDefEntryMap.Put(key, fastList); } Def2Entry<V> defEntry = new Def2Entry<V>(extension, key.SourceType, key.TargetType, sourceDistance, targetDistance); HashMap<Strong2Key<V>, List<Def2Entry<V>>> definitionReverseMap = classEntry.definitionReverseMap; Strong2Key<V> strongKey = new Strong2Key<V>(extension, strongTypeKey); List<Def2Entry<V>> typeEntries = definitionReverseMap.Get(strongKey); if (typeEntries == null) { typeEntries = new List<Def2Entry<V>>(); definitionReverseMap.Put(strongKey, typeEntries); } typeEntries.Add(defEntry); InterfaceFastList<Def2Entry<V>>.InsertOrdered((InterfaceFastList<Def2Entry<V>>)fastList, defEntry); TypeToDefEntryMapChanged(classEntry, key); return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.VisualBasic { public enum CallType { Get = 2, Let = 4, Method = 1, Set = 8, } [Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute] public sealed partial class Constants { internal Constants() { } public const string vbBack = "\b"; public const string vbCr = "\r"; public const string vbCrLf = "\r\n"; public const string vbFormFeed = "\f"; public const string vbLf = "\n"; public const string vbNewLine = "\r\n"; public const string vbNullChar = "\0"; public const string vbNullString = null; public const string vbTab = "\t"; public const string vbVerticalTab = "\v"; } [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false, Inherited = false)] public sealed partial class HideModuleNameAttribute : System.Attribute { public HideModuleNameAttribute() { } } [Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute] public sealed partial class Strings { internal Strings() { } public static int AscW(char String) { return default(int); } public static int AscW(string String) { return default(int); } public static char ChrW(int CharCode) { return default(char); } } } namespace Microsoft.VisualBasic.CompilerServices { [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class Conversions { internal Conversions() { } public static object ChangeType(object Expression, System.Type TargetType) { return default(object); } public static bool ToBoolean(object Value) { return default(bool); } public static bool ToBoolean(string Value) { return default(bool); } public static byte ToByte(object Value) { return default(byte); } public static byte ToByte(string Value) { return default(byte); } public static char ToChar(object Value) { return default(char); } public static char ToChar(string Value) { return default(char); } public static char[] ToCharArrayRankOne(object Value) { return default(char[]); } public static char[] ToCharArrayRankOne(string Value) { return default(char[]); } public static System.DateTime ToDate(object Value) { return default(System.DateTime); } public static System.DateTime ToDate(string Value) { return default(System.DateTime); } public static decimal ToDecimal(bool Value) { return default(decimal); } public static decimal ToDecimal(object Value) { return default(decimal); } public static decimal ToDecimal(string Value) { return default(decimal); } public static double ToDouble(object Value) { return default(double); } public static double ToDouble(string Value) { return default(double); } public static T ToGenericParameter<T>(object Value) { return default(T); } public static int ToInteger(object Value) { return default(int); } public static int ToInteger(string Value) { return default(int); } public static long ToLong(object Value) { return default(long); } public static long ToLong(string Value) { return default(long); } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(object Value) { return default(sbyte); } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(string Value) { return default(sbyte); } public static short ToShort(object Value) { return default(short); } public static short ToShort(string Value) { return default(short); } public static float ToSingle(object Value) { return default(float); } public static float ToSingle(string Value) { return default(float); } public static string ToString(bool Value) { return default(string); } public static string ToString(byte Value) { return default(string); } public static string ToString(char Value) { return default(string); } public static string ToString(System.DateTime Value) { return default(string); } public static string ToString(decimal Value) { return default(string); } public static string ToString(double Value) { return default(string); } public static string ToString(short Value) { return default(string); } public static string ToString(int Value) { return default(string); } public static string ToString(long Value) { return default(string); } public static string ToString(object Value) { return default(string); } public static string ToString(float Value) { return default(string); } [System.CLSCompliantAttribute(false)] public static string ToString(uint Value) { return default(string); } [System.CLSCompliantAttribute(false)] public static string ToString(ulong Value) { return default(string); } [System.CLSCompliantAttribute(false)] public static uint ToUInteger(object Value) { return default(uint); } [System.CLSCompliantAttribute(false)] public static uint ToUInteger(string Value) { return default(uint); } [System.CLSCompliantAttribute(false)] public static ulong ToULong(object Value) { return default(ulong); } [System.CLSCompliantAttribute(false)] public static ulong ToULong(string Value) { return default(ulong); } [System.CLSCompliantAttribute(false)] public static ushort ToUShort(object Value) { return default(ushort); } [System.CLSCompliantAttribute(false)] public static ushort ToUShort(string Value) { return default(ushort); } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false, Inherited = false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class DesignerGeneratedAttribute : System.Attribute { public DesignerGeneratedAttribute() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class IncompleteInitialization : System.Exception { public IncompleteInitialization() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class NewLateBinding { internal NewLateBinding() { } public static object LateCall(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack, bool IgnoreReturn) { return default(object); } public static object LateGet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack) { return default(object); } public static object LateIndexGet(object Instance, object[] Arguments, string[] ArgumentNames) { return default(object); } public static void LateIndexSet(object Instance, object[] Arguments, string[] ArgumentNames) { } public static void LateIndexSetComplex(object Instance, object[] Arguments, string[] ArgumentNames, bool OptimisticSet, bool RValueBase) { } public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments) { } public static void LateSet(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase, Microsoft.VisualBasic.CallType CallType) { } public static void LateSetComplex(object Instance, System.Type Type, string MemberName, object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool OptimisticSet, bool RValueBase) { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class ObjectFlowControl { internal ObjectFlowControl() { } public static void CheckForSyncLockOnValueType(object Expression) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class ForLoopControl { internal ForLoopControl() { } public static bool ForLoopInitObj(object Counter, object Start, object Limit, object StepValue, ref object LoopForResult, ref object CounterResult) { return default(bool); } public static bool ForNextCheckDec(decimal count, decimal limit, decimal StepValue) { return default(bool); } public static bool ForNextCheckObj(object Counter, object LoopObj, ref object CounterResult) { return default(bool); } public static bool ForNextCheckR4(float count, float limit, float StepValue) { return default(bool); } public static bool ForNextCheckR8(double count, double limit, double StepValue) { return default(bool); } } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class Operators { internal Operators() { } public static object AddObject(object Left, object Right) { return default(object); } public static object AndObject(object Left, object Right) { return default(object); } public static object CompareObjectEqual(object Left, object Right, bool TextCompare) { return default(object); } public static object CompareObjectGreater(object Left, object Right, bool TextCompare) { return default(object); } public static object CompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { return default(object); } public static object CompareObjectLess(object Left, object Right, bool TextCompare) { return default(object); } public static object CompareObjectLessEqual(object Left, object Right, bool TextCompare) { return default(object); } public static object CompareObjectNotEqual(object Left, object Right, bool TextCompare) { return default(object); } public static int CompareString(string Left, string Right, bool TextCompare) { return default(int); } public static object ConcatenateObject(object Left, object Right) { return default(object); } public static bool ConditionalCompareObjectEqual(object Left, object Right, bool TextCompare) { return default(bool); } public static bool ConditionalCompareObjectGreater(object Left, object Right, bool TextCompare) { return default(bool); } public static bool ConditionalCompareObjectGreaterEqual(object Left, object Right, bool TextCompare) { return default(bool); } public static bool ConditionalCompareObjectLess(object Left, object Right, bool TextCompare) { return default(bool); } public static bool ConditionalCompareObjectLessEqual(object Left, object Right, bool TextCompare) { return default(bool); } public static bool ConditionalCompareObjectNotEqual(object Left, object Right, bool TextCompare) { return default(bool); } public static object DivideObject(object Left, object Right) { return default(object); } public static object ExponentObject(object Left, object Right) { return default(object); } public static object IntDivideObject(object Left, object Right) { return default(object); } public static object LeftShiftObject(object Operand, object Amount) { return default(object); } public static object ModObject(object Left, object Right) { return default(object); } public static object MultiplyObject(object Left, object Right) { return default(object); } public static object NegateObject(object Operand) { return default(object); } public static object NotObject(object Operand) { return default(object); } public static object OrObject(object Left, object Right) { return default(object); } public static object PlusObject(object Operand) { return default(object); } public static object RightShiftObject(object Operand, object Amount) { return default(object); } public static object SubtractObject(object Left, object Right) { return default(object); } public static object XorObject(object Left, object Right) { return default(object); } } [System.AttributeUsageAttribute((System.AttributeTargets)(2048), Inherited = false, AllowMultiple = false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class OptionCompareAttribute : System.Attribute { public OptionCompareAttribute() { } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = false, AllowMultiple = false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class OptionTextAttribute : System.Attribute { public OptionTextAttribute() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class ProjectData { internal ProjectData() { } [System.Security.SecuritySafeCriticalAttribute] public static void ClearProjectError() { } [System.Security.SecuritySafeCriticalAttribute] public static void SetProjectError(System.Exception ex) { } [System.Security.SecuritySafeCriticalAttribute] public static void SetProjectError(System.Exception ex, int lErl) { } } [System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = false, AllowMultiple = false)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class StandardModuleAttribute : System.Attribute { public StandardModuleAttribute() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class StaticLocalInitFlag { public short State; public StaticLocalInitFlag() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class Utils { internal Utils() { } public static System.Array CopyArray(System.Array arySrc, System.Array aryDest) { return default(System.Array); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Monitor { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// MetricDefinitionsOperations operations. /// </summary> internal partial class MetricDefinitionsOperations : IServiceOperations<MonitorClient>, IMetricDefinitionsOperations { /// <summary> /// Initializes a new instance of the MetricDefinitionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal MetricDefinitionsOperations(MonitorClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorClient /// </summary> public MonitorClient Client { get; private set; } /// <summary> /// Lists the metric definitions for the resource. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </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> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<MetricDefinition>>> ListWithHttpMessagesAsync(string resourceUri, ODataQuery<MetricDefinition> odataQuery = default(ODataQuery<MetricDefinition>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/metricDefinitions").ToString(); _url = _url.Replace("{resourceUri}", resourceUri); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<MetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System.Collections.Generic; using System.Threading.Tasks; using Ivvy.API.Crm; namespace Ivvy.API { public partial class ApiClient : IApiClient { /// <inheritdoc /> public async Task<ResultOrError<ResultList<Lead>>> GetLeadListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<Lead>>( "crm", "getLeadList", new { perPage, start, filter = filterRequest } ); } /// <inheritdoc /> public async Task<ResultOrError<ResultList<LeadStage>>> GetLeadStageListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<LeadStage>>( "crm", "getLeadStageList", new { perPage, start, filter = filterRequest } ); } /// <inheritdoc /> public async Task<ResultOrError<ResultList<LeadType>>> GetLeadTypeListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<LeadType>>( "crm", "getLeadTypeList", new { perPage, start, filter = filterRequest } ); } /// <inheritdoc /> public async Task<ResultOrError<ResultList<Opportunity>>> GetOpportunityListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<Opportunity>>( "crm", "getOpportunityList", new { perPage, start, filter = filterRequest }); } /// <inheritdoc /> public async Task<ResultOrError<ResultObject>> AddOrUpdateOpportunityAsync(Opportunity opportunity) { return await CallAsync<ResultObject>( "venue", "addOrUpdateOpportunity", opportunity ); } /// <inheritdoc /> public async Task<ResultOrError<ResultList<Crm.EventTask>>> GetTaskListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<Crm.EventTask>>( "crm", "getTaskList", new { perPage, start, filter = filterRequest }); } /// <inheritdoc /> public async Task<ResultOrError<ResultObject>> AddOrUpdateTaskAsync(EventTask task) { return await CallAsync<ResultObject>( "crm", "addOrUpdateTask", task ); } /// <inheritdoc /> public async Task<ResultOrError<ResultList<Crm.EventActivity>>> GetActivityListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<Crm.EventActivity>>( "crm", "getActivityList", new { perPage, start, filter = filterRequest }); } /// <inheritdoc /> public async Task<ResultOrError<ResultObject>> AddOrUpdateActivityAsync(EventActivity activity) { return await CallAsync<ResultObject>( "crm", "addOrUpdateActivity", activity ); } /// <inheritdoc /> public async Task<ResultOrError<ResultList<LeadSource>>> GetLeadSourceListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<LeadSource>>( "crm", "getLeadSourceList", new { perPage, start, filter = filterRequest } ); } /// <inheritdoc /> public async Task<ResultOrError<ResultObject>> AddOrUpdateLeadSourceAsync( LeadSource source) { return await CallAsync<ResultObject>( "crm", "addOrUpdateLeadSource", source); } /// <inheritdoc /> public async Task<ResultOrError<ResultList<LeadChannel>>> GetLeadChannelListAsync( int perPage, int start, Dictionary<string, object> filterRequest = null) { return await CallAsync<ResultList<LeadChannel>>( "crm", "getLeadChannelList", new { perPage, start, filter = filterRequest } ); } /// <inheritdoc /> public async Task<ResultOrError<ResultObject>> AddOrUpdateLeadChannelAsync( LeadChannel channel) { return await CallAsync<ResultObject>( "crm", "addOrUpdateLeadChannel", channel); } /// <inheritdoc /> public async Task<ResultOrError<HowToAllocateOpportunity>> GetHowToAllocateOpportunity( int venueId, HowToAllocateOpportunity.OpportunityTypes opportunityType, int eventTypeId, int estimatedValue) { if (eventTypeId > 0) { return await CallAsync<HowToAllocateOpportunity>( "crm", "getHowToAllocateOpportunity", new { venueId, opportunityType, eventTypeId, estimatedValue } ); } else { return await CallAsync<HowToAllocateOpportunity>( "crm", "getHowToAllocateOpportunity", new { venueId, opportunityType, estimatedValue } ); } } } }
// Radial Menu|Prefabs|0040 namespace VRTK { using UnityEngine; using System.Collections; using UnityEngine.Events; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; public delegate void HapticPulseEventHandler(float strength); /// <summary> /// This adds a UI element into the world space that can be dropped into a Controller object and used to create and use Radial Menus from the touchpad. /// </summary> /// <remarks> /// If the RadialMenu is placed inside a controller, it will automatically find a `VRTK_ControllerEvents` in its parent to use at the input. However, a `VRTK_ControllerEvents` can be defined explicitly by setting the `Events` parameter of the `Radial Menu Controller` script also attached to the prefab. /// /// The RadialMenu can also be placed inside a `VRTK_InteractableObject` for the RadialMenu to be anchored to a world object instead of the controller. The `Events Manager` parameter will automatically be set if the RadialMenu is a child of an InteractableObject, but it can also be set manually in the inspector. Additionally, for the RadialMenu to be anchored in the world, the `RadialMenuController` script in the prefab must be replaced with `VRTK_IndependentRadialMenuController`. See the script information for further details on making the RadialMenu independent of the controllers. /// </remarks> /// <example> /// `VRTK/Examples/030_Controls_RadialTouchpadMenu` displays a radial menu for each controller. The left controller uses the `Hide On Release` variable, so it will only be visible if the left touchpad is being touched. It also uses the `Execute On Unclick` variable to delay execution until the touchpad button is unclicked. The example scene also contains a demonstration of anchoring the RadialMenu to an interactable cube instead of a controller. /// </example> [ExecuteInEditMode] public class VRTK_RadialMenu : MonoBehaviour { [System.Serializable] public class RadialMenuButton { public Sprite ButtonIcon; public UnityEvent OnClick = new UnityEvent(); public UnityEvent OnHold = new UnityEvent(); public UnityEvent OnHoverEnter = new UnityEvent(); public UnityEvent OnHoverExit = new UnityEvent(); } public enum ButtonEvent { hoverOn, hoverOff, click, unclick } [Tooltip("An array of Buttons that define the interactive buttons required to be displayed as part of the radial menu.")] public List<RadialMenuButton> buttons; [Tooltip("The base for each button in the menu, by default set to a dynamic circle arc that will fill up a portion of the menu.")] public GameObject buttonPrefab; [Tooltip("If checked, then the buttons will be auto generated on awake.")] public bool generateOnAwake = true; [Tooltip("Percentage of the menu the buttons should fill, 1.0 is a pie slice, 0.1 is a thin ring.")] [Range(0f, 1f)] public float buttonThickness = 0.5f; [Tooltip("The background colour of the buttons, default is white.")] public Color buttonColor = Color.white; [Tooltip("The distance the buttons should move away from the centre. This creates space between the individual buttons.")] public float offsetDistance = 1; [Tooltip("The additional rotation of the Radial Menu.")] [Range(0, 359)] public float offsetRotation; [Tooltip("Whether button icons should rotate according to their arc or be vertical compared to the controller.")] public bool rotateIcons; [Tooltip("The margin in pixels that the icon should keep within the button.")] public float iconMargin; [Tooltip("Whether the buttons are shown")] public bool isShown; [Tooltip("Whether the buttons should be visible when not in use.")] public bool hideOnRelease; [Tooltip("Whether the button action should happen when the button is released, as opposed to happening immediately when the button is pressed.")] public bool executeOnUnclick; [Tooltip("The base strength of the haptic pulses when the selected button is changed, or a button is pressed. Set to zero to disable.")] [Range(0, 1)] public float baseHapticStrength; public event HapticPulseEventHandler FireHapticPulse; //Has to be public to keep state from editor -> play mode? [Tooltip("The actual GameObjects that make up the radial menu.")] public List<GameObject> menuButtons; protected int currentHover = -1; protected int currentPress = -1; protected Coroutine tweenMenuScaleRoutine; /// <summary> /// The HoverButton method is used to set the button hover at a given angle. /// </summary> /// <param name="angle">The angle on the radial menu.</param> public virtual void HoverButton(float angle) { InteractButton(angle, ButtonEvent.hoverOn); } /// <summary> /// The ClickButton method is used to set the button click at a given angle. /// </summary> /// <param name="angle">The angle on the radial menu.</param> public virtual void ClickButton(float angle) { InteractButton(angle, ButtonEvent.click); } /// <summary> /// The UnClickButton method is used to set the button unclick at a given angle. /// </summary> /// <param name="angle">The angle on the radial menu.</param> public virtual void UnClickButton(float angle) { InteractButton(angle, ButtonEvent.unclick); } /// <summary> /// The ToggleMenu method is used to show or hide the radial menu. /// </summary> public virtual void ToggleMenu() { if (isShown) { HideMenu(true); } else { ShowMenu(); } } /// <summary> /// The StopTouching method is used to stop touching the menu. /// </summary> public virtual void StopTouching() { if (currentHover != -1) { PointerEventData pointer = new PointerEventData(EventSystem.current); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); currentHover = -1; } } /// <summary> /// The ShowMenu method is used to show the menu. /// </summary> public virtual void ShowMenu() { if (!isShown) { isShown = true; InitTweenMenuScale(isShown); } } /// <summary> /// The GetButton method is used to get a button from the menu. /// </summary> /// <param name="id">The id of the button to retrieve.</param> /// <returns>The found radial menu button.</returns> public virtual RadialMenuButton GetButton(int id) { if (id < buttons.Count) { return buttons[id]; } return null; } /// <summary> /// The HideMenu method is used to hide the menu. /// </summary> /// <param name="force">If true then the menu is always hidden.</param> public virtual void HideMenu(bool force) { if (isShown && (hideOnRelease || force)) { isShown = false; InitTweenMenuScale(isShown); } } /// <summary> /// The RegenerateButtons method creates all the button arcs and populates them with desired icons. /// </summary> public void RegenerateButtons() { RemoveAllButtons(); for (int i = 0; i < buttons.Count; i++) { // Initial placement/instantiation GameObject newButton = Instantiate(buttonPrefab); newButton.transform.SetParent(transform); newButton.transform.localScale = Vector3.one; newButton.GetComponent<RectTransform>().offsetMax = Vector2.zero; newButton.GetComponent<RectTransform>().offsetMin = Vector2.zero; //Setup button arc UICircle circle = newButton.GetComponent<UICircle>(); if (buttonThickness == 1) { circle.fill = true; } else { circle.thickness = (int)(buttonThickness * (GetComponent<RectTransform>().rect.width / 2f)); } int fillPerc = (int)(100f / buttons.Count); circle.fillPercent = fillPerc; circle.color = buttonColor; //Final placement/rotation float angle = ((360 / buttons.Count) * i) + offsetRotation; newButton.transform.localEulerAngles = new Vector3(0, 0, angle); newButton.layer = 4; //UI Layer newButton.transform.localPosition = Vector3.zero; if (circle.fillPercent < 55) { float angleRad = (angle * Mathf.PI) / 180f; Vector2 angleVector = new Vector2(-Mathf.Cos(angleRad), -Mathf.Sin(angleRad)); newButton.transform.localPosition += (Vector3)angleVector * offsetDistance; } //Place and populate Button Icon GameObject buttonIcon = newButton.GetComponentInChildren<RadialButtonIcon>().gameObject; if (buttons[i].ButtonIcon == null) { buttonIcon.SetActive(false); } else { buttonIcon.GetComponent<Image>().sprite = buttons[i].ButtonIcon; buttonIcon.transform.localPosition = new Vector2(-1 * ((newButton.GetComponent<RectTransform>().rect.width / 2f) - (circle.thickness / 2f)), 0); //Min icon size from thickness and arc float scale1 = Mathf.Abs(circle.thickness); float R = Mathf.Abs(buttonIcon.transform.localPosition.x); float bAngle = (359f * circle.fillPercent * 0.01f * Mathf.PI) / 180f; float scale2 = (R * 2 * Mathf.Sin(bAngle / 2f)); if (circle.fillPercent > 24) //Scale calc doesn't work for > 90 degrees { scale2 = float.MaxValue; } float iconScale = Mathf.Min(scale1, scale2) - iconMargin; buttonIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(iconScale, iconScale); //Rotate icons all vertically if desired if (!rotateIcons) { buttonIcon.transform.eulerAngles = GetComponentInParent<Canvas>().transform.eulerAngles; } } menuButtons.Add(newButton); } } /// <summary> /// The AddButton method is used to add a new button to the menu. /// </summary> /// <param name="newButton">The button to add.</param> public void AddButton(RadialMenuButton newButton) { buttons.Add(newButton); RegenerateButtons(); } protected virtual void Awake() { if (Application.isPlaying) { if (!isShown) { transform.localScale = Vector3.zero; } if (generateOnAwake) { RegenerateButtons(); } } } protected virtual void Update() { //Keep track of pressed button and constantly invoke Hold event if (currentPress != -1) { buttons[currentPress].OnHold.Invoke(); } } //Turns and Angle and Event type into a button action protected virtual void InteractButton(float angle, ButtonEvent evt) //Can't pass ExecuteEvents as parameter? Unity gives error { //Get button ID from angle float buttonAngle = 360f / buttons.Count; //Each button is an arc with this angle angle = VRTK_SharedMethods.Mod((angle + -offsetRotation), 360); //Offset the touch coordinate with our offset int buttonID = (int)VRTK_SharedMethods.Mod(((angle + (buttonAngle / 2f)) / buttonAngle), buttons.Count); //Convert angle into ButtonID (This is the magic) PointerEventData pointer = new PointerEventData(EventSystem.current); //Create a new EventSystem (UI) Event //If we changed buttons while moving, un-hover and un-click the last button we were on if (currentHover != buttonID && currentHover != -1) { ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerUpHandler); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); if (executeOnUnclick && currentPress != -1) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); AttempHapticPulse(baseHapticStrength * 1.666f); } } if (evt == ButtonEvent.click) //Click button if click, and keep track of current press (executes button action) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); currentPress = buttonID; if (!executeOnUnclick) { buttons[buttonID].OnClick.Invoke(); AttempHapticPulse(baseHapticStrength * 2.5f); } } else if (evt == ButtonEvent.unclick) //Clear press id to stop invoking OnHold method (hide menu) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerUpHandler); currentPress = -1; if (executeOnUnclick) { AttempHapticPulse(baseHapticStrength * 2.5f); buttons[buttonID].OnClick.Invoke(); } } else if (evt == ButtonEvent.hoverOn && currentHover != buttonID) // Show hover UI event (darken button etc). Show menu { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerEnterHandler); buttons[buttonID].OnHoverEnter.Invoke(); AttempHapticPulse(baseHapticStrength); } currentHover = buttonID; //Set current hover ID, need this to un-hover if selected button changes } protected virtual void InitTweenMenuScale(bool isShown) { if (tweenMenuScaleRoutine != null) { StopCoroutine(tweenMenuScaleRoutine); } tweenMenuScaleRoutine = StartCoroutine(TweenMenuScale(isShown)); } //Simple tweening for menu, scales linearly from 0 to 1 and 1 to 0 protected virtual IEnumerator TweenMenuScale(bool show) { float targetScale = 0; Vector3 Dir = -1 * Vector3.one; if (show) { targetScale = 1; Dir = Vector3.one; } int i = 0; //Sanity check for infinite loops while (i < 250 && ((show && transform.localScale.x < targetScale) || (!show && transform.localScale.x > targetScale))) { transform.localScale += Dir * Time.deltaTime * 4f; //Tweening function - currently 0.25 second linear yield return true; i++; } transform.localScale = Dir * targetScale; } protected virtual void AttempHapticPulse(float strength) { if (strength > 0 && FireHapticPulse != null) { FireHapticPulse(strength); } } protected virtual void RemoveAllButtons() { if (menuButtons == null) { menuButtons = new List<GameObject>(); } for (int i = 0; i < menuButtons.Count; i++) { DestroyImmediate(menuButtons[i]); } menuButtons = new List<GameObject>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace System.ServiceModel.Diagnostics { internal class ServiceModelActivity : IDisposable { [ThreadStatic] private static ServiceModelActivity s_currentActivity; private static string[] s_ActivityTypeNames = new string[(int)ActivityType.NumItems]; private static string s_activityBoundaryDescription = null; private bool _autoStop = false; private bool _autoResume = false; private bool _disposed = false; private bool _isAsync = false; private int _stopCount = 0; private const int AsyncStopCount = 2; private TransferActivity _activity = null; static ServiceModelActivity() { s_ActivityTypeNames[(int)ActivityType.Unknown] = "Unknown"; s_ActivityTypeNames[(int)ActivityType.Close] = "Close"; s_ActivityTypeNames[(int)ActivityType.Construct] = "Construct"; s_ActivityTypeNames[(int)ActivityType.ExecuteUserCode] = "ExecuteUserCode"; s_ActivityTypeNames[(int)ActivityType.ListenAt] = "ListenAt"; s_ActivityTypeNames[(int)ActivityType.Open] = "Open"; s_ActivityTypeNames[(int)ActivityType.OpenClient] = "Open"; s_ActivityTypeNames[(int)ActivityType.ProcessMessage] = "ProcessMessage"; s_ActivityTypeNames[(int)ActivityType.ProcessAction] = "ProcessAction"; s_ActivityTypeNames[(int)ActivityType.ReceiveBytes] = "ReceiveBytes"; s_ActivityTypeNames[(int)ActivityType.SecuritySetup] = "SecuritySetup"; s_ActivityTypeNames[(int)ActivityType.TransferToComPlus] = "TransferToComPlus"; s_ActivityTypeNames[(int)ActivityType.WmiGetObject] = "WmiGetObject"; s_ActivityTypeNames[(int)ActivityType.WmiPutInstance] = "WmiPutInstance"; } private ServiceModelActivity(Guid activityId) { Id = activityId; PreviousActivity = ServiceModelActivity.Current; } private static string ActivityBoundaryDescription { get { if (ServiceModelActivity.s_activityBoundaryDescription == null) { ServiceModelActivity.s_activityBoundaryDescription = SR.ActivityBoundary; } return ServiceModelActivity.s_activityBoundaryDescription; } } internal ActivityType ActivityType { get; private set; } = ActivityType.Unknown; internal ServiceModelActivity PreviousActivity { get; } = null; static internal Activity BoundOperation(ServiceModelActivity activity) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } return ServiceModelActivity.BoundOperation(activity, false); } static internal Activity BoundOperation(ServiceModelActivity activity, bool addTransfer) { return activity == null ? null : ServiceModelActivity.BoundOperationCore(activity, addTransfer); } private static Activity BoundOperationCore(ServiceModelActivity activity, bool addTransfer) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } TransferActivity retval = null; if (activity != null) { retval = TransferActivity.CreateActivity(activity.Id, addTransfer); if (retval != null) { retval.SetPreviousServiceModelActivity(ServiceModelActivity.Current); } ServiceModelActivity.Current = activity; } return retval; } internal static ServiceModelActivity CreateActivity() { if (!DiagnosticUtility.ShouldUseActivity) { return null; } return ServiceModelActivity.CreateActivity(Guid.NewGuid(), true); } internal static ServiceModelActivity CreateActivity(bool autoStop) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activity = ServiceModelActivity.CreateActivity(Guid.NewGuid(), true); if (activity != null) { activity._autoStop = autoStop; } return activity; } internal static ServiceModelActivity CreateActivity(bool autoStop, string activityName, ActivityType activityType) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activity = ServiceModelActivity.CreateActivity(autoStop); ServiceModelActivity.Start(activity, activityName, activityType); return activity; } internal static ServiceModelActivity CreateAsyncActivity() { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activity = ServiceModelActivity.CreateActivity(true); if (activity != null) { activity._isAsync = true; } return activity; } internal static ServiceModelActivity CreateBoundedActivity() { return ServiceModelActivity.CreateBoundedActivity(false); } internal static ServiceModelActivity CreateBoundedActivity(bool suspendCurrent) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity activityToSuspend = ServiceModelActivity.Current; ServiceModelActivity retval = ServiceModelActivity.CreateActivity(true); if (retval != null) { retval._activity = (TransferActivity)ServiceModelActivity.BoundOperation(retval, true); retval._activity.SetPreviousServiceModelActivity(activityToSuspend); if (suspendCurrent) { retval._autoResume = true; } } if (suspendCurrent && activityToSuspend != null) { activityToSuspend.Suspend(); } return retval; } internal static ServiceModelActivity CreateBoundedActivity(Guid activityId) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = ServiceModelActivity.CreateActivity(activityId, true); if (retval != null) { retval._activity = (TransferActivity)ServiceModelActivity.BoundOperation(retval, true); } return retval; } internal static ServiceModelActivity CreateBoundedActivityWithTransferInOnly(Guid activityId) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = ServiceModelActivity.CreateActivity(activityId, true); if (retval != null) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(activityId); } retval._activity = (TransferActivity)ServiceModelActivity.BoundOperation(retval); } return retval; } internal static ServiceModelActivity CreateLightWeightAsyncActivity(Guid activityId) { return new ServiceModelActivity(activityId); } internal static ServiceModelActivity CreateActivity(Guid activityId) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = null; if (activityId != Guid.Empty) { retval = new ServiceModelActivity(activityId); } if (retval != null) { ServiceModelActivity.Current = retval; } return retval; } internal static ServiceModelActivity CreateActivity(Guid activityId, bool autoStop) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } ServiceModelActivity retval = ServiceModelActivity.CreateActivity(activityId); if (retval != null) { retval._autoStop = autoStop; } return retval; } internal static ServiceModelActivity Current { get { return ServiceModelActivity.s_currentActivity; } private set { ServiceModelActivity.s_currentActivity = value; } } public void Dispose() { if (!_disposed) { _disposed = true; try { if (_activity != null) { _activity.Dispose(); } if (_autoStop) { Stop(); } if (_autoResume && ServiceModelActivity.Current != null) { ServiceModelActivity.Current.Resume(); } } finally { ServiceModelActivity.Current = PreviousActivity; GC.SuppressFinalize(this); } } } internal Guid Id { get; } private ActivityState LastState { get; set; } = ActivityState.Unknown; internal string Name { get; set; } = null; internal void Resume() { if (LastState == ActivityState.Suspend) { LastState = ActivityState.Resume; } } internal void Resume(string activityName) { if (string.IsNullOrEmpty(Name)) { Name = activityName; } Resume(); } static internal void Start(ServiceModelActivity activity, string activityName, ActivityType activityType) { if (activity != null && activity.LastState == ActivityState.Unknown) { activity.LastState = ActivityState.Start; activity.Name = activityName; activity.ActivityType = activityType; } } internal void Stop() { int newStopCount = 0; if (_isAsync) { newStopCount = Interlocked.Increment(ref _stopCount); } if (LastState != ActivityState.Stop && (!_isAsync || (_isAsync && newStopCount >= ServiceModelActivity.AsyncStopCount))) { LastState = ActivityState.Stop; } } static internal void Stop(ServiceModelActivity activity) { if (activity != null) { activity.Stop(); } } internal void Suspend() { if (LastState != ActivityState.Stop) { LastState = ActivityState.Suspend; } } public override string ToString() { return Id.ToString(); } private enum ActivityState { Unknown, Start, Suspend, Resume, Stop, } internal class TransferActivity : Activity { private bool _addTransfer = false; private bool _changeCurrentServiceModelActivity = false; private ServiceModelActivity _previousActivity = null; private TransferActivity(Guid activityId, Guid parentId) : base(activityId, parentId) { } internal static TransferActivity CreateActivity(Guid activityId, bool addTransfer) { if (!DiagnosticUtility.ShouldUseActivity) { return null; } TransferActivity retval = null; return retval; } internal void SetPreviousServiceModelActivity(ServiceModelActivity previous) { _previousActivity = previous; _changeCurrentServiceModelActivity = true; } public override void Dispose() { try { if (_addTransfer) { // Make sure that we are transferring from our AID to the // parent. It is possible for someone else to change the ambient // in user code (MB 49318). using (Activity.CreateActivity(Id)) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(parentId); } } } } finally { if (_changeCurrentServiceModelActivity) { ServiceModelActivity.Current = _previousActivity; } base.Dispose(); } } } } }